1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/CXXInheritance.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DependenceFlags.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
39 
40 using namespace clang;
41 using namespace sema;
42 
43 using AllowedExplicit = Sema::AllowedExplicit;
44 
functionHasPassObjectSizeParams(const FunctionDecl * FD)45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47     return P->hasAttr<PassObjectSizeAttr>();
48   });
49 }
50 
51 /// A convenience routine for creating a decayed reference to a function.
52 static ExprResult
CreateFunctionRefExpr(Sema & S,FunctionDecl * Fn,NamedDecl * FoundDecl,const Expr * Base,bool HadMultipleCandidates,SourceLocation Loc=SourceLocation (),const DeclarationNameLoc & LocInfo=DeclarationNameLoc ())53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54                       const Expr *Base, bool HadMultipleCandidates,
55                       SourceLocation Loc = SourceLocation(),
56                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58     return ExprError();
59   // If FoundDecl is different from Fn (such as if one is a template
60   // and the other a specialization), make sure DiagnoseUseOfDecl is
61   // called on both.
62   // FIXME: This would be more comprehensively addressed by modifying
63   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64   // being used.
65   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66     return ExprError();
67   DeclRefExpr *DRE = new (S.Context)
68       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69   if (HadMultipleCandidates)
70     DRE->setHadMultipleCandidates(true);
71 
72   S.MarkDeclRefReferenced(DRE, Base);
73   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75       S.ResolveExceptionSpec(Loc, FPT);
76       DRE->setType(Fn->getType());
77     }
78   }
79   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80                              CK_FunctionToPointerDecay);
81 }
82 
83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84                                  bool InOverloadResolution,
85                                  StandardConversionSequence &SCS,
86                                  bool CStyle,
87                                  bool AllowObjCWritebackConversion);
88 
89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90                                                  QualType &ToType,
91                                                  bool InOverloadResolution,
92                                                  StandardConversionSequence &SCS,
93                                                  bool CStyle);
94 static OverloadingResult
95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96                         UserDefinedConversionSequence& User,
97                         OverloadCandidateSet& Conversions,
98                         AllowedExplicit AllowExplicit,
99                         bool AllowObjCConversionOnExplicit);
100 
101 static ImplicitConversionSequence::CompareKind
102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103                                    const StandardConversionSequence& SCS1,
104                                    const StandardConversionSequence& SCS2);
105 
106 static ImplicitConversionSequence::CompareKind
107 CompareQualificationConversions(Sema &S,
108                                 const StandardConversionSequence& SCS1,
109                                 const StandardConversionSequence& SCS2);
110 
111 static ImplicitConversionSequence::CompareKind
112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113                                 const StandardConversionSequence& SCS1,
114                                 const StandardConversionSequence& SCS2);
115 
116 /// GetConversionRank - Retrieve the implicit conversion rank
117 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119   static const ImplicitConversionRank
120     Rank[(int)ICK_Num_Conversion_Kinds] = {
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Exact_Match,
127     ICR_Promotion,
128     ICR_Promotion,
129     ICR_Promotion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_OCL_Scalar_Widening,
141     ICR_Complex_Real_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Writeback_Conversion,
145     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146                      // it was omitted by the patch that added
147                      // ICK_Zero_Event_Conversion
148     ICR_C_Conversion,
149     ICR_C_Conversion_Extension
150   };
151   return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158     "No conversion",
159     "Lvalue-to-rvalue",
160     "Array-to-pointer",
161     "Function-to-pointer",
162     "Function pointer conversion",
163     "Qualification",
164     "Integral promotion",
165     "Floating point promotion",
166     "Complex promotion",
167     "Integral conversion",
168     "Floating conversion",
169     "Complex conversion",
170     "Floating-integral conversion",
171     "Pointer conversion",
172     "Pointer-to-member conversion",
173     "Boolean conversion",
174     "Compatible-types conversion",
175     "Derived-to-base conversion",
176     "Vector conversion",
177     "Vector splat",
178     "Complex-real conversion",
179     "Block Pointer conversion",
180     "Transparent Union Conversion",
181     "Writeback conversion",
182     "OpenCL Zero Event Conversion",
183     "C specific type conversion",
184     "Incompatible pointer conversion"
185   };
186   return Name[Kind];
187 }
188 
189 /// StandardConversionSequence - Set the standard conversion
190 /// sequence to the identity conversion.
setAsIdentityConversion()191 void StandardConversionSequence::setAsIdentityConversion() {
192   First = ICK_Identity;
193   Second = ICK_Identity;
194   Third = ICK_Identity;
195   DeprecatedStringLiteralToCharPtr = false;
196   QualificationIncludesObjCLifetime = false;
197   ReferenceBinding = false;
198   DirectBinding = false;
199   IsLvalueReference = true;
200   BindsToFunctionLvalue = false;
201   BindsToRvalue = false;
202   BindsImplicitObjectArgumentWithoutRefQualifier = false;
203   ObjCLifetimeConversionBinding = false;
204   CopyConstructor = nullptr;
205 }
206 
207 /// getRank - Retrieve the rank of this standard conversion sequence
208 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
209 /// implicit conversions.
getRank() const210 ImplicitConversionRank StandardConversionSequence::getRank() const {
211   ImplicitConversionRank Rank = ICR_Exact_Match;
212   if  (GetConversionRank(First) > Rank)
213     Rank = GetConversionRank(First);
214   if  (GetConversionRank(Second) > Rank)
215     Rank = GetConversionRank(Second);
216   if  (GetConversionRank(Third) > Rank)
217     Rank = GetConversionRank(Third);
218   return Rank;
219 }
220 
221 /// isPointerConversionToBool - Determines whether this conversion is
222 /// a conversion of a pointer or pointer-to-member to bool. This is
223 /// used as part of the ranking of standard conversion sequences
224 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const225 bool StandardConversionSequence::isPointerConversionToBool() const {
226   // Note that FromType has not necessarily been transformed by the
227   // array-to-pointer or function-to-pointer implicit conversions, so
228   // check for their presence as well as checking whether FromType is
229   // a pointer.
230   if (getToType(1)->isBooleanType() &&
231       (getFromType()->isPointerType() ||
232        getFromType()->isMemberPointerType() ||
233        getFromType()->isObjCObjectPointerType() ||
234        getFromType()->isBlockPointerType() ||
235        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
236     return true;
237 
238   return false;
239 }
240 
241 /// isPointerConversionToVoidPointer - Determines whether this
242 /// conversion is a conversion of a pointer to a void pointer. This is
243 /// used as part of the ranking of standard conversion sequences (C++
244 /// 13.3.3.2p4).
245 bool
246 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const247 isPointerConversionToVoidPointer(ASTContext& Context) const {
248   QualType FromType = getFromType();
249   QualType ToType = getToType(1);
250 
251   // Note that FromType has not necessarily been transformed by the
252   // array-to-pointer implicit conversion, so check for its presence
253   // and redo the conversion to get a pointer.
254   if (First == ICK_Array_To_Pointer)
255     FromType = Context.getArrayDecayedType(FromType);
256 
257   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
258     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
259       return ToPtrType->getPointeeType()->isVoidType();
260 
261   return false;
262 }
263 
264 /// Skip any implicit casts which could be either part of a narrowing conversion
265 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(ASTContext & Ctx,const Expr * Converted)266 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
267                                              const Expr *Converted) {
268   // We can have cleanups wrapping the converted expression; these need to be
269   // preserved so that destructors run if necessary.
270   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
271     Expr *Inner =
272         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
273     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
274                                     EWC->getObjects());
275   }
276 
277   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
278     switch (ICE->getCastKind()) {
279     case CK_NoOp:
280     case CK_IntegralCast:
281     case CK_IntegralToBoolean:
282     case CK_IntegralToFloating:
283     case CK_BooleanToSignedIntegral:
284     case CK_FloatingToIntegral:
285     case CK_FloatingToBoolean:
286     case CK_FloatingCast:
287       Converted = ICE->getSubExpr();
288       continue;
289 
290     default:
291       return Converted;
292     }
293   }
294 
295   return Converted;
296 }
297 
298 /// Check if this standard conversion sequence represents a narrowing
299 /// conversion, according to C++11 [dcl.init.list]p7.
300 ///
301 /// \param Ctx  The AST context.
302 /// \param Converted  The result of applying this standard conversion sequence.
303 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
304 ///        value of the expression prior to the narrowing conversion.
305 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
306 ///        type of the expression prior to the narrowing conversion.
307 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
308 ///        from floating point types to integral types should be ignored.
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType,bool IgnoreFloatToIntegralConversion) const309 NarrowingKind StandardConversionSequence::getNarrowingKind(
310     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
311     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
312   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
313 
314   // C++11 [dcl.init.list]p7:
315   //   A narrowing conversion is an implicit conversion ...
316   QualType FromType = getToType(0);
317   QualType ToType = getToType(1);
318 
319   // A conversion to an enumeration type is narrowing if the conversion to
320   // the underlying type is narrowing. This only arises for expressions of
321   // the form 'Enum{init}'.
322   if (auto *ET = ToType->getAs<EnumType>())
323     ToType = ET->getDecl()->getIntegerType();
324 
325   // Converting from capability to pointer/integral is always narrowing
326   if (FromType->isCHERICapabilityType(Ctx) && !ToType->isCHERICapabilityType(Ctx))
327     return NK_Type_Narrowing;
328 
329   switch (Second) {
330   // 'bool' is an integral type; dispatch to the right place to handle it.
331   case ICK_Boolean_Conversion:
332     if (FromType->isRealFloatingType())
333       goto FloatingIntegralConversion;
334     if (FromType->isIntegralOrUnscopedEnumerationType())
335       goto IntegralConversion;
336     // -- from a pointer type or pointer-to-member type to bool, or
337     return NK_Type_Narrowing;
338 
339   // -- from a floating-point type to an integer type, or
340   //
341   // -- from an integer type or unscoped enumeration type to a floating-point
342   //    type, except where the source is a constant expression and the actual
343   //    value after conversion will fit into the target type and will produce
344   //    the original value when converted back to the original type, or
345   case ICK_Floating_Integral:
346   FloatingIntegralConversion:
347     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
348       return NK_Type_Narrowing;
349     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
350                ToType->isRealFloatingType()) {
351       if (IgnoreFloatToIntegralConversion)
352         return NK_Not_Narrowing;
353       llvm::APSInt IntConstantValue;
354       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
355       assert(Initializer && "Unknown conversion expression");
356 
357       // If it's value-dependent, we can't tell whether it's narrowing.
358       if (Initializer->isValueDependent())
359         return NK_Dependent_Narrowing;
360 
361       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
362         // Convert the integer to the floating type.
363         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
364         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
365                                 llvm::APFloat::rmNearestTiesToEven);
366         // And back.
367         llvm::APSInt ConvertedValue = IntConstantValue;
368         bool ignored;
369         Result.convertToInteger(ConvertedValue,
370                                 llvm::APFloat::rmTowardZero, &ignored);
371         // If the resulting value is different, this was a narrowing conversion.
372         if (IntConstantValue != ConvertedValue) {
373           ConstantValue = APValue(IntConstantValue);
374           ConstantType = Initializer->getType();
375           return NK_Constant_Narrowing;
376         }
377       } else {
378         // Variables are always narrowings.
379         return NK_Variable_Narrowing;
380       }
381     }
382     return NK_Not_Narrowing;
383 
384   // -- from long double to double or float, or from double to float, except
385   //    where the source is a constant expression and the actual value after
386   //    conversion is within the range of values that can be represented (even
387   //    if it cannot be represented exactly), or
388   case ICK_Floating_Conversion:
389     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
390         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
391       // FromType is larger than ToType.
392       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
393 
394       // If it's value-dependent, we can't tell whether it's narrowing.
395       if (Initializer->isValueDependent())
396         return NK_Dependent_Narrowing;
397 
398       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
399         // Constant!
400         assert(ConstantValue.isFloat());
401         llvm::APFloat FloatVal = ConstantValue.getFloat();
402         // Convert the source value into the target type.
403         bool ignored;
404         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
405           Ctx.getFloatTypeSemantics(ToType),
406           llvm::APFloat::rmNearestTiesToEven, &ignored);
407         // If there was no overflow, the source value is within the range of
408         // values that can be represented.
409         if (ConvertStatus & llvm::APFloat::opOverflow) {
410           ConstantType = Initializer->getType();
411           return NK_Constant_Narrowing;
412         }
413       } else {
414         return NK_Variable_Narrowing;
415       }
416     }
417     return NK_Not_Narrowing;
418 
419   // -- from an integer type or unscoped enumeration type to an integer type
420   //    that cannot represent all the values of the original type, except where
421   //    the source is a constant expression and the actual value after
422   //    conversion will fit into the target type and will produce the original
423   //    value when converted back to the original type.
424   case ICK_Integral_Conversion:
425   IntegralConversion: {
426     assert(FromType->isIntegralOrUnscopedEnumerationType());
427     assert(ToType->isIntegralOrUnscopedEnumerationType());
428     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
429     const unsigned FromWidth = Ctx.getIntWidth(FromType);
430     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
431     const unsigned ToWidth = Ctx.getIntWidth(ToType);
432 
433     if (FromWidth > ToWidth ||
434         (FromWidth == ToWidth && FromSigned != ToSigned) ||
435         (FromSigned && !ToSigned)) {
436       // Not all values of FromType can be represented in ToType.
437       llvm::APSInt InitializerValue;
438       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439 
440       // If it's value-dependent, we can't tell whether it's narrowing.
441       if (Initializer->isValueDependent())
442         return NK_Dependent_Narrowing;
443 
444       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
445         // Such conversions on variables are always narrowing.
446         return NK_Variable_Narrowing;
447       }
448       bool Narrowing = false;
449       if (FromWidth < ToWidth) {
450         // Negative -> unsigned is narrowing. Otherwise, more bits is never
451         // narrowing.
452         if (InitializerValue.isSigned() && InitializerValue.isNegative())
453           Narrowing = true;
454       } else {
455         // Add a bit to the InitializerValue so we don't have to worry about
456         // signed vs. unsigned comparisons.
457         InitializerValue = InitializerValue.extend(
458           InitializerValue.getBitWidth() + 1);
459         // Convert the initializer to and from the target width and signed-ness.
460         llvm::APSInt ConvertedValue = InitializerValue;
461         ConvertedValue = ConvertedValue.trunc(ToWidth);
462         ConvertedValue.setIsSigned(ToSigned);
463         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
464         ConvertedValue.setIsSigned(InitializerValue.isSigned());
465         // If the result is different, this was a narrowing conversion.
466         if (ConvertedValue != InitializerValue)
467           Narrowing = true;
468       }
469       if (Narrowing) {
470         ConstantType = Initializer->getType();
471         ConstantValue = APValue(InitializerValue);
472         return NK_Constant_Narrowing;
473       }
474     }
475     return NK_Not_Narrowing;
476   }
477 
478   default:
479     // Other kinds of conversions are not narrowings.
480     return NK_Not_Narrowing;
481   }
482 }
483 
484 /// dump - Print this standard conversion sequence to standard
485 /// error. Useful for debugging overloading issues.
dump() const486 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
487   raw_ostream &OS = llvm::errs();
488   bool PrintedSomething = false;
489   if (First != ICK_Identity) {
490     OS << GetImplicitConversionName(First);
491     PrintedSomething = true;
492   }
493 
494   if (Second != ICK_Identity) {
495     if (PrintedSomething) {
496       OS << " -> ";
497     }
498     OS << GetImplicitConversionName(Second);
499 
500     if (CopyConstructor) {
501       OS << " (by copy constructor)";
502     } else if (DirectBinding) {
503       OS << " (direct reference binding)";
504     } else if (ReferenceBinding) {
505       OS << " (reference binding)";
506     }
507     PrintedSomething = true;
508   }
509 
510   if (Third != ICK_Identity) {
511     if (PrintedSomething) {
512       OS << " -> ";
513     }
514     OS << GetImplicitConversionName(Third);
515     PrintedSomething = true;
516   }
517 
518   if (!PrintedSomething) {
519     OS << "No conversions required";
520   }
521 }
522 
523 /// dump - Print this user-defined conversion sequence to standard
524 /// error. Useful for debugging overloading issues.
dump() const525 void UserDefinedConversionSequence::dump() const {
526   raw_ostream &OS = llvm::errs();
527   if (Before.First || Before.Second || Before.Third) {
528     Before.dump();
529     OS << " -> ";
530   }
531   if (ConversionFunction)
532     OS << '\'' << *ConversionFunction << '\'';
533   else
534     OS << "aggregate initialization";
535   if (After.First || After.Second || After.Third) {
536     OS << " -> ";
537     After.dump();
538   }
539 }
540 
541 /// dump - Print this implicit conversion sequence to standard
542 /// error. Useful for debugging overloading issues.
dump() const543 void ImplicitConversionSequence::dump() const {
544   raw_ostream &OS = llvm::errs();
545   if (isStdInitializerListElement())
546     OS << "Worst std::initializer_list element conversion: ";
547   switch (ConversionKind) {
548   case StandardConversion:
549     OS << "Standard conversion: ";
550     Standard.dump();
551     break;
552   case UserDefinedConversion:
553     OS << "User-defined conversion: ";
554     UserDefined.dump();
555     break;
556   case EllipsisConversion:
557     OS << "Ellipsis conversion";
558     break;
559   case AmbiguousConversion:
560     OS << "Ambiguous conversion";
561     break;
562   case BadConversion:
563     OS << "Bad conversion";
564     break;
565   }
566 
567   OS << "\n";
568 }
569 
construct()570 void AmbiguousConversionSequence::construct() {
571   new (&conversions()) ConversionSet();
572 }
573 
destruct()574 void AmbiguousConversionSequence::destruct() {
575   conversions().~ConversionSet();
576 }
577 
578 void
copyFrom(const AmbiguousConversionSequence & O)579 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
580   FromTypePtr = O.FromTypePtr;
581   ToTypePtr = O.ToTypePtr;
582   new (&conversions()) ConversionSet(O.conversions());
583 }
584 
585 namespace {
586   // Structure used by DeductionFailureInfo to store
587   // template argument information.
588   struct DFIArguments {
589     TemplateArgument FirstArg;
590     TemplateArgument SecondArg;
591   };
592   // Structure used by DeductionFailureInfo to store
593   // template parameter and template argument information.
594   struct DFIParamWithArguments : DFIArguments {
595     TemplateParameter Param;
596   };
597   // Structure used by DeductionFailureInfo to store template argument
598   // information and the index of the problematic call argument.
599   struct DFIDeducedMismatchArgs : DFIArguments {
600     TemplateArgumentList *TemplateArgs;
601     unsigned CallArgIndex;
602   };
603   // Structure used by DeductionFailureInfo to store information about
604   // unsatisfied constraints.
605   struct CNSInfo {
606     TemplateArgumentList *TemplateArgs;
607     ConstraintSatisfaction Satisfaction;
608   };
609 }
610 
611 /// Convert from Sema's representation of template deduction information
612 /// to the form used in overload-candidate information.
613 DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext & Context,Sema::TemplateDeductionResult TDK,TemplateDeductionInfo & Info)614 clang::MakeDeductionFailureInfo(ASTContext &Context,
615                                 Sema::TemplateDeductionResult TDK,
616                                 TemplateDeductionInfo &Info) {
617   DeductionFailureInfo Result;
618   Result.Result = static_cast<unsigned>(TDK);
619   Result.HasDiagnostic = false;
620   switch (TDK) {
621   case Sema::TDK_Invalid:
622   case Sema::TDK_InstantiationDepth:
623   case Sema::TDK_TooManyArguments:
624   case Sema::TDK_TooFewArguments:
625   case Sema::TDK_MiscellaneousDeductionFailure:
626   case Sema::TDK_CUDATargetMismatch:
627     Result.Data = nullptr;
628     break;
629 
630   case Sema::TDK_Incomplete:
631   case Sema::TDK_InvalidExplicitArguments:
632     Result.Data = Info.Param.getOpaqueValue();
633     break;
634 
635   case Sema::TDK_DeducedMismatch:
636   case Sema::TDK_DeducedMismatchNested: {
637     // FIXME: Should allocate from normal heap so that we can free this later.
638     auto *Saved = new (Context) DFIDeducedMismatchArgs;
639     Saved->FirstArg = Info.FirstArg;
640     Saved->SecondArg = Info.SecondArg;
641     Saved->TemplateArgs = Info.take();
642     Saved->CallArgIndex = Info.CallArgIndex;
643     Result.Data = Saved;
644     break;
645   }
646 
647   case Sema::TDK_NonDeducedMismatch: {
648     // FIXME: Should allocate from normal heap so that we can free this later.
649     DFIArguments *Saved = new (Context) DFIArguments;
650     Saved->FirstArg = Info.FirstArg;
651     Saved->SecondArg = Info.SecondArg;
652     Result.Data = Saved;
653     break;
654   }
655 
656   case Sema::TDK_IncompletePack:
657     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
658   case Sema::TDK_Inconsistent:
659   case Sema::TDK_Underqualified: {
660     // FIXME: Should allocate from normal heap so that we can free this later.
661     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
662     Saved->Param = Info.Param;
663     Saved->FirstArg = Info.FirstArg;
664     Saved->SecondArg = Info.SecondArg;
665     Result.Data = Saved;
666     break;
667   }
668 
669   case Sema::TDK_SubstitutionFailure:
670     Result.Data = Info.take();
671     if (Info.hasSFINAEDiagnostic()) {
672       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
673           SourceLocation(), PartialDiagnostic::NullDiagnostic());
674       Info.takeSFINAEDiagnostic(*Diag);
675       Result.HasDiagnostic = true;
676     }
677     break;
678 
679   case Sema::TDK_ConstraintsNotSatisfied: {
680     CNSInfo *Saved = new (Context) CNSInfo;
681     Saved->TemplateArgs = Info.take();
682     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
683     Result.Data = Saved;
684     break;
685   }
686 
687   case Sema::TDK_Success:
688   case Sema::TDK_NonDependentConversionFailure:
689     llvm_unreachable("not a deduction failure");
690   }
691 
692   return Result;
693 }
694 
Destroy()695 void DeductionFailureInfo::Destroy() {
696   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
697   case Sema::TDK_Success:
698   case Sema::TDK_Invalid:
699   case Sema::TDK_InstantiationDepth:
700   case Sema::TDK_Incomplete:
701   case Sema::TDK_TooManyArguments:
702   case Sema::TDK_TooFewArguments:
703   case Sema::TDK_InvalidExplicitArguments:
704   case Sema::TDK_CUDATargetMismatch:
705   case Sema::TDK_NonDependentConversionFailure:
706     break;
707 
708   case Sema::TDK_IncompletePack:
709   case Sema::TDK_Inconsistent:
710   case Sema::TDK_Underqualified:
711   case Sema::TDK_DeducedMismatch:
712   case Sema::TDK_DeducedMismatchNested:
713   case Sema::TDK_NonDeducedMismatch:
714     // FIXME: Destroy the data?
715     Data = nullptr;
716     break;
717 
718   case Sema::TDK_SubstitutionFailure:
719     // FIXME: Destroy the template argument list?
720     Data = nullptr;
721     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
722       Diag->~PartialDiagnosticAt();
723       HasDiagnostic = false;
724     }
725     break;
726 
727   case Sema::TDK_ConstraintsNotSatisfied:
728     // FIXME: Destroy the template argument list?
729     Data = nullptr;
730     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
731       Diag->~PartialDiagnosticAt();
732       HasDiagnostic = false;
733     }
734     break;
735 
736   // Unhandled
737   case Sema::TDK_MiscellaneousDeductionFailure:
738     break;
739   }
740 }
741 
getSFINAEDiagnostic()742 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
743   if (HasDiagnostic)
744     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
745   return nullptr;
746 }
747 
getTemplateParameter()748 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
749   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
750   case Sema::TDK_Success:
751   case Sema::TDK_Invalid:
752   case Sema::TDK_InstantiationDepth:
753   case Sema::TDK_TooManyArguments:
754   case Sema::TDK_TooFewArguments:
755   case Sema::TDK_SubstitutionFailure:
756   case Sema::TDK_DeducedMismatch:
757   case Sema::TDK_DeducedMismatchNested:
758   case Sema::TDK_NonDeducedMismatch:
759   case Sema::TDK_CUDATargetMismatch:
760   case Sema::TDK_NonDependentConversionFailure:
761   case Sema::TDK_ConstraintsNotSatisfied:
762     return TemplateParameter();
763 
764   case Sema::TDK_Incomplete:
765   case Sema::TDK_InvalidExplicitArguments:
766     return TemplateParameter::getFromOpaqueValue(Data);
767 
768   case Sema::TDK_IncompletePack:
769   case Sema::TDK_Inconsistent:
770   case Sema::TDK_Underqualified:
771     return static_cast<DFIParamWithArguments*>(Data)->Param;
772 
773   // Unhandled
774   case Sema::TDK_MiscellaneousDeductionFailure:
775     break;
776   }
777 
778   return TemplateParameter();
779 }
780 
getTemplateArgumentList()781 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
782   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
783   case Sema::TDK_Success:
784   case Sema::TDK_Invalid:
785   case Sema::TDK_InstantiationDepth:
786   case Sema::TDK_TooManyArguments:
787   case Sema::TDK_TooFewArguments:
788   case Sema::TDK_Incomplete:
789   case Sema::TDK_IncompletePack:
790   case Sema::TDK_InvalidExplicitArguments:
791   case Sema::TDK_Inconsistent:
792   case Sema::TDK_Underqualified:
793   case Sema::TDK_NonDeducedMismatch:
794   case Sema::TDK_CUDATargetMismatch:
795   case Sema::TDK_NonDependentConversionFailure:
796     return nullptr;
797 
798   case Sema::TDK_DeducedMismatch:
799   case Sema::TDK_DeducedMismatchNested:
800     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
801 
802   case Sema::TDK_SubstitutionFailure:
803     return static_cast<TemplateArgumentList*>(Data);
804 
805   case Sema::TDK_ConstraintsNotSatisfied:
806     return static_cast<CNSInfo*>(Data)->TemplateArgs;
807 
808   // Unhandled
809   case Sema::TDK_MiscellaneousDeductionFailure:
810     break;
811   }
812 
813   return nullptr;
814 }
815 
getFirstArg()816 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
817   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
818   case Sema::TDK_Success:
819   case Sema::TDK_Invalid:
820   case Sema::TDK_InstantiationDepth:
821   case Sema::TDK_Incomplete:
822   case Sema::TDK_TooManyArguments:
823   case Sema::TDK_TooFewArguments:
824   case Sema::TDK_InvalidExplicitArguments:
825   case Sema::TDK_SubstitutionFailure:
826   case Sema::TDK_CUDATargetMismatch:
827   case Sema::TDK_NonDependentConversionFailure:
828   case Sema::TDK_ConstraintsNotSatisfied:
829     return nullptr;
830 
831   case Sema::TDK_IncompletePack:
832   case Sema::TDK_Inconsistent:
833   case Sema::TDK_Underqualified:
834   case Sema::TDK_DeducedMismatch:
835   case Sema::TDK_DeducedMismatchNested:
836   case Sema::TDK_NonDeducedMismatch:
837     return &static_cast<DFIArguments*>(Data)->FirstArg;
838 
839   // Unhandled
840   case Sema::TDK_MiscellaneousDeductionFailure:
841     break;
842   }
843 
844   return nullptr;
845 }
846 
getSecondArg()847 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
848   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
849   case Sema::TDK_Success:
850   case Sema::TDK_Invalid:
851   case Sema::TDK_InstantiationDepth:
852   case Sema::TDK_Incomplete:
853   case Sema::TDK_IncompletePack:
854   case Sema::TDK_TooManyArguments:
855   case Sema::TDK_TooFewArguments:
856   case Sema::TDK_InvalidExplicitArguments:
857   case Sema::TDK_SubstitutionFailure:
858   case Sema::TDK_CUDATargetMismatch:
859   case Sema::TDK_NonDependentConversionFailure:
860   case Sema::TDK_ConstraintsNotSatisfied:
861     return nullptr;
862 
863   case Sema::TDK_Inconsistent:
864   case Sema::TDK_Underqualified:
865   case Sema::TDK_DeducedMismatch:
866   case Sema::TDK_DeducedMismatchNested:
867   case Sema::TDK_NonDeducedMismatch:
868     return &static_cast<DFIArguments*>(Data)->SecondArg;
869 
870   // Unhandled
871   case Sema::TDK_MiscellaneousDeductionFailure:
872     break;
873   }
874 
875   return nullptr;
876 }
877 
getCallArgIndex()878 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
879   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
880   case Sema::TDK_DeducedMismatch:
881   case Sema::TDK_DeducedMismatchNested:
882     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
883 
884   default:
885     return llvm::None;
886   }
887 }
888 
shouldAddReversed(OverloadedOperatorKind Op)889 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
890     OverloadedOperatorKind Op) {
891   if (!AllowRewrittenCandidates)
892     return false;
893   return Op == OO_EqualEqual || Op == OO_Spaceship;
894 }
895 
shouldAddReversed(ASTContext & Ctx,const FunctionDecl * FD)896 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
897     ASTContext &Ctx, const FunctionDecl *FD) {
898   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
899     return false;
900   // Don't bother adding a reversed candidate that can never be a better
901   // match than the non-reversed version.
902   return FD->getNumParams() != 2 ||
903          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
904                                      FD->getParamDecl(1)->getType()) ||
905          FD->hasAttr<EnableIfAttr>();
906 }
907 
destroyCandidates()908 void OverloadCandidateSet::destroyCandidates() {
909   for (iterator i = begin(), e = end(); i != e; ++i) {
910     for (auto &C : i->Conversions)
911       C.~ImplicitConversionSequence();
912     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
913       i->DeductionFailure.Destroy();
914   }
915 }
916 
clear(CandidateSetKind CSK)917 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
918   destroyCandidates();
919   SlabAllocator.Reset();
920   NumInlineBytesUsed = 0;
921   Candidates.clear();
922   Functions.clear();
923   Kind = CSK;
924 }
925 
926 namespace {
927   class UnbridgedCastsSet {
928     struct Entry {
929       Expr **Addr;
930       Expr *Saved;
931     };
932     SmallVector<Entry, 2> Entries;
933 
934   public:
save(Sema & S,Expr * & E)935     void save(Sema &S, Expr *&E) {
936       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
937       Entry entry = { &E, E };
938       Entries.push_back(entry);
939       E = S.stripARCUnbridgedCast(E);
940     }
941 
restore()942     void restore() {
943       for (SmallVectorImpl<Entry>::iterator
944              i = Entries.begin(), e = Entries.end(); i != e; ++i)
945         *i->Addr = i->Saved;
946     }
947   };
948 }
949 
950 /// checkPlaceholderForOverload - Do any interesting placeholder-like
951 /// preprocessing on the given expression.
952 ///
953 /// \param unbridgedCasts a collection to which to add unbridged casts;
954 ///   without this, they will be immediately diagnosed as errors
955 ///
956 /// Return true on unrecoverable error.
957 static bool
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=nullptr)958 checkPlaceholderForOverload(Sema &S, Expr *&E,
959                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
960   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
961     // We can't handle overloaded expressions here because overload
962     // resolution might reasonably tweak them.
963     if (placeholder->getKind() == BuiltinType::Overload) return false;
964 
965     // If the context potentially accepts unbridged ARC casts, strip
966     // the unbridged cast and add it to the collection for later restoration.
967     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
968         unbridgedCasts) {
969       unbridgedCasts->save(S, E);
970       return false;
971     }
972 
973     // Go ahead and check everything else.
974     ExprResult result = S.CheckPlaceholderExpr(E);
975     if (result.isInvalid())
976       return true;
977 
978     E = result.get();
979     return false;
980   }
981 
982   // Nothing to do.
983   return false;
984 }
985 
986 /// checkArgPlaceholdersForOverload - Check a set of call operands for
987 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,MultiExprArg Args,UnbridgedCastsSet & unbridged)988 static bool checkArgPlaceholdersForOverload(Sema &S,
989                                             MultiExprArg Args,
990                                             UnbridgedCastsSet &unbridged) {
991   for (unsigned i = 0, e = Args.size(); i != e; ++i)
992     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
993       return true;
994 
995   return false;
996 }
997 
998 /// Determine whether the given New declaration is an overload of the
999 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1000 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1001 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1002 /// functions (or function templates) at all. When it does return Ovl_Match or
1003 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1004 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1005 /// declaration.
1006 ///
1007 /// Example: Given the following input:
1008 ///
1009 ///   void f(int, float); // #1
1010 ///   void f(int, int); // #2
1011 ///   int f(int, int); // #3
1012 ///
1013 /// When we process #1, there is no previous declaration of "f", so IsOverload
1014 /// will not be used.
1015 ///
1016 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1017 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1018 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1019 /// unchanged.
1020 ///
1021 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1022 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1023 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1024 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1025 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1026 ///
1027 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1028 /// by a using declaration. The rules for whether to hide shadow declarations
1029 /// ignore some properties which otherwise figure into a function template's
1030 /// signature.
1031 Sema::OverloadKind
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)1032 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1033                     NamedDecl *&Match, bool NewIsUsingDecl) {
1034   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1035          I != E; ++I) {
1036     NamedDecl *OldD = *I;
1037 
1038     bool OldIsUsingDecl = false;
1039     if (isa<UsingShadowDecl>(OldD)) {
1040       OldIsUsingDecl = true;
1041 
1042       // We can always introduce two using declarations into the same
1043       // context, even if they have identical signatures.
1044       if (NewIsUsingDecl) continue;
1045 
1046       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1047     }
1048 
1049     // A using-declaration does not conflict with another declaration
1050     // if one of them is hidden.
1051     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1052       continue;
1053 
1054     // If either declaration was introduced by a using declaration,
1055     // we'll need to use slightly different rules for matching.
1056     // Essentially, these rules are the normal rules, except that
1057     // function templates hide function templates with different
1058     // return types or template parameter lists.
1059     bool UseMemberUsingDeclRules =
1060       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1061       !New->getFriendObjectKind();
1062 
1063     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1064       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1065         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1066           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1067           continue;
1068         }
1069 
1070         if (!isa<FunctionTemplateDecl>(OldD) &&
1071             !shouldLinkPossiblyHiddenDecl(*I, New))
1072           continue;
1073 
1074         Match = *I;
1075         return Ovl_Match;
1076       }
1077 
1078       // Builtins that have custom typechecking or have a reference should
1079       // not be overloadable or redeclarable.
1080       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1081         Match = *I;
1082         return Ovl_NonFunction;
1083       }
1084     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1085       // We can overload with these, which can show up when doing
1086       // redeclaration checks for UsingDecls.
1087       assert(Old.getLookupKind() == LookupUsingDeclName);
1088     } else if (isa<TagDecl>(OldD)) {
1089       // We can always overload with tags by hiding them.
1090     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1091       // Optimistically assume that an unresolved using decl will
1092       // overload; if it doesn't, we'll have to diagnose during
1093       // template instantiation.
1094       //
1095       // Exception: if the scope is dependent and this is not a class
1096       // member, the using declaration can only introduce an enumerator.
1097       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1098         Match = *I;
1099         return Ovl_NonFunction;
1100       }
1101     } else {
1102       // (C++ 13p1):
1103       //   Only function declarations can be overloaded; object and type
1104       //   declarations cannot be overloaded.
1105       Match = *I;
1106       return Ovl_NonFunction;
1107     }
1108   }
1109 
1110   // C++ [temp.friend]p1:
1111   //   For a friend function declaration that is not a template declaration:
1112   //    -- if the name of the friend is a qualified or unqualified template-id,
1113   //       [...], otherwise
1114   //    -- if the name of the friend is a qualified-id and a matching
1115   //       non-template function is found in the specified class or namespace,
1116   //       the friend declaration refers to that function, otherwise,
1117   //    -- if the name of the friend is a qualified-id and a matching function
1118   //       template is found in the specified class or namespace, the friend
1119   //       declaration refers to the deduced specialization of that function
1120   //       template, otherwise
1121   //    -- the name shall be an unqualified-id [...]
1122   // If we get here for a qualified friend declaration, we've just reached the
1123   // third bullet. If the type of the friend is dependent, skip this lookup
1124   // until instantiation.
1125   if (New->getFriendObjectKind() && New->getQualifier() &&
1126       !New->getDescribedFunctionTemplate() &&
1127       !New->getDependentSpecializationInfo() &&
1128       !New->getType()->isDependentType()) {
1129     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1130     TemplateSpecResult.addAllDecls(Old);
1131     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1132                                             /*QualifiedFriend*/true)) {
1133       New->setInvalidDecl();
1134       return Ovl_Overload;
1135     }
1136 
1137     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1138     return Ovl_Match;
1139   }
1140 
1141   return Ovl_Overload;
1142 }
1143 
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs,bool ConsiderRequiresClauses)1144 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1145                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1146                       bool ConsiderRequiresClauses) {
1147   // C++ [basic.start.main]p2: This function shall not be overloaded.
1148   if (New->isMain())
1149     return false;
1150 
1151   // MSVCRT user defined entry points cannot be overloaded.
1152   if (New->isMSVCRTEntryPoint())
1153     return false;
1154 
1155   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1156   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1157 
1158   // C++ [temp.fct]p2:
1159   //   A function template can be overloaded with other function templates
1160   //   and with normal (non-template) functions.
1161   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1162     return true;
1163 
1164   // Is the function New an overload of the function Old?
1165   QualType OldQType = Context.getCanonicalType(Old->getType());
1166   QualType NewQType = Context.getCanonicalType(New->getType());
1167 
1168   // Compare the signatures (C++ 1.3.10) of the two functions to
1169   // determine whether they are overloads. If we find any mismatch
1170   // in the signature, they are overloads.
1171 
1172   // If either of these functions is a K&R-style function (no
1173   // prototype), then we consider them to have matching signatures.
1174   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1175       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1176     return false;
1177 
1178   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1179   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1180 
1181   // The signature of a function includes the types of its
1182   // parameters (C++ 1.3.10), which includes the presence or absence
1183   // of the ellipsis; see C++ DR 357).
1184   if (OldQType != NewQType &&
1185       (OldType->getNumParams() != NewType->getNumParams() ||
1186        OldType->isVariadic() != NewType->isVariadic() ||
1187        !FunctionParamTypesAreEqual(OldType, NewType)))
1188     return true;
1189 
1190   // C++ [temp.over.link]p4:
1191   //   The signature of a function template consists of its function
1192   //   signature, its return type and its template parameter list. The names
1193   //   of the template parameters are significant only for establishing the
1194   //   relationship between the template parameters and the rest of the
1195   //   signature.
1196   //
1197   // We check the return type and template parameter lists for function
1198   // templates first; the remaining checks follow.
1199   //
1200   // However, we don't consider either of these when deciding whether
1201   // a member introduced by a shadow declaration is hidden.
1202   if (!UseMemberUsingDeclRules && NewTemplate &&
1203       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1204                                        OldTemplate->getTemplateParameters(),
1205                                        false, TPL_TemplateMatch) ||
1206        !Context.hasSameType(Old->getDeclaredReturnType(),
1207                             New->getDeclaredReturnType())))
1208     return true;
1209 
1210   // If the function is a class member, its signature includes the
1211   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1212   //
1213   // As part of this, also check whether one of the member functions
1214   // is static, in which case they are not overloads (C++
1215   // 13.1p2). While not part of the definition of the signature,
1216   // this check is important to determine whether these functions
1217   // can be overloaded.
1218   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1219   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1220   if (OldMethod && NewMethod &&
1221       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1222     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1223       if (!UseMemberUsingDeclRules &&
1224           (OldMethod->getRefQualifier() == RQ_None ||
1225            NewMethod->getRefQualifier() == RQ_None)) {
1226         // C++0x [over.load]p2:
1227         //   - Member function declarations with the same name and the same
1228         //     parameter-type-list as well as member function template
1229         //     declarations with the same name, the same parameter-type-list, and
1230         //     the same template parameter lists cannot be overloaded if any of
1231         //     them, but not all, have a ref-qualifier (8.3.5).
1232         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1233           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1234         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1235       }
1236       return true;
1237     }
1238 
1239     // We may not have applied the implicit const for a constexpr member
1240     // function yet (because we haven't yet resolved whether this is a static
1241     // or non-static member function). Add it now, on the assumption that this
1242     // is a redeclaration of OldMethod.
1243     auto OldQuals = OldMethod->getMethodQualifiers();
1244     auto NewQuals = NewMethod->getMethodQualifiers();
1245     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1246         !isa<CXXConstructorDecl>(NewMethod))
1247       NewQuals.addConst();
1248     // We do not allow overloading based off of '__restrict'.
1249     OldQuals.removeRestrict();
1250     NewQuals.removeRestrict();
1251     if (OldQuals != NewQuals)
1252       return true;
1253   }
1254 
1255   // Though pass_object_size is placed on parameters and takes an argument, we
1256   // consider it to be a function-level modifier for the sake of function
1257   // identity. Either the function has one or more parameters with
1258   // pass_object_size or it doesn't.
1259   if (functionHasPassObjectSizeParams(New) !=
1260       functionHasPassObjectSizeParams(Old))
1261     return true;
1262 
1263   // enable_if attributes are an order-sensitive part of the signature.
1264   for (specific_attr_iterator<EnableIfAttr>
1265          NewI = New->specific_attr_begin<EnableIfAttr>(),
1266          NewE = New->specific_attr_end<EnableIfAttr>(),
1267          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1268          OldE = Old->specific_attr_end<EnableIfAttr>();
1269        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1270     if (NewI == NewE || OldI == OldE)
1271       return true;
1272     llvm::FoldingSetNodeID NewID, OldID;
1273     NewI->getCond()->Profile(NewID, Context, true);
1274     OldI->getCond()->Profile(OldID, Context, true);
1275     if (NewID != OldID)
1276       return true;
1277   }
1278 
1279   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1280     // Don't allow overloading of destructors.  (In theory we could, but it
1281     // would be a giant change to clang.)
1282     if (!isa<CXXDestructorDecl>(New)) {
1283       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1284                          OldTarget = IdentifyCUDATarget(Old);
1285       if (NewTarget != CFT_InvalidTarget) {
1286         assert((OldTarget != CFT_InvalidTarget) &&
1287                "Unexpected invalid target.");
1288 
1289         // Allow overloading of functions with same signature and different CUDA
1290         // target attributes.
1291         if (NewTarget != OldTarget)
1292           return true;
1293       }
1294     }
1295   }
1296 
1297   if (ConsiderRequiresClauses) {
1298     Expr *NewRC = New->getTrailingRequiresClause(),
1299          *OldRC = Old->getTrailingRequiresClause();
1300     if ((NewRC != nullptr) != (OldRC != nullptr))
1301       // RC are most certainly different - these are overloads.
1302       return true;
1303 
1304     if (NewRC) {
1305       llvm::FoldingSetNodeID NewID, OldID;
1306       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1307       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1308       if (NewID != OldID)
1309         // RCs are not equivalent - these are overloads.
1310         return true;
1311     }
1312   }
1313 
1314   // The signatures match; this is not an overload.
1315   return false;
1316 }
1317 
1318 /// Tries a user-defined conversion from From to ToType.
1319 ///
1320 /// Produces an implicit conversion sequence for when a standard conversion
1321 /// is not an option. See TryImplicitConversion for more information.
1322 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1323 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1324                          bool SuppressUserConversions,
1325                          AllowedExplicit AllowExplicit,
1326                          bool InOverloadResolution,
1327                          bool CStyle,
1328                          bool AllowObjCWritebackConversion,
1329                          bool AllowObjCConversionOnExplicit) {
1330   ImplicitConversionSequence ICS;
1331 
1332   if (SuppressUserConversions) {
1333     // We're not in the case above, so there is no conversion that
1334     // we can perform.
1335     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1336     return ICS;
1337   }
1338 
1339   // Attempt user-defined conversion.
1340   OverloadCandidateSet Conversions(From->getExprLoc(),
1341                                    OverloadCandidateSet::CSK_Normal);
1342   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1343                                   Conversions, AllowExplicit,
1344                                   AllowObjCConversionOnExplicit)) {
1345   case OR_Success:
1346   case OR_Deleted:
1347     ICS.setUserDefined();
1348     // C++ [over.ics.user]p4:
1349     //   A conversion of an expression of class type to the same class
1350     //   type is given Exact Match rank, and a conversion of an
1351     //   expression of class type to a base class of that type is
1352     //   given Conversion rank, in spite of the fact that a copy
1353     //   constructor (i.e., a user-defined conversion function) is
1354     //   called for those cases.
1355     if (CXXConstructorDecl *Constructor
1356           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1357       QualType FromCanon
1358         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1359       QualType ToCanon
1360         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1361       if (Constructor->isCopyConstructor() &&
1362           (FromCanon == ToCanon ||
1363            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1364         // Turn this into a "standard" conversion sequence, so that it
1365         // gets ranked with standard conversion sequences.
1366         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1367         ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
1368         ICS.Standard.setAsIdentityConversion();
1369         ICS.Standard.setFromType(From->getType());
1370         ICS.Standard.setAllToTypes(ToType);
1371         ICS.Standard.CopyConstructor = Constructor;
1372         ICS.Standard.FoundCopyConstructor = Found;
1373         if (ToCanon != FromCanon)
1374           ICS.Standard.Second = ICK_Derived_To_Base;
1375       }
1376     }
1377     break;
1378 
1379   case OR_Ambiguous:
1380     ICS.setAmbiguous();
1381     ICS.Ambiguous.setFromType(From->getType());
1382     ICS.Ambiguous.setToType(ToType);
1383     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1384          Cand != Conversions.end(); ++Cand)
1385       if (Cand->Best)
1386         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1387     break;
1388 
1389     // Fall through.
1390   case OR_No_Viable_Function:
1391     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1392     break;
1393   }
1394 
1395   return ICS;
1396 }
1397 
1398 /// TryImplicitConversion - Attempt to perform an implicit conversion
1399 /// from the given expression (Expr) to the given type (ToType). This
1400 /// function returns an implicit conversion sequence that can be used
1401 /// to perform the initialization. Given
1402 ///
1403 ///   void f(float f);
1404 ///   void g(int i) { f(i); }
1405 ///
1406 /// this routine would produce an implicit conversion sequence to
1407 /// describe the initialization of f from i, which will be a standard
1408 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1409 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1410 //
1411 /// Note that this routine only determines how the conversion can be
1412 /// performed; it does not actually perform the conversion. As such,
1413 /// it will not produce any diagnostics if no conversion is available,
1414 /// but will instead return an implicit conversion sequence of kind
1415 /// "BadConversion".
1416 ///
1417 /// If @p SuppressUserConversions, then user-defined conversions are
1418 /// not permitted.
1419 /// If @p AllowExplicit, then explicit user-defined conversions are
1420 /// permitted.
1421 ///
1422 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1423 /// writeback conversion, which allows __autoreleasing id* parameters to
1424 /// be initialized with __strong id* or __weak id* arguments.
1425 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1426 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1427                       bool SuppressUserConversions,
1428                       AllowedExplicit AllowExplicit,
1429                       bool InOverloadResolution,
1430                       bool CStyle,
1431                       bool AllowObjCWritebackConversion,
1432                       bool AllowObjCConversionOnExplicit) {
1433   ImplicitConversionSequence ICS;
1434   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1435                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1436     ICS.setStandard(ImplicitConversionSequence::KeepState);
1437     return ICS;
1438   }
1439 
1440   if (!S.getLangOpts().CPlusPlus) {
1441     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1442     return ICS;
1443   }
1444 
1445   // C++ [over.ics.user]p4:
1446   //   A conversion of an expression of class type to the same class
1447   //   type is given Exact Match rank, and a conversion of an
1448   //   expression of class type to a base class of that type is
1449   //   given Conversion rank, in spite of the fact that a copy/move
1450   //   constructor (i.e., a user-defined conversion function) is
1451   //   called for those cases.
1452   QualType FromType = From->getType();
1453   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1454       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1455        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1456     ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
1457     ICS.Standard.setAsIdentityConversion();
1458     ICS.Standard.setFromType(FromType);
1459     ICS.Standard.setAllToTypes(ToType);
1460 
1461     // We don't actually check at this point whether there is a valid
1462     // copy/move constructor, since overloading just assumes that it
1463     // exists. When we actually perform initialization, we'll find the
1464     // appropriate constructor to copy the returned object, if needed.
1465     ICS.Standard.CopyConstructor = nullptr;
1466 
1467     // Determine whether this is considered a derived-to-base conversion.
1468     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1469       ICS.Standard.Second = ICK_Derived_To_Base;
1470 
1471     return ICS;
1472   }
1473 
1474   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1475                                   AllowExplicit, InOverloadResolution, CStyle,
1476                                   AllowObjCWritebackConversion,
1477                                   AllowObjCConversionOnExplicit);
1478 }
1479 
1480 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1481 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1482                             bool SuppressUserConversions,
1483                             AllowedExplicit AllowExplicit,
1484                             bool InOverloadResolution,
1485                             bool CStyle,
1486                             bool AllowObjCWritebackConversion) {
1487   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1488                                  AllowExplicit, InOverloadResolution, CStyle,
1489                                  AllowObjCWritebackConversion,
1490                                  /*AllowObjCConversionOnExplicit=*/false);
1491 }
1492 
1493 /// PerformImplicitConversion - Perform an implicit conversion of the
1494 /// expression From to the type ToType. Returns the
1495 /// converted expression. Flavor is the kind of conversion we're
1496 /// performing, used in the error message. If @p AllowExplicit,
1497 /// explicit user-defined conversions are permitted.
1498 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1499 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1500                                 AssignmentAction Action, bool AllowExplicit) {
1501   ImplicitConversionSequence ICS;
1502   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1503 }
1504 
1505 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit,ImplicitConversionSequence & ICS)1506 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1507                                 AssignmentAction Action, bool AllowExplicit,
1508                                 ImplicitConversionSequence& ICS) {
1509   if (checkPlaceholderForOverload(*this, From))
1510     return ExprError();
1511 
1512   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1513   bool AllowObjCWritebackConversion
1514     = getLangOpts().ObjCAutoRefCount &&
1515       (Action == AA_Passing || Action == AA_Sending);
1516   if (getLangOpts().ObjC)
1517     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1518                                       From->getType(), From);
1519   ICS = ::TryImplicitConversion(*this, From, ToType,
1520                                 /*SuppressUserConversions=*/false,
1521                                 AllowExplicit ? AllowedExplicit::All
1522                                               : AllowedExplicit::None,
1523                                 /*InOverloadResolution=*/false,
1524                                 /*CStyle=*/false, AllowObjCWritebackConversion,
1525                                 /*AllowObjCConversionOnExplicit=*/false);
1526   return PerformImplicitConversion(From, ToType, ICS, Action);
1527 }
1528 
1529 /// Determine whether the conversion from FromType to ToType is a valid
1530 /// conversion that strips "noexcept" or "noreturn" off the nested function
1531 /// type.
IsFunctionConversion(QualType FromType,QualType ToType,QualType & ResultTy)1532 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1533                                 QualType &ResultTy) {
1534   if (Context.hasSameUnqualifiedType(FromType, ToType))
1535     return false;
1536 
1537   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1538   //                    or F(t noexcept) -> F(t)
1539   // where F adds one of the following at most once:
1540   //   - a pointer
1541   //   - a member pointer
1542   //   - a block pointer
1543   // Changes here need matching changes in FindCompositePointerType.
1544   CanQualType CanTo = Context.getCanonicalType(ToType);
1545   CanQualType CanFrom = Context.getCanonicalType(FromType);
1546   Type::TypeClass TyClass = CanTo->getTypeClass();
1547   if (TyClass != CanFrom->getTypeClass()) return false;
1548   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1549     if (TyClass == Type::Pointer) {
1550       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1551       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1552     } else if (TyClass == Type::BlockPointer) {
1553       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1554       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1555     } else if (TyClass == Type::MemberPointer) {
1556       auto ToMPT = CanTo.castAs<MemberPointerType>();
1557       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1558       // A function pointer conversion cannot change the class of the function.
1559       if (ToMPT->getClass() != FromMPT->getClass())
1560         return false;
1561       CanTo = ToMPT->getPointeeType();
1562       CanFrom = FromMPT->getPointeeType();
1563     } else {
1564       return false;
1565     }
1566 
1567     TyClass = CanTo->getTypeClass();
1568     if (TyClass != CanFrom->getTypeClass()) return false;
1569     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1570       return false;
1571   }
1572 
1573   const auto *FromFn = cast<FunctionType>(CanFrom);
1574   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1575 
1576   const auto *ToFn = cast<FunctionType>(CanTo);
1577   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1578 
1579   bool Changed = false;
1580 
1581   // Drop 'noreturn' if not present in target type.
1582   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1583     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1584     Changed = true;
1585   }
1586 
1587   // Drop 'noexcept' if not present in target type.
1588   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1589     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1590     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1591       FromFn = cast<FunctionType>(
1592           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1593                                                    EST_None)
1594                  .getTypePtr());
1595       Changed = true;
1596     }
1597 
1598     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1599     // only if the ExtParameterInfo lists of the two function prototypes can be
1600     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1601     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1602     bool CanUseToFPT, CanUseFromFPT;
1603     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1604                                       CanUseFromFPT, NewParamInfos) &&
1605         CanUseToFPT && !CanUseFromFPT) {
1606       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1607       ExtInfo.ExtParameterInfos =
1608           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1609       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1610                                             FromFPT->getParamTypes(), ExtInfo);
1611       FromFn = QT->getAs<FunctionType>();
1612       Changed = true;
1613     }
1614   }
1615 
1616   if (!Changed)
1617     return false;
1618 
1619   assert(QualType(FromFn, 0).isCanonical());
1620   if (QualType(FromFn, 0) != CanTo) return false;
1621 
1622   ResultTy = ToType;
1623   return true;
1624 }
1625 
1626 /// Determine whether the conversion from FromType to ToType is a valid
1627 /// vector conversion.
1628 ///
1629 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1630 /// conversion.
IsVectorConversion(Sema & S,QualType FromType,QualType ToType,ImplicitConversionKind & ICK)1631 static bool IsVectorConversion(Sema &S, QualType FromType,
1632                                QualType ToType, ImplicitConversionKind &ICK) {
1633   // We need at least one of these types to be a vector type to have a vector
1634   // conversion.
1635   if (!ToType->isVectorType() && !FromType->isVectorType())
1636     return false;
1637 
1638   // Identical types require no conversions.
1639   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1640     return false;
1641 
1642   // There are no conversions between extended vector types, only identity.
1643   if (ToType->isExtVectorType()) {
1644     // There are no conversions between extended vector types other than the
1645     // identity conversion.
1646     if (FromType->isExtVectorType())
1647       return false;
1648 
1649     // Vector splat from any arithmetic type to a vector.
1650     if (FromType->isArithmeticType()) {
1651       ICK = ICK_Vector_Splat;
1652       return true;
1653     }
1654   }
1655 
1656   // We can perform the conversion between vector types in the following cases:
1657   // 1)vector types are equivalent AltiVec and GCC vector types
1658   // 2)lax vector conversions are permitted and the vector types are of the
1659   //   same size
1660   // 3)the destination type does not have the ARM MVE strict-polymorphism
1661   //   attribute, which inhibits lax vector conversion for overload resolution
1662   //   only
1663   if (ToType->isVectorType() && FromType->isVectorType()) {
1664     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1665         (S.isLaxVectorConversion(FromType, ToType) &&
1666          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1667       ICK = ICK_Vector_Conversion;
1668       return true;
1669     }
1670   }
1671 
1672   return false;
1673 }
1674 
1675 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1676                                 bool InOverloadResolution,
1677                                 StandardConversionSequence &SCS,
1678                                 bool CStyle);
1679 
1680 /// IsStandardConversion - Determines whether there is a standard
1681 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1682 /// expression From to the type ToType. Standard conversion sequences
1683 /// only consider non-class types; for conversions that involve class
1684 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1685 /// contain the standard conversion sequence required to perform this
1686 /// conversion and this routine will return true. Otherwise, this
1687 /// routine will return false and the value of SCS is unspecified.
IsStandardConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle,bool AllowObjCWritebackConversion)1688 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1689                                  bool InOverloadResolution,
1690                                  StandardConversionSequence &SCS,
1691                                  bool CStyle,
1692                                  bool AllowObjCWritebackConversion) {
1693   QualType FromType = From->getType();
1694 
1695   // Standard conversions (C++ [conv])
1696   SCS.setAsIdentityConversion();
1697   SCS.IncompatibleObjC = false;
1698   SCS.setFromType(FromType);
1699   SCS.CopyConstructor = nullptr;
1700 
1701   // There are no standard conversions for class types in C++, so
1702   // abort early. When overloading in C, however, we do permit them.
1703   if (S.getLangOpts().CPlusPlus &&
1704       (FromType->isRecordType() || ToType->isRecordType()))
1705     return false;
1706 
1707   // The first conversion can be an lvalue-to-rvalue conversion,
1708   // array-to-pointer conversion, or function-to-pointer conversion
1709   // (C++ 4p1).
1710 
1711   if (FromType == S.Context.OverloadTy) {
1712     DeclAccessPair AccessPair;
1713     if (FunctionDecl *Fn
1714           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1715                                                  AccessPair)) {
1716       // We were able to resolve the address of the overloaded function,
1717       // so we can convert to the type of that function.
1718       FromType = Fn->getType();
1719       SCS.setFromType(FromType);
1720 
1721       // we can sometimes resolve &foo<int> regardless of ToType, so check
1722       // if the type matches (identity) or we are converting to bool
1723       if (!S.Context.hasSameUnqualifiedType(
1724                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1725         QualType resultTy;
1726         // if the function type matches except for [[noreturn]], it's ok
1727         if (!S.IsFunctionConversion(FromType,
1728               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1729           // otherwise, only a boolean conversion is standard
1730           if (!ToType->isBooleanType())
1731             return false;
1732       }
1733 
1734       // Check if the "from" expression is taking the address of an overloaded
1735       // function and recompute the FromType accordingly. Take advantage of the
1736       // fact that non-static member functions *must* have such an address-of
1737       // expression.
1738       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1739       if (Method && !Method->isStatic()) {
1740         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1741                "Non-unary operator on non-static member address");
1742         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1743                == UO_AddrOf &&
1744                "Non-address-of operator on non-static member address");
1745         const Type *ClassType
1746           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1747         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1748       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1749         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1750                UO_AddrOf &&
1751                "Non-address-of operator for overloaded function expression");
1752         FromType = S.Context.getPointerType(FromType);
1753       }
1754 
1755       // Check that we've computed the proper type after overload resolution.
1756       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1757       // be calling it from within an NDEBUG block.
1758       assert(S.Context.hasSameType(
1759         FromType,
1760         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1761     } else {
1762       return false;
1763     }
1764   }
1765   // Lvalue-to-rvalue conversion (C++11 4.1):
1766   //   A glvalue (3.10) of a non-function, non-array type T can
1767   //   be converted to a prvalue.
1768   bool argIsLValue = From->isGLValue();
1769   if (argIsLValue &&
1770       !FromType->isFunctionType() && !FromType->isArrayType() &&
1771       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1772     SCS.First = ICK_Lvalue_To_Rvalue;
1773 
1774     // C11 6.3.2.1p2:
1775     //   ... if the lvalue has atomic type, the value has the non-atomic version
1776     //   of the type of the lvalue ...
1777     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1778       FromType = Atomic->getValueType();
1779 
1780     // If T is a non-class type, the type of the rvalue is the
1781     // cv-unqualified version of T. Otherwise, the type of the rvalue
1782     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1783     // just strip the qualifiers because they don't matter.
1784     FromType = FromType.getUnqualifiedType();
1785   } else if (FromType->isArrayType()) {
1786     // Array-to-pointer conversion (C++ 4.2)
1787     SCS.First = ICK_Array_To_Pointer;
1788 
1789     // An lvalue or rvalue of type "array of N T" or "array of unknown
1790     // bound of T" can be converted to an rvalue of type "pointer to
1791     // T" (C++ 4.2p1).
1792     FromType = S.Context.getArrayDecayedType(FromType);
1793 
1794     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1795       // This conversion is deprecated in C++03 (D.4)
1796       SCS.DeprecatedStringLiteralToCharPtr = true;
1797 
1798       // For the purpose of ranking in overload resolution
1799       // (13.3.3.1.1), this conversion is considered an
1800       // array-to-pointer conversion followed by a qualification
1801       // conversion (4.4). (C++ 4.2p2)
1802       SCS.Second = ICK_Identity;
1803       SCS.Third = ICK_Qualification;
1804       SCS.QualificationIncludesObjCLifetime = false;
1805       SCS.setAllToTypes(FromType);
1806       return true;
1807     }
1808   } else if (FromType->isFunctionType() && argIsLValue) {
1809     // Function-to-pointer conversion (C++ 4.3).
1810     SCS.First = ICK_Function_To_Pointer;
1811 
1812     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1813       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1814         if (!S.checkAddressOfFunctionIsAvailable(FD))
1815           return false;
1816 
1817     // An lvalue of function type T can be converted to an rvalue of
1818     // type "pointer to T." The result is a pointer to the
1819     // function. (C++ 4.3p1).
1820     FromType = S.Context.getPointerType(FromType);
1821   } else {
1822     // We don't require any conversions for the first step.
1823     SCS.First = ICK_Identity;
1824   }
1825   SCS.setToType(0, FromType);
1826 
1827   // The second conversion can be an integral promotion, floating
1828   // point promotion, integral conversion, floating point conversion,
1829   // floating-integral conversion, pointer conversion,
1830   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1831   // For overloading in C, this can also be a "compatible-type"
1832   // conversion.
1833   bool IncompatibleObjC = false;
1834   ImplicitConversionKind SecondICK = ICK_Identity;
1835   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1836     // The unqualified versions of the types are the same: there's no
1837     // conversion to do.
1838     SCS.Second = ICK_Identity;
1839   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1840     // Integral promotion (C++ 4.5).
1841     SCS.Second = ICK_Integral_Promotion;
1842     FromType = ToType.getUnqualifiedType();
1843   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1844     // Floating point promotion (C++ 4.6).
1845     SCS.Second = ICK_Floating_Promotion;
1846     FromType = ToType.getUnqualifiedType();
1847   } else if (S.IsComplexPromotion(FromType, ToType)) {
1848     // Complex promotion (Clang extension)
1849     SCS.Second = ICK_Complex_Promotion;
1850     FromType = ToType.getUnqualifiedType();
1851   } else if (ToType->isBooleanType() &&
1852              (FromType->isArithmeticType() ||
1853               FromType->isAnyPointerType() ||
1854               FromType->isBlockPointerType() ||
1855               FromType->isMemberPointerType())) {
1856     // Boolean conversions (C++ 4.12).
1857     SCS.Second = ICK_Boolean_Conversion;
1858     FromType = S.Context.BoolTy;
1859   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1860              ToType->isIntegralType(S.Context)) {
1861     // Integral conversions (C++ 4.7).
1862     SCS.Second = ICK_Integral_Conversion;
1863     FromType = ToType.getUnqualifiedType();
1864   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1865     // Complex conversions (C99 6.3.1.6)
1866     SCS.Second = ICK_Complex_Conversion;
1867     FromType = ToType.getUnqualifiedType();
1868   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1869              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1870     // Complex-real conversions (C99 6.3.1.7)
1871     SCS.Second = ICK_Complex_Real;
1872     FromType = ToType.getUnqualifiedType();
1873   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1874     // FIXME: disable conversions between long double and __float128 if
1875     // their representation is different until there is back end support
1876     // We of course allow this conversion if long double is really double.
1877 
1878     // Conversions between bfloat and other floats are not permitted.
1879     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1880       return false;
1881     if (&S.Context.getFloatTypeSemantics(FromType) !=
1882         &S.Context.getFloatTypeSemantics(ToType)) {
1883       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1884                                     ToType == S.Context.LongDoubleTy) ||
1885                                    (FromType == S.Context.LongDoubleTy &&
1886                                     ToType == S.Context.Float128Ty));
1887       if (Float128AndLongDouble &&
1888           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1889            &llvm::APFloat::PPCDoubleDouble()))
1890         return false;
1891     }
1892     // Floating point conversions (C++ 4.8).
1893     SCS.Second = ICK_Floating_Conversion;
1894     FromType = ToType.getUnqualifiedType();
1895   } else if ((FromType->isRealFloatingType() &&
1896               ToType->isIntegralType(S.Context)) ||
1897              (FromType->isIntegralOrUnscopedEnumerationType() &&
1898               ToType->isRealFloatingType())) {
1899     // Conversions between bfloat and int are not permitted.
1900     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1901       return false;
1902 
1903     // Floating-integral conversions (C++ 4.9).
1904     SCS.Second = ICK_Floating_Integral;
1905     FromType = ToType.getUnqualifiedType();
1906   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1907     SCS.Second = ICK_Block_Pointer_Conversion;
1908   } else if (AllowObjCWritebackConversion &&
1909              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1910     SCS.Second = ICK_Writeback_Conversion;
1911   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1912                                    FromType, IncompatibleObjC)) {
1913     // Pointer conversions (C++ 4.10).
1914     SCS.Second = ICK_Pointer_Conversion;
1915     SCS.IncompatibleObjC = IncompatibleObjC;
1916     FromType = FromType.getUnqualifiedType();
1917   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1918                                          InOverloadResolution, FromType)) {
1919     // Pointer to member conversions (4.11).
1920     SCS.Second = ICK_Pointer_Member;
1921   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1922     SCS.Second = SecondICK;
1923     FromType = ToType.getUnqualifiedType();
1924   } else if (!S.getLangOpts().CPlusPlus &&
1925              S.Context.typesAreCompatible(ToType, FromType)) {
1926     // Compatible conversions (Clang extension for C function overloading)
1927     SCS.Second = ICK_Compatible_Conversion;
1928     FromType = ToType.getUnqualifiedType();
1929   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1930                                              InOverloadResolution,
1931                                              SCS, CStyle)) {
1932     SCS.Second = ICK_TransparentUnionConversion;
1933     FromType = ToType;
1934   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1935                                  CStyle)) {
1936     // tryAtomicConversion has updated the standard conversion sequence
1937     // appropriately.
1938     return true;
1939   } else if (ToType->isEventT() &&
1940              From->isIntegerConstantExpr(S.getASTContext()) &&
1941              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1942     SCS.Second = ICK_Zero_Event_Conversion;
1943     FromType = ToType;
1944   } else if (ToType->isQueueT() &&
1945              From->isIntegerConstantExpr(S.getASTContext()) &&
1946              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1947     SCS.Second = ICK_Zero_Queue_Conversion;
1948     FromType = ToType;
1949   } else if (ToType->isSamplerT() &&
1950              From->isIntegerConstantExpr(S.getASTContext())) {
1951     SCS.Second = ICK_Compatible_Conversion;
1952     FromType = ToType;
1953   } else {
1954     // No second conversion required.
1955     SCS.Second = ICK_Identity;
1956   }
1957   SCS.setToType(1, FromType);
1958 
1959   // The third conversion can be a function pointer conversion or a
1960   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1961   bool ObjCLifetimeConversion;
1962   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1963     // Function pointer conversions (removing 'noexcept') including removal of
1964     // 'noreturn' (Clang extension).
1965     SCS.Third = ICK_Function_Conversion;
1966   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1967                                          ObjCLifetimeConversion)) {
1968     SCS.Third = ICK_Qualification;
1969     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1970     FromType = ToType;
1971   } else {
1972     // No conversion required
1973     SCS.Third = ICK_Identity;
1974   }
1975 
1976   // C++ [over.best.ics]p6:
1977   //   [...] Any difference in top-level cv-qualification is
1978   //   subsumed by the initialization itself and does not constitute
1979   //   a conversion. [...]
1980   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1981   QualType CanonTo = S.Context.getCanonicalType(ToType);
1982   if (CanonFrom.getLocalUnqualifiedType()
1983                                      == CanonTo.getLocalUnqualifiedType() &&
1984       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1985     FromType = ToType;
1986     CanonFrom = CanonTo;
1987   }
1988 
1989   SCS.setToType(2, FromType);
1990 
1991   if (CanonFrom == CanonTo)
1992     return true;
1993 
1994   // If we have not converted the argument type to the parameter type,
1995   // this is a bad conversion sequence, unless we're resolving an overload in C.
1996   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1997     return false;
1998 
1999   ExprResult ER = ExprResult{From};
2000   Sema::AssignConvertType Conv =
2001       S.CheckSingleAssignmentConstraints(ToType, ER,
2002                                          /*Diagnose=*/false,
2003                                          /*DiagnoseCFAudited=*/false,
2004                                          /*ConvertRHS=*/false);
2005   ImplicitConversionKind SecondConv;
2006   switch (Conv) {
2007   case Sema::Compatible:
2008     SecondConv = ICK_C_Only_Conversion;
2009     break;
2010   // For our purposes, discarding qualifiers is just as bad as using an
2011   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2012   // qualifiers, as well.
2013   case Sema::CompatiblePointerDiscardsQualifiers:
2014   case Sema::IncompatiblePointer:
2015   case Sema::IncompatiblePointerSign:
2016     SecondConv = ICK_Incompatible_Pointer_Conversion;
2017     break;
2018   default:
2019     return false;
2020   }
2021 
2022   // First can only be an lvalue conversion, so we pretend that this was the
2023   // second conversion. First should already be valid from earlier in the
2024   // function.
2025   SCS.Second = SecondConv;
2026   SCS.setToType(1, ToType);
2027 
2028   // Third is Identity, because Second should rank us worse than any other
2029   // conversion. This could also be ICK_Qualification, but it's simpler to just
2030   // lump everything in with the second conversion, and we don't gain anything
2031   // from making this ICK_Qualification.
2032   SCS.Third = ICK_Identity;
2033   SCS.setToType(2, ToType);
2034   return true;
2035 }
2036 
2037 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)2038 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2039                                      QualType &ToType,
2040                                      bool InOverloadResolution,
2041                                      StandardConversionSequence &SCS,
2042                                      bool CStyle) {
2043 
2044   const RecordType *UT = ToType->getAsUnionType();
2045   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2046     return false;
2047   // The field to initialize within the transparent union.
2048   RecordDecl *UD = UT->getDecl();
2049   // It's compatible if the expression matches any of the fields.
2050   for (const auto *it : UD->fields()) {
2051     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2052                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2053       ToType = it->getType();
2054       return true;
2055     }
2056   }
2057   return false;
2058 }
2059 
2060 /// IsIntegralPromotion - Determines whether the conversion from the
2061 /// expression From (whose potentially-adjusted type is FromType) to
2062 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2063 /// sets PromotedType to the promoted type.
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)2064 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2065   const BuiltinType *To = ToType->getAs<BuiltinType>();
2066   // All integers are built-in.
2067   if (!To) {
2068     return false;
2069   }
2070 
2071   // An rvalue of type char, signed char, unsigned char, short int, or
2072   // unsigned short int can be converted to an rvalue of type int if
2073   // int can represent all the values of the source type; otherwise,
2074   // the source rvalue can be converted to an rvalue of type unsigned
2075   // int (C++ 4.5p1).
2076   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2077       !FromType->isEnumeralType()) {
2078     if (// We can promote any signed, promotable integer type to an int
2079         (FromType->isSignedIntegerType() ||
2080          // We can promote any unsigned integer type whose size is
2081          // less than int to an int.
2082          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2083       return To->getKind() == BuiltinType::Int;
2084     }
2085 
2086     return To->getKind() == BuiltinType::UInt;
2087   }
2088 
2089   // C++11 [conv.prom]p3:
2090   //   A prvalue of an unscoped enumeration type whose underlying type is not
2091   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2092   //   following types that can represent all the values of the enumeration
2093   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2094   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2095   //   long long int. If none of the types in that list can represent all the
2096   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2097   //   type can be converted to an rvalue a prvalue of the extended integer type
2098   //   with lowest integer conversion rank (4.13) greater than the rank of long
2099   //   long in which all the values of the enumeration can be represented. If
2100   //   there are two such extended types, the signed one is chosen.
2101   // C++11 [conv.prom]p4:
2102   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2103   //   can be converted to a prvalue of its underlying type. Moreover, if
2104   //   integral promotion can be applied to its underlying type, a prvalue of an
2105   //   unscoped enumeration type whose underlying type is fixed can also be
2106   //   converted to a prvalue of the promoted underlying type.
2107   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2108     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2109     // provided for a scoped enumeration.
2110     if (FromEnumType->getDecl()->isScoped())
2111       return false;
2112 
2113     // We can perform an integral promotion to the underlying type of the enum,
2114     // even if that's not the promoted type. Note that the check for promoting
2115     // the underlying type is based on the type alone, and does not consider
2116     // the bitfield-ness of the actual source expression.
2117     if (FromEnumType->getDecl()->isFixed()) {
2118       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2119       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2120              IsIntegralPromotion(nullptr, Underlying, ToType);
2121     }
2122 
2123     // We have already pre-calculated the promotion type, so this is trivial.
2124     if (ToType->isIntegerType() &&
2125         isCompleteType(From->getBeginLoc(), FromType))
2126       return Context.hasSameUnqualifiedType(
2127           ToType, FromEnumType->getDecl()->getPromotionType());
2128 
2129     // C++ [conv.prom]p5:
2130     //   If the bit-field has an enumerated type, it is treated as any other
2131     //   value of that type for promotion purposes.
2132     //
2133     // ... so do not fall through into the bit-field checks below in C++.
2134     if (getLangOpts().CPlusPlus)
2135       return false;
2136   }
2137 
2138   // C++0x [conv.prom]p2:
2139   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2140   //   to an rvalue a prvalue of the first of the following types that can
2141   //   represent all the values of its underlying type: int, unsigned int,
2142   //   long int, unsigned long int, long long int, or unsigned long long int.
2143   //   If none of the types in that list can represent all the values of its
2144   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2145   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2146   //   type.
2147   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2148       ToType->isIntegerType()) {
2149     // Determine whether the type we're converting from is signed or
2150     // unsigned.
2151     bool FromIsSigned = FromType->isSignedIntegerType();
2152     uint64_t FromSize = Context.getTypeSize(FromType);
2153 
2154     // The types we'll try to promote to, in the appropriate
2155     // order. Try each of these types.
2156     QualType PromoteTypes[6] = {
2157       Context.IntTy, Context.UnsignedIntTy,
2158       Context.LongTy, Context.UnsignedLongTy ,
2159       Context.LongLongTy, Context.UnsignedLongLongTy
2160     };
2161     for (int Idx = 0; Idx < 6; ++Idx) {
2162       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2163       if (FromSize < ToSize ||
2164           (FromSize == ToSize &&
2165            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2166         // We found the type that we can promote to. If this is the
2167         // type we wanted, we have a promotion. Otherwise, no
2168         // promotion.
2169         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2170       }
2171     }
2172   }
2173 
2174   // An rvalue for an integral bit-field (9.6) can be converted to an
2175   // rvalue of type int if int can represent all the values of the
2176   // bit-field; otherwise, it can be converted to unsigned int if
2177   // unsigned int can represent all the values of the bit-field. If
2178   // the bit-field is larger yet, no integral promotion applies to
2179   // it. If the bit-field has an enumerated type, it is treated as any
2180   // other value of that type for promotion purposes (C++ 4.5p3).
2181   // FIXME: We should delay checking of bit-fields until we actually perform the
2182   // conversion.
2183   //
2184   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2185   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2186   // bit-fields and those whose underlying type is larger than int) for GCC
2187   // compatibility.
2188   if (From) {
2189     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2190       llvm::APSInt BitWidth;
2191       if (FromType->isIntegralType(Context) &&
2192           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2193         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2194         ToSize = Context.getTypeSize(ToType);
2195 
2196         // Are we promoting to an int from a bitfield that fits in an int?
2197         if (BitWidth < ToSize ||
2198             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2199           return To->getKind() == BuiltinType::Int;
2200         }
2201 
2202         // Are we promoting to an unsigned int from an unsigned bitfield
2203         // that fits into an unsigned int?
2204         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2205           return To->getKind() == BuiltinType::UInt;
2206         }
2207 
2208         return false;
2209       }
2210     }
2211   }
2212 
2213   // An rvalue of type bool can be converted to an rvalue of type int,
2214   // with false becoming zero and true becoming one (C++ 4.5p4).
2215   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2216     return true;
2217   }
2218 
2219   return false;
2220 }
2221 
2222 /// IsFloatingPointPromotion - Determines whether the conversion from
2223 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2224 /// returns true and sets PromotedType to the promoted type.
IsFloatingPointPromotion(QualType FromType,QualType ToType)2225 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2226   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2227     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2228       /// An rvalue of type float can be converted to an rvalue of type
2229       /// double. (C++ 4.6p1).
2230       if (FromBuiltin->getKind() == BuiltinType::Float &&
2231           ToBuiltin->getKind() == BuiltinType::Double)
2232         return true;
2233 
2234       // C99 6.3.1.5p1:
2235       //   When a float is promoted to double or long double, or a
2236       //   double is promoted to long double [...].
2237       if (!getLangOpts().CPlusPlus &&
2238           (FromBuiltin->getKind() == BuiltinType::Float ||
2239            FromBuiltin->getKind() == BuiltinType::Double) &&
2240           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2241            ToBuiltin->getKind() == BuiltinType::Float128))
2242         return true;
2243 
2244       // Half can be promoted to float.
2245       if (!getLangOpts().NativeHalfType &&
2246            FromBuiltin->getKind() == BuiltinType::Half &&
2247           ToBuiltin->getKind() == BuiltinType::Float)
2248         return true;
2249     }
2250 
2251   return false;
2252 }
2253 
2254 /// Determine if a conversion is a complex promotion.
2255 ///
2256 /// A complex promotion is defined as a complex -> complex conversion
2257 /// where the conversion between the underlying real types is a
2258 /// floating-point or integral promotion.
IsComplexPromotion(QualType FromType,QualType ToType)2259 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2260   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2261   if (!FromComplex)
2262     return false;
2263 
2264   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2265   if (!ToComplex)
2266     return false;
2267 
2268   return IsFloatingPointPromotion(FromComplex->getElementType(),
2269                                   ToComplex->getElementType()) ||
2270     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2271                         ToComplex->getElementType());
2272 }
2273 
2274 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2275 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2276 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2277 /// if non-empty, will be a pointer to ToType that may or may not have
2278 /// the right set of qualifiers on its pointee.
2279 ///
2280 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)2281 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2282                                    QualType ToPointee, QualType ToType,
2283                                    ASTContext &Context,
2284                                    bool StripObjCLifetime = false) {
2285   assert((FromPtr->getTypeClass() == Type::Pointer ||
2286           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2287          "Invalid similarly-qualified pointer type");
2288 
2289   /// Conversions to 'id' subsume cv-qualifier conversions.
2290   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2291     return ToType.getUnqualifiedType();
2292 
2293   const bool FromIsCap = FromPtr->isCHERICapabilityType(Context);
2294   PointerInterpretationKind PIK = FromIsCap ? PIK_Capability : PIK_Integer;
2295   QualType CanonFromPointee
2296     = Context.getCanonicalType(FromPtr->getPointeeType());
2297   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2298   Qualifiers Quals = CanonFromPointee.getQualifiers();
2299 
2300   if (StripObjCLifetime)
2301     Quals.removeObjCLifetime();
2302 
2303   // Exact qualifier match -> return the pointer type we're converting to.
2304   if (CanonToPointee.getLocalQualifiers() == Quals) {
2305     // ToType is exactly what we need. Return it.
2306     // XXXAR: but only if the memory capability qualifier matches
2307     if (ToType->isCHERICapabilityType(Context) == FromIsCap && !ToType.isNull())
2308       return ToType.getUnqualifiedType();
2309 
2310     // Build a pointer to ToPointee. It has the right qualifiers
2311     // already.
2312     if (isa<ObjCObjectPointerType>(ToType))
2313       return Context.getObjCObjectPointerType(ToPointee);
2314     return Context.getPointerType(ToPointee, PIK);
2315   }
2316 
2317   // Just build a canonical type that has the right qualifiers.
2318   QualType QualifiedCanonToPointee
2319     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2320 
2321   if (isa<ObjCObjectPointerType>(ToType))
2322     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2323   return Context.getPointerType(QualifiedCanonToPointee, PIK);
2324 }
2325 
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)2326 static bool isNullPointerConstantForConversion(Expr *Expr,
2327                                                bool InOverloadResolution,
2328                                                ASTContext &Context) {
2329   // Handle value-dependent integral null pointer constants correctly.
2330   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2331   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2332       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2333     return !InOverloadResolution;
2334 
2335   return Expr->isNullPointerConstant(Context,
2336                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2337                                         : Expr::NPC_ValueDependentIsNull);
2338 }
2339 
2340 /// IsPointerConversion - Determines whether the conversion of the
2341 /// expression From, which has the (possibly adjusted) type FromType,
2342 /// can be converted to the type ToType via a pointer conversion (C++
2343 /// 4.10). If so, returns true and places the converted type (that
2344 /// might differ from ToType in its cv-qualifiers at some level) into
2345 /// ConvertedType.
2346 ///
2347 /// This routine also supports conversions to and from block pointers
2348 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2349 /// pointers to interfaces. FIXME: Once we've determined the
2350 /// appropriate overloading rules for Objective-C, we may want to
2351 /// split the Objective-C checks into a different routine; however,
2352 /// GCC seems to consider all of these conversions to be pointer
2353 /// conversions, so for now they live here. IncompatibleObjC will be
2354 /// set if the conversion is an allowed Objective-C conversion that
2355 /// should result in a warning.
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)2356 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2357                                bool InOverloadResolution,
2358                                QualType& ConvertedType,
2359                                bool &IncompatibleObjC) {
2360   IncompatibleObjC = false;
2361   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2362                               IncompatibleObjC))
2363     return true;
2364 
2365   // Conversion from a null pointer constant to any Objective-C pointer type.
2366   if (ToType->isObjCObjectPointerType() &&
2367       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2368     ConvertedType = ToType;
2369     return true;
2370   }
2371 
2372   // Blocks: Block pointers can be converted to void*.
2373   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2374       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2375     ConvertedType = ToType;
2376     return true;
2377   }
2378   // Blocks: A null pointer constant can be converted to a block
2379   // pointer type.
2380   if (ToType->isBlockPointerType() &&
2381       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2382     ConvertedType = ToType;
2383     return true;
2384   }
2385 
2386   // If the left-hand-side is nullptr_t, the right side can be a null
2387   // pointer constant.
2388   if (ToType->isNullPtrType() &&
2389       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2390     ConvertedType = ToType;
2391     return true;
2392   }
2393 
2394   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2395   if (!ToTypePtr)
2396     return false;
2397 
2398   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2399   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2400     ConvertedType = ToType;
2401     return true;
2402   }
2403 
2404   // Beyond this point, both types need to be pointers
2405   // , including objective-c pointers.
2406   QualType ToPointeeType = ToTypePtr->getPointeeType();
2407   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2408       !getLangOpts().ObjCAutoRefCount) {
2409     ConvertedType = BuildSimilarlyQualifiedPointerType(
2410                                       FromType->getAs<ObjCObjectPointerType>(),
2411                                                        ToPointeeType,
2412                                                        ToType, Context);
2413     return true;
2414   }
2415   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2416   if (!FromTypePtr)
2417     return false;
2418 
2419   QualType FromPointeeType = FromTypePtr->getPointeeType();
2420 
2421   // If the unqualified pointee types are the same, this can't be a
2422   // pointer conversion, so don't do all of the work below.
2423   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2424     return false;
2425 
2426   // An rvalue of type "pointer to cv T," where T is an object type,
2427   // can be converted to an rvalue of type "pointer to cv void" (C++
2428   // 4.10p2).
2429   if (FromPointeeType->isIncompleteOrObjectType() &&
2430       ToPointeeType->isVoidType()) {
2431     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2432                                                        ToPointeeType,
2433                                                        ToType, Context,
2434                                                    /*StripObjCLifetime=*/true);
2435     assert(FromType->isCHERICapabilityType(Context) ==
2436            ConvertedType->isCHERICapabilityType(Context) &&
2437            "Converted type should retain capability/pointer");
2438     return true;
2439   }
2440 
2441   // MSVC allows implicit function to void* type conversion.
2442   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2443       ToPointeeType->isVoidType()) {
2444     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2445                                                        ToPointeeType,
2446                                                        ToType, Context);
2447     return true;
2448   }
2449 
2450   // When we're overloading in C, we allow a special kind of pointer
2451   // conversion for compatible-but-not-identical pointee types.
2452   if (!getLangOpts().CPlusPlus &&
2453       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2454     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2455                                                        ToPointeeType,
2456                                                        ToType, Context);
2457     return true;
2458   }
2459 
2460   // C++ [conv.ptr]p3:
2461   //
2462   //   An rvalue of type "pointer to cv D," where D is a class type,
2463   //   can be converted to an rvalue of type "pointer to cv B," where
2464   //   B is a base class (clause 10) of D. If B is an inaccessible
2465   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2466   //   necessitates this conversion is ill-formed. The result of the
2467   //   conversion is a pointer to the base class sub-object of the
2468   //   derived class object. The null pointer value is converted to
2469   //   the null pointer value of the destination type.
2470   //
2471   // Note that we do not check for ambiguity or inaccessibility
2472   // here. That is handled by CheckPointerConversion.
2473   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2474       ToPointeeType->isRecordType() &&
2475       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2476       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2477     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478                                                        ToPointeeType,
2479                                                        ToType, Context);
2480     return true;
2481   }
2482 
2483   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2484       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2485     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2486                                                        ToPointeeType,
2487                                                        ToType, Context);
2488     return true;
2489   }
2490 
2491   return false;
2492 }
2493 
2494 /// Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)2495 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2496   Qualifiers TQs = T.getQualifiers();
2497 
2498   // Check whether qualifiers already match.
2499   if (TQs == Qs)
2500     return T;
2501 
2502   if (Qs.compatiblyIncludes(TQs))
2503     return Context.getQualifiedType(T, Qs);
2504 
2505   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2506 }
2507 
2508 /// isObjCPointerConversion - Determines whether this is an
2509 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2510 /// with the same arguments and return values.
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)2511 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2512                                    QualType& ConvertedType,
2513                                    bool &IncompatibleObjC) {
2514   if (!getLangOpts().ObjC)
2515     return false;
2516 
2517   // The set of qualifiers on the type we're converting from.
2518   Qualifiers FromQualifiers = FromType.getQualifiers();
2519 
2520   // First, we handle all conversions on ObjC object pointer types.
2521   const ObjCObjectPointerType* ToObjCPtr =
2522     ToType->getAs<ObjCObjectPointerType>();
2523   const ObjCObjectPointerType *FromObjCPtr =
2524     FromType->getAs<ObjCObjectPointerType>();
2525 
2526   if (ToObjCPtr && FromObjCPtr) {
2527     // If the pointee types are the same (ignoring qualifications),
2528     // then this is not a pointer conversion.
2529     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2530                                        FromObjCPtr->getPointeeType()))
2531       return false;
2532 
2533     // Conversion between Objective-C pointers.
2534     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2535       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2536       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2537       if (getLangOpts().CPlusPlus && LHS && RHS &&
2538           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2539                                                 FromObjCPtr->getPointeeType()))
2540         return false;
2541       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2542                                                    ToObjCPtr->getPointeeType(),
2543                                                          ToType, Context);
2544       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2545       return true;
2546     }
2547 
2548     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2549       // Okay: this is some kind of implicit downcast of Objective-C
2550       // interfaces, which is permitted. However, we're going to
2551       // complain about it.
2552       IncompatibleObjC = true;
2553       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2554                                                    ToObjCPtr->getPointeeType(),
2555                                                          ToType, Context);
2556       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2557       return true;
2558     }
2559   }
2560   // Beyond this point, both types need to be C pointers or block pointers.
2561   QualType ToPointeeType;
2562   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2563     ToPointeeType = ToCPtr->getPointeeType();
2564   else if (const BlockPointerType *ToBlockPtr =
2565             ToType->getAs<BlockPointerType>()) {
2566     // Objective C++: We're able to convert from a pointer to any object
2567     // to a block pointer type.
2568     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2569       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2570       return true;
2571     }
2572     ToPointeeType = ToBlockPtr->getPointeeType();
2573   }
2574   else if (FromType->getAs<BlockPointerType>() &&
2575            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2576     // Objective C++: We're able to convert from a block pointer type to a
2577     // pointer to any object.
2578     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2579     return true;
2580   }
2581   else
2582     return false;
2583 
2584   QualType FromPointeeType;
2585   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2586     FromPointeeType = FromCPtr->getPointeeType();
2587   else if (const BlockPointerType *FromBlockPtr =
2588            FromType->getAs<BlockPointerType>())
2589     FromPointeeType = FromBlockPtr->getPointeeType();
2590   else
2591     return false;
2592 
2593   // If we have pointers to pointers, recursively check whether this
2594   // is an Objective-C conversion.
2595   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2596       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2597                               IncompatibleObjC)) {
2598     // We always complain about this conversion.
2599     IncompatibleObjC = true;
2600     ConvertedType = Context.getPointerType(ConvertedType);
2601     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2602     return true;
2603   }
2604   // Allow conversion of pointee being objective-c pointer to another one;
2605   // as in I* to id.
2606   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2607       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2608       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2609                               IncompatibleObjC)) {
2610 
2611     ConvertedType = Context.getPointerType(ConvertedType);
2612     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2613     return true;
2614   }
2615 
2616   // If we have pointers to functions or blocks, check whether the only
2617   // differences in the argument and result types are in Objective-C
2618   // pointer conversions. If so, we permit the conversion (but
2619   // complain about it).
2620   const FunctionProtoType *FromFunctionType
2621     = FromPointeeType->getAs<FunctionProtoType>();
2622   const FunctionProtoType *ToFunctionType
2623     = ToPointeeType->getAs<FunctionProtoType>();
2624   if (FromFunctionType && ToFunctionType) {
2625     // If the function types are exactly the same, this isn't an
2626     // Objective-C pointer conversion.
2627     if (Context.getCanonicalType(FromPointeeType)
2628           == Context.getCanonicalType(ToPointeeType))
2629       return false;
2630 
2631     // Perform the quick checks that will tell us whether these
2632     // function types are obviously different.
2633     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2634         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2635         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2636       return false;
2637 
2638     bool HasObjCConversion = false;
2639     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2640         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2641       // Okay, the types match exactly. Nothing to do.
2642     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2643                                        ToFunctionType->getReturnType(),
2644                                        ConvertedType, IncompatibleObjC)) {
2645       // Okay, we have an Objective-C pointer conversion.
2646       HasObjCConversion = true;
2647     } else {
2648       // Function types are too different. Abort.
2649       return false;
2650     }
2651 
2652     // Check argument types.
2653     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2654          ArgIdx != NumArgs; ++ArgIdx) {
2655       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2656       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2657       if (Context.getCanonicalType(FromArgType)
2658             == Context.getCanonicalType(ToArgType)) {
2659         // Okay, the types match exactly. Nothing to do.
2660       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2661                                          ConvertedType, IncompatibleObjC)) {
2662         // Okay, we have an Objective-C pointer conversion.
2663         HasObjCConversion = true;
2664       } else {
2665         // Argument types are too different. Abort.
2666         return false;
2667       }
2668     }
2669 
2670     if (HasObjCConversion) {
2671       // We had an Objective-C conversion. Allow this pointer
2672       // conversion, but complain about it.
2673       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2674       IncompatibleObjC = true;
2675       return true;
2676     }
2677   }
2678 
2679   return false;
2680 }
2681 
2682 /// Determine whether this is an Objective-C writeback conversion,
2683 /// used for parameter passing when performing automatic reference counting.
2684 ///
2685 /// \param FromType The type we're converting form.
2686 ///
2687 /// \param ToType The type we're converting to.
2688 ///
2689 /// \param ConvertedType The type that will be produced after applying
2690 /// this conversion.
isObjCWritebackConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2691 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2692                                      QualType &ConvertedType) {
2693   if (!getLangOpts().ObjCAutoRefCount ||
2694       Context.hasSameUnqualifiedType(FromType, ToType))
2695     return false;
2696 
2697   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2698   QualType ToPointee;
2699   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2700     ToPointee = ToPointer->getPointeeType();
2701   else
2702     return false;
2703 
2704   Qualifiers ToQuals = ToPointee.getQualifiers();
2705   if (!ToPointee->isObjCLifetimeType() ||
2706       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2707       !ToQuals.withoutObjCLifetime().empty())
2708     return false;
2709 
2710   // Argument must be a pointer to __strong to __weak.
2711   QualType FromPointee;
2712   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2713     FromPointee = FromPointer->getPointeeType();
2714   else
2715     return false;
2716 
2717   Qualifiers FromQuals = FromPointee.getQualifiers();
2718   if (!FromPointee->isObjCLifetimeType() ||
2719       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2720        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2721     return false;
2722 
2723   // Make sure that we have compatible qualifiers.
2724   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2725   if (!ToQuals.compatiblyIncludes(FromQuals))
2726     return false;
2727 
2728   // Remove qualifiers from the pointee type we're converting from; they
2729   // aren't used in the compatibility check belong, and we'll be adding back
2730   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2731   FromPointee = FromPointee.getUnqualifiedType();
2732 
2733   // The unqualified form of the pointee types must be compatible.
2734   ToPointee = ToPointee.getUnqualifiedType();
2735   bool IncompatibleObjC;
2736   if (Context.typesAreCompatible(FromPointee, ToPointee))
2737     FromPointee = ToPointee;
2738   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2739                                     IncompatibleObjC))
2740     return false;
2741 
2742   /// Construct the type we're converting to, which is a pointer to
2743   /// __autoreleasing pointee.
2744   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2745   ConvertedType = Context.getPointerType(FromPointee);
2746   return true;
2747 }
2748 
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2749 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2750                                     QualType& ConvertedType) {
2751   QualType ToPointeeType;
2752   if (const BlockPointerType *ToBlockPtr =
2753         ToType->getAs<BlockPointerType>())
2754     ToPointeeType = ToBlockPtr->getPointeeType();
2755   else
2756     return false;
2757 
2758   QualType FromPointeeType;
2759   if (const BlockPointerType *FromBlockPtr =
2760       FromType->getAs<BlockPointerType>())
2761     FromPointeeType = FromBlockPtr->getPointeeType();
2762   else
2763     return false;
2764   // We have pointer to blocks, check whether the only
2765   // differences in the argument and result types are in Objective-C
2766   // pointer conversions. If so, we permit the conversion.
2767 
2768   const FunctionProtoType *FromFunctionType
2769     = FromPointeeType->getAs<FunctionProtoType>();
2770   const FunctionProtoType *ToFunctionType
2771     = ToPointeeType->getAs<FunctionProtoType>();
2772 
2773   if (!FromFunctionType || !ToFunctionType)
2774     return false;
2775 
2776   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2777     return true;
2778 
2779   // Perform the quick checks that will tell us whether these
2780   // function types are obviously different.
2781   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2782       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2783     return false;
2784 
2785   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2786   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2787   if (FromEInfo != ToEInfo)
2788     return false;
2789 
2790   bool IncompatibleObjC = false;
2791   if (Context.hasSameType(FromFunctionType->getReturnType(),
2792                           ToFunctionType->getReturnType())) {
2793     // Okay, the types match exactly. Nothing to do.
2794   } else {
2795     QualType RHS = FromFunctionType->getReturnType();
2796     QualType LHS = ToFunctionType->getReturnType();
2797     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2798         !RHS.hasQualifiers() && LHS.hasQualifiers())
2799        LHS = LHS.getUnqualifiedType();
2800 
2801      if (Context.hasSameType(RHS,LHS)) {
2802        // OK exact match.
2803      } else if (isObjCPointerConversion(RHS, LHS,
2804                                         ConvertedType, IncompatibleObjC)) {
2805      if (IncompatibleObjC)
2806        return false;
2807      // Okay, we have an Objective-C pointer conversion.
2808      }
2809      else
2810        return false;
2811    }
2812 
2813    // Check argument types.
2814    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2815         ArgIdx != NumArgs; ++ArgIdx) {
2816      IncompatibleObjC = false;
2817      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2818      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2819      if (Context.hasSameType(FromArgType, ToArgType)) {
2820        // Okay, the types match exactly. Nothing to do.
2821      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2822                                         ConvertedType, IncompatibleObjC)) {
2823        if (IncompatibleObjC)
2824          return false;
2825        // Okay, we have an Objective-C pointer conversion.
2826      } else
2827        // Argument types are too different. Abort.
2828        return false;
2829    }
2830 
2831    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2832    bool CanUseToFPT, CanUseFromFPT;
2833    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2834                                       CanUseToFPT, CanUseFromFPT,
2835                                       NewParamInfos))
2836      return false;
2837 
2838    ConvertedType = ToType;
2839    return true;
2840 }
2841 
2842 enum {
2843   ft_default,
2844   ft_different_class,
2845   ft_parameter_arity,
2846   ft_parameter_mismatch,
2847   ft_return_type,
2848   ft_qualifer_mismatch,
2849   ft_noexcept
2850 };
2851 
2852 /// Attempts to get the FunctionProtoType from a Type. Handles
2853 /// MemberFunctionPointers properly.
tryGetFunctionProtoType(QualType FromType)2854 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2855   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2856     return FPT;
2857 
2858   if (auto *MPT = FromType->getAs<MemberPointerType>())
2859     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2860 
2861   return nullptr;
2862 }
2863 
2864 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2865 /// function types.  Catches different number of parameter, mismatch in
2866 /// parameter types, and different return types.
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)2867 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2868                                       QualType FromType, QualType ToType) {
2869   // If either type is not valid, include no extra info.
2870   if (FromType.isNull() || ToType.isNull()) {
2871     PDiag << ft_default;
2872     return;
2873   }
2874 
2875   // Get the function type from the pointers.
2876   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2877     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2878                *ToMember = ToType->castAs<MemberPointerType>();
2879     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2880       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2881             << QualType(FromMember->getClass(), 0);
2882       return;
2883     }
2884     FromType = FromMember->getPointeeType();
2885     ToType = ToMember->getPointeeType();
2886   }
2887 
2888   if (FromType->isPointerType())
2889     FromType = FromType->getPointeeType();
2890   if (ToType->isPointerType())
2891     ToType = ToType->getPointeeType();
2892 
2893   // Remove references.
2894   FromType = FromType.getNonReferenceType();
2895   ToType = ToType.getNonReferenceType();
2896 
2897   // Don't print extra info for non-specialized template functions.
2898   if (FromType->isInstantiationDependentType() &&
2899       !FromType->getAs<TemplateSpecializationType>()) {
2900     PDiag << ft_default;
2901     return;
2902   }
2903 
2904   // No extra info for same types.
2905   if (Context.hasSameType(FromType, ToType)) {
2906     PDiag << ft_default;
2907     return;
2908   }
2909 
2910   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2911                           *ToFunction = tryGetFunctionProtoType(ToType);
2912 
2913   // Both types need to be function types.
2914   if (!FromFunction || !ToFunction) {
2915     PDiag << ft_default;
2916     return;
2917   }
2918 
2919   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2920     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2921           << FromFunction->getNumParams();
2922     return;
2923   }
2924 
2925   // Handle different parameter types.
2926   unsigned ArgPos;
2927   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2928     PDiag << ft_parameter_mismatch << ArgPos + 1
2929           << ToFunction->getParamType(ArgPos)
2930           << FromFunction->getParamType(ArgPos);
2931     return;
2932   }
2933 
2934   // Handle different return type.
2935   if (!Context.hasSameType(FromFunction->getReturnType(),
2936                            ToFunction->getReturnType())) {
2937     PDiag << ft_return_type << ToFunction->getReturnType()
2938           << FromFunction->getReturnType();
2939     return;
2940   }
2941 
2942   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2943     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2944           << FromFunction->getMethodQuals();
2945     return;
2946   }
2947 
2948   // Handle exception specification differences on canonical type (in C++17
2949   // onwards).
2950   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2951           ->isNothrow() !=
2952       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2953           ->isNothrow()) {
2954     PDiag << ft_noexcept;
2955     return;
2956   }
2957 
2958   // Unable to find a difference, so add no extra info.
2959   PDiag << ft_default;
2960 }
2961 
2962 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2963 /// for equality of their argument types. Caller has already checked that
2964 /// they have same number of arguments.  If the parameters are different,
2965 /// ArgPos will have the parameter index of the first different parameter.
FunctionParamTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos)2966 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2967                                       const FunctionProtoType *NewType,
2968                                       unsigned *ArgPos) {
2969   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2970                                               N = NewType->param_type_begin(),
2971                                               E = OldType->param_type_end();
2972        O && (O != E); ++O, ++N) {
2973     // Ignore address spaces in pointee type. This is to disallow overloading
2974     // on __ptr32/__ptr64 address spaces.
2975     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2976     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2977 
2978     if (!Context.hasSameType(Old, New)) {
2979       if (ArgPos)
2980         *ArgPos = O - OldType->param_type_begin();
2981       return false;
2982     }
2983   }
2984   return true;
2985 }
2986 
2987 /// CheckPointerConversion - Check the pointer conversion from the
2988 /// expression From to the type ToType. This routine checks for
2989 /// ambiguous or inaccessible derived-to-base pointer
2990 /// conversions for which IsPointerConversion has already returned
2991 /// true. It returns true and produces a diagnostic if there was an
2992 /// error, or returns false otherwise.
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess,bool Diagnose)2993 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2994                                   CastKind &Kind,
2995                                   CXXCastPath& BasePath,
2996                                   bool IgnoreBaseAccess,
2997                                   bool Diagnose) {
2998   QualType FromType = From->getType();
2999   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3000 
3001   Kind = CK_BitCast;
3002 
3003   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3004       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3005           Expr::NPCK_ZeroExpression) {
3006     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3007       DiagRuntimeBehavior(From->getExprLoc(), From,
3008                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3009                             << ToType << From->getSourceRange());
3010     else if (!isUnevaluatedContext())
3011       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3012         << ToType << From->getSourceRange();
3013   }
3014   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3015     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3016       QualType FromPointeeType = FromPtrType->getPointeeType(),
3017                ToPointeeType   = ToPtrType->getPointeeType();
3018 
3019       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3020           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3021         // We must have a derived-to-base conversion. Check an
3022         // ambiguous or inaccessible conversion.
3023         unsigned InaccessibleID = 0;
3024         unsigned AmbiguousID = 0;
3025         if (Diagnose) {
3026           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3027           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3028         }
3029         if (CheckDerivedToBaseConversion(
3030                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3031                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3032                 &BasePath, IgnoreBaseAccess))
3033           return true;
3034 
3035         // The conversion was successful.
3036         Kind = CK_DerivedToBase;
3037       }
3038 
3039       if (Diagnose && !IsCStyleOrFunctionalCast &&
3040           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3041         assert(getLangOpts().MSVCCompat &&
3042                "this should only be possible with MSVCCompat!");
3043         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3044             << From->getSourceRange();
3045       }
3046     }
3047   } else if (const ObjCObjectPointerType *ToPtrType =
3048                ToType->getAs<ObjCObjectPointerType>()) {
3049     if (const ObjCObjectPointerType *FromPtrType =
3050           FromType->getAs<ObjCObjectPointerType>()) {
3051       // Objective-C++ conversions are always okay.
3052       // FIXME: We should have a different class of conversions for the
3053       // Objective-C++ implicit conversions.
3054       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3055         return false;
3056     } else if (FromType->isBlockPointerType()) {
3057       Kind = CK_BlockPointerToObjCPointerCast;
3058     } else {
3059       Kind = CK_CPointerToObjCPointerCast;
3060     }
3061   } else if (ToType->isBlockPointerType()) {
3062     if (!FromType->isBlockPointerType())
3063       Kind = CK_AnyPointerToBlockPointerCast;
3064   }
3065 
3066   // We shouldn't fall into this case unless it's valid for other
3067   // reasons.
3068   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3069     Kind = CK_NullToPointer;
3070 
3071   return false;
3072 }
3073 
3074 /// IsMemberPointerConversion - Determines whether the conversion of the
3075 /// expression From, which has the (possibly adjusted) type FromType, can be
3076 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3077 /// If so, returns true and places the converted type (that might differ from
3078 /// ToType in its cv-qualifiers at some level) into ConvertedType.
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)3079 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3080                                      QualType ToType,
3081                                      bool InOverloadResolution,
3082                                      QualType &ConvertedType) {
3083   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3084   if (!ToTypePtr)
3085     return false;
3086 
3087   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3088   if (From->isNullPointerConstant(Context,
3089                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3090                                         : Expr::NPC_ValueDependentIsNull)) {
3091     ConvertedType = ToType;
3092     return true;
3093   }
3094 
3095   // Otherwise, both types have to be member pointers.
3096   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3097   if (!FromTypePtr)
3098     return false;
3099 
3100   // A pointer to member of B can be converted to a pointer to member of D,
3101   // where D is derived from B (C++ 4.11p2).
3102   QualType FromClass(FromTypePtr->getClass(), 0);
3103   QualType ToClass(ToTypePtr->getClass(), 0);
3104 
3105   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3106       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3107     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3108                                                  ToClass.getTypePtr());
3109     return true;
3110   }
3111 
3112   return false;
3113 }
3114 
3115 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3116 /// expression From to the type ToType. This routine checks for ambiguous or
3117 /// virtual or inaccessible base-to-derived member pointer conversions
3118 /// for which IsMemberPointerConversion has already returned true. It returns
3119 /// true and produces a diagnostic if there was an error, or returns false
3120 /// otherwise.
CheckMemberPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)3121 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3122                                         CastKind &Kind,
3123                                         CXXCastPath &BasePath,
3124                                         bool IgnoreBaseAccess) {
3125   QualType FromType = From->getType();
3126   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3127   if (!FromPtrType) {
3128     // This must be a null pointer to member pointer conversion
3129     assert(From->isNullPointerConstant(Context,
3130                                        Expr::NPC_ValueDependentIsNull) &&
3131            "Expr must be null pointer constant!");
3132     Kind = CK_NullToMemberPointer;
3133     return false;
3134   }
3135 
3136   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3137   assert(ToPtrType && "No member pointer cast has a target type "
3138                       "that is not a member pointer.");
3139 
3140   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3141   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3142 
3143   // FIXME: What about dependent types?
3144   assert(FromClass->isRecordType() && "Pointer into non-class.");
3145   assert(ToClass->isRecordType() && "Pointer into non-class.");
3146 
3147   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3148                      /*DetectVirtual=*/true);
3149   bool DerivationOkay =
3150       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3151   assert(DerivationOkay &&
3152          "Should not have been called if derivation isn't OK.");
3153   (void)DerivationOkay;
3154 
3155   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3156                                   getUnqualifiedType())) {
3157     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3158     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3159       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3160     return true;
3161   }
3162 
3163   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3164     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3165       << FromClass << ToClass << QualType(VBase, 0)
3166       << From->getSourceRange();
3167     return true;
3168   }
3169 
3170   if (!IgnoreBaseAccess)
3171     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3172                          Paths.front(),
3173                          diag::err_downcast_from_inaccessible_base);
3174 
3175   // Must be a base to derived member conversion.
3176   BuildBasePathArray(Paths, BasePath);
3177   Kind = CK_BaseToDerivedMemberPointer;
3178   return false;
3179 }
3180 
3181 /// Determine whether the lifetime conversion between the two given
3182 /// qualifiers sets is nontrivial.
isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,Qualifiers ToQuals)3183 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3184                                                Qualifiers ToQuals) {
3185   // Converting anything to const __unsafe_unretained is trivial.
3186   if (ToQuals.hasConst() &&
3187       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3188     return false;
3189 
3190   return true;
3191 }
3192 
3193 /// Perform a single iteration of the loop for checking if a qualification
3194 /// conversion is valid.
3195 ///
3196 /// Specifically, check whether any change between the qualifiers of \p
3197 /// FromType and \p ToType is permissible, given knowledge about whether every
3198 /// outer layer is const-qualified.
isQualificationConversionStep(QualType FromType,QualType ToType,bool CStyle,bool IsTopLevel,bool & PreviousToQualsIncludeConst,bool & ObjCLifetimeConversion)3199 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3200                                           bool CStyle, bool IsTopLevel,
3201                                           bool &PreviousToQualsIncludeConst,
3202                                           bool &ObjCLifetimeConversion) {
3203   Qualifiers FromQuals = FromType.getQualifiers();
3204   Qualifiers ToQuals = ToType.getQualifiers();
3205 
3206   // Ignore __unaligned qualifier if this type is void.
3207   if (ToType.getUnqualifiedType()->isVoidType())
3208     FromQuals.removeUnaligned();
3209 
3210   // Objective-C ARC:
3211   //   Check Objective-C lifetime conversions.
3212   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3213     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3214       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3215         ObjCLifetimeConversion = true;
3216       FromQuals.removeObjCLifetime();
3217       ToQuals.removeObjCLifetime();
3218     } else {
3219       // Qualification conversions cannot cast between different
3220       // Objective-C lifetime qualifiers.
3221       return false;
3222     }
3223   }
3224 
3225   // Allow addition/removal of GC attributes but not changing GC attributes.
3226   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3227       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3228     FromQuals.removeObjCGCAttr();
3229     ToQuals.removeObjCGCAttr();
3230   }
3231 
3232   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3233   //      2,j, and similarly for volatile.
3234   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3235     return false;
3236 
3237   // If address spaces mismatch:
3238   //  - in top level it is only valid to convert to addr space that is a
3239   //    superset in all cases apart from C-style casts where we allow
3240   //    conversions between overlapping address spaces.
3241   //  - in non-top levels it is not a valid conversion.
3242   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3243       (!IsTopLevel ||
3244        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3245          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3246     return false;
3247 
3248   //   -- if the cv 1,j and cv 2,j are different, then const is in
3249   //      every cv for 0 < k < j.
3250   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3251       !PreviousToQualsIncludeConst)
3252     return false;
3253 
3254   // Keep track of whether all prior cv-qualifiers in the "to" type
3255   // include const.
3256   PreviousToQualsIncludeConst =
3257       PreviousToQualsIncludeConst && ToQuals.hasConst();
3258   return true;
3259 }
3260 
3261 /// IsQualificationConversion - Determines whether the conversion from
3262 /// an rvalue of type FromType to ToType is a qualification conversion
3263 /// (C++ 4.4).
3264 ///
3265 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3266 /// when the qualification conversion involves a change in the Objective-C
3267 /// object lifetime.
3268 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)3269 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3270                                 bool CStyle, bool &ObjCLifetimeConversion) {
3271   FromType = Context.getCanonicalType(FromType);
3272   ToType = Context.getCanonicalType(ToType);
3273   ObjCLifetimeConversion = false;
3274 
3275   // If FromType and ToType are the same type, this is not a
3276   // qualification conversion.
3277   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3278     return false;
3279 
3280   // (C++ 4.4p4):
3281   //   A conversion can add cv-qualifiers at levels other than the first
3282   //   in multi-level pointers, subject to the following rules: [...]
3283   bool PreviousToQualsIncludeConst = true;
3284   bool UnwrappedAnyPointer = false;
3285   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3286     if (!isQualificationConversionStep(
3287             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3288             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3289       return false;
3290     UnwrappedAnyPointer = true;
3291   }
3292 
3293   // We are left with FromType and ToType being the pointee types
3294   // after unwrapping the original FromType and ToType the same number
3295   // of times. If we unwrapped any pointers, and if FromType and
3296   // ToType have the same unqualified type (since we checked
3297   // qualifiers above), then this is a qualification conversion.
3298   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3299 }
3300 
3301 /// - Determine whether this is a conversion from a scalar type to an
3302 /// atomic type.
3303 ///
3304 /// If successful, updates \c SCS's second and third steps in the conversion
3305 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)3306 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3307                                 bool InOverloadResolution,
3308                                 StandardConversionSequence &SCS,
3309                                 bool CStyle) {
3310   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3311   if (!ToAtomic)
3312     return false;
3313 
3314   StandardConversionSequence InnerSCS;
3315   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3316                             InOverloadResolution, InnerSCS,
3317                             CStyle, /*AllowObjCWritebackConversion=*/false))
3318     return false;
3319 
3320   SCS.Second = InnerSCS.Second;
3321   SCS.setToType(1, InnerSCS.getToType(1));
3322   SCS.Third = InnerSCS.Third;
3323   SCS.QualificationIncludesObjCLifetime
3324     = InnerSCS.QualificationIncludesObjCLifetime;
3325   SCS.setToType(2, InnerSCS.getToType(2));
3326   return true;
3327 }
3328 
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)3329 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3330                                               CXXConstructorDecl *Constructor,
3331                                               QualType Type) {
3332   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3333   if (CtorType->getNumParams() > 0) {
3334     QualType FirstArg = CtorType->getParamType(0);
3335     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3336       return true;
3337   }
3338   return false;
3339 }
3340 
3341 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)3342 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3343                                        CXXRecordDecl *To,
3344                                        UserDefinedConversionSequence &User,
3345                                        OverloadCandidateSet &CandidateSet,
3346                                        bool AllowExplicit) {
3347   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3348   for (auto *D : S.LookupConstructors(To)) {
3349     auto Info = getConstructorInfo(D);
3350     if (!Info)
3351       continue;
3352 
3353     bool Usable = !Info.Constructor->isInvalidDecl() &&
3354                   S.isInitListConstructor(Info.Constructor);
3355     if (Usable) {
3356       // If the first argument is (a reference to) the target type,
3357       // suppress conversions.
3358       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3359           S.Context, Info.Constructor, ToType);
3360       if (Info.ConstructorTmpl)
3361         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3362                                        /*ExplicitArgs*/ nullptr, From,
3363                                        CandidateSet, SuppressUserConversions,
3364                                        /*PartialOverloading*/ false,
3365                                        AllowExplicit);
3366       else
3367         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3368                                CandidateSet, SuppressUserConversions,
3369                                /*PartialOverloading*/ false, AllowExplicit);
3370     }
3371   }
3372 
3373   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3374 
3375   OverloadCandidateSet::iterator Best;
3376   switch (auto Result =
3377               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3378   case OR_Deleted:
3379   case OR_Success: {
3380     // Record the standard conversion we used and the conversion function.
3381     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3382     QualType ThisType = Constructor->getThisType();
3383     // Initializer lists don't have conversions as such.
3384     User.Before.setAsIdentityConversion();
3385     User.HadMultipleCandidates = HadMultipleCandidates;
3386     User.ConversionFunction = Constructor;
3387     User.FoundConversionFunction = Best->FoundDecl;
3388     User.After.setAsIdentityConversion();
3389     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3390     User.After.setAllToTypes(ToType);
3391     return Result;
3392   }
3393 
3394   case OR_No_Viable_Function:
3395     return OR_No_Viable_Function;
3396   case OR_Ambiguous:
3397     return OR_Ambiguous;
3398   }
3399 
3400   llvm_unreachable("Invalid OverloadResult!");
3401 }
3402 
3403 /// Determines whether there is a user-defined conversion sequence
3404 /// (C++ [over.ics.user]) that converts expression From to the type
3405 /// ToType. If such a conversion exists, User will contain the
3406 /// user-defined conversion sequence that performs such a conversion
3407 /// and this routine will return true. Otherwise, this routine returns
3408 /// false and User is unspecified.
3409 ///
3410 /// \param AllowExplicit  true if the conversion should consider C++0x
3411 /// "explicit" conversion functions as well as non-explicit conversion
3412 /// functions (C++0x [class.conv.fct]p2).
3413 ///
3414 /// \param AllowObjCConversionOnExplicit true if the conversion should
3415 /// allow an extra Objective-C pointer conversion on uses of explicit
3416 /// constructors. Requires \c AllowExplicit to also be set.
3417 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,AllowedExplicit AllowExplicit,bool AllowObjCConversionOnExplicit)3418 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3419                         UserDefinedConversionSequence &User,
3420                         OverloadCandidateSet &CandidateSet,
3421                         AllowedExplicit AllowExplicit,
3422                         bool AllowObjCConversionOnExplicit) {
3423   assert(AllowExplicit != AllowedExplicit::None ||
3424          !AllowObjCConversionOnExplicit);
3425   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3426 
3427   // Whether we will only visit constructors.
3428   bool ConstructorsOnly = false;
3429 
3430   // If the type we are conversion to is a class type, enumerate its
3431   // constructors.
3432   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3433     // C++ [over.match.ctor]p1:
3434     //   When objects of class type are direct-initialized (8.5), or
3435     //   copy-initialized from an expression of the same or a
3436     //   derived class type (8.5), overload resolution selects the
3437     //   constructor. [...] For copy-initialization, the candidate
3438     //   functions are all the converting constructors (12.3.1) of
3439     //   that class. The argument list is the expression-list within
3440     //   the parentheses of the initializer.
3441     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3442         (From->getType()->getAs<RecordType>() &&
3443          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3444       ConstructorsOnly = true;
3445 
3446     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3447       // We're not going to find any constructors.
3448     } else if (CXXRecordDecl *ToRecordDecl
3449                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3450 
3451       Expr **Args = &From;
3452       unsigned NumArgs = 1;
3453       bool ListInitializing = false;
3454       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3455         // But first, see if there is an init-list-constructor that will work.
3456         OverloadingResult Result = IsInitializerListConstructorConversion(
3457             S, From, ToType, ToRecordDecl, User, CandidateSet,
3458             AllowExplicit == AllowedExplicit::All);
3459         if (Result != OR_No_Viable_Function)
3460           return Result;
3461         // Never mind.
3462         CandidateSet.clear(
3463             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3464 
3465         // If we're list-initializing, we pass the individual elements as
3466         // arguments, not the entire list.
3467         Args = InitList->getInits();
3468         NumArgs = InitList->getNumInits();
3469         ListInitializing = true;
3470       }
3471 
3472       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3473         auto Info = getConstructorInfo(D);
3474         if (!Info)
3475           continue;
3476 
3477         bool Usable = !Info.Constructor->isInvalidDecl();
3478         if (!ListInitializing)
3479           Usable = Usable && Info.Constructor->isConvertingConstructor(
3480                                  /*AllowExplicit*/ true);
3481         if (Usable) {
3482           bool SuppressUserConversions = !ConstructorsOnly;
3483           if (SuppressUserConversions && ListInitializing) {
3484             SuppressUserConversions = false;
3485             if (NumArgs == 1) {
3486               // If the first argument is (a reference to) the target type,
3487               // suppress conversions.
3488               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3489                   S.Context, Info.Constructor, ToType);
3490             }
3491           }
3492           if (Info.ConstructorTmpl)
3493             S.AddTemplateOverloadCandidate(
3494                 Info.ConstructorTmpl, Info.FoundDecl,
3495                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3496                 CandidateSet, SuppressUserConversions,
3497                 /*PartialOverloading*/ false,
3498                 AllowExplicit == AllowedExplicit::All);
3499           else
3500             // Allow one user-defined conversion when user specifies a
3501             // From->ToType conversion via an static cast (c-style, etc).
3502             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3503                                    llvm::makeArrayRef(Args, NumArgs),
3504                                    CandidateSet, SuppressUserConversions,
3505                                    /*PartialOverloading*/ false,
3506                                    AllowExplicit == AllowedExplicit::All);
3507         }
3508       }
3509     }
3510   }
3511 
3512   // Enumerate conversion functions, if we're allowed to.
3513   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3514   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3515     // No conversion functions from incomplete types.
3516   } else if (const RecordType *FromRecordType =
3517                  From->getType()->getAs<RecordType>()) {
3518     if (CXXRecordDecl *FromRecordDecl
3519          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3520       // Add all of the conversion functions as candidates.
3521       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3522       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3523         DeclAccessPair FoundDecl = I.getPair();
3524         NamedDecl *D = FoundDecl.getDecl();
3525         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3526         if (isa<UsingShadowDecl>(D))
3527           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3528 
3529         CXXConversionDecl *Conv;
3530         FunctionTemplateDecl *ConvTemplate;
3531         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3532           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3533         else
3534           Conv = cast<CXXConversionDecl>(D);
3535 
3536         if (ConvTemplate)
3537           S.AddTemplateConversionCandidate(
3538               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3539               CandidateSet, AllowObjCConversionOnExplicit,
3540               AllowExplicit != AllowedExplicit::None);
3541         else
3542           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3543                                    CandidateSet, AllowObjCConversionOnExplicit,
3544                                    AllowExplicit != AllowedExplicit::None);
3545       }
3546     }
3547   }
3548 
3549   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3550 
3551   OverloadCandidateSet::iterator Best;
3552   switch (auto Result =
3553               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3554   case OR_Success:
3555   case OR_Deleted:
3556     // Record the standard conversion we used and the conversion function.
3557     if (CXXConstructorDecl *Constructor
3558           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3559       // C++ [over.ics.user]p1:
3560       //   If the user-defined conversion is specified by a
3561       //   constructor (12.3.1), the initial standard conversion
3562       //   sequence converts the source type to the type required by
3563       //   the argument of the constructor.
3564       //
3565       QualType ThisType = Constructor->getThisType();
3566       if (isa<InitListExpr>(From)) {
3567         // Initializer lists don't have conversions as such.
3568         User.Before.setAsIdentityConversion();
3569       } else {
3570         if (Best->Conversions[0].isEllipsis())
3571           User.EllipsisConversion = true;
3572         else {
3573           User.Before = Best->Conversions[0].Standard;
3574           User.EllipsisConversion = false;
3575         }
3576       }
3577       User.HadMultipleCandidates = HadMultipleCandidates;
3578       User.ConversionFunction = Constructor;
3579       User.FoundConversionFunction = Best->FoundDecl;
3580       User.After.setAsIdentityConversion();
3581       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3582       User.After.setAllToTypes(ToType);
3583       return Result;
3584     }
3585     if (CXXConversionDecl *Conversion
3586                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3587       // C++ [over.ics.user]p1:
3588       //
3589       //   [...] If the user-defined conversion is specified by a
3590       //   conversion function (12.3.2), the initial standard
3591       //   conversion sequence converts the source type to the
3592       //   implicit object parameter of the conversion function.
3593       User.Before = Best->Conversions[0].Standard;
3594       User.HadMultipleCandidates = HadMultipleCandidates;
3595       User.ConversionFunction = Conversion;
3596       User.FoundConversionFunction = Best->FoundDecl;
3597       User.EllipsisConversion = false;
3598 
3599       // C++ [over.ics.user]p2:
3600       //   The second standard conversion sequence converts the
3601       //   result of the user-defined conversion to the target type
3602       //   for the sequence. Since an implicit conversion sequence
3603       //   is an initialization, the special rules for
3604       //   initialization by user-defined conversion apply when
3605       //   selecting the best user-defined conversion for a
3606       //   user-defined conversion sequence (see 13.3.3 and
3607       //   13.3.3.1).
3608       User.After = Best->FinalConversion;
3609       return Result;
3610     }
3611     llvm_unreachable("Not a constructor or conversion function?");
3612 
3613   case OR_No_Viable_Function:
3614     return OR_No_Viable_Function;
3615 
3616   case OR_Ambiguous:
3617     return OR_Ambiguous;
3618   }
3619 
3620   llvm_unreachable("Invalid OverloadResult!");
3621 }
3622 
3623 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)3624 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3625   ImplicitConversionSequence ICS;
3626   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3627                                     OverloadCandidateSet::CSK_Normal);
3628   OverloadingResult OvResult =
3629     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3630                             CandidateSet, AllowedExplicit::None, false);
3631 
3632   if (!(OvResult == OR_Ambiguous ||
3633         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3634     return false;
3635 
3636   auto Cands = CandidateSet.CompleteCandidates(
3637       *this,
3638       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3639       From);
3640   if (OvResult == OR_Ambiguous)
3641     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3642         << From->getType() << ToType << From->getSourceRange();
3643   else { // OR_No_Viable_Function && !CandidateSet.empty()
3644     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3645                              diag::err_typecheck_nonviable_condition_incomplete,
3646                              From->getType(), From->getSourceRange()))
3647       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3648           << false << From->getType() << From->getSourceRange() << ToType;
3649   }
3650 
3651   CandidateSet.NoteCandidates(
3652                               *this, From, Cands);
3653   return true;
3654 }
3655 
3656 /// Compare the user-defined conversion functions or constructors
3657 /// of two user-defined conversion sequences to determine whether any ordering
3658 /// is possible.
3659 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)3660 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3661                            FunctionDecl *Function2) {
3662   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3663     return ImplicitConversionSequence::Indistinguishable;
3664 
3665   // Objective-C++:
3666   //   If both conversion functions are implicitly-declared conversions from
3667   //   a lambda closure type to a function pointer and a block pointer,
3668   //   respectively, always prefer the conversion to a function pointer,
3669   //   because the function pointer is more lightweight and is more likely
3670   //   to keep code working.
3671   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3672   if (!Conv1)
3673     return ImplicitConversionSequence::Indistinguishable;
3674 
3675   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3676   if (!Conv2)
3677     return ImplicitConversionSequence::Indistinguishable;
3678 
3679   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3680     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3681     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3682     if (Block1 != Block2)
3683       return Block1 ? ImplicitConversionSequence::Worse
3684                     : ImplicitConversionSequence::Better;
3685   }
3686 
3687   return ImplicitConversionSequence::Indistinguishable;
3688 }
3689 
hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence & ICS)3690 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3691     const ImplicitConversionSequence &ICS) {
3692   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3693          (ICS.isUserDefined() &&
3694           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3695 }
3696 
3697 /// CompareImplicitConversionSequences - Compare two implicit
3698 /// conversion sequences to determine whether one is better than the
3699 /// other or if they are indistinguishable (C++ 13.3.3.2).
3700 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,SourceLocation Loc,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)3701 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3702                                    const ImplicitConversionSequence& ICS1,
3703                                    const ImplicitConversionSequence& ICS2)
3704 {
3705   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3706   // conversion sequences (as defined in 13.3.3.1)
3707   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3708   //      conversion sequence than a user-defined conversion sequence or
3709   //      an ellipsis conversion sequence, and
3710   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3711   //      conversion sequence than an ellipsis conversion sequence
3712   //      (13.3.3.1.3).
3713   //
3714   // C++0x [over.best.ics]p10:
3715   //   For the purpose of ranking implicit conversion sequences as
3716   //   described in 13.3.3.2, the ambiguous conversion sequence is
3717   //   treated as a user-defined sequence that is indistinguishable
3718   //   from any other user-defined conversion sequence.
3719 
3720   // String literal to 'char *' conversion has been deprecated in C++03. It has
3721   // been removed from C++11. We still accept this conversion, if it happens at
3722   // the best viable function. Otherwise, this conversion is considered worse
3723   // than ellipsis conversion. Consider this as an extension; this is not in the
3724   // standard. For example:
3725   //
3726   // int &f(...);    // #1
3727   // void f(char*);  // #2
3728   // void g() { int &r = f("foo"); }
3729   //
3730   // In C++03, we pick #2 as the best viable function.
3731   // In C++11, we pick #1 as the best viable function, because ellipsis
3732   // conversion is better than string-literal to char* conversion (since there
3733   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3734   // convert arguments, #2 would be the best viable function in C++11.
3735   // If the best viable function has this conversion, a warning will be issued
3736   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3737 
3738   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3739       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3740       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3741     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3742                ? ImplicitConversionSequence::Worse
3743                : ImplicitConversionSequence::Better;
3744 
3745   if (ICS1.getKindRank() < ICS2.getKindRank())
3746     return ImplicitConversionSequence::Better;
3747   if (ICS2.getKindRank() < ICS1.getKindRank())
3748     return ImplicitConversionSequence::Worse;
3749 
3750   // The following checks require both conversion sequences to be of
3751   // the same kind.
3752   if (ICS1.getKind() != ICS2.getKind())
3753     return ImplicitConversionSequence::Indistinguishable;
3754 
3755   ImplicitConversionSequence::CompareKind Result =
3756       ImplicitConversionSequence::Indistinguishable;
3757 
3758   // Two implicit conversion sequences of the same form are
3759   // indistinguishable conversion sequences unless one of the
3760   // following rules apply: (C++ 13.3.3.2p3):
3761 
3762   // List-initialization sequence L1 is a better conversion sequence than
3763   // list-initialization sequence L2 if:
3764   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3765   //   if not that,
3766   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3767   //   and N1 is smaller than N2.,
3768   // even if one of the other rules in this paragraph would otherwise apply.
3769   if (!ICS1.isBad()) {
3770     if (ICS1.isStdInitializerListElement() &&
3771         !ICS2.isStdInitializerListElement())
3772       return ImplicitConversionSequence::Better;
3773     if (!ICS1.isStdInitializerListElement() &&
3774         ICS2.isStdInitializerListElement())
3775       return ImplicitConversionSequence::Worse;
3776   }
3777 
3778   if (ICS1.isStandard())
3779     // Standard conversion sequence S1 is a better conversion sequence than
3780     // standard conversion sequence S2 if [...]
3781     Result = CompareStandardConversionSequences(S, Loc,
3782                                                 ICS1.Standard, ICS2.Standard);
3783   else if (ICS1.isUserDefined()) {
3784     // User-defined conversion sequence U1 is a better conversion
3785     // sequence than another user-defined conversion sequence U2 if
3786     // they contain the same user-defined conversion function or
3787     // constructor and if the second standard conversion sequence of
3788     // U1 is better than the second standard conversion sequence of
3789     // U2 (C++ 13.3.3.2p3).
3790     if (ICS1.UserDefined.ConversionFunction ==
3791           ICS2.UserDefined.ConversionFunction)
3792       Result = CompareStandardConversionSequences(S, Loc,
3793                                                   ICS1.UserDefined.After,
3794                                                   ICS2.UserDefined.After);
3795     else
3796       Result = compareConversionFunctions(S,
3797                                           ICS1.UserDefined.ConversionFunction,
3798                                           ICS2.UserDefined.ConversionFunction);
3799   }
3800 
3801   return Result;
3802 }
3803 
3804 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3805 // determine if one is a proper subset of the other.
3806 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3807 compareStandardConversionSubsets(ASTContext &Context,
3808                                  const StandardConversionSequence& SCS1,
3809                                  const StandardConversionSequence& SCS2) {
3810   ImplicitConversionSequence::CompareKind Result
3811     = ImplicitConversionSequence::Indistinguishable;
3812 
3813   // the identity conversion sequence is considered to be a subsequence of
3814   // any non-identity conversion sequence
3815   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3816     return ImplicitConversionSequence::Better;
3817   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3818     return ImplicitConversionSequence::Worse;
3819 
3820   if (SCS1.Second != SCS2.Second) {
3821     if (SCS1.Second == ICK_Identity)
3822       Result = ImplicitConversionSequence::Better;
3823     else if (SCS2.Second == ICK_Identity)
3824       Result = ImplicitConversionSequence::Worse;
3825     else
3826       return ImplicitConversionSequence::Indistinguishable;
3827   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3828     return ImplicitConversionSequence::Indistinguishable;
3829 
3830   if (SCS1.Third == SCS2.Third) {
3831     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3832                              : ImplicitConversionSequence::Indistinguishable;
3833   }
3834 
3835   if (SCS1.Third == ICK_Identity)
3836     return Result == ImplicitConversionSequence::Worse
3837              ? ImplicitConversionSequence::Indistinguishable
3838              : ImplicitConversionSequence::Better;
3839 
3840   if (SCS2.Third == ICK_Identity)
3841     return Result == ImplicitConversionSequence::Better
3842              ? ImplicitConversionSequence::Indistinguishable
3843              : ImplicitConversionSequence::Worse;
3844 
3845   return ImplicitConversionSequence::Indistinguishable;
3846 }
3847 
3848 /// Determine whether one of the given reference bindings is better
3849 /// than the other based on what kind of bindings they are.
3850 static bool
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3851 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3852                              const StandardConversionSequence &SCS2) {
3853   // C++0x [over.ics.rank]p3b4:
3854   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3855   //      implicit object parameter of a non-static member function declared
3856   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3857   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3858   //      lvalue reference to a function lvalue and S2 binds an rvalue
3859   //      reference*.
3860   //
3861   // FIXME: Rvalue references. We're going rogue with the above edits,
3862   // because the semantics in the current C++0x working paper (N3225 at the
3863   // time of this writing) break the standard definition of std::forward
3864   // and std::reference_wrapper when dealing with references to functions.
3865   // Proposed wording changes submitted to CWG for consideration.
3866   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3867       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3868     return false;
3869 
3870   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3871           SCS2.IsLvalueReference) ||
3872          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3873           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3874 }
3875 
3876 enum class FixedEnumPromotion {
3877   None,
3878   ToUnderlyingType,
3879   ToPromotedUnderlyingType
3880 };
3881 
3882 /// Returns kind of fixed enum promotion the \a SCS uses.
3883 static FixedEnumPromotion
getFixedEnumPromtion(Sema & S,const StandardConversionSequence & SCS)3884 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3885 
3886   if (SCS.Second != ICK_Integral_Promotion)
3887     return FixedEnumPromotion::None;
3888 
3889   QualType FromType = SCS.getFromType();
3890   if (!FromType->isEnumeralType())
3891     return FixedEnumPromotion::None;
3892 
3893   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3894   if (!Enum->isFixed())
3895     return FixedEnumPromotion::None;
3896 
3897   QualType UnderlyingType = Enum->getIntegerType();
3898   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3899     return FixedEnumPromotion::ToUnderlyingType;
3900 
3901   return FixedEnumPromotion::ToPromotedUnderlyingType;
3902 }
3903 
3904 /// CompareStandardConversionSequences - Compare two standard
3905 /// conversion sequences to determine whether one is better than the
3906 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3907 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3908 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3909                                    const StandardConversionSequence& SCS1,
3910                                    const StandardConversionSequence& SCS2)
3911 {
3912   // Standard conversion sequence S1 is a better conversion sequence
3913   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3914 
3915   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3916   //     sequences in the canonical form defined by 13.3.3.1.1,
3917   //     excluding any Lvalue Transformation; the identity conversion
3918   //     sequence is considered to be a subsequence of any
3919   //     non-identity conversion sequence) or, if not that,
3920   if (ImplicitConversionSequence::CompareKind CK
3921         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3922     return CK;
3923 
3924   //  -- the rank of S1 is better than the rank of S2 (by the rules
3925   //     defined below), or, if not that,
3926   ImplicitConversionRank Rank1 = SCS1.getRank();
3927   ImplicitConversionRank Rank2 = SCS2.getRank();
3928   if (Rank1 < Rank2)
3929     return ImplicitConversionSequence::Better;
3930   else if (Rank2 < Rank1)
3931     return ImplicitConversionSequence::Worse;
3932 
3933   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3934   // are indistinguishable unless one of the following rules
3935   // applies:
3936 
3937   //   A conversion that is not a conversion of a pointer, or
3938   //   pointer to member, to bool is better than another conversion
3939   //   that is such a conversion.
3940   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3941     return SCS2.isPointerConversionToBool()
3942              ? ImplicitConversionSequence::Better
3943              : ImplicitConversionSequence::Worse;
3944 
3945   // C++14 [over.ics.rank]p4b2:
3946   // This is retroactively applied to C++11 by CWG 1601.
3947   //
3948   //   A conversion that promotes an enumeration whose underlying type is fixed
3949   //   to its underlying type is better than one that promotes to the promoted
3950   //   underlying type, if the two are different.
3951   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3952   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3953   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3954       FEP1 != FEP2)
3955     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3956                ? ImplicitConversionSequence::Better
3957                : ImplicitConversionSequence::Worse;
3958 
3959   // C++ [over.ics.rank]p4b2:
3960   //
3961   //   If class B is derived directly or indirectly from class A,
3962   //   conversion of B* to A* is better than conversion of B* to
3963   //   void*, and conversion of A* to void* is better than conversion
3964   //   of B* to void*.
3965   bool SCS1ConvertsToVoid
3966     = SCS1.isPointerConversionToVoidPointer(S.Context);
3967   bool SCS2ConvertsToVoid
3968     = SCS2.isPointerConversionToVoidPointer(S.Context);
3969   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3970     // Exactly one of the conversion sequences is a conversion to
3971     // a void pointer; it's the worse conversion.
3972     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3973                               : ImplicitConversionSequence::Worse;
3974   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3975     // Neither conversion sequence converts to a void pointer; compare
3976     // their derived-to-base conversions.
3977     if (ImplicitConversionSequence::CompareKind DerivedCK
3978           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3979       return DerivedCK;
3980   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3981              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3982     // Both conversion sequences are conversions to void
3983     // pointers. Compare the source types to determine if there's an
3984     // inheritance relationship in their sources.
3985     QualType FromType1 = SCS1.getFromType();
3986     QualType FromType2 = SCS2.getFromType();
3987 
3988     // Adjust the types we're converting from via the array-to-pointer
3989     // conversion, if we need to.
3990     if (SCS1.First == ICK_Array_To_Pointer)
3991       FromType1 = S.Context.getArrayDecayedType(FromType1);
3992     if (SCS2.First == ICK_Array_To_Pointer)
3993       FromType2 = S.Context.getArrayDecayedType(FromType2);
3994 
3995     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3996     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3997 
3998     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3999       return ImplicitConversionSequence::Better;
4000     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4001       return ImplicitConversionSequence::Worse;
4002 
4003     // Objective-C++: If one interface is more specific than the
4004     // other, it is the better one.
4005     const ObjCObjectPointerType* FromObjCPtr1
4006       = FromType1->getAs<ObjCObjectPointerType>();
4007     const ObjCObjectPointerType* FromObjCPtr2
4008       = FromType2->getAs<ObjCObjectPointerType>();
4009     if (FromObjCPtr1 && FromObjCPtr2) {
4010       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4011                                                           FromObjCPtr2);
4012       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4013                                                            FromObjCPtr1);
4014       if (AssignLeft != AssignRight) {
4015         return AssignLeft? ImplicitConversionSequence::Better
4016                          : ImplicitConversionSequence::Worse;
4017       }
4018     }
4019   }
4020 
4021   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4022     // Check for a better reference binding based on the kind of bindings.
4023     if (isBetterReferenceBindingKind(SCS1, SCS2))
4024       return ImplicitConversionSequence::Better;
4025     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4026       return ImplicitConversionSequence::Worse;
4027   }
4028 
4029   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4030   // bullet 3).
4031   if (ImplicitConversionSequence::CompareKind QualCK
4032         = CompareQualificationConversions(S, SCS1, SCS2))
4033     return QualCK;
4034 
4035   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4036     // C++ [over.ics.rank]p3b4:
4037     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4038     //      which the references refer are the same type except for
4039     //      top-level cv-qualifiers, and the type to which the reference
4040     //      initialized by S2 refers is more cv-qualified than the type
4041     //      to which the reference initialized by S1 refers.
4042     QualType T1 = SCS1.getToType(2);
4043     QualType T2 = SCS2.getToType(2);
4044     T1 = S.Context.getCanonicalType(T1);
4045     T2 = S.Context.getCanonicalType(T2);
4046     Qualifiers T1Quals, T2Quals;
4047     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4048     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4049     if (UnqualT1 == UnqualT2) {
4050       // Objective-C++ ARC: If the references refer to objects with different
4051       // lifetimes, prefer bindings that don't change lifetime.
4052       if (SCS1.ObjCLifetimeConversionBinding !=
4053                                           SCS2.ObjCLifetimeConversionBinding) {
4054         return SCS1.ObjCLifetimeConversionBinding
4055                                            ? ImplicitConversionSequence::Worse
4056                                            : ImplicitConversionSequence::Better;
4057       }
4058 
4059       // If the type is an array type, promote the element qualifiers to the
4060       // type for comparison.
4061       if (isa<ArrayType>(T1) && T1Quals)
4062         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4063       if (isa<ArrayType>(T2) && T2Quals)
4064         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4065       if (T2.isMoreQualifiedThan(T1))
4066         return ImplicitConversionSequence::Better;
4067       if (T1.isMoreQualifiedThan(T2))
4068         return ImplicitConversionSequence::Worse;
4069     }
4070   }
4071 
4072   // In Microsoft mode, prefer an integral conversion to a
4073   // floating-to-integral conversion if the integral conversion
4074   // is between types of the same size.
4075   // For example:
4076   // void f(float);
4077   // void f(int);
4078   // int main {
4079   //    long a;
4080   //    f(a);
4081   // }
4082   // Here, MSVC will call f(int) instead of generating a compile error
4083   // as clang will do in standard mode.
4084   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4085       SCS2.Second == ICK_Floating_Integral &&
4086       S.Context.getTypeSize(SCS1.getFromType()) ==
4087           S.Context.getTypeSize(SCS1.getToType(2)))
4088     return ImplicitConversionSequence::Better;
4089 
4090   // Prefer a compatible vector conversion over a lax vector conversion
4091   // For example:
4092   //
4093   // typedef float __v4sf __attribute__((__vector_size__(16)));
4094   // void f(vector float);
4095   // void f(vector signed int);
4096   // int main() {
4097   //   __v4sf a;
4098   //   f(a);
4099   // }
4100   // Here, we'd like to choose f(vector float) and not
4101   // report an ambiguous call error
4102   if (SCS1.Second == ICK_Vector_Conversion &&
4103       SCS2.Second == ICK_Vector_Conversion) {
4104     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4105         SCS1.getFromType(), SCS1.getToType(2));
4106     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4107         SCS2.getFromType(), SCS2.getToType(2));
4108 
4109     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4110       return SCS1IsCompatibleVectorConversion
4111                  ? ImplicitConversionSequence::Better
4112                  : ImplicitConversionSequence::Worse;
4113   }
4114 
4115   return ImplicitConversionSequence::Indistinguishable;
4116 }
4117 
4118 /// CompareQualificationConversions - Compares two standard conversion
4119 /// sequences to determine whether they can be ranked based on their
4120 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4121 static ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4122 CompareQualificationConversions(Sema &S,
4123                                 const StandardConversionSequence& SCS1,
4124                                 const StandardConversionSequence& SCS2) {
4125   // C++ 13.3.3.2p3:
4126   //  -- S1 and S2 differ only in their qualification conversion and
4127   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4128   //     cv-qualification signature of type T1 is a proper subset of
4129   //     the cv-qualification signature of type T2, and S1 is not the
4130   //     deprecated string literal array-to-pointer conversion (4.2).
4131   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4132       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4133     return ImplicitConversionSequence::Indistinguishable;
4134 
4135   // FIXME: the example in the standard doesn't use a qualification
4136   // conversion (!)
4137   QualType T1 = SCS1.getToType(2);
4138   QualType T2 = SCS2.getToType(2);
4139   T1 = S.Context.getCanonicalType(T1);
4140   T2 = S.Context.getCanonicalType(T2);
4141   assert(!T1->isReferenceType() && !T2->isReferenceType());
4142   Qualifiers T1Quals, T2Quals;
4143   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4144   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4145 
4146   // If the types are the same, we won't learn anything by unwrapping
4147   // them.
4148   if (UnqualT1 == UnqualT2)
4149     return ImplicitConversionSequence::Indistinguishable;
4150 
4151   ImplicitConversionSequence::CompareKind Result
4152     = ImplicitConversionSequence::Indistinguishable;
4153 
4154   // Objective-C++ ARC:
4155   //   Prefer qualification conversions not involving a change in lifetime
4156   //   to qualification conversions that do not change lifetime.
4157   if (SCS1.QualificationIncludesObjCLifetime !=
4158                                       SCS2.QualificationIncludesObjCLifetime) {
4159     Result = SCS1.QualificationIncludesObjCLifetime
4160                ? ImplicitConversionSequence::Worse
4161                : ImplicitConversionSequence::Better;
4162   }
4163 
4164   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4165     // Within each iteration of the loop, we check the qualifiers to
4166     // determine if this still looks like a qualification
4167     // conversion. Then, if all is well, we unwrap one more level of
4168     // pointers or pointers-to-members and do it all again
4169     // until there are no more pointers or pointers-to-members left
4170     // to unwrap. This essentially mimics what
4171     // IsQualificationConversion does, but here we're checking for a
4172     // strict subset of qualifiers.
4173     if (T1.getQualifiers().withoutObjCLifetime() ==
4174         T2.getQualifiers().withoutObjCLifetime())
4175       // The qualifiers are the same, so this doesn't tell us anything
4176       // about how the sequences rank.
4177       // ObjC ownership quals are omitted above as they interfere with
4178       // the ARC overload rule.
4179       ;
4180     else if (T2.isMoreQualifiedThan(T1)) {
4181       // T1 has fewer qualifiers, so it could be the better sequence.
4182       if (Result == ImplicitConversionSequence::Worse)
4183         // Neither has qualifiers that are a subset of the other's
4184         // qualifiers.
4185         return ImplicitConversionSequence::Indistinguishable;
4186 
4187       Result = ImplicitConversionSequence::Better;
4188     } else if (T1.isMoreQualifiedThan(T2)) {
4189       // T2 has fewer qualifiers, so it could be the better sequence.
4190       if (Result == ImplicitConversionSequence::Better)
4191         // Neither has qualifiers that are a subset of the other's
4192         // qualifiers.
4193         return ImplicitConversionSequence::Indistinguishable;
4194 
4195       Result = ImplicitConversionSequence::Worse;
4196     } else {
4197       // Qualifiers are disjoint.
4198       return ImplicitConversionSequence::Indistinguishable;
4199     }
4200 
4201     // If the types after this point are equivalent, we're done.
4202     if (S.Context.hasSameUnqualifiedType(T1, T2))
4203       break;
4204   }
4205 
4206   // Check that the winning standard conversion sequence isn't using
4207   // the deprecated string literal array to pointer conversion.
4208   switch (Result) {
4209   case ImplicitConversionSequence::Better:
4210     if (SCS1.DeprecatedStringLiteralToCharPtr)
4211       Result = ImplicitConversionSequence::Indistinguishable;
4212     break;
4213 
4214   case ImplicitConversionSequence::Indistinguishable:
4215     break;
4216 
4217   case ImplicitConversionSequence::Worse:
4218     if (SCS2.DeprecatedStringLiteralToCharPtr)
4219       Result = ImplicitConversionSequence::Indistinguishable;
4220     break;
4221   }
4222 
4223   return Result;
4224 }
4225 
4226 /// CompareDerivedToBaseConversions - Compares two standard conversion
4227 /// sequences to determine whether they can be ranked based on their
4228 /// various kinds of derived-to-base conversions (C++
4229 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4230 /// conversions between Objective-C interface types.
4231 static ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4232 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4233                                 const StandardConversionSequence& SCS1,
4234                                 const StandardConversionSequence& SCS2) {
4235   QualType FromType1 = SCS1.getFromType();
4236   QualType ToType1 = SCS1.getToType(1);
4237   QualType FromType2 = SCS2.getFromType();
4238   QualType ToType2 = SCS2.getToType(1);
4239 
4240   // Adjust the types we're converting from via the array-to-pointer
4241   // conversion, if we need to.
4242   if (SCS1.First == ICK_Array_To_Pointer)
4243     FromType1 = S.Context.getArrayDecayedType(FromType1);
4244   if (SCS2.First == ICK_Array_To_Pointer)
4245     FromType2 = S.Context.getArrayDecayedType(FromType2);
4246 
4247   // Canonicalize all of the types.
4248   FromType1 = S.Context.getCanonicalType(FromType1);
4249   ToType1 = S.Context.getCanonicalType(ToType1);
4250   FromType2 = S.Context.getCanonicalType(FromType2);
4251   ToType2 = S.Context.getCanonicalType(ToType2);
4252 
4253   // C++ [over.ics.rank]p4b3:
4254   //
4255   //   If class B is derived directly or indirectly from class A and
4256   //   class C is derived directly or indirectly from B,
4257   //
4258   // Compare based on pointer conversions.
4259   if (SCS1.Second == ICK_Pointer_Conversion &&
4260       SCS2.Second == ICK_Pointer_Conversion &&
4261       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4262       FromType1->isPointerType() && FromType2->isPointerType() &&
4263       ToType1->isPointerType() && ToType2->isPointerType()) {
4264     QualType FromPointee1 =
4265         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4266     QualType ToPointee1 =
4267         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4268     QualType FromPointee2 =
4269         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4270     QualType ToPointee2 =
4271         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4272 
4273     //   -- conversion of C* to B* is better than conversion of C* to A*,
4274     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4275       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4276         return ImplicitConversionSequence::Better;
4277       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4278         return ImplicitConversionSequence::Worse;
4279     }
4280 
4281     //   -- conversion of B* to A* is better than conversion of C* to A*,
4282     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4283       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4284         return ImplicitConversionSequence::Better;
4285       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4286         return ImplicitConversionSequence::Worse;
4287     }
4288   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4289              SCS2.Second == ICK_Pointer_Conversion) {
4290     const ObjCObjectPointerType *FromPtr1
4291       = FromType1->getAs<ObjCObjectPointerType>();
4292     const ObjCObjectPointerType *FromPtr2
4293       = FromType2->getAs<ObjCObjectPointerType>();
4294     const ObjCObjectPointerType *ToPtr1
4295       = ToType1->getAs<ObjCObjectPointerType>();
4296     const ObjCObjectPointerType *ToPtr2
4297       = ToType2->getAs<ObjCObjectPointerType>();
4298 
4299     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4300       // Apply the same conversion ranking rules for Objective-C pointer types
4301       // that we do for C++ pointers to class types. However, we employ the
4302       // Objective-C pseudo-subtyping relationship used for assignment of
4303       // Objective-C pointer types.
4304       bool FromAssignLeft
4305         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4306       bool FromAssignRight
4307         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4308       bool ToAssignLeft
4309         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4310       bool ToAssignRight
4311         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4312 
4313       // A conversion to an a non-id object pointer type or qualified 'id'
4314       // type is better than a conversion to 'id'.
4315       if (ToPtr1->isObjCIdType() &&
4316           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4317         return ImplicitConversionSequence::Worse;
4318       if (ToPtr2->isObjCIdType() &&
4319           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4320         return ImplicitConversionSequence::Better;
4321 
4322       // A conversion to a non-id object pointer type is better than a
4323       // conversion to a qualified 'id' type
4324       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4325         return ImplicitConversionSequence::Worse;
4326       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4327         return ImplicitConversionSequence::Better;
4328 
4329       // A conversion to an a non-Class object pointer type or qualified 'Class'
4330       // type is better than a conversion to 'Class'.
4331       if (ToPtr1->isObjCClassType() &&
4332           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4333         return ImplicitConversionSequence::Worse;
4334       if (ToPtr2->isObjCClassType() &&
4335           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4336         return ImplicitConversionSequence::Better;
4337 
4338       // A conversion to a non-Class object pointer type is better than a
4339       // conversion to a qualified 'Class' type.
4340       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4341         return ImplicitConversionSequence::Worse;
4342       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4343         return ImplicitConversionSequence::Better;
4344 
4345       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4346       if (S.Context.hasSameType(FromType1, FromType2) &&
4347           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4348           (ToAssignLeft != ToAssignRight)) {
4349         if (FromPtr1->isSpecialized()) {
4350           // "conversion of B<A> * to B * is better than conversion of B * to
4351           // C *.
4352           bool IsFirstSame =
4353               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4354           bool IsSecondSame =
4355               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4356           if (IsFirstSame) {
4357             if (!IsSecondSame)
4358               return ImplicitConversionSequence::Better;
4359           } else if (IsSecondSame)
4360             return ImplicitConversionSequence::Worse;
4361         }
4362         return ToAssignLeft? ImplicitConversionSequence::Worse
4363                            : ImplicitConversionSequence::Better;
4364       }
4365 
4366       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4367       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4368           (FromAssignLeft != FromAssignRight))
4369         return FromAssignLeft? ImplicitConversionSequence::Better
4370         : ImplicitConversionSequence::Worse;
4371     }
4372   }
4373 
4374   // Ranking of member-pointer types.
4375   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4376       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4377       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4378     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4379     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4380     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4381     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4382     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4383     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4384     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4385     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4386     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4387     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4388     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4389     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4390     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4391     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4392       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4393         return ImplicitConversionSequence::Worse;
4394       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4395         return ImplicitConversionSequence::Better;
4396     }
4397     // conversion of B::* to C::* is better than conversion of A::* to C::*
4398     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4399       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4400         return ImplicitConversionSequence::Better;
4401       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4402         return ImplicitConversionSequence::Worse;
4403     }
4404   }
4405 
4406   if (SCS1.Second == ICK_Derived_To_Base) {
4407     //   -- conversion of C to B is better than conversion of C to A,
4408     //   -- binding of an expression of type C to a reference of type
4409     //      B& is better than binding an expression of type C to a
4410     //      reference of type A&,
4411     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4412         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4413       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4414         return ImplicitConversionSequence::Better;
4415       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4416         return ImplicitConversionSequence::Worse;
4417     }
4418 
4419     //   -- conversion of B to A is better than conversion of C to A.
4420     //   -- binding of an expression of type B to a reference of type
4421     //      A& is better than binding an expression of type C to a
4422     //      reference of type A&,
4423     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4424         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4425       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4426         return ImplicitConversionSequence::Better;
4427       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4428         return ImplicitConversionSequence::Worse;
4429     }
4430   }
4431 
4432   return ImplicitConversionSequence::Indistinguishable;
4433 }
4434 
4435 /// Determine whether the given type is valid, e.g., it is not an invalid
4436 /// C++ class.
isTypeValid(QualType T)4437 static bool isTypeValid(QualType T) {
4438   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4439     return !Record->isInvalidDecl();
4440 
4441   return true;
4442 }
4443 
withoutUnaligned(ASTContext & Ctx,QualType T)4444 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4445   if (!T.getQualifiers().hasUnaligned())
4446     return T;
4447 
4448   Qualifiers Q;
4449   T = Ctx.getUnqualifiedArrayType(T, Q);
4450   Q.removeUnaligned();
4451   return Ctx.getQualifiedType(T, Q);
4452 }
4453 
4454 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4455 /// determine whether they are reference-compatible,
4456 /// reference-related, or incompatible, for use in C++ initialization by
4457 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4458 /// type, and the first type (T1) is the pointee type of the reference
4459 /// type being initialized.
4460 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,ReferenceConversions * ConvOut)4461 Sema::CompareReferenceRelationship(SourceLocation Loc,
4462                                    QualType OrigT1, QualType OrigT2,
4463                                    ReferenceConversions *ConvOut) {
4464   assert(!OrigT1->isReferenceType() &&
4465     "T1 must be the pointee type of the reference type");
4466   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4467 
4468   QualType T1 = Context.getCanonicalType(OrigT1);
4469   QualType T2 = Context.getCanonicalType(OrigT2);
4470   Qualifiers T1Quals, T2Quals;
4471   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4472   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4473 
4474   ReferenceConversions ConvTmp;
4475   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4476   Conv = ReferenceConversions();
4477 
4478   // C++2a [dcl.init.ref]p4:
4479   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4480   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4481   //   T1 is a base class of T2.
4482   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4483   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4484   //   "pointer to cv1 T1" via a standard conversion sequence.
4485 
4486   // Check for standard conversions we can apply to pointers: derived-to-base
4487   // conversions, ObjC pointer conversions, and function pointer conversions.
4488   // (Qualification conversions are checked last.)
4489   QualType ConvertedT2;
4490   if (UnqualT1 == UnqualT2) {
4491     // Nothing to do.
4492   } else if (isCompleteType(Loc, OrigT2) &&
4493              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4494              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4495     Conv |= ReferenceConversions::DerivedToBase;
4496   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4497            UnqualT2->isObjCObjectOrInterfaceType() &&
4498            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4499     Conv |= ReferenceConversions::ObjC;
4500   else if (UnqualT2->isFunctionType() &&
4501            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4502     Conv |= ReferenceConversions::Function;
4503     // No need to check qualifiers; function types don't have them.
4504     return Ref_Compatible;
4505   }
4506   bool ConvertedReferent = Conv != 0;
4507 
4508   // We can have a qualification conversion. Compute whether the types are
4509   // similar at the same time.
4510   bool PreviousToQualsIncludeConst = true;
4511   bool TopLevel = true;
4512   do {
4513     if (T1 == T2)
4514       break;
4515 
4516     // We will need a qualification conversion.
4517     Conv |= ReferenceConversions::Qualification;
4518 
4519     // Track whether we performed a qualification conversion anywhere other
4520     // than the top level. This matters for ranking reference bindings in
4521     // overload resolution.
4522     if (!TopLevel)
4523       Conv |= ReferenceConversions::NestedQualification;
4524 
4525     // MS compiler ignores __unaligned qualifier for references; do the same.
4526     T1 = withoutUnaligned(Context, T1);
4527     T2 = withoutUnaligned(Context, T2);
4528 
4529     // If we find a qualifier mismatch, the types are not reference-compatible,
4530     // but are still be reference-related if they're similar.
4531     bool ObjCLifetimeConversion = false;
4532     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4533                                        PreviousToQualsIncludeConst,
4534                                        ObjCLifetimeConversion))
4535       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4536                  ? Ref_Related
4537                  : Ref_Incompatible;
4538 
4539     // FIXME: Should we track this for any level other than the first?
4540     if (ObjCLifetimeConversion)
4541       Conv |= ReferenceConversions::ObjCLifetime;
4542 
4543     TopLevel = false;
4544   } while (Context.UnwrapSimilarTypes(T1, T2));
4545 
4546   // At this point, if the types are reference-related, we must either have the
4547   // same inner type (ignoring qualifiers), or must have already worked out how
4548   // to convert the referent.
4549   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4550              ? Ref_Compatible
4551              : Ref_Incompatible;
4552 }
4553 
4554 /// Look for a user-defined conversion to a value reference-compatible
4555 ///        with DeclType. Return true if something definite is found.
4556 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)4557 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4558                          QualType DeclType, SourceLocation DeclLoc,
4559                          Expr *Init, QualType T2, bool AllowRvalues,
4560                          bool AllowExplicit) {
4561   assert(T2->isRecordType() && "Can only find conversions of record types.");
4562   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4563 
4564   OverloadCandidateSet CandidateSet(
4565       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4566   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4567   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4568     NamedDecl *D = *I;
4569     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4570     if (isa<UsingShadowDecl>(D))
4571       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4572 
4573     FunctionTemplateDecl *ConvTemplate
4574       = dyn_cast<FunctionTemplateDecl>(D);
4575     CXXConversionDecl *Conv;
4576     if (ConvTemplate)
4577       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4578     else
4579       Conv = cast<CXXConversionDecl>(D);
4580 
4581     if (AllowRvalues) {
4582       // If we are initializing an rvalue reference, don't permit conversion
4583       // functions that return lvalues.
4584       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4585         const ReferenceType *RefType
4586           = Conv->getConversionType()->getAs<LValueReferenceType>();
4587         if (RefType && !RefType->getPointeeType()->isFunctionType())
4588           continue;
4589       }
4590 
4591       if (!ConvTemplate &&
4592           S.CompareReferenceRelationship(
4593               DeclLoc,
4594               Conv->getConversionType()
4595                   .getNonReferenceType()
4596                   .getUnqualifiedType(),
4597               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4598               Sema::Ref_Incompatible)
4599         continue;
4600     } else {
4601       // If the conversion function doesn't return a reference type,
4602       // it can't be considered for this conversion. An rvalue reference
4603       // is only acceptable if its referencee is a function type.
4604 
4605       const ReferenceType *RefType =
4606         Conv->getConversionType()->getAs<ReferenceType>();
4607       if (!RefType ||
4608           (!RefType->isLValueReferenceType() &&
4609            !RefType->getPointeeType()->isFunctionType()))
4610         continue;
4611     }
4612 
4613     if (ConvTemplate)
4614       S.AddTemplateConversionCandidate(
4615           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4616           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4617     else
4618       S.AddConversionCandidate(
4619           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4620           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4621   }
4622 
4623   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4624 
4625   OverloadCandidateSet::iterator Best;
4626   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4627   case OR_Success:
4628     // C++ [over.ics.ref]p1:
4629     //
4630     //   [...] If the parameter binds directly to the result of
4631     //   applying a conversion function to the argument
4632     //   expression, the implicit conversion sequence is a
4633     //   user-defined conversion sequence (13.3.3.1.2), with the
4634     //   second standard conversion sequence either an identity
4635     //   conversion or, if the conversion function returns an
4636     //   entity of a type that is a derived class of the parameter
4637     //   type, a derived-to-base Conversion.
4638     if (!Best->FinalConversion.DirectBinding)
4639       return false;
4640 
4641     ICS.setUserDefined();
4642     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4643     ICS.UserDefined.After = Best->FinalConversion;
4644     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4645     ICS.UserDefined.ConversionFunction = Best->Function;
4646     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4647     ICS.UserDefined.EllipsisConversion = false;
4648     assert(ICS.UserDefined.After.ReferenceBinding &&
4649            ICS.UserDefined.After.DirectBinding &&
4650            "Expected a direct reference binding!");
4651     return true;
4652 
4653   case OR_Ambiguous:
4654     ICS.setAmbiguous();
4655     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4656          Cand != CandidateSet.end(); ++Cand)
4657       if (Cand->Best)
4658         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4659     return true;
4660 
4661   case OR_No_Viable_Function:
4662   case OR_Deleted:
4663     // There was no suitable conversion, or we found a deleted
4664     // conversion; continue with other checks.
4665     return false;
4666   }
4667 
4668   llvm_unreachable("Invalid OverloadResult!");
4669 }
4670 
4671 /// Compute an implicit conversion sequence for reference
4672 /// initialization.
4673 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)4674 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4675                  SourceLocation DeclLoc,
4676                  bool SuppressUserConversions,
4677                  bool AllowExplicit) {
4678   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4679 
4680   // Most paths end in a failed conversion.
4681   ImplicitConversionSequence ICS;
4682   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4683 
4684   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4685   QualType T2 = Init->getType();
4686 
4687   // If the initializer is the address of an overloaded function, try
4688   // to resolve the overloaded function. If all goes well, T2 is the
4689   // type of the resulting function.
4690   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4691     DeclAccessPair Found;
4692     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4693                                                                 false, Found))
4694       T2 = Fn->getType();
4695   }
4696 
4697   // Compute some basic properties of the types and the initializer.
4698   bool isRValRef = DeclType->isRValueReferenceType();
4699   Expr::Classification InitCategory = Init->Classify(S.Context);
4700 
4701   Sema::ReferenceConversions RefConv;
4702   Sema::ReferenceCompareResult RefRelationship =
4703       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4704 
4705   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4706     ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
4707     ICS.Standard.First = ICK_Identity;
4708     // FIXME: A reference binding can be a function conversion too. We should
4709     // consider that when ordering reference-to-function bindings.
4710     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4711                               ? ICK_Derived_To_Base
4712                               : (RefConv & Sema::ReferenceConversions::ObjC)
4713                                     ? ICK_Compatible_Conversion
4714                                     : ICK_Identity;
4715     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4716     // a reference binding that performs a non-top-level qualification
4717     // conversion as a qualification conversion, not as an identity conversion.
4718     ICS.Standard.Third = (RefConv &
4719                               Sema::ReferenceConversions::NestedQualification)
4720                              ? ICK_Qualification
4721                              : ICK_Identity;
4722     ICS.Standard.setFromType(T2);
4723     ICS.Standard.setToType(0, T2);
4724     ICS.Standard.setToType(1, T1);
4725     ICS.Standard.setToType(2, T1);
4726     ICS.Standard.ReferenceBinding = true;
4727     ICS.Standard.DirectBinding = BindsDirectly;
4728     ICS.Standard.IsLvalueReference = !isRValRef;
4729     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4730     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4731     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4732     ICS.Standard.ObjCLifetimeConversionBinding =
4733         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4734     ICS.Standard.CopyConstructor = nullptr;
4735     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4736   };
4737 
4738   // C++0x [dcl.init.ref]p5:
4739   //   A reference to type "cv1 T1" is initialized by an expression
4740   //   of type "cv2 T2" as follows:
4741 
4742   //     -- If reference is an lvalue reference and the initializer expression
4743   if (!isRValRef) {
4744     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4745     //        reference-compatible with "cv2 T2," or
4746     //
4747     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4748     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4749       // C++ [over.ics.ref]p1:
4750       //   When a parameter of reference type binds directly (8.5.3)
4751       //   to an argument expression, the implicit conversion sequence
4752       //   is the identity conversion, unless the argument expression
4753       //   has a type that is a derived class of the parameter type,
4754       //   in which case the implicit conversion sequence is a
4755       //   derived-to-base Conversion (13.3.3.1).
4756       SetAsReferenceBinding(/*BindsDirectly=*/true);
4757 
4758       // Nothing more to do: the inaccessibility/ambiguity check for
4759       // derived-to-base conversions is suppressed when we're
4760       // computing the implicit conversion sequence (C++
4761       // [over.best.ics]p2).
4762       return ICS;
4763     }
4764 
4765     //       -- has a class type (i.e., T2 is a class type), where T1 is
4766     //          not reference-related to T2, and can be implicitly
4767     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4768     //          is reference-compatible with "cv3 T3" 92) (this
4769     //          conversion is selected by enumerating the applicable
4770     //          conversion functions (13.3.1.6) and choosing the best
4771     //          one through overload resolution (13.3)),
4772     if (!SuppressUserConversions && T2->isRecordType() &&
4773         S.isCompleteType(DeclLoc, T2) &&
4774         RefRelationship == Sema::Ref_Incompatible) {
4775       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4776                                    Init, T2, /*AllowRvalues=*/false,
4777                                    AllowExplicit))
4778         return ICS;
4779     }
4780   }
4781 
4782   //     -- Otherwise, the reference shall be an lvalue reference to a
4783   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4784   //        shall be an rvalue reference.
4785   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4786     return ICS;
4787 
4788   //       -- If the initializer expression
4789   //
4790   //            -- is an xvalue, class prvalue, array prvalue or function
4791   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4792   if (RefRelationship == Sema::Ref_Compatible &&
4793       (InitCategory.isXValue() ||
4794        (InitCategory.isPRValue() &&
4795           (T2->isRecordType() || T2->isArrayType())) ||
4796        (InitCategory.isLValue() && T2->isFunctionType()))) {
4797     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4798     // binding unless we're binding to a class prvalue.
4799     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4800     // allow the use of rvalue references in C++98/03 for the benefit of
4801     // standard library implementors; therefore, we need the xvalue check here.
4802     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4803                           !(InitCategory.isPRValue() || T2->isRecordType()));
4804     return ICS;
4805   }
4806 
4807   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4808   //               reference-related to T2, and can be implicitly converted to
4809   //               an xvalue, class prvalue, or function lvalue of type
4810   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4811   //               "cv3 T3",
4812   //
4813   //          then the reference is bound to the value of the initializer
4814   //          expression in the first case and to the result of the conversion
4815   //          in the second case (or, in either case, to an appropriate base
4816   //          class subobject).
4817   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4818       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4819       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4820                                Init, T2, /*AllowRvalues=*/true,
4821                                AllowExplicit)) {
4822     // In the second case, if the reference is an rvalue reference
4823     // and the second standard conversion sequence of the
4824     // user-defined conversion sequence includes an lvalue-to-rvalue
4825     // conversion, the program is ill-formed.
4826     if (ICS.isUserDefined() && isRValRef &&
4827         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4828       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4829 
4830     return ICS;
4831   }
4832 
4833   // A temporary of function type cannot be created; don't even try.
4834   if (T1->isFunctionType())
4835     return ICS;
4836 
4837   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4838   //          initialized from the initializer expression using the
4839   //          rules for a non-reference copy initialization (8.5). The
4840   //          reference is then bound to the temporary. If T1 is
4841   //          reference-related to T2, cv1 must be the same
4842   //          cv-qualification as, or greater cv-qualification than,
4843   //          cv2; otherwise, the program is ill-formed.
4844   if (RefRelationship == Sema::Ref_Related) {
4845     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4846     // we would be reference-compatible or reference-compatible with
4847     // added qualification. But that wasn't the case, so the reference
4848     // initialization fails.
4849     //
4850     // Note that we only want to check address spaces and cvr-qualifiers here.
4851     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4852     Qualifiers T1Quals = T1.getQualifiers();
4853     Qualifiers T2Quals = T2.getQualifiers();
4854     T1Quals.removeObjCGCAttr();
4855     T1Quals.removeObjCLifetime();
4856     T2Quals.removeObjCGCAttr();
4857     T2Quals.removeObjCLifetime();
4858     // MS compiler ignores __unaligned qualifier for references; do the same.
4859     T1Quals.removeUnaligned();
4860     T2Quals.removeUnaligned();
4861     if (!T1Quals.compatiblyIncludes(T2Quals))
4862       return ICS;
4863   }
4864 
4865   // If at least one of the types is a class type, the types are not
4866   // related, and we aren't allowed any user conversions, the
4867   // reference binding fails. This case is important for breaking
4868   // recursion, since TryImplicitConversion below will attempt to
4869   // create a temporary through the use of a copy constructor.
4870   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4871       (T1->isRecordType() || T2->isRecordType()))
4872     return ICS;
4873 
4874   // If T1 is reference-related to T2 and the reference is an rvalue
4875   // reference, the initializer expression shall not be an lvalue.
4876   if (RefRelationship >= Sema::Ref_Related &&
4877       isRValRef && Init->Classify(S.Context).isLValue())
4878     return ICS;
4879 
4880   // C++ [over.ics.ref]p2:
4881   //   When a parameter of reference type is not bound directly to
4882   //   an argument expression, the conversion sequence is the one
4883   //   required to convert the argument expression to the
4884   //   underlying type of the reference according to
4885   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4886   //   to copy-initializing a temporary of the underlying type with
4887   //   the argument expression. Any difference in top-level
4888   //   cv-qualification is subsumed by the initialization itself
4889   //   and does not constitute a conversion.
4890   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4891                               AllowedExplicit::None,
4892                               /*InOverloadResolution=*/false,
4893                               /*CStyle=*/false,
4894                               /*AllowObjCWritebackConversion=*/false,
4895                               /*AllowObjCConversionOnExplicit=*/false);
4896 
4897   // Of course, that's still a reference binding.
4898   if (ICS.isStandard()) {
4899     ICS.Standard.ReferenceBinding = true;
4900     ICS.Standard.IsLvalueReference = !isRValRef;
4901     ICS.Standard.BindsToFunctionLvalue = false;
4902     ICS.Standard.BindsToRvalue = true;
4903     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4904     ICS.Standard.ObjCLifetimeConversionBinding = false;
4905   } else if (ICS.isUserDefined()) {
4906     const ReferenceType *LValRefType =
4907         ICS.UserDefined.ConversionFunction->getReturnType()
4908             ->getAs<LValueReferenceType>();
4909 
4910     // C++ [over.ics.ref]p3:
4911     //   Except for an implicit object parameter, for which see 13.3.1, a
4912     //   standard conversion sequence cannot be formed if it requires [...]
4913     //   binding an rvalue reference to an lvalue other than a function
4914     //   lvalue.
4915     // Note that the function case is not possible here.
4916     if (DeclType->isRValueReferenceType() && LValRefType) {
4917       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4918       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4919       // reference to an rvalue!
4920       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4921       return ICS;
4922     }
4923 
4924     ICS.UserDefined.After.ReferenceBinding = true;
4925     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4926     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4927     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4928     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4929     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4930   }
4931 
4932   return ICS;
4933 }
4934 
4935 static ImplicitConversionSequence
4936 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4937                       bool SuppressUserConversions,
4938                       bool InOverloadResolution,
4939                       bool AllowObjCWritebackConversion,
4940                       bool AllowExplicit = false);
4941 
4942 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4943 /// initializer list From.
4944 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)4945 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4946                   bool SuppressUserConversions,
4947                   bool InOverloadResolution,
4948                   bool AllowObjCWritebackConversion) {
4949   // C++11 [over.ics.list]p1:
4950   //   When an argument is an initializer list, it is not an expression and
4951   //   special rules apply for converting it to a parameter type.
4952 
4953   ImplicitConversionSequence Result;
4954   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4955 
4956   // We need a complete type for what follows. Incomplete types can never be
4957   // initialized from init lists.
4958   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4959     return Result;
4960 
4961   // Per DR1467:
4962   //   If the parameter type is a class X and the initializer list has a single
4963   //   element of type cv U, where U is X or a class derived from X, the
4964   //   implicit conversion sequence is the one required to convert the element
4965   //   to the parameter type.
4966   //
4967   //   Otherwise, if the parameter type is a character array [... ]
4968   //   and the initializer list has a single element that is an
4969   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4970   //   implicit conversion sequence is the identity conversion.
4971   if (From->getNumInits() == 1) {
4972     if (ToType->isRecordType()) {
4973       QualType InitType = From->getInit(0)->getType();
4974       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4975           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4976         return TryCopyInitialization(S, From->getInit(0), ToType,
4977                                      SuppressUserConversions,
4978                                      InOverloadResolution,
4979                                      AllowObjCWritebackConversion);
4980     }
4981     // FIXME: Check the other conditions here: array of character type,
4982     // initializer is a string literal.
4983     if (ToType->isArrayType()) {
4984       InitializedEntity Entity =
4985         InitializedEntity::InitializeParameter(S.Context, ToType,
4986                                                /*Consumed=*/false);
4987       if (S.CanPerformCopyInitialization(Entity, From)) {
4988         Result.setAsIdentityConversion(ToType);
4989         return Result;
4990       }
4991     }
4992   }
4993 
4994   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4995   // C++11 [over.ics.list]p2:
4996   //   If the parameter type is std::initializer_list<X> or "array of X" and
4997   //   all the elements can be implicitly converted to X, the implicit
4998   //   conversion sequence is the worst conversion necessary to convert an
4999   //   element of the list to X.
5000   //
5001   // C++14 [over.ics.list]p3:
5002   //   Otherwise, if the parameter type is "array of N X", if the initializer
5003   //   list has exactly N elements or if it has fewer than N elements and X is
5004   //   default-constructible, and if all the elements of the initializer list
5005   //   can be implicitly converted to X, the implicit conversion sequence is
5006   //   the worst conversion necessary to convert an element of the list to X.
5007   //
5008   // FIXME: We're missing a lot of these checks.
5009   bool toStdInitializerList = false;
5010   QualType X;
5011   if (ToType->isArrayType())
5012     X = S.Context.getAsArrayType(ToType)->getElementType();
5013   else
5014     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5015   if (!X.isNull()) {
5016     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5017       Expr *Init = From->getInit(i);
5018       ImplicitConversionSequence ICS =
5019           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5020                                 InOverloadResolution,
5021                                 AllowObjCWritebackConversion);
5022       // If a single element isn't convertible, fail.
5023       if (ICS.isBad()) {
5024         Result = ICS;
5025         break;
5026       }
5027       // Otherwise, look for the worst conversion.
5028       if (Result.isBad() || CompareImplicitConversionSequences(
5029                                 S, From->getBeginLoc(), ICS, Result) ==
5030                                 ImplicitConversionSequence::Worse)
5031         Result = ICS;
5032     }
5033 
5034     // For an empty list, we won't have computed any conversion sequence.
5035     // Introduce the identity conversion sequence.
5036     if (From->getNumInits() == 0) {
5037       Result.setAsIdentityConversion(ToType);
5038     }
5039 
5040     Result.setStdInitializerListElement(toStdInitializerList);
5041     return Result;
5042   }
5043 
5044   // C++14 [over.ics.list]p4:
5045   // C++11 [over.ics.list]p3:
5046   //   Otherwise, if the parameter is a non-aggregate class X and overload
5047   //   resolution chooses a single best constructor [...] the implicit
5048   //   conversion sequence is a user-defined conversion sequence. If multiple
5049   //   constructors are viable but none is better than the others, the
5050   //   implicit conversion sequence is a user-defined conversion sequence.
5051   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5052     // This function can deal with initializer lists.
5053     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5054                                     AllowedExplicit::None,
5055                                     InOverloadResolution, /*CStyle=*/false,
5056                                     AllowObjCWritebackConversion,
5057                                     /*AllowObjCConversionOnExplicit=*/false);
5058   }
5059 
5060   // C++14 [over.ics.list]p5:
5061   // C++11 [over.ics.list]p4:
5062   //   Otherwise, if the parameter has an aggregate type which can be
5063   //   initialized from the initializer list [...] the implicit conversion
5064   //   sequence is a user-defined conversion sequence.
5065   if (ToType->isAggregateType()) {
5066     // Type is an aggregate, argument is an init list. At this point it comes
5067     // down to checking whether the initialization works.
5068     // FIXME: Find out whether this parameter is consumed or not.
5069     InitializedEntity Entity =
5070         InitializedEntity::InitializeParameter(S.Context, ToType,
5071                                                /*Consumed=*/false);
5072     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5073                                                                  From)) {
5074       Result.setUserDefined();
5075       Result.UserDefined.Before.setAsIdentityConversion();
5076       // Initializer lists don't have a type.
5077       Result.UserDefined.Before.setFromType(QualType());
5078       Result.UserDefined.Before.setAllToTypes(QualType());
5079 
5080       Result.UserDefined.After.setAsIdentityConversion();
5081       Result.UserDefined.After.setFromType(ToType);
5082       Result.UserDefined.After.setAllToTypes(ToType);
5083       Result.UserDefined.ConversionFunction = nullptr;
5084     }
5085     return Result;
5086   }
5087 
5088   // C++14 [over.ics.list]p6:
5089   // C++11 [over.ics.list]p5:
5090   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5091   if (ToType->isReferenceType()) {
5092     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5093     // mention initializer lists in any way. So we go by what list-
5094     // initialization would do and try to extrapolate from that.
5095 
5096     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5097 
5098     // If the initializer list has a single element that is reference-related
5099     // to the parameter type, we initialize the reference from that.
5100     if (From->getNumInits() == 1) {
5101       Expr *Init = From->getInit(0);
5102 
5103       QualType T2 = Init->getType();
5104 
5105       // If the initializer is the address of an overloaded function, try
5106       // to resolve the overloaded function. If all goes well, T2 is the
5107       // type of the resulting function.
5108       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5109         DeclAccessPair Found;
5110         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5111                                    Init, ToType, false, Found))
5112           T2 = Fn->getType();
5113       }
5114 
5115       // Compute some basic properties of the types and the initializer.
5116       Sema::ReferenceCompareResult RefRelationship =
5117           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5118 
5119       if (RefRelationship >= Sema::Ref_Related) {
5120         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5121                                 SuppressUserConversions,
5122                                 /*AllowExplicit=*/false);
5123       }
5124     }
5125 
5126     // Otherwise, we bind the reference to a temporary created from the
5127     // initializer list.
5128     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5129                                InOverloadResolution,
5130                                AllowObjCWritebackConversion);
5131     if (Result.isFailure())
5132       return Result;
5133     assert(!Result.isEllipsis() &&
5134            "Sub-initialization cannot result in ellipsis conversion.");
5135 
5136     // Can we even bind to a temporary?
5137     if (ToType->isRValueReferenceType() ||
5138         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5139       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5140                                             Result.UserDefined.After;
5141       SCS.ReferenceBinding = true;
5142       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5143       SCS.BindsToRvalue = true;
5144       SCS.BindsToFunctionLvalue = false;
5145       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5146       SCS.ObjCLifetimeConversionBinding = false;
5147     } else
5148       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5149                     From, ToType);
5150     return Result;
5151   }
5152 
5153   // C++14 [over.ics.list]p7:
5154   // C++11 [over.ics.list]p6:
5155   //   Otherwise, if the parameter type is not a class:
5156   if (!ToType->isRecordType()) {
5157     //    - if the initializer list has one element that is not itself an
5158     //      initializer list, the implicit conversion sequence is the one
5159     //      required to convert the element to the parameter type.
5160     unsigned NumInits = From->getNumInits();
5161     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5162       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5163                                      SuppressUserConversions,
5164                                      InOverloadResolution,
5165                                      AllowObjCWritebackConversion);
5166     //    - if the initializer list has no elements, the implicit conversion
5167     //      sequence is the identity conversion.
5168     else if (NumInits == 0) {
5169       Result.setAsIdentityConversion(ToType);
5170     }
5171     return Result;
5172   }
5173 
5174   // C++14 [over.ics.list]p8:
5175   // C++11 [over.ics.list]p7:
5176   //   In all cases other than those enumerated above, no conversion is possible
5177   return Result;
5178 }
5179 
5180 /// TryCopyInitialization - Try to copy-initialize a value of type
5181 /// ToType from the expression From. Return the implicit conversion
5182 /// sequence required to pass this argument, which may be a bad
5183 /// conversion sequence (meaning that the argument cannot be passed to
5184 /// a parameter of this type). If @p SuppressUserConversions, then we
5185 /// do not permit any user-defined conversion sequences.
5186 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)5187 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5188                       bool SuppressUserConversions,
5189                       bool InOverloadResolution,
5190                       bool AllowObjCWritebackConversion,
5191                       bool AllowExplicit) {
5192   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5193     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5194                              InOverloadResolution,AllowObjCWritebackConversion);
5195 
5196   if (ToType->isReferenceType())
5197     return TryReferenceInit(S, From, ToType,
5198                             /*FIXME:*/ From->getBeginLoc(),
5199                             SuppressUserConversions, AllowExplicit);
5200 
5201   return TryImplicitConversion(S, From, ToType,
5202                                SuppressUserConversions,
5203                                AllowedExplicit::None,
5204                                InOverloadResolution,
5205                                /*CStyle=*/false,
5206                                AllowObjCWritebackConversion,
5207                                /*AllowObjCConversionOnExplicit=*/false);
5208 }
5209 
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)5210 static bool TryCopyInitialization(const CanQualType FromQTy,
5211                                   const CanQualType ToQTy,
5212                                   Sema &S,
5213                                   SourceLocation Loc,
5214                                   ExprValueKind FromVK) {
5215   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5216   ImplicitConversionSequence ICS =
5217     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5218 
5219   return !ICS.isBad();
5220 }
5221 
5222 /// TryObjectArgumentInitialization - Try to initialize the object
5223 /// parameter of the given member function (@c Method) from the
5224 /// expression @p From.
5225 static ImplicitConversionSequence
TryObjectArgumentInitialization(Sema & S,SourceLocation Loc,QualType FromType,Expr::Classification FromClassification,CXXMethodDecl * Method,CXXRecordDecl * ActingContext)5226 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5227                                 Expr::Classification FromClassification,
5228                                 CXXMethodDecl *Method,
5229                                 CXXRecordDecl *ActingContext) {
5230   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5231   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5232   //                 const volatile object.
5233   Qualifiers Quals = Method->getMethodQualifiers();
5234   if (isa<CXXDestructorDecl>(Method)) {
5235     Quals.addConst();
5236     Quals.addVolatile();
5237   }
5238 
5239   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5240 
5241   // Set up the conversion sequence as a "bad" conversion, to allow us
5242   // to exit early.
5243   ImplicitConversionSequence ICS;
5244 
5245   // We need to have an object of class type.
5246   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5247     FromType = PT->getPointeeType();
5248 
5249     // When we had a pointer, it's implicitly dereferenced, so we
5250     // better have an lvalue.
5251     assert(FromClassification.isLValue());
5252   }
5253 
5254   assert(FromType->isRecordType());
5255 
5256   // C++0x [over.match.funcs]p4:
5257   //   For non-static member functions, the type of the implicit object
5258   //   parameter is
5259   //
5260   //     - "lvalue reference to cv X" for functions declared without a
5261   //        ref-qualifier or with the & ref-qualifier
5262   //     - "rvalue reference to cv X" for functions declared with the &&
5263   //        ref-qualifier
5264   //
5265   // where X is the class of which the function is a member and cv is the
5266   // cv-qualification on the member function declaration.
5267   //
5268   // However, when finding an implicit conversion sequence for the argument, we
5269   // are not allowed to perform user-defined conversions
5270   // (C++ [over.match.funcs]p5). We perform a simplified version of
5271   // reference binding here, that allows class rvalues to bind to
5272   // non-constant references.
5273 
5274   // First check the qualifiers.
5275   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5276   if (ImplicitParamType.getCVRQualifiers()
5277                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5278       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5279     ICS.setBad(BadConversionSequence::bad_qualifiers,
5280                FromType, ImplicitParamType);
5281     return ICS;
5282   }
5283 
5284   if (FromTypeCanon.hasAddressSpace()) {
5285     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5286     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5287     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5288       ICS.setBad(BadConversionSequence::bad_qualifiers,
5289                  FromType, ImplicitParamType);
5290       return ICS;
5291     }
5292   }
5293 
5294   // Check that we have either the same type or a derived type. It
5295   // affects the conversion rank.
5296   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5297   ImplicitConversionKind SecondKind;
5298   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5299     SecondKind = ICK_Identity;
5300   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5301     SecondKind = ICK_Derived_To_Base;
5302   else {
5303     ICS.setBad(BadConversionSequence::unrelated_class,
5304                FromType, ImplicitParamType);
5305     return ICS;
5306   }
5307 
5308   // Check the ref-qualifier.
5309   switch (Method->getRefQualifier()) {
5310   case RQ_None:
5311     // Do nothing; we don't care about lvalueness or rvalueness.
5312     break;
5313 
5314   case RQ_LValue:
5315     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5316       // non-const lvalue reference cannot bind to an rvalue
5317       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5318                  ImplicitParamType);
5319       return ICS;
5320     }
5321     break;
5322 
5323   case RQ_RValue:
5324     if (!FromClassification.isRValue()) {
5325       // rvalue reference cannot bind to an lvalue
5326       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5327                  ImplicitParamType);
5328       return ICS;
5329     }
5330     break;
5331   }
5332 
5333   // Success. Mark this as a reference binding.
5334   // XXXAR: FIXME: DO CHERI CHECK
5335   ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
5336   ICS.Standard.setAsIdentityConversion();
5337   ICS.Standard.Second = SecondKind;
5338   ICS.Standard.setFromType(FromType);
5339   ICS.Standard.setAllToTypes(ImplicitParamType);
5340   ICS.Standard.ReferenceBinding = true;
5341   ICS.Standard.DirectBinding = true;
5342   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5343   ICS.Standard.BindsToFunctionLvalue = false;
5344   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5345   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5346     = (Method->getRefQualifier() == RQ_None);
5347   return ICS;
5348 }
5349 
5350 /// PerformObjectArgumentInitialization - Perform initialization of
5351 /// the implicit object parameter for the given Method with the given
5352 /// expression.
5353 ExprResult
PerformObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)5354 Sema::PerformObjectArgumentInitialization(Expr *From,
5355                                           NestedNameSpecifier *Qualifier,
5356                                           NamedDecl *FoundDecl,
5357                                           CXXMethodDecl *Method) {
5358   QualType FromRecordType, DestType;
5359   QualType ImplicitParamRecordType  =
5360     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5361 
5362   Expr::Classification FromClassification;
5363   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5364     FromRecordType = PT->getPointeeType();
5365     DestType = Method->getThisType();
5366     FromClassification = Expr::Classification::makeSimpleLValue();
5367   } else {
5368     FromRecordType = From->getType();
5369     DestType = ImplicitParamRecordType;
5370     FromClassification = From->Classify(Context);
5371 
5372     // When performing member access on an rvalue, materialize a temporary.
5373     if (From->isRValue()) {
5374       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5375                                             Method->getRefQualifier() !=
5376                                                 RefQualifierKind::RQ_RValue);
5377     }
5378   }
5379 
5380   // Note that we always use the true parent context when performing
5381   // the actual argument initialization.
5382   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5383       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5384       Method->getParent());
5385   if (ICS.isBad()) {
5386     switch (ICS.Bad.Kind) {
5387     case BadConversionSequence::bad_qualifiers: {
5388       Qualifiers FromQs = FromRecordType.getQualifiers();
5389       Qualifiers ToQs = DestType.getQualifiers();
5390       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5391       if (CVR) {
5392         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5393             << Method->getDeclName() << FromRecordType << (CVR - 1)
5394             << From->getSourceRange();
5395         Diag(Method->getLocation(), diag::note_previous_decl)
5396           << Method->getDeclName();
5397         return ExprError();
5398       }
5399       break;
5400     }
5401 
5402     case BadConversionSequence::lvalue_ref_to_rvalue:
5403     case BadConversionSequence::rvalue_ref_to_lvalue: {
5404       bool IsRValueQualified =
5405         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5406       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5407           << Method->getDeclName() << FromClassification.isRValue()
5408           << IsRValueQualified;
5409       Diag(Method->getLocation(), diag::note_previous_decl)
5410         << Method->getDeclName();
5411       return ExprError();
5412     }
5413 
5414     case BadConversionSequence::no_conversion:
5415     case BadConversionSequence::unrelated_class:
5416       break;
5417     }
5418 
5419     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5420            << ImplicitParamRecordType << FromRecordType
5421            << From->getSourceRange();
5422   }
5423 
5424   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5425     ExprResult FromRes =
5426       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5427     if (FromRes.isInvalid())
5428       return ExprError();
5429     From = FromRes.get();
5430   }
5431 
5432   if (!Context.hasSameType(From->getType(), DestType)) {
5433     CastKind CK;
5434     QualType PteeTy = DestType->getPointeeType();
5435     LangAS DestAS =
5436         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5437     if (FromRecordType.getAddressSpace() != DestAS)
5438       CK = CK_AddressSpaceConversion;
5439     else
5440       CK = CK_NoOp;
5441     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5442   }
5443   return From;
5444 }
5445 
5446 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5447 /// expression From to bool (C++0x [conv]p3).
5448 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)5449 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5450   // C++ [dcl.init]/17.8:
5451   //   - Otherwise, if the initialization is direct-initialization, the source
5452   //     type is std::nullptr_t, and the destination type is bool, the initial
5453   //     value of the object being initialized is false.
5454   if (From->getType()->isNullPtrType())
5455     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5456                                                         S.Context.BoolTy,
5457                                                         From->isGLValue());
5458 
5459   // All other direct-initialization of bool is equivalent to an implicit
5460   // conversion to bool in which explicit conversions are permitted.
5461   return TryImplicitConversion(S, From, S.Context.BoolTy,
5462                                /*SuppressUserConversions=*/false,
5463                                AllowedExplicit::Conversions,
5464                                /*InOverloadResolution=*/false,
5465                                /*CStyle=*/false,
5466                                /*AllowObjCWritebackConversion=*/false,
5467                                /*AllowObjCConversionOnExplicit=*/false);
5468 }
5469 
5470 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5471 /// of the expression From to bool (C++0x [conv]p3).
PerformContextuallyConvertToBool(Expr * From)5472 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5473   if (checkPlaceholderForOverload(*this, From))
5474     return ExprError();
5475 
5476   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5477   if (!ICS.isBad())
5478     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5479 
5480   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5481     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5482            << From->getType() << From->getSourceRange();
5483   return ExprError();
5484 }
5485 
5486 /// Check that the specified conversion is permitted in a converted constant
5487 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5488 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)5489 static bool CheckConvertedConstantConversions(Sema &S,
5490                                               StandardConversionSequence &SCS) {
5491   // Since we know that the target type is an integral or unscoped enumeration
5492   // type, most conversion kinds are impossible. All possible First and Third
5493   // conversions are fine.
5494   switch (SCS.Second) {
5495   case ICK_Identity:
5496   case ICK_Function_Conversion:
5497   case ICK_Integral_Promotion:
5498   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5499   case ICK_Zero_Queue_Conversion:
5500     return true;
5501 
5502   case ICK_Boolean_Conversion:
5503     // Conversion from an integral or unscoped enumeration type to bool is
5504     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5505     // conversion, so we allow it in a converted constant expression.
5506     //
5507     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5508     // a lot of popular code. We should at least add a warning for this
5509     // (non-conforming) extension.
5510     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5511            SCS.getToType(2)->isBooleanType();
5512 
5513   case ICK_Pointer_Conversion:
5514   case ICK_Pointer_Member:
5515     // C++1z: null pointer conversions and null member pointer conversions are
5516     // only permitted if the source type is std::nullptr_t.
5517     return SCS.getFromType()->isNullPtrType();
5518 
5519   case ICK_Floating_Promotion:
5520   case ICK_Complex_Promotion:
5521   case ICK_Floating_Conversion:
5522   case ICK_Complex_Conversion:
5523   case ICK_Floating_Integral:
5524   case ICK_Compatible_Conversion:
5525   case ICK_Derived_To_Base:
5526   case ICK_Vector_Conversion:
5527   case ICK_Vector_Splat:
5528   case ICK_Complex_Real:
5529   case ICK_Block_Pointer_Conversion:
5530   case ICK_TransparentUnionConversion:
5531   case ICK_Writeback_Conversion:
5532   case ICK_Zero_Event_Conversion:
5533   case ICK_C_Only_Conversion:
5534   case ICK_Incompatible_Pointer_Conversion:
5535     return false;
5536 
5537   case ICK_Lvalue_To_Rvalue:
5538   case ICK_Array_To_Pointer:
5539   case ICK_Function_To_Pointer:
5540     llvm_unreachable("found a first conversion kind in Second");
5541 
5542   case ICK_Qualification:
5543     llvm_unreachable("found a third conversion kind in Second");
5544 
5545   case ICK_Num_Conversion_Kinds:
5546     break;
5547   }
5548 
5549   llvm_unreachable("unknown conversion kind");
5550 }
5551 
5552 /// CheckConvertedConstantExpression - Check that the expression From is a
5553 /// converted constant expression of type T, perform the conversion and produce
5554 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Sema & S,Expr * From,QualType T,APValue & Value,Sema::CCEKind CCE,bool RequireInt)5555 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5556                                                    QualType T, APValue &Value,
5557                                                    Sema::CCEKind CCE,
5558                                                    bool RequireInt) {
5559   assert(S.getLangOpts().CPlusPlus11 &&
5560          "converted constant expression outside C++11");
5561 
5562   if (checkPlaceholderForOverload(S, From))
5563     return ExprError();
5564 
5565   // C++1z [expr.const]p3:
5566   //  A converted constant expression of type T is an expression,
5567   //  implicitly converted to type T, where the converted
5568   //  expression is a constant expression and the implicit conversion
5569   //  sequence contains only [... list of conversions ...].
5570   // C++1z [stmt.if]p2:
5571   //  If the if statement is of the form if constexpr, the value of the
5572   //  condition shall be a contextually converted constant expression of type
5573   //  bool.
5574   ImplicitConversionSequence ICS =
5575       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5576           ? TryContextuallyConvertToBool(S, From)
5577           : TryCopyInitialization(S, From, T,
5578                                   /*SuppressUserConversions=*/false,
5579                                   /*InOverloadResolution=*/false,
5580                                   /*AllowObjCWritebackConversion=*/false,
5581                                   /*AllowExplicit=*/false);
5582   StandardConversionSequence *SCS = nullptr;
5583   switch (ICS.getKind()) {
5584   case ImplicitConversionSequence::StandardConversion:
5585     SCS = &ICS.Standard;
5586     break;
5587   case ImplicitConversionSequence::UserDefinedConversion:
5588     // We are converting to a non-class type, so the Before sequence
5589     // must be trivial.
5590     SCS = &ICS.UserDefined.After;
5591     break;
5592   case ImplicitConversionSequence::AmbiguousConversion:
5593   case ImplicitConversionSequence::BadConversion:
5594     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5595       return S.Diag(From->getBeginLoc(),
5596                     diag::err_typecheck_converted_constant_expression)
5597              << From->getType() << From->getSourceRange() << T;
5598     return ExprError();
5599 
5600   case ImplicitConversionSequence::EllipsisConversion:
5601     llvm_unreachable("ellipsis conversion in converted constant expression");
5602   }
5603 
5604   // Check that we would only use permitted conversions.
5605   if (!CheckConvertedConstantConversions(S, *SCS)) {
5606     return S.Diag(From->getBeginLoc(),
5607                   diag::err_typecheck_converted_constant_expression_disallowed)
5608            << From->getType() << From->getSourceRange() << T;
5609   }
5610   // [...] and where the reference binding (if any) binds directly.
5611   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5612     return S.Diag(From->getBeginLoc(),
5613                   diag::err_typecheck_converted_constant_expression_indirect)
5614            << From->getType() << From->getSourceRange() << T;
5615   }
5616 
5617   ExprResult Result =
5618       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5619   if (Result.isInvalid())
5620     return Result;
5621 
5622   // C++2a [intro.execution]p5:
5623   //   A full-expression is [...] a constant-expression [...]
5624   Result =
5625       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5626                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5627   if (Result.isInvalid())
5628     return Result;
5629 
5630   // Check for a narrowing implicit conversion.
5631   APValue PreNarrowingValue;
5632   QualType PreNarrowingType;
5633   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5634                                 PreNarrowingType)) {
5635   case NK_Dependent_Narrowing:
5636     // Implicit conversion to a narrower type, but the expression is
5637     // value-dependent so we can't tell whether it's actually narrowing.
5638   case NK_Variable_Narrowing:
5639     // Implicit conversion to a narrower type, and the value is not a constant
5640     // expression. We'll diagnose this in a moment.
5641   case NK_Not_Narrowing:
5642     break;
5643 
5644   case NK_Constant_Narrowing:
5645     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5646         << CCE << /*Constant*/ 1
5647         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5648     break;
5649 
5650   case NK_Type_Narrowing:
5651     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5652         << CCE << /*Constant*/ 0 << From->getType() << T;
5653     break;
5654   }
5655 
5656   if (Result.get()->isValueDependent()) {
5657     Value = APValue();
5658     return Result;
5659   }
5660 
5661   // Check the expression is a constant expression.
5662   SmallVector<PartialDiagnosticAt, 8> Notes;
5663   Expr::EvalResult Eval;
5664   Eval.Diag = &Notes;
5665   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5666                                    ? Expr::EvaluateForMangling
5667                                    : Expr::EvaluateForCodeGen;
5668 
5669   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5670       (RequireInt && !Eval.Val.isInt())) {
5671     // The expression can't be folded, so we can't keep it at this position in
5672     // the AST.
5673     Result = ExprError();
5674   } else {
5675     Value = Eval.Val;
5676 
5677     if (Notes.empty()) {
5678       // It's a constant expression.
5679       return ConstantExpr::Create(S.Context, Result.get(), Value);
5680     }
5681   }
5682 
5683   // It's not a constant expression. Produce an appropriate diagnostic.
5684   if (Notes.size() == 1 &&
5685       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5686     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5687   else {
5688     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5689         << CCE << From->getSourceRange();
5690     for (unsigned I = 0; I < Notes.size(); ++I)
5691       S.Diag(Notes[I].first, Notes[I].second);
5692   }
5693   return ExprError();
5694 }
5695 
CheckConvertedConstantExpression(Expr * From,QualType T,APValue & Value,CCEKind CCE)5696 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5697                                                   APValue &Value, CCEKind CCE) {
5698   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5699 }
5700 
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)5701 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5702                                                   llvm::APSInt &Value,
5703                                                   CCEKind CCE) {
5704   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5705 
5706   APValue V;
5707   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5708   if (!R.isInvalid() && !R.get()->isValueDependent())
5709     Value = V.getInt();
5710   return R;
5711 }
5712 
5713 
5714 /// dropPointerConversions - If the given standard conversion sequence
5715 /// involves any pointer conversions, remove them.  This may change
5716 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)5717 static void dropPointerConversion(StandardConversionSequence &SCS) {
5718   if (SCS.Second == ICK_Pointer_Conversion) {
5719     SCS.Second = ICK_Identity;
5720     SCS.Third = ICK_Identity;
5721     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5722   }
5723 }
5724 
5725 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5726 /// convert the expression From to an Objective-C pointer type.
5727 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)5728 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5729   // Do an implicit conversion to 'id'.
5730   QualType Ty = S.Context.getObjCIdType();
5731   ImplicitConversionSequence ICS
5732     = TryImplicitConversion(S, From, Ty,
5733                             // FIXME: Are these flags correct?
5734                             /*SuppressUserConversions=*/false,
5735                             AllowedExplicit::Conversions,
5736                             /*InOverloadResolution=*/false,
5737                             /*CStyle=*/false,
5738                             /*AllowObjCWritebackConversion=*/false,
5739                             /*AllowObjCConversionOnExplicit=*/true);
5740 
5741   // Strip off any final conversions to 'id'.
5742   switch (ICS.getKind()) {
5743   case ImplicitConversionSequence::BadConversion:
5744   case ImplicitConversionSequence::AmbiguousConversion:
5745   case ImplicitConversionSequence::EllipsisConversion:
5746     break;
5747 
5748   case ImplicitConversionSequence::UserDefinedConversion:
5749     dropPointerConversion(ICS.UserDefined.After);
5750     break;
5751 
5752   case ImplicitConversionSequence::StandardConversion:
5753     dropPointerConversion(ICS.Standard);
5754     break;
5755   }
5756 
5757   return ICS;
5758 }
5759 
5760 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5761 /// conversion of the expression From to an Objective-C pointer type.
5762 /// Returns a valid but null ExprResult if no conversion sequence exists.
PerformContextuallyConvertToObjCPointer(Expr * From)5763 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5764   if (checkPlaceholderForOverload(*this, From))
5765     return ExprError();
5766 
5767   QualType Ty = Context.getObjCIdType();
5768   ImplicitConversionSequence ICS =
5769     TryContextuallyConvertToObjCPointer(*this, From);
5770   if (!ICS.isBad())
5771     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5772   return ExprResult();
5773 }
5774 
5775 /// Determine whether the provided type is an integral type, or an enumeration
5776 /// type of a permitted flavor.
match(QualType T)5777 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5778   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5779                                  : T->isIntegralOrUnscopedEnumerationType();
5780 }
5781 
5782 static ExprResult
diagnoseAmbiguousConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter,QualType T,UnresolvedSetImpl & ViableConversions)5783 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5784                             Sema::ContextualImplicitConverter &Converter,
5785                             QualType T, UnresolvedSetImpl &ViableConversions) {
5786 
5787   if (Converter.Suppress)
5788     return ExprError();
5789 
5790   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5791   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5792     CXXConversionDecl *Conv =
5793         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5794     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5795     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5796   }
5797   return From;
5798 }
5799 
5800 static bool
diagnoseNoViableConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,UnresolvedSetImpl & ExplicitConversions)5801 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5802                            Sema::ContextualImplicitConverter &Converter,
5803                            QualType T, bool HadMultipleCandidates,
5804                            UnresolvedSetImpl &ExplicitConversions) {
5805   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5806     DeclAccessPair Found = ExplicitConversions[0];
5807     CXXConversionDecl *Conversion =
5808         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5809 
5810     // The user probably meant to invoke the given explicit
5811     // conversion; use it.
5812     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5813     std::string TypeStr;
5814     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5815 
5816     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5817         << FixItHint::CreateInsertion(From->getBeginLoc(),
5818                                       "static_cast<" + TypeStr + ">(")
5819         << FixItHint::CreateInsertion(
5820                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5821     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5822 
5823     // If we aren't in a SFINAE context, build a call to the
5824     // explicit conversion function.
5825     if (SemaRef.isSFINAEContext())
5826       return true;
5827 
5828     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5829     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5830                                                        HadMultipleCandidates);
5831     if (Result.isInvalid())
5832       return true;
5833     // Record usage of conversion in an implicit cast.
5834     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5835                                     CK_UserDefinedConversion, Result.get(),
5836                                     nullptr, Result.get()->getValueKind());
5837   }
5838   return false;
5839 }
5840 
recordConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,DeclAccessPair & Found)5841 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5842                              Sema::ContextualImplicitConverter &Converter,
5843                              QualType T, bool HadMultipleCandidates,
5844                              DeclAccessPair &Found) {
5845   CXXConversionDecl *Conversion =
5846       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5847   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5848 
5849   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5850   if (!Converter.SuppressConversion) {
5851     if (SemaRef.isSFINAEContext())
5852       return true;
5853 
5854     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5855         << From->getSourceRange();
5856   }
5857 
5858   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5859                                                      HadMultipleCandidates);
5860   if (Result.isInvalid())
5861     return true;
5862   // Record usage of conversion in an implicit cast.
5863   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5864                                   CK_UserDefinedConversion, Result.get(),
5865                                   nullptr, Result.get()->getValueKind());
5866   return false;
5867 }
5868 
finishContextualImplicitConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter)5869 static ExprResult finishContextualImplicitConversion(
5870     Sema &SemaRef, SourceLocation Loc, Expr *From,
5871     Sema::ContextualImplicitConverter &Converter) {
5872   if (!Converter.match(From->getType()) && !Converter.Suppress)
5873     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5874         << From->getSourceRange();
5875 
5876   return SemaRef.DefaultLvalueConversion(From);
5877 }
5878 
5879 static void
collectViableConversionCandidates(Sema & SemaRef,Expr * From,QualType ToType,UnresolvedSetImpl & ViableConversions,OverloadCandidateSet & CandidateSet)5880 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5881                                   UnresolvedSetImpl &ViableConversions,
5882                                   OverloadCandidateSet &CandidateSet) {
5883   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5884     DeclAccessPair FoundDecl = ViableConversions[I];
5885     NamedDecl *D = FoundDecl.getDecl();
5886     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5887     if (isa<UsingShadowDecl>(D))
5888       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5889 
5890     CXXConversionDecl *Conv;
5891     FunctionTemplateDecl *ConvTemplate;
5892     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5893       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5894     else
5895       Conv = cast<CXXConversionDecl>(D);
5896 
5897     if (ConvTemplate)
5898       SemaRef.AddTemplateConversionCandidate(
5899           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5900           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5901     else
5902       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5903                                      ToType, CandidateSet,
5904                                      /*AllowObjCConversionOnExplicit=*/false,
5905                                      /*AllowExplicit*/ true);
5906   }
5907 }
5908 
5909 /// Attempt to convert the given expression to a type which is accepted
5910 /// by the given converter.
5911 ///
5912 /// This routine will attempt to convert an expression of class type to a
5913 /// type accepted by the specified converter. In C++11 and before, the class
5914 /// must have a single non-explicit conversion function converting to a matching
5915 /// type. In C++1y, there can be multiple such conversion functions, but only
5916 /// one target type.
5917 ///
5918 /// \param Loc The source location of the construct that requires the
5919 /// conversion.
5920 ///
5921 /// \param From The expression we're converting from.
5922 ///
5923 /// \param Converter Used to control and diagnose the conversion process.
5924 ///
5925 /// \returns The expression, converted to an integral or enumeration type if
5926 /// successful.
PerformContextualImplicitConversion(SourceLocation Loc,Expr * From,ContextualImplicitConverter & Converter)5927 ExprResult Sema::PerformContextualImplicitConversion(
5928     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5929   // We can't perform any more checking for type-dependent expressions.
5930   if (From->isTypeDependent())
5931     return From;
5932 
5933   // Process placeholders immediately.
5934   if (From->hasPlaceholderType()) {
5935     ExprResult result = CheckPlaceholderExpr(From);
5936     if (result.isInvalid())
5937       return result;
5938     From = result.get();
5939   }
5940 
5941   // If the expression already has a matching type, we're golden.
5942   QualType T = From->getType();
5943   if (Converter.match(T))
5944     return DefaultLvalueConversion(From);
5945 
5946   // FIXME: Check for missing '()' if T is a function type?
5947 
5948   // We can only perform contextual implicit conversions on objects of class
5949   // type.
5950   const RecordType *RecordTy = T->getAs<RecordType>();
5951   if (!RecordTy || !getLangOpts().CPlusPlus) {
5952     if (!Converter.Suppress)
5953       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5954     return From;
5955   }
5956 
5957   // We must have a complete class type.
5958   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5959     ContextualImplicitConverter &Converter;
5960     Expr *From;
5961 
5962     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5963         : Converter(Converter), From(From) {}
5964 
5965     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5966       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5967     }
5968   } IncompleteDiagnoser(Converter, From);
5969 
5970   if (Converter.Suppress ? !isCompleteType(Loc, T)
5971                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5972     return From;
5973 
5974   // Look for a conversion to an integral or enumeration type.
5975   UnresolvedSet<4>
5976       ViableConversions; // These are *potentially* viable in C++1y.
5977   UnresolvedSet<4> ExplicitConversions;
5978   const auto &Conversions =
5979       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5980 
5981   bool HadMultipleCandidates =
5982       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5983 
5984   // To check that there is only one target type, in C++1y:
5985   QualType ToType;
5986   bool HasUniqueTargetType = true;
5987 
5988   // Collect explicit or viable (potentially in C++1y) conversions.
5989   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5990     NamedDecl *D = (*I)->getUnderlyingDecl();
5991     CXXConversionDecl *Conversion;
5992     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5993     if (ConvTemplate) {
5994       if (getLangOpts().CPlusPlus14)
5995         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5996       else
5997         continue; // C++11 does not consider conversion operator templates(?).
5998     } else
5999       Conversion = cast<CXXConversionDecl>(D);
6000 
6001     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6002            "Conversion operator templates are considered potentially "
6003            "viable in C++1y");
6004 
6005     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6006     if (Converter.match(CurToType) || ConvTemplate) {
6007 
6008       if (Conversion->isExplicit()) {
6009         // FIXME: For C++1y, do we need this restriction?
6010         // cf. diagnoseNoViableConversion()
6011         if (!ConvTemplate)
6012           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6013       } else {
6014         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6015           if (ToType.isNull())
6016             ToType = CurToType.getUnqualifiedType();
6017           else if (HasUniqueTargetType &&
6018                    (CurToType.getUnqualifiedType() != ToType))
6019             HasUniqueTargetType = false;
6020         }
6021         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6022       }
6023     }
6024   }
6025 
6026   if (getLangOpts().CPlusPlus14) {
6027     // C++1y [conv]p6:
6028     // ... An expression e of class type E appearing in such a context
6029     // is said to be contextually implicitly converted to a specified
6030     // type T and is well-formed if and only if e can be implicitly
6031     // converted to a type T that is determined as follows: E is searched
6032     // for conversion functions whose return type is cv T or reference to
6033     // cv T such that T is allowed by the context. There shall be
6034     // exactly one such T.
6035 
6036     // If no unique T is found:
6037     if (ToType.isNull()) {
6038       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6039                                      HadMultipleCandidates,
6040                                      ExplicitConversions))
6041         return ExprError();
6042       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6043     }
6044 
6045     // If more than one unique Ts are found:
6046     if (!HasUniqueTargetType)
6047       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6048                                          ViableConversions);
6049 
6050     // If one unique T is found:
6051     // First, build a candidate set from the previously recorded
6052     // potentially viable conversions.
6053     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6054     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6055                                       CandidateSet);
6056 
6057     // Then, perform overload resolution over the candidate set.
6058     OverloadCandidateSet::iterator Best;
6059     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6060     case OR_Success: {
6061       // Apply this conversion.
6062       DeclAccessPair Found =
6063           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6064       if (recordConversion(*this, Loc, From, Converter, T,
6065                            HadMultipleCandidates, Found))
6066         return ExprError();
6067       break;
6068     }
6069     case OR_Ambiguous:
6070       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6071                                          ViableConversions);
6072     case OR_No_Viable_Function:
6073       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6074                                      HadMultipleCandidates,
6075                                      ExplicitConversions))
6076         return ExprError();
6077       LLVM_FALLTHROUGH;
6078     case OR_Deleted:
6079       // We'll complain below about a non-integral condition type.
6080       break;
6081     }
6082   } else {
6083     switch (ViableConversions.size()) {
6084     case 0: {
6085       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6086                                      HadMultipleCandidates,
6087                                      ExplicitConversions))
6088         return ExprError();
6089 
6090       // We'll complain below about a non-integral condition type.
6091       break;
6092     }
6093     case 1: {
6094       // Apply this conversion.
6095       DeclAccessPair Found = ViableConversions[0];
6096       if (recordConversion(*this, Loc, From, Converter, T,
6097                            HadMultipleCandidates, Found))
6098         return ExprError();
6099       break;
6100     }
6101     default:
6102       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6103                                          ViableConversions);
6104     }
6105   }
6106 
6107   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6108 }
6109 
6110 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6111 /// an acceptable non-member overloaded operator for a call whose
6112 /// arguments have types T1 (and, if non-empty, T2). This routine
6113 /// implements the check in C++ [over.match.oper]p3b2 concerning
6114 /// enumeration types.
IsAcceptableNonMemberOperatorCandidate(ASTContext & Context,FunctionDecl * Fn,ArrayRef<Expr * > Args)6115 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6116                                                    FunctionDecl *Fn,
6117                                                    ArrayRef<Expr *> Args) {
6118   QualType T1 = Args[0]->getType();
6119   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6120 
6121   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6122     return true;
6123 
6124   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6125     return true;
6126 
6127   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6128   if (Proto->getNumParams() < 1)
6129     return false;
6130 
6131   if (T1->isEnumeralType()) {
6132     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6133     if (Context.hasSameUnqualifiedType(T1, ArgType))
6134       return true;
6135   }
6136 
6137   if (Proto->getNumParams() < 2)
6138     return false;
6139 
6140   if (!T2.isNull() && T2->isEnumeralType()) {
6141     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6142     if (Context.hasSameUnqualifiedType(T2, ArgType))
6143       return true;
6144   }
6145 
6146   return false;
6147 }
6148 
6149 /// AddOverloadCandidate - Adds the given function to the set of
6150 /// candidate functions, using the given function call arguments.  If
6151 /// @p SuppressUserConversions, then don't allow user-defined
6152 /// conversions via constructors or conversion operators.
6153 ///
6154 /// \param PartialOverloading true if we are performing "partial" overloading
6155 /// based on an incomplete set of function arguments. This feature is used by
6156 /// code completion.
AddOverloadCandidate(FunctionDecl * Function,DeclAccessPair FoundDecl,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit,bool AllowExplicitConversions,ADLCallKind IsADLCandidate,ConversionSequenceList EarlyConversions,OverloadCandidateParamOrder PO)6157 void Sema::AddOverloadCandidate(
6158     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6159     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6160     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6161     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6162     OverloadCandidateParamOrder PO) {
6163   const FunctionProtoType *Proto
6164     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6165   assert(Proto && "Functions without a prototype cannot be overloaded");
6166   assert(!Function->getDescribedFunctionTemplate() &&
6167          "Use AddTemplateOverloadCandidate for function templates");
6168 
6169   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6170     if (!isa<CXXConstructorDecl>(Method)) {
6171       // If we get here, it's because we're calling a member function
6172       // that is named without a member access expression (e.g.,
6173       // "this->f") that was either written explicitly or created
6174       // implicitly. This can happen with a qualified call to a member
6175       // function, e.g., X::f(). We use an empty type for the implied
6176       // object argument (C++ [over.call.func]p3), and the acting context
6177       // is irrelevant.
6178       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6179                          Expr::Classification::makeSimpleLValue(), Args,
6180                          CandidateSet, SuppressUserConversions,
6181                          PartialOverloading, EarlyConversions, PO);
6182       return;
6183     }
6184     // We treat a constructor like a non-member function, since its object
6185     // argument doesn't participate in overload resolution.
6186   }
6187 
6188   if (!CandidateSet.isNewCandidate(Function, PO))
6189     return;
6190 
6191   // C++11 [class.copy]p11: [DR1402]
6192   //   A defaulted move constructor that is defined as deleted is ignored by
6193   //   overload resolution.
6194   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6195   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6196       Constructor->isMoveConstructor())
6197     return;
6198 
6199   // Overload resolution is always an unevaluated context.
6200   EnterExpressionEvaluationContext Unevaluated(
6201       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6202 
6203   // C++ [over.match.oper]p3:
6204   //   if no operand has a class type, only those non-member functions in the
6205   //   lookup set that have a first parameter of type T1 or "reference to
6206   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6207   //   is a right operand) a second parameter of type T2 or "reference to
6208   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6209   //   candidate functions.
6210   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6211       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6212     return;
6213 
6214   // Add this candidate
6215   OverloadCandidate &Candidate =
6216       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6217   Candidate.FoundDecl = FoundDecl;
6218   Candidate.Function = Function;
6219   Candidate.Viable = true;
6220   Candidate.RewriteKind =
6221       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6222   Candidate.IsSurrogate = false;
6223   Candidate.IsADLCandidate = IsADLCandidate;
6224   Candidate.IgnoreObjectArgument = false;
6225   Candidate.ExplicitCallArguments = Args.size();
6226 
6227   // Explicit functions are not actually candidates at all if we're not
6228   // allowing them in this context, but keep them around so we can point
6229   // to them in diagnostics.
6230   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6231     Candidate.Viable = false;
6232     Candidate.FailureKind = ovl_fail_explicit;
6233     return;
6234   }
6235 
6236   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6237       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6238     Candidate.Viable = false;
6239     Candidate.FailureKind = ovl_non_default_multiversion_function;
6240     return;
6241   }
6242 
6243   if (Constructor) {
6244     // C++ [class.copy]p3:
6245     //   A member function template is never instantiated to perform the copy
6246     //   of a class object to an object of its class type.
6247     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6248     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6249         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6250          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6251                        ClassType))) {
6252       Candidate.Viable = false;
6253       Candidate.FailureKind = ovl_fail_illegal_constructor;
6254       return;
6255     }
6256 
6257     // C++ [over.match.funcs]p8: (proposed DR resolution)
6258     //   A constructor inherited from class type C that has a first parameter
6259     //   of type "reference to P" (including such a constructor instantiated
6260     //   from a template) is excluded from the set of candidate functions when
6261     //   constructing an object of type cv D if the argument list has exactly
6262     //   one argument and D is reference-related to P and P is reference-related
6263     //   to C.
6264     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6265     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6266         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6267       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6268       QualType C = Context.getRecordType(Constructor->getParent());
6269       QualType D = Context.getRecordType(Shadow->getParent());
6270       SourceLocation Loc = Args.front()->getExprLoc();
6271       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6272           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6273         Candidate.Viable = false;
6274         Candidate.FailureKind = ovl_fail_inhctor_slice;
6275         return;
6276       }
6277     }
6278 
6279     // Check that the constructor is capable of constructing an object in the
6280     // destination address space.
6281     if (!Qualifiers::isAddressSpaceSupersetOf(
6282             Constructor->getMethodQualifiers().getAddressSpace(),
6283             CandidateSet.getDestAS())) {
6284       Candidate.Viable = false;
6285       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6286     }
6287   }
6288 
6289   unsigned NumParams = Proto->getNumParams();
6290 
6291   // (C++ 13.3.2p2): A candidate function having fewer than m
6292   // parameters is viable only if it has an ellipsis in its parameter
6293   // list (8.3.5).
6294   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6295       !Proto->isVariadic()) {
6296     Candidate.Viable = false;
6297     Candidate.FailureKind = ovl_fail_too_many_arguments;
6298     return;
6299   }
6300 
6301   // (C++ 13.3.2p2): A candidate function having more than m parameters
6302   // is viable only if the (m+1)st parameter has a default argument
6303   // (8.3.6). For the purposes of overload resolution, the
6304   // parameter list is truncated on the right, so that there are
6305   // exactly m parameters.
6306   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6307   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6308     // Not enough arguments.
6309     Candidate.Viable = false;
6310     Candidate.FailureKind = ovl_fail_too_few_arguments;
6311     return;
6312   }
6313 
6314   // (CUDA B.1): Check for invalid calls between targets.
6315   if (getLangOpts().CUDA)
6316     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6317       // Skip the check for callers that are implicit members, because in this
6318       // case we may not yet know what the member's target is; the target is
6319       // inferred for the member automatically, based on the bases and fields of
6320       // the class.
6321       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6322         Candidate.Viable = false;
6323         Candidate.FailureKind = ovl_fail_bad_target;
6324         return;
6325       }
6326 
6327   if (Function->getTrailingRequiresClause()) {
6328     ConstraintSatisfaction Satisfaction;
6329     if (CheckFunctionConstraints(Function, Satisfaction) ||
6330         !Satisfaction.IsSatisfied) {
6331       Candidate.Viable = false;
6332       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6333       return;
6334     }
6335   }
6336 
6337   // Determine the implicit conversion sequences for each of the
6338   // arguments.
6339   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6340     unsigned ConvIdx =
6341         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6342     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6343       // We already formed a conversion sequence for this parameter during
6344       // template argument deduction.
6345     } else if (ArgIdx < NumParams) {
6346       // (C++ 13.3.2p3): for F to be a viable function, there shall
6347       // exist for each argument an implicit conversion sequence
6348       // (13.3.3.1) that converts that argument to the corresponding
6349       // parameter of F.
6350       QualType ParamType = Proto->getParamType(ArgIdx);
6351       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6352           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6353           /*InOverloadResolution=*/true,
6354           /*AllowObjCWritebackConversion=*/
6355           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6356       if (Candidate.Conversions[ConvIdx].isBad()) {
6357         Candidate.Viable = false;
6358         Candidate.FailureKind = ovl_fail_bad_conversion;
6359         return;
6360       }
6361     } else {
6362       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6363       // argument for which there is no corresponding parameter is
6364       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6365       Candidate.Conversions[ConvIdx].setEllipsis();
6366     }
6367   }
6368 
6369   if (EnableIfAttr *FailedAttr =
6370           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6371     Candidate.Viable = false;
6372     Candidate.FailureKind = ovl_fail_enable_if;
6373     Candidate.DeductionFailure.Data = FailedAttr;
6374     return;
6375   }
6376 
6377   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6378     Candidate.Viable = false;
6379     Candidate.FailureKind = ovl_fail_ext_disabled;
6380     return;
6381   }
6382 }
6383 
6384 ObjCMethodDecl *
SelectBestMethod(Selector Sel,MultiExprArg Args,bool IsInstance,SmallVectorImpl<ObjCMethodDecl * > & Methods)6385 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6386                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6387   if (Methods.size() <= 1)
6388     return nullptr;
6389 
6390   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6391     bool Match = true;
6392     ObjCMethodDecl *Method = Methods[b];
6393     unsigned NumNamedArgs = Sel.getNumArgs();
6394     // Method might have more arguments than selector indicates. This is due
6395     // to addition of c-style arguments in method.
6396     if (Method->param_size() > NumNamedArgs)
6397       NumNamedArgs = Method->param_size();
6398     if (Args.size() < NumNamedArgs)
6399       continue;
6400 
6401     for (unsigned i = 0; i < NumNamedArgs; i++) {
6402       // We can't do any type-checking on a type-dependent argument.
6403       if (Args[i]->isTypeDependent()) {
6404         Match = false;
6405         break;
6406       }
6407 
6408       ParmVarDecl *param = Method->parameters()[i];
6409       Expr *argExpr = Args[i];
6410       assert(argExpr && "SelectBestMethod(): missing expression");
6411 
6412       // Strip the unbridged-cast placeholder expression off unless it's
6413       // a consumed argument.
6414       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6415           !param->hasAttr<CFConsumedAttr>())
6416         argExpr = stripARCUnbridgedCast(argExpr);
6417 
6418       // If the parameter is __unknown_anytype, move on to the next method.
6419       if (param->getType() == Context.UnknownAnyTy) {
6420         Match = false;
6421         break;
6422       }
6423 
6424       ImplicitConversionSequence ConversionState
6425         = TryCopyInitialization(*this, argExpr, param->getType(),
6426                                 /*SuppressUserConversions*/false,
6427                                 /*InOverloadResolution=*/true,
6428                                 /*AllowObjCWritebackConversion=*/
6429                                 getLangOpts().ObjCAutoRefCount,
6430                                 /*AllowExplicit*/false);
6431       // This function looks for a reasonably-exact match, so we consider
6432       // incompatible pointer conversions to be a failure here.
6433       if (ConversionState.isBad() ||
6434           (ConversionState.isStandard() &&
6435            ConversionState.Standard.Second ==
6436                ICK_Incompatible_Pointer_Conversion)) {
6437         Match = false;
6438         break;
6439       }
6440     }
6441     // Promote additional arguments to variadic methods.
6442     if (Match && Method->isVariadic()) {
6443       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6444         if (Args[i]->isTypeDependent()) {
6445           Match = false;
6446           break;
6447         }
6448         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6449                                                           nullptr);
6450         if (Arg.isInvalid()) {
6451           Match = false;
6452           break;
6453         }
6454       }
6455     } else {
6456       // Check for extra arguments to non-variadic methods.
6457       if (Args.size() != NumNamedArgs)
6458         Match = false;
6459       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6460         // Special case when selectors have no argument. In this case, select
6461         // one with the most general result type of 'id'.
6462         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6463           QualType ReturnT = Methods[b]->getReturnType();
6464           if (ReturnT->isObjCIdType())
6465             return Methods[b];
6466         }
6467       }
6468     }
6469 
6470     if (Match)
6471       return Method;
6472   }
6473   return nullptr;
6474 }
6475 
convertArgsForAvailabilityChecks(Sema & S,FunctionDecl * Function,Expr * ThisArg,SourceLocation CallLoc,ArrayRef<Expr * > Args,Sema::SFINAETrap & Trap,bool MissingImplicitThis,Expr * & ConvertedThis,SmallVectorImpl<Expr * > & ConvertedArgs)6476 static bool convertArgsForAvailabilityChecks(
6477     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6478     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6479     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6480   if (ThisArg) {
6481     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6482     assert(!isa<CXXConstructorDecl>(Method) &&
6483            "Shouldn't have `this` for ctors!");
6484     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6485     ExprResult R = S.PerformObjectArgumentInitialization(
6486         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6487     if (R.isInvalid())
6488       return false;
6489     ConvertedThis = R.get();
6490   } else {
6491     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6492       (void)MD;
6493       assert((MissingImplicitThis || MD->isStatic() ||
6494               isa<CXXConstructorDecl>(MD)) &&
6495              "Expected `this` for non-ctor instance methods");
6496     }
6497     ConvertedThis = nullptr;
6498   }
6499 
6500   // Ignore any variadic arguments. Converting them is pointless, since the
6501   // user can't refer to them in the function condition.
6502   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6503 
6504   // Convert the arguments.
6505   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6506     ExprResult R;
6507     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6508                                         S.Context, Function->getParamDecl(I)),
6509                                     SourceLocation(), Args[I]);
6510 
6511     if (R.isInvalid())
6512       return false;
6513 
6514     ConvertedArgs.push_back(R.get());
6515   }
6516 
6517   if (Trap.hasErrorOccurred())
6518     return false;
6519 
6520   // Push default arguments if needed.
6521   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6522     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6523       ParmVarDecl *P = Function->getParamDecl(i);
6524       if (!P->hasDefaultArg())
6525         return false;
6526       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6527       if (R.isInvalid())
6528         return false;
6529       ConvertedArgs.push_back(R.get());
6530     }
6531 
6532     if (Trap.hasErrorOccurred())
6533       return false;
6534   }
6535   return true;
6536 }
6537 
CheckEnableIf(FunctionDecl * Function,SourceLocation CallLoc,ArrayRef<Expr * > Args,bool MissingImplicitThis)6538 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6539                                   SourceLocation CallLoc,
6540                                   ArrayRef<Expr *> Args,
6541                                   bool MissingImplicitThis) {
6542   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6543   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6544     return nullptr;
6545 
6546   SFINAETrap Trap(*this);
6547   SmallVector<Expr *, 16> ConvertedArgs;
6548   // FIXME: We should look into making enable_if late-parsed.
6549   Expr *DiscardedThis;
6550   if (!convertArgsForAvailabilityChecks(
6551           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6552           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6553     return *EnableIfAttrs.begin();
6554 
6555   for (auto *EIA : EnableIfAttrs) {
6556     APValue Result;
6557     // FIXME: This doesn't consider value-dependent cases, because doing so is
6558     // very difficult. Ideally, we should handle them more gracefully.
6559     if (EIA->getCond()->isValueDependent() ||
6560         !EIA->getCond()->EvaluateWithSubstitution(
6561             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6562       return EIA;
6563 
6564     if (!Result.isInt() || !Result.getInt().getBoolValue())
6565       return EIA;
6566   }
6567   return nullptr;
6568 }
6569 
6570 template <typename CheckFn>
diagnoseDiagnoseIfAttrsWith(Sema & S,const NamedDecl * ND,bool ArgDependent,SourceLocation Loc,CheckFn && IsSuccessful)6571 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6572                                         bool ArgDependent, SourceLocation Loc,
6573                                         CheckFn &&IsSuccessful) {
6574   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6575   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6576     if (ArgDependent == DIA->getArgDependent())
6577       Attrs.push_back(DIA);
6578   }
6579 
6580   // Common case: No diagnose_if attributes, so we can quit early.
6581   if (Attrs.empty())
6582     return false;
6583 
6584   auto WarningBegin = std::stable_partition(
6585       Attrs.begin(), Attrs.end(),
6586       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6587 
6588   // Note that diagnose_if attributes are late-parsed, so they appear in the
6589   // correct order (unlike enable_if attributes).
6590   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6591                                IsSuccessful);
6592   if (ErrAttr != WarningBegin) {
6593     const DiagnoseIfAttr *DIA = *ErrAttr;
6594     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6595     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6596         << DIA->getParent() << DIA->getCond()->getSourceRange();
6597     return true;
6598   }
6599 
6600   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6601     if (IsSuccessful(DIA)) {
6602       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6603       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6604           << DIA->getParent() << DIA->getCond()->getSourceRange();
6605     }
6606 
6607   return false;
6608 }
6609 
diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl * Function,const Expr * ThisArg,ArrayRef<const Expr * > Args,SourceLocation Loc)6610 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6611                                                const Expr *ThisArg,
6612                                                ArrayRef<const Expr *> Args,
6613                                                SourceLocation Loc) {
6614   return diagnoseDiagnoseIfAttrsWith(
6615       *this, Function, /*ArgDependent=*/true, Loc,
6616       [&](const DiagnoseIfAttr *DIA) {
6617         APValue Result;
6618         // It's sane to use the same Args for any redecl of this function, since
6619         // EvaluateWithSubstitution only cares about the position of each
6620         // argument in the arg list, not the ParmVarDecl* it maps to.
6621         if (!DIA->getCond()->EvaluateWithSubstitution(
6622                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6623           return false;
6624         return Result.isInt() && Result.getInt().getBoolValue();
6625       });
6626 }
6627 
diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl * ND,SourceLocation Loc)6628 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6629                                                  SourceLocation Loc) {
6630   return diagnoseDiagnoseIfAttrsWith(
6631       *this, ND, /*ArgDependent=*/false, Loc,
6632       [&](const DiagnoseIfAttr *DIA) {
6633         bool Result;
6634         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6635                Result;
6636       });
6637 }
6638 
6639 /// Add all of the function declarations in the given function set to
6640 /// the overload candidate set.
AddFunctionCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs,bool SuppressUserConversions,bool PartialOverloading,bool FirstArgumentIsBase)6641 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6642                                  ArrayRef<Expr *> Args,
6643                                  OverloadCandidateSet &CandidateSet,
6644                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6645                                  bool SuppressUserConversions,
6646                                  bool PartialOverloading,
6647                                  bool FirstArgumentIsBase) {
6648   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6649     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6650     ArrayRef<Expr *> FunctionArgs = Args;
6651 
6652     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6653     FunctionDecl *FD =
6654         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6655 
6656     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6657       QualType ObjectType;
6658       Expr::Classification ObjectClassification;
6659       if (Args.size() > 0) {
6660         if (Expr *E = Args[0]) {
6661           // Use the explicit base to restrict the lookup:
6662           ObjectType = E->getType();
6663           // Pointers in the object arguments are implicitly dereferenced, so we
6664           // always classify them as l-values.
6665           if (!ObjectType.isNull() && ObjectType->isPointerType())
6666             ObjectClassification = Expr::Classification::makeSimpleLValue();
6667           else
6668             ObjectClassification = E->Classify(Context);
6669         } // .. else there is an implicit base.
6670         FunctionArgs = Args.slice(1);
6671       }
6672       if (FunTmpl) {
6673         AddMethodTemplateCandidate(
6674             FunTmpl, F.getPair(),
6675             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6676             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6677             FunctionArgs, CandidateSet, SuppressUserConversions,
6678             PartialOverloading);
6679       } else {
6680         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6681                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6682                            ObjectClassification, FunctionArgs, CandidateSet,
6683                            SuppressUserConversions, PartialOverloading);
6684       }
6685     } else {
6686       // This branch handles both standalone functions and static methods.
6687 
6688       // Slice the first argument (which is the base) when we access
6689       // static method as non-static.
6690       if (Args.size() > 0 &&
6691           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6692                         !isa<CXXConstructorDecl>(FD)))) {
6693         assert(cast<CXXMethodDecl>(FD)->isStatic());
6694         FunctionArgs = Args.slice(1);
6695       }
6696       if (FunTmpl) {
6697         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6698                                      ExplicitTemplateArgs, FunctionArgs,
6699                                      CandidateSet, SuppressUserConversions,
6700                                      PartialOverloading);
6701       } else {
6702         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6703                              SuppressUserConversions, PartialOverloading);
6704       }
6705     }
6706   }
6707 }
6708 
6709 /// AddMethodCandidate - Adds a named decl (which is some kind of
6710 /// method) as a method candidate to the given overload set.
AddMethodCandidate(DeclAccessPair FoundDecl,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,OverloadCandidateParamOrder PO)6711 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6712                               Expr::Classification ObjectClassification,
6713                               ArrayRef<Expr *> Args,
6714                               OverloadCandidateSet &CandidateSet,
6715                               bool SuppressUserConversions,
6716                               OverloadCandidateParamOrder PO) {
6717   NamedDecl *Decl = FoundDecl.getDecl();
6718   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6719 
6720   if (isa<UsingShadowDecl>(Decl))
6721     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6722 
6723   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6724     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6725            "Expected a member function template");
6726     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6727                                /*ExplicitArgs*/ nullptr, ObjectType,
6728                                ObjectClassification, Args, CandidateSet,
6729                                SuppressUserConversions, false, PO);
6730   } else {
6731     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6732                        ObjectType, ObjectClassification, Args, CandidateSet,
6733                        SuppressUserConversions, false, None, PO);
6734   }
6735 }
6736 
6737 /// AddMethodCandidate - Adds the given C++ member function to the set
6738 /// of candidate functions, using the given function call arguments
6739 /// and the object argument (@c Object). For example, in a call
6740 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6741 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6742 /// allow user-defined conversions via constructors or conversion
6743 /// operators.
6744 void
AddMethodCandidate(CXXMethodDecl * Method,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,ConversionSequenceList EarlyConversions,OverloadCandidateParamOrder PO)6745 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6746                          CXXRecordDecl *ActingContext, QualType ObjectType,
6747                          Expr::Classification ObjectClassification,
6748                          ArrayRef<Expr *> Args,
6749                          OverloadCandidateSet &CandidateSet,
6750                          bool SuppressUserConversions,
6751                          bool PartialOverloading,
6752                          ConversionSequenceList EarlyConversions,
6753                          OverloadCandidateParamOrder PO) {
6754   const FunctionProtoType *Proto
6755     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6756   assert(Proto && "Methods without a prototype cannot be overloaded");
6757   assert(!isa<CXXConstructorDecl>(Method) &&
6758          "Use AddOverloadCandidate for constructors");
6759 
6760   if (!CandidateSet.isNewCandidate(Method, PO))
6761     return;
6762 
6763   // C++11 [class.copy]p23: [DR1402]
6764   //   A defaulted move assignment operator that is defined as deleted is
6765   //   ignored by overload resolution.
6766   if (Method->isDefaulted() && Method->isDeleted() &&
6767       Method->isMoveAssignmentOperator())
6768     return;
6769 
6770   // Overload resolution is always an unevaluated context.
6771   EnterExpressionEvaluationContext Unevaluated(
6772       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6773 
6774   // Add this candidate
6775   OverloadCandidate &Candidate =
6776       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6777   Candidate.FoundDecl = FoundDecl;
6778   Candidate.Function = Method;
6779   Candidate.RewriteKind =
6780       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6781   Candidate.IsSurrogate = false;
6782   Candidate.IgnoreObjectArgument = false;
6783   Candidate.ExplicitCallArguments = Args.size();
6784 
6785   unsigned NumParams = Proto->getNumParams();
6786 
6787   // (C++ 13.3.2p2): A candidate function having fewer than m
6788   // parameters is viable only if it has an ellipsis in its parameter
6789   // list (8.3.5).
6790   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6791       !Proto->isVariadic()) {
6792     Candidate.Viable = false;
6793     Candidate.FailureKind = ovl_fail_too_many_arguments;
6794     return;
6795   }
6796 
6797   // (C++ 13.3.2p2): A candidate function having more than m parameters
6798   // is viable only if the (m+1)st parameter has a default argument
6799   // (8.3.6). For the purposes of overload resolution, the
6800   // parameter list is truncated on the right, so that there are
6801   // exactly m parameters.
6802   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6803   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6804     // Not enough arguments.
6805     Candidate.Viable = false;
6806     Candidate.FailureKind = ovl_fail_too_few_arguments;
6807     return;
6808   }
6809 
6810   Candidate.Viable = true;
6811 
6812   if (Method->isStatic() || ObjectType.isNull())
6813     // The implicit object argument is ignored.
6814     Candidate.IgnoreObjectArgument = true;
6815   else {
6816     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6817     // Determine the implicit conversion sequence for the object
6818     // parameter.
6819     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6820         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6821         Method, ActingContext);
6822     if (Candidate.Conversions[ConvIdx].isBad()) {
6823       Candidate.Viable = false;
6824       Candidate.FailureKind = ovl_fail_bad_conversion;
6825       return;
6826     }
6827   }
6828 
6829   // (CUDA B.1): Check for invalid calls between targets.
6830   if (getLangOpts().CUDA)
6831     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6832       if (!IsAllowedCUDACall(Caller, Method)) {
6833         Candidate.Viable = false;
6834         Candidate.FailureKind = ovl_fail_bad_target;
6835         return;
6836       }
6837 
6838   if (Method->getTrailingRequiresClause()) {
6839     ConstraintSatisfaction Satisfaction;
6840     if (CheckFunctionConstraints(Method, Satisfaction) ||
6841         !Satisfaction.IsSatisfied) {
6842       Candidate.Viable = false;
6843       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6844       return;
6845     }
6846   }
6847 
6848   // Determine the implicit conversion sequences for each of the
6849   // arguments.
6850   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6851     unsigned ConvIdx =
6852         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6853     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6854       // We already formed a conversion sequence for this parameter during
6855       // template argument deduction.
6856     } else if (ArgIdx < NumParams) {
6857       // (C++ 13.3.2p3): for F to be a viable function, there shall
6858       // exist for each argument an implicit conversion sequence
6859       // (13.3.3.1) that converts that argument to the corresponding
6860       // parameter of F.
6861       QualType ParamType = Proto->getParamType(ArgIdx);
6862       Candidate.Conversions[ConvIdx]
6863         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6864                                 SuppressUserConversions,
6865                                 /*InOverloadResolution=*/true,
6866                                 /*AllowObjCWritebackConversion=*/
6867                                   getLangOpts().ObjCAutoRefCount);
6868       if (Candidate.Conversions[ConvIdx].isBad()) {
6869         Candidate.Viable = false;
6870         Candidate.FailureKind = ovl_fail_bad_conversion;
6871         return;
6872       }
6873     } else {
6874       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6875       // argument for which there is no corresponding parameter is
6876       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6877       Candidate.Conversions[ConvIdx].setEllipsis();
6878     }
6879   }
6880 
6881   if (EnableIfAttr *FailedAttr =
6882           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6883     Candidate.Viable = false;
6884     Candidate.FailureKind = ovl_fail_enable_if;
6885     Candidate.DeductionFailure.Data = FailedAttr;
6886     return;
6887   }
6888 
6889   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6890       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6891     Candidate.Viable = false;
6892     Candidate.FailureKind = ovl_non_default_multiversion_function;
6893   }
6894 }
6895 
6896 /// Add a C++ member function template as a candidate to the candidate
6897 /// set, using template argument deduction to produce an appropriate member
6898 /// function template specialization.
AddMethodTemplateCandidate(FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,OverloadCandidateParamOrder PO)6899 void Sema::AddMethodTemplateCandidate(
6900     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6901     CXXRecordDecl *ActingContext,
6902     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6903     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6904     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6905     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6906   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6907     return;
6908 
6909   // C++ [over.match.funcs]p7:
6910   //   In each case where a candidate is a function template, candidate
6911   //   function template specializations are generated using template argument
6912   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6913   //   candidate functions in the usual way.113) A given name can refer to one
6914   //   or more function templates and also to a set of overloaded non-template
6915   //   functions. In such a case, the candidate functions generated from each
6916   //   function template are combined with the set of non-template candidate
6917   //   functions.
6918   TemplateDeductionInfo Info(CandidateSet.getLocation());
6919   FunctionDecl *Specialization = nullptr;
6920   ConversionSequenceList Conversions;
6921   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6922           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6923           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6924             return CheckNonDependentConversions(
6925                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6926                 SuppressUserConversions, ActingContext, ObjectType,
6927                 ObjectClassification, PO);
6928           })) {
6929     OverloadCandidate &Candidate =
6930         CandidateSet.addCandidate(Conversions.size(), Conversions);
6931     Candidate.FoundDecl = FoundDecl;
6932     Candidate.Function = MethodTmpl->getTemplatedDecl();
6933     Candidate.Viable = false;
6934     Candidate.RewriteKind =
6935       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6936     Candidate.IsSurrogate = false;
6937     Candidate.IgnoreObjectArgument =
6938         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6939         ObjectType.isNull();
6940     Candidate.ExplicitCallArguments = Args.size();
6941     if (Result == TDK_NonDependentConversionFailure)
6942       Candidate.FailureKind = ovl_fail_bad_conversion;
6943     else {
6944       Candidate.FailureKind = ovl_fail_bad_deduction;
6945       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6946                                                             Info);
6947     }
6948     return;
6949   }
6950 
6951   // Add the function template specialization produced by template argument
6952   // deduction as a candidate.
6953   assert(Specialization && "Missing member function template specialization?");
6954   assert(isa<CXXMethodDecl>(Specialization) &&
6955          "Specialization is not a member function?");
6956   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6957                      ActingContext, ObjectType, ObjectClassification, Args,
6958                      CandidateSet, SuppressUserConversions, PartialOverloading,
6959                      Conversions, PO);
6960 }
6961 
6962 /// Determine whether a given function template has a simple explicit specifier
6963 /// or a non-value-dependent explicit-specification that evaluates to true.
isNonDependentlyExplicit(FunctionTemplateDecl * FTD)6964 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6965   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6966 }
6967 
6968 /// Add a C++ function template specialization as a candidate
6969 /// in the candidate set, using template argument deduction to produce
6970 /// an appropriate function template specialization.
AddTemplateOverloadCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit,ADLCallKind IsADLCandidate,OverloadCandidateParamOrder PO)6971 void Sema::AddTemplateOverloadCandidate(
6972     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6973     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6974     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6975     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6976     OverloadCandidateParamOrder PO) {
6977   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6978     return;
6979 
6980   // If the function template has a non-dependent explicit specification,
6981   // exclude it now if appropriate; we are not permitted to perform deduction
6982   // and substitution in this case.
6983   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6984     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6985     Candidate.FoundDecl = FoundDecl;
6986     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6987     Candidate.Viable = false;
6988     Candidate.FailureKind = ovl_fail_explicit;
6989     return;
6990   }
6991 
6992   // C++ [over.match.funcs]p7:
6993   //   In each case where a candidate is a function template, candidate
6994   //   function template specializations are generated using template argument
6995   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6996   //   candidate functions in the usual way.113) A given name can refer to one
6997   //   or more function templates and also to a set of overloaded non-template
6998   //   functions. In such a case, the candidate functions generated from each
6999   //   function template are combined with the set of non-template candidate
7000   //   functions.
7001   TemplateDeductionInfo Info(CandidateSet.getLocation());
7002   FunctionDecl *Specialization = nullptr;
7003   ConversionSequenceList Conversions;
7004   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7005           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7006           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7007             return CheckNonDependentConversions(
7008                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7009                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7010           })) {
7011     OverloadCandidate &Candidate =
7012         CandidateSet.addCandidate(Conversions.size(), Conversions);
7013     Candidate.FoundDecl = FoundDecl;
7014     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7015     Candidate.Viable = false;
7016     Candidate.RewriteKind =
7017       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7018     Candidate.IsSurrogate = false;
7019     Candidate.IsADLCandidate = IsADLCandidate;
7020     // Ignore the object argument if there is one, since we don't have an object
7021     // type.
7022     Candidate.IgnoreObjectArgument =
7023         isa<CXXMethodDecl>(Candidate.Function) &&
7024         !isa<CXXConstructorDecl>(Candidate.Function);
7025     Candidate.ExplicitCallArguments = Args.size();
7026     if (Result == TDK_NonDependentConversionFailure)
7027       Candidate.FailureKind = ovl_fail_bad_conversion;
7028     else {
7029       Candidate.FailureKind = ovl_fail_bad_deduction;
7030       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7031                                                             Info);
7032     }
7033     return;
7034   }
7035 
7036   // Add the function template specialization produced by template argument
7037   // deduction as a candidate.
7038   assert(Specialization && "Missing function template specialization?");
7039   AddOverloadCandidate(
7040       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7041       PartialOverloading, AllowExplicit,
7042       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7043 }
7044 
7045 /// Check that implicit conversion sequences can be formed for each argument
7046 /// whose corresponding parameter has a non-dependent type, per DR1391's
7047 /// [temp.deduct.call]p10.
CheckNonDependentConversions(FunctionTemplateDecl * FunctionTemplate,ArrayRef<QualType> ParamTypes,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,ConversionSequenceList & Conversions,bool SuppressUserConversions,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,OverloadCandidateParamOrder PO)7048 bool Sema::CheckNonDependentConversions(
7049     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7050     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7051     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7052     CXXRecordDecl *ActingContext, QualType ObjectType,
7053     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7054   // FIXME: The cases in which we allow explicit conversions for constructor
7055   // arguments never consider calling a constructor template. It's not clear
7056   // that is correct.
7057   const bool AllowExplicit = false;
7058 
7059   auto *FD = FunctionTemplate->getTemplatedDecl();
7060   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7061   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7062   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7063 
7064   Conversions =
7065       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7066 
7067   // Overload resolution is always an unevaluated context.
7068   EnterExpressionEvaluationContext Unevaluated(
7069       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7070 
7071   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7072   // require that, but this check should never result in a hard error, and
7073   // overload resolution is permitted to sidestep instantiations.
7074   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7075       !ObjectType.isNull()) {
7076     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7077     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7078         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7079         Method, ActingContext);
7080     if (Conversions[ConvIdx].isBad())
7081       return true;
7082   }
7083 
7084   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7085        ++I) {
7086     QualType ParamType = ParamTypes[I];
7087     if (!ParamType->isDependentType()) {
7088       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7089                              ? 0
7090                              : (ThisConversions + I);
7091       Conversions[ConvIdx]
7092         = TryCopyInitialization(*this, Args[I], ParamType,
7093                                 SuppressUserConversions,
7094                                 /*InOverloadResolution=*/true,
7095                                 /*AllowObjCWritebackConversion=*/
7096                                   getLangOpts().ObjCAutoRefCount,
7097                                 AllowExplicit);
7098       if (Conversions[ConvIdx].isBad())
7099         return true;
7100     }
7101   }
7102 
7103   return false;
7104 }
7105 
7106 /// Determine whether this is an allowable conversion from the result
7107 /// of an explicit conversion operator to the expected type, per C++
7108 /// [over.match.conv]p1 and [over.match.ref]p1.
7109 ///
7110 /// \param ConvType The return type of the conversion function.
7111 ///
7112 /// \param ToType The type we are converting to.
7113 ///
7114 /// \param AllowObjCPointerConversion Allow a conversion from one
7115 /// Objective-C pointer to another.
7116 ///
7117 /// \returns true if the conversion is allowable, false otherwise.
isAllowableExplicitConversion(Sema & S,QualType ConvType,QualType ToType,bool AllowObjCPointerConversion)7118 static bool isAllowableExplicitConversion(Sema &S,
7119                                           QualType ConvType, QualType ToType,
7120                                           bool AllowObjCPointerConversion) {
7121   QualType ToNonRefType = ToType.getNonReferenceType();
7122 
7123   // Easy case: the types are the same.
7124   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7125     return true;
7126 
7127   // Allow qualification conversions.
7128   bool ObjCLifetimeConversion;
7129   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7130                                   ObjCLifetimeConversion))
7131     return true;
7132 
7133   // If we're not allowed to consider Objective-C pointer conversions,
7134   // we're done.
7135   if (!AllowObjCPointerConversion)
7136     return false;
7137 
7138   // Is this an Objective-C pointer conversion?
7139   bool IncompatibleObjC = false;
7140   QualType ConvertedType;
7141   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7142                                    IncompatibleObjC);
7143 }
7144 
7145 /// AddConversionCandidate - Add a C++ conversion function as a
7146 /// candidate in the candidate set (C++ [over.match.conv],
7147 /// C++ [over.match.copy]). From is the expression we're converting from,
7148 /// and ToType is the type that we're eventually trying to convert to
7149 /// (which may or may not be the same type as the type that the
7150 /// conversion function produces).
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion)7151 void Sema::AddConversionCandidate(
7152     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7153     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7154     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7155     bool AllowExplicit, bool AllowResultConversion) {
7156   assert(!Conversion->getDescribedFunctionTemplate() &&
7157          "Conversion function templates use AddTemplateConversionCandidate");
7158   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7159   if (!CandidateSet.isNewCandidate(Conversion))
7160     return;
7161 
7162   // If the conversion function has an undeduced return type, trigger its
7163   // deduction now.
7164   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7165     if (DeduceReturnType(Conversion, From->getExprLoc()))
7166       return;
7167     ConvType = Conversion->getConversionType().getNonReferenceType();
7168   }
7169 
7170   // If we don't allow any conversion of the result type, ignore conversion
7171   // functions that don't convert to exactly (possibly cv-qualified) T.
7172   if (!AllowResultConversion &&
7173       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7174     return;
7175 
7176   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7177   // operator is only a candidate if its return type is the target type or
7178   // can be converted to the target type with a qualification conversion.
7179   //
7180   // FIXME: Include such functions in the candidate list and explain why we
7181   // can't select them.
7182   if (Conversion->isExplicit() &&
7183       !isAllowableExplicitConversion(*this, ConvType, ToType,
7184                                      AllowObjCConversionOnExplicit))
7185     return;
7186 
7187   // Overload resolution is always an unevaluated context.
7188   EnterExpressionEvaluationContext Unevaluated(
7189       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7190 
7191   // Add this candidate
7192   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7193   Candidate.FoundDecl = FoundDecl;
7194   Candidate.Function = Conversion;
7195   Candidate.IsSurrogate = false;
7196   Candidate.IgnoreObjectArgument = false;
7197   Candidate.FinalConversion.setAsIdentityConversion();
7198   Candidate.FinalConversion.setFromType(ConvType);
7199   Candidate.FinalConversion.setAllToTypes(ToType);
7200   Candidate.Viable = true;
7201   Candidate.ExplicitCallArguments = 1;
7202 
7203   // Explicit functions are not actually candidates at all if we're not
7204   // allowing them in this context, but keep them around so we can point
7205   // to them in diagnostics.
7206   if (!AllowExplicit && Conversion->isExplicit()) {
7207     Candidate.Viable = false;
7208     Candidate.FailureKind = ovl_fail_explicit;
7209     return;
7210   }
7211 
7212   // C++ [over.match.funcs]p4:
7213   //   For conversion functions, the function is considered to be a member of
7214   //   the class of the implicit implied object argument for the purpose of
7215   //   defining the type of the implicit object parameter.
7216   //
7217   // Determine the implicit conversion sequence for the implicit
7218   // object parameter.
7219   QualType ImplicitParamType = From->getType();
7220   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7221     ImplicitParamType = FromPtrType->getPointeeType();
7222   CXXRecordDecl *ConversionContext
7223     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7224 
7225   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7226       *this, CandidateSet.getLocation(), From->getType(),
7227       From->Classify(Context), Conversion, ConversionContext);
7228 
7229   if (Candidate.Conversions[0].isBad()) {
7230     Candidate.Viable = false;
7231     Candidate.FailureKind = ovl_fail_bad_conversion;
7232     return;
7233   }
7234 
7235   if (Conversion->getTrailingRequiresClause()) {
7236     ConstraintSatisfaction Satisfaction;
7237     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7238         !Satisfaction.IsSatisfied) {
7239       Candidate.Viable = false;
7240       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7241       return;
7242     }
7243   }
7244 
7245   // We won't go through a user-defined type conversion function to convert a
7246   // derived to base as such conversions are given Conversion Rank. They only
7247   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7248   QualType FromCanon
7249     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7250   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7251   if (FromCanon == ToCanon ||
7252       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7253     Candidate.Viable = false;
7254     Candidate.FailureKind = ovl_fail_trivial_conversion;
7255     return;
7256   }
7257 
7258   // To determine what the conversion from the result of calling the
7259   // conversion function to the type we're eventually trying to
7260   // convert to (ToType), we need to synthesize a call to the
7261   // conversion function and attempt copy initialization from it. This
7262   // makes sure that we get the right semantics with respect to
7263   // lvalues/rvalues and the type. Fortunately, we can allocate this
7264   // call on the stack and we don't need its arguments to be
7265   // well-formed.
7266   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7267                             VK_LValue, From->getBeginLoc());
7268   ImplicitCastExpr ConversionFn(
7269       ImplicitCastExpr::OnStack, Context.getPointerType(Conversion->getType()),
7270       CK_FunctionToPointerDecay, &ConversionRef, VK_RValue, Context);
7271 
7272   QualType ConversionType = Conversion->getConversionType();
7273   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7274     Candidate.Viable = false;
7275     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7276     return;
7277   }
7278 
7279   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7280 
7281   // Note that it is safe to allocate CallExpr on the stack here because
7282   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7283   // allocator).
7284   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7285 
7286   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7287   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7288       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7289 
7290   ImplicitConversionSequence ICS =
7291       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7292                             /*SuppressUserConversions=*/true,
7293                             /*InOverloadResolution=*/false,
7294                             /*AllowObjCWritebackConversion=*/false);
7295 
7296   switch (ICS.getKind()) {
7297   case ImplicitConversionSequence::StandardConversion:
7298     Candidate.FinalConversion = ICS.Standard;
7299 
7300     // C++ [over.ics.user]p3:
7301     //   If the user-defined conversion is specified by a specialization of a
7302     //   conversion function template, the second standard conversion sequence
7303     //   shall have exact match rank.
7304     if (Conversion->getPrimaryTemplate() &&
7305         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7306       Candidate.Viable = false;
7307       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7308       return;
7309     }
7310 
7311     // C++0x [dcl.init.ref]p5:
7312     //    In the second case, if the reference is an rvalue reference and
7313     //    the second standard conversion sequence of the user-defined
7314     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7315     //    program is ill-formed.
7316     if (ToType->isRValueReferenceType() &&
7317         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7318       Candidate.Viable = false;
7319       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7320       return;
7321     }
7322     break;
7323 
7324   case ImplicitConversionSequence::BadConversion:
7325     Candidate.Viable = false;
7326     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7327     return;
7328 
7329   default:
7330     llvm_unreachable(
7331            "Can only end up with a standard conversion sequence or failure");
7332   }
7333 
7334   if (EnableIfAttr *FailedAttr =
7335           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7336     Candidate.Viable = false;
7337     Candidate.FailureKind = ovl_fail_enable_if;
7338     Candidate.DeductionFailure.Data = FailedAttr;
7339     return;
7340   }
7341 
7342   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7343       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7344     Candidate.Viable = false;
7345     Candidate.FailureKind = ovl_non_default_multiversion_function;
7346   }
7347 }
7348 
7349 /// Adds a conversion function template specialization
7350 /// candidate to the overload set, using template argument deduction
7351 /// to deduce the template arguments of the conversion function
7352 /// template from the type that we are converting to (C++
7353 /// [temp.deduct.conv]).
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion)7354 void Sema::AddTemplateConversionCandidate(
7355     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7356     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7357     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7358     bool AllowExplicit, bool AllowResultConversion) {
7359   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7360          "Only conversion function templates permitted here");
7361 
7362   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7363     return;
7364 
7365   // If the function template has a non-dependent explicit specification,
7366   // exclude it now if appropriate; we are not permitted to perform deduction
7367   // and substitution in this case.
7368   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7369     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7370     Candidate.FoundDecl = FoundDecl;
7371     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7372     Candidate.Viable = false;
7373     Candidate.FailureKind = ovl_fail_explicit;
7374     return;
7375   }
7376 
7377   TemplateDeductionInfo Info(CandidateSet.getLocation());
7378   CXXConversionDecl *Specialization = nullptr;
7379   if (TemplateDeductionResult Result
7380         = DeduceTemplateArguments(FunctionTemplate, ToType,
7381                                   Specialization, Info)) {
7382     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7383     Candidate.FoundDecl = FoundDecl;
7384     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7385     Candidate.Viable = false;
7386     Candidate.FailureKind = ovl_fail_bad_deduction;
7387     Candidate.IsSurrogate = false;
7388     Candidate.IgnoreObjectArgument = false;
7389     Candidate.ExplicitCallArguments = 1;
7390     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7391                                                           Info);
7392     return;
7393   }
7394 
7395   // Add the conversion function template specialization produced by
7396   // template argument deduction as a candidate.
7397   assert(Specialization && "Missing function template specialization?");
7398   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7399                          CandidateSet, AllowObjCConversionOnExplicit,
7400                          AllowExplicit, AllowResultConversion);
7401 }
7402 
7403 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7404 /// converts the given @c Object to a function pointer via the
7405 /// conversion function @c Conversion, and then attempts to call it
7406 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7407 /// the type of function that we'll eventually be calling.
AddSurrogateCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,const FunctionProtoType * Proto,Expr * Object,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)7408 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7409                                  DeclAccessPair FoundDecl,
7410                                  CXXRecordDecl *ActingContext,
7411                                  const FunctionProtoType *Proto,
7412                                  Expr *Object,
7413                                  ArrayRef<Expr *> Args,
7414                                  OverloadCandidateSet& CandidateSet) {
7415   if (!CandidateSet.isNewCandidate(Conversion))
7416     return;
7417 
7418   // Overload resolution is always an unevaluated context.
7419   EnterExpressionEvaluationContext Unevaluated(
7420       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7421 
7422   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7423   Candidate.FoundDecl = FoundDecl;
7424   Candidate.Function = nullptr;
7425   Candidate.Surrogate = Conversion;
7426   Candidate.Viable = true;
7427   Candidate.IsSurrogate = true;
7428   Candidate.IgnoreObjectArgument = false;
7429   Candidate.ExplicitCallArguments = Args.size();
7430 
7431   // Determine the implicit conversion sequence for the implicit
7432   // object parameter.
7433   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7434       *this, CandidateSet.getLocation(), Object->getType(),
7435       Object->Classify(Context), Conversion, ActingContext);
7436   if (ObjectInit.isBad()) {
7437     Candidate.Viable = false;
7438     Candidate.FailureKind = ovl_fail_bad_conversion;
7439     Candidate.Conversions[0] = ObjectInit;
7440     return;
7441   }
7442 
7443   // The first conversion is actually a user-defined conversion whose
7444   // first conversion is ObjectInit's standard conversion (which is
7445   // effectively a reference binding). Record it as such.
7446   Candidate.Conversions[0].setUserDefined();
7447   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7448   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7449   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7450   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7451   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7452   Candidate.Conversions[0].UserDefined.After
7453     = Candidate.Conversions[0].UserDefined.Before;
7454   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7455 
7456   // Find the
7457   unsigned NumParams = Proto->getNumParams();
7458 
7459   // (C++ 13.3.2p2): A candidate function having fewer than m
7460   // parameters is viable only if it has an ellipsis in its parameter
7461   // list (8.3.5).
7462   if (Args.size() > NumParams && !Proto->isVariadic()) {
7463     Candidate.Viable = false;
7464     Candidate.FailureKind = ovl_fail_too_many_arguments;
7465     return;
7466   }
7467 
7468   // Function types don't have any default arguments, so just check if
7469   // we have enough arguments.
7470   if (Args.size() < NumParams) {
7471     // Not enough arguments.
7472     Candidate.Viable = false;
7473     Candidate.FailureKind = ovl_fail_too_few_arguments;
7474     return;
7475   }
7476 
7477   // Determine the implicit conversion sequences for each of the
7478   // arguments.
7479   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7480     if (ArgIdx < NumParams) {
7481       // (C++ 13.3.2p3): for F to be a viable function, there shall
7482       // exist for each argument an implicit conversion sequence
7483       // (13.3.3.1) that converts that argument to the corresponding
7484       // parameter of F.
7485       QualType ParamType = Proto->getParamType(ArgIdx);
7486       Candidate.Conversions[ArgIdx + 1]
7487         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7488                                 /*SuppressUserConversions=*/false,
7489                                 /*InOverloadResolution=*/false,
7490                                 /*AllowObjCWritebackConversion=*/
7491                                   getLangOpts().ObjCAutoRefCount);
7492       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7493         Candidate.Viable = false;
7494         Candidate.FailureKind = ovl_fail_bad_conversion;
7495         return;
7496       }
7497     } else {
7498       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7499       // argument for which there is no corresponding parameter is
7500       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7501       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7502     }
7503   }
7504 
7505   if (EnableIfAttr *FailedAttr =
7506           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7507     Candidate.Viable = false;
7508     Candidate.FailureKind = ovl_fail_enable_if;
7509     Candidate.DeductionFailure.Data = FailedAttr;
7510     return;
7511   }
7512 }
7513 
7514 /// Add all of the non-member operator function declarations in the given
7515 /// function set to the overload candidate set.
AddNonMemberOperatorCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs)7516 void Sema::AddNonMemberOperatorCandidates(
7517     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7518     OverloadCandidateSet &CandidateSet,
7519     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7520   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7521     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7522     ArrayRef<Expr *> FunctionArgs = Args;
7523 
7524     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7525     FunctionDecl *FD =
7526         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7527 
7528     // Don't consider rewritten functions if we're not rewriting.
7529     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7530       continue;
7531 
7532     assert(!isa<CXXMethodDecl>(FD) &&
7533            "unqualified operator lookup found a member function");
7534 
7535     if (FunTmpl) {
7536       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7537                                    FunctionArgs, CandidateSet);
7538       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7539         AddTemplateOverloadCandidate(
7540             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7541             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7542             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7543     } else {
7544       if (ExplicitTemplateArgs)
7545         continue;
7546       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7547       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7548         AddOverloadCandidate(FD, F.getPair(),
7549                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7550                              false, false, true, false, ADLCallKind::NotADL,
7551                              None, OverloadCandidateParamOrder::Reversed);
7552     }
7553   }
7554 }
7555 
7556 /// Add overload candidates for overloaded operators that are
7557 /// member functions.
7558 ///
7559 /// Add the overloaded operator candidates that are member functions
7560 /// for the operator Op that was used in an operator expression such
7561 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7562 /// CandidateSet will store the added overload candidates. (C++
7563 /// [over.match.oper]).
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,OverloadCandidateParamOrder PO)7564 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7565                                        SourceLocation OpLoc,
7566                                        ArrayRef<Expr *> Args,
7567                                        OverloadCandidateSet &CandidateSet,
7568                                        OverloadCandidateParamOrder PO) {
7569   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7570 
7571   // C++ [over.match.oper]p3:
7572   //   For a unary operator @ with an operand of a type whose
7573   //   cv-unqualified version is T1, and for a binary operator @ with
7574   //   a left operand of a type whose cv-unqualified version is T1 and
7575   //   a right operand of a type whose cv-unqualified version is T2,
7576   //   three sets of candidate functions, designated member
7577   //   candidates, non-member candidates and built-in candidates, are
7578   //   constructed as follows:
7579   QualType T1 = Args[0]->getType();
7580 
7581   //     -- If T1 is a complete class type or a class currently being
7582   //        defined, the set of member candidates is the result of the
7583   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7584   //        the set of member candidates is empty.
7585   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7586     // Complete the type if it can be completed.
7587     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7588       return;
7589     // If the type is neither complete nor being defined, bail out now.
7590     if (!T1Rec->getDecl()->getDefinition())
7591       return;
7592 
7593     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7594     LookupQualifiedName(Operators, T1Rec->getDecl());
7595     Operators.suppressDiagnostics();
7596 
7597     for (LookupResult::iterator Oper = Operators.begin(),
7598                              OperEnd = Operators.end();
7599          Oper != OperEnd;
7600          ++Oper)
7601       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7602                          Args[0]->Classify(Context), Args.slice(1),
7603                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7604   }
7605 }
7606 
7607 /// AddBuiltinCandidate - Add a candidate for a built-in
7608 /// operator. ResultTy and ParamTys are the result and parameter types
7609 /// of the built-in candidate, respectively. Args and NumArgs are the
7610 /// arguments being passed to the candidate. IsAssignmentOperator
7611 /// should be true when this built-in candidate is an assignment
7612 /// operator. NumContextualBoolArguments is the number of arguments
7613 /// (at the beginning of the argument list) that will be contextually
7614 /// converted to bool.
AddBuiltinCandidate(QualType * ParamTys,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)7615 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7616                                OverloadCandidateSet& CandidateSet,
7617                                bool IsAssignmentOperator,
7618                                unsigned NumContextualBoolArguments) {
7619   // Overload resolution is always an unevaluated context.
7620   EnterExpressionEvaluationContext Unevaluated(
7621       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7622 
7623   // Add this candidate
7624   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7625   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7626   Candidate.Function = nullptr;
7627   Candidate.IsSurrogate = false;
7628   Candidate.IgnoreObjectArgument = false;
7629   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7630 
7631   // Determine the implicit conversion sequences for each of the
7632   // arguments.
7633   Candidate.Viable = true;
7634   Candidate.ExplicitCallArguments = Args.size();
7635   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7636     // C++ [over.match.oper]p4:
7637     //   For the built-in assignment operators, conversions of the
7638     //   left operand are restricted as follows:
7639     //     -- no temporaries are introduced to hold the left operand, and
7640     //     -- no user-defined conversions are applied to the left
7641     //        operand to achieve a type match with the left-most
7642     //        parameter of a built-in candidate.
7643     //
7644     // We block these conversions by turning off user-defined
7645     // conversions, since that is the only way that initialization of
7646     // a reference to a non-class type can occur from something that
7647     // is not of the same type.
7648     if (ArgIdx < NumContextualBoolArguments) {
7649       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7650              "Contextual conversion to bool requires bool type");
7651       Candidate.Conversions[ArgIdx]
7652         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7653     } else {
7654       Candidate.Conversions[ArgIdx]
7655         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7656                                 ArgIdx == 0 && IsAssignmentOperator,
7657                                 /*InOverloadResolution=*/false,
7658                                 /*AllowObjCWritebackConversion=*/
7659                                   getLangOpts().ObjCAutoRefCount);
7660     }
7661     if (Candidate.Conversions[ArgIdx].isBad()) {
7662       Candidate.Viable = false;
7663       Candidate.FailureKind = ovl_fail_bad_conversion;
7664       break;
7665     }
7666   }
7667 }
7668 
7669 namespace {
7670 
7671 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7672 /// candidate operator functions for built-in operators (C++
7673 /// [over.built]). The types are separated into pointer types and
7674 /// enumeration types.
7675 class BuiltinCandidateTypeSet  {
7676   /// TypeSet - A set of types.
7677   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7678                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7679 
7680   /// PointerTypes - The set of pointer types that will be used in the
7681   /// built-in candidates.
7682   TypeSet PointerTypes;
7683 
7684   /// MemberPointerTypes - The set of member pointer types that will be
7685   /// used in the built-in candidates.
7686   TypeSet MemberPointerTypes;
7687 
7688   /// EnumerationTypes - The set of enumeration types that will be
7689   /// used in the built-in candidates.
7690   TypeSet EnumerationTypes;
7691 
7692   /// The set of vector types that will be used in the built-in
7693   /// candidates.
7694   TypeSet VectorTypes;
7695 
7696   /// The set of matrix types that will be used in the built-in
7697   /// candidates.
7698   TypeSet MatrixTypes;
7699 
7700   /// A flag indicating non-record types are viable candidates
7701   bool HasNonRecordTypes;
7702 
7703   /// A flag indicating whether either arithmetic or enumeration types
7704   /// were present in the candidate set.
7705   bool HasArithmeticOrEnumeralTypes;
7706 
7707   /// A flag indicating whether the nullptr type was present in the
7708   /// candidate set.
7709   bool HasNullPtrType;
7710 
7711   /// Sema - The semantic analysis instance where we are building the
7712   /// candidate type set.
7713   Sema &SemaRef;
7714 
7715   /// Context - The AST context in which we will build the type sets.
7716   ASTContext &Context;
7717 
7718   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7719                                                const Qualifiers &VisibleQuals);
7720   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7721 
7722 public:
7723   /// iterator - Iterates through the types that are part of the set.
7724   typedef TypeSet::iterator iterator;
7725 
BuiltinCandidateTypeSet(Sema & SemaRef)7726   BuiltinCandidateTypeSet(Sema &SemaRef)
7727     : HasNonRecordTypes(false),
7728       HasArithmeticOrEnumeralTypes(false),
7729       HasNullPtrType(false),
7730       SemaRef(SemaRef),
7731       Context(SemaRef.Context) { }
7732 
7733   void AddTypesConvertedFrom(QualType Ty,
7734                              SourceLocation Loc,
7735                              bool AllowUserConversions,
7736                              bool AllowExplicitConversions,
7737                              const Qualifiers &VisibleTypeConversionsQuals);
7738 
7739   /// pointer_begin - First pointer type found;
pointer_begin()7740   iterator pointer_begin() { return PointerTypes.begin(); }
7741 
7742   /// pointer_end - Past the last pointer type found;
pointer_end()7743   iterator pointer_end() { return PointerTypes.end(); }
7744 
7745   /// member_pointer_begin - First member pointer type found;
member_pointer_begin()7746   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7747 
7748   /// member_pointer_end - Past the last member pointer type found;
member_pointer_end()7749   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7750 
7751   /// enumeration_begin - First enumeration type found;
enumeration_begin()7752   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7753 
7754   /// enumeration_end - Past the last enumeration type found;
enumeration_end()7755   iterator enumeration_end() { return EnumerationTypes.end(); }
7756 
vector_types()7757   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7758 
matrix_types()7759   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7760 
containsMatrixType(QualType Ty) const7761   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
hasNonRecordTypes()7762   bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()7763   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const7764   bool hasNullPtrType() const { return HasNullPtrType; }
7765 };
7766 
7767 } // end anonymous namespace
7768 
7769 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7770 /// the set of pointer types along with any more-qualified variants of
7771 /// that type. For example, if @p Ty is "int const *", this routine
7772 /// will add "int const *", "int const volatile *", "int const
7773 /// restrict *", and "int const volatile restrict *" to the set of
7774 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7775 /// false otherwise.
7776 ///
7777 /// FIXME: what to do about extended qualifiers?
7778 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)7779 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7780                                              const Qualifiers &VisibleQuals) {
7781 
7782   // Insert this type.
7783   if (!PointerTypes.insert(Ty))
7784     return false;
7785 
7786   QualType PointeeTy;
7787   const PointerType *PointerTy = Ty->getAs<PointerType>();
7788   bool buildObjCPtr = false;
7789   if (!PointerTy) {
7790     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7791     PointeeTy = PTy->getPointeeType();
7792     buildObjCPtr = true;
7793   } else {
7794     PointeeTy = PointerTy->getPointeeType();
7795   }
7796 
7797   // Don't add qualified variants of arrays. For one, they're not allowed
7798   // (the qualifier would sink to the element type), and for another, the
7799   // only overload situation where it matters is subscript or pointer +- int,
7800   // and those shouldn't have qualifier variants anyway.
7801   if (PointeeTy->isArrayType())
7802     return true;
7803 
7804   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7805   bool hasVolatile = VisibleQuals.hasVolatile();
7806   bool hasRestrict = VisibleQuals.hasRestrict();
7807 
7808   // Iterate through all strict supersets of BaseCVR.
7809   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7810     if ((CVR | BaseCVR) != CVR) continue;
7811     // Skip over volatile if no volatile found anywhere in the types.
7812     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7813 
7814     // Skip over restrict if no restrict found anywhere in the types, or if
7815     // the type cannot be restrict-qualified.
7816     if ((CVR & Qualifiers::Restrict) &&
7817         (!hasRestrict ||
7818          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7819       continue;
7820 
7821     // Build qualified pointee type.
7822     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7823 
7824     // Build qualified pointer type.
7825     QualType QPointerTy;
7826     if (!buildObjCPtr)
7827       QPointerTy = Context.getPointerType(QPointeeTy);
7828     else
7829       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7830 
7831     // Insert qualified pointer type.
7832     PointerTypes.insert(QPointerTy);
7833   }
7834 
7835   return true;
7836 }
7837 
7838 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7839 /// to the set of pointer types along with any more-qualified variants of
7840 /// that type. For example, if @p Ty is "int const *", this routine
7841 /// will add "int const *", "int const volatile *", "int const
7842 /// restrict *", and "int const volatile restrict *" to the set of
7843 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7844 /// false otherwise.
7845 ///
7846 /// FIXME: what to do about extended qualifiers?
7847 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)7848 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7849     QualType Ty) {
7850   // Insert this type.
7851   if (!MemberPointerTypes.insert(Ty))
7852     return false;
7853 
7854   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7855   assert(PointerTy && "type was not a member pointer type!");
7856 
7857   QualType PointeeTy = PointerTy->getPointeeType();
7858   // Don't add qualified variants of arrays. For one, they're not allowed
7859   // (the qualifier would sink to the element type), and for another, the
7860   // only overload situation where it matters is subscript or pointer +- int,
7861   // and those shouldn't have qualifier variants anyway.
7862   if (PointeeTy->isArrayType())
7863     return true;
7864   const Type *ClassTy = PointerTy->getClass();
7865 
7866   // Iterate through all strict supersets of the pointee type's CVR
7867   // qualifiers.
7868   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7869   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7870     if ((CVR | BaseCVR) != CVR) continue;
7871 
7872     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7873     MemberPointerTypes.insert(
7874       Context.getMemberPointerType(QPointeeTy, ClassTy));
7875   }
7876 
7877   return true;
7878 }
7879 
7880 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7881 /// Ty can be implicit converted to the given set of @p Types. We're
7882 /// primarily interested in pointer types and enumeration types. We also
7883 /// take member pointer types, for the conditional operator.
7884 /// AllowUserConversions is true if we should look at the conversion
7885 /// functions of a class type, and AllowExplicitConversions if we
7886 /// should also include the explicit conversion functions of a class
7887 /// type.
7888 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)7889 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7890                                                SourceLocation Loc,
7891                                                bool AllowUserConversions,
7892                                                bool AllowExplicitConversions,
7893                                                const Qualifiers &VisibleQuals) {
7894   // Only deal with canonical types.
7895   Ty = Context.getCanonicalType(Ty);
7896 
7897   // Look through reference types; they aren't part of the type of an
7898   // expression for the purposes of conversions.
7899   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7900     Ty = RefTy->getPointeeType();
7901 
7902   // If we're dealing with an array type, decay to the pointer.
7903   if (Ty->isArrayType())
7904     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7905 
7906   // Otherwise, we don't care about qualifiers on the type.
7907   Ty = Ty.getLocalUnqualifiedType();
7908 
7909   // Flag if we ever add a non-record type.
7910   const RecordType *TyRec = Ty->getAs<RecordType>();
7911   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7912 
7913   // Flag if we encounter an arithmetic type.
7914   HasArithmeticOrEnumeralTypes =
7915     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7916 
7917   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7918     PointerTypes.insert(Ty);
7919   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7920     // Insert our type, and its more-qualified variants, into the set
7921     // of types.
7922     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7923       return;
7924   } else if (Ty->isMemberPointerType()) {
7925     // Member pointers are far easier, since the pointee can't be converted.
7926     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7927       return;
7928   } else if (Ty->isEnumeralType()) {
7929     HasArithmeticOrEnumeralTypes = true;
7930     EnumerationTypes.insert(Ty);
7931   } else if (Ty->isVectorType()) {
7932     // We treat vector types as arithmetic types in many contexts as an
7933     // extension.
7934     HasArithmeticOrEnumeralTypes = true;
7935     VectorTypes.insert(Ty);
7936   } else if (Ty->isMatrixType()) {
7937     // Similar to vector types, we treat vector types as arithmetic types in
7938     // many contexts as an extension.
7939     HasArithmeticOrEnumeralTypes = true;
7940     MatrixTypes.insert(Ty);
7941   } else if (Ty->isNullPtrType()) {
7942     HasNullPtrType = true;
7943   } else if (AllowUserConversions && TyRec) {
7944     // No conversion functions in incomplete types.
7945     if (!SemaRef.isCompleteType(Loc, Ty))
7946       return;
7947 
7948     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7949     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7950       if (isa<UsingShadowDecl>(D))
7951         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7952 
7953       // Skip conversion function templates; they don't tell us anything
7954       // about which builtin types we can convert to.
7955       if (isa<FunctionTemplateDecl>(D))
7956         continue;
7957 
7958       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7959       if (AllowExplicitConversions || !Conv->isExplicit()) {
7960         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7961                               VisibleQuals);
7962       }
7963     }
7964   }
7965 }
7966 /// Helper function for adjusting address spaces for the pointer or reference
7967 /// operands of builtin operators depending on the argument.
AdjustAddressSpaceForBuiltinOperandType(Sema & S,QualType T,Expr * Arg)7968 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7969                                                         Expr *Arg) {
7970   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7971 }
7972 
7973 /// Helper function for AddBuiltinOperatorCandidates() that adds
7974 /// the volatile- and non-volatile-qualified assignment operators for the
7975 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)7976 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7977                                                    QualType T,
7978                                                    ArrayRef<Expr *> Args,
7979                                     OverloadCandidateSet &CandidateSet) {
7980   QualType ParamTypes[2];
7981 
7982   // T& operator=(T&, T)
7983   ParamTypes[0] = S.Context.getLValueReferenceType(
7984       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7985   ParamTypes[1] = T;
7986   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7987                         /*IsAssignmentOperator=*/true);
7988 
7989   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7990     // volatile T& operator=(volatile T&, T)
7991     ParamTypes[0] = S.Context.getLValueReferenceType(
7992         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7993                                                 Args[0]));
7994     ParamTypes[1] = T;
7995     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7996                           /*IsAssignmentOperator=*/true);
7997   }
7998 }
7999 
8000 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8001 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)8002 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8003     Qualifiers VRQuals;
8004     const RecordType *TyRec;
8005     if (const MemberPointerType *RHSMPType =
8006         ArgExpr->getType()->getAs<MemberPointerType>())
8007       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8008     else
8009       TyRec = ArgExpr->getType()->getAs<RecordType>();
8010     if (!TyRec) {
8011       // Just to be safe, assume the worst case.
8012       VRQuals.addVolatile();
8013       VRQuals.addRestrict();
8014       return VRQuals;
8015     }
8016 
8017     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8018     if (!ClassDecl->hasDefinition())
8019       return VRQuals;
8020 
8021     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8022       if (isa<UsingShadowDecl>(D))
8023         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8024       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8025         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8026         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8027           CanTy = ResTypeRef->getPointeeType();
8028         // Need to go down the pointer/mempointer chain and add qualifiers
8029         // as see them.
8030         bool done = false;
8031         while (!done) {
8032           if (CanTy.isRestrictQualified())
8033             VRQuals.addRestrict();
8034           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8035             CanTy = ResTypePtr->getPointeeType();
8036           else if (const MemberPointerType *ResTypeMPtr =
8037                 CanTy->getAs<MemberPointerType>())
8038             CanTy = ResTypeMPtr->getPointeeType();
8039           else
8040             done = true;
8041           if (CanTy.isVolatileQualified())
8042             VRQuals.addVolatile();
8043           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8044             return VRQuals;
8045         }
8046       }
8047     }
8048     return VRQuals;
8049 }
8050 
8051 namespace {
8052 
8053 /// Helper class to manage the addition of builtin operator overload
8054 /// candidates. It provides shared state and utility methods used throughout
8055 /// the process, as well as a helper method to add each group of builtin
8056 /// operator overloads from the standard to a candidate set.
8057 class BuiltinOperatorOverloadBuilder {
8058   // Common instance state available to all overload candidate addition methods.
8059   Sema &S;
8060   ArrayRef<Expr *> Args;
8061   Qualifiers VisibleTypeConversionsQuals;
8062   bool HasArithmeticOrEnumeralCandidateType;
8063   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8064   OverloadCandidateSet &CandidateSet;
8065 
8066   static constexpr int ArithmeticTypesCap = 24;
8067   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8068 
8069   // Define some indices used to iterate over the arithmetic types in
8070   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8071   // types are that preserved by promotion (C++ [over.built]p2).
8072   unsigned FirstIntegralType,
8073            LastIntegralType;
8074   unsigned FirstPromotedIntegralType,
8075            LastPromotedIntegralType;
8076   unsigned FirstPromotedArithmeticType,
8077            LastPromotedArithmeticType;
8078   unsigned FirstCapabilityType,
8079            LastCapabilityType;
8080   unsigned NumArithmeticTypes;
8081 
InitArithmeticTypes()8082   void InitArithmeticTypes() {
8083     // Start of promoted types.
8084     FirstPromotedArithmeticType = 0;
8085     ArithmeticTypes.push_back(S.Context.FloatTy);
8086     ArithmeticTypes.push_back(S.Context.DoubleTy);
8087     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8088     if (S.Context.getTargetInfo().hasFloat128Type())
8089       ArithmeticTypes.push_back(S.Context.Float128Ty);
8090 
8091     // Start of integral types.
8092     FirstIntegralType = ArithmeticTypes.size();
8093     FirstPromotedIntegralType = ArithmeticTypes.size();
8094     ArithmeticTypes.push_back(S.Context.IntTy);
8095     ArithmeticTypes.push_back(S.Context.LongTy);
8096     ArithmeticTypes.push_back(S.Context.LongLongTy);
8097     if (S.Context.getTargetInfo().hasInt128Type())
8098       ArithmeticTypes.push_back(S.Context.Int128Ty);
8099     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8100     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8101     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8102     if (S.Context.getTargetInfo().hasInt128Type())
8103       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8104 
8105     // Capability types
8106     FirstCapabilityType = ArithmeticTypes.size();
8107     if (S.Context.getTargetInfo().SupportsCapabilities()) {
8108       ArithmeticTypes.push_back(S.Context.IntCapTy);
8109       ArithmeticTypes.push_back(S.Context.UnsignedIntCapTy);
8110     }
8111     LastCapabilityType = ArithmeticTypes.size();
8112 
8113     LastPromotedIntegralType = ArithmeticTypes.size();
8114     LastPromotedArithmeticType = ArithmeticTypes.size();
8115     // End of promoted types.
8116 
8117     ArithmeticTypes.push_back(S.Context.BoolTy);
8118     ArithmeticTypes.push_back(S.Context.CharTy);
8119     ArithmeticTypes.push_back(S.Context.WCharTy);
8120     if (S.Context.getLangOpts().Char8)
8121       ArithmeticTypes.push_back(S.Context.Char8Ty);
8122     ArithmeticTypes.push_back(S.Context.Char16Ty);
8123     ArithmeticTypes.push_back(S.Context.Char32Ty);
8124     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8125     ArithmeticTypes.push_back(S.Context.ShortTy);
8126     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8127     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8128     LastIntegralType = ArithmeticTypes.size();
8129     NumArithmeticTypes = ArithmeticTypes.size();
8130     // End of integral types.
8131     // FIXME: What about complex? What about half?
8132 
8133     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8134            "Enough inline storage for all arithmetic types.");
8135   }
8136 
8137   /// Helper method to factor out the common pattern of adding overloads
8138   /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile,bool HasRestrict)8139   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8140                                            bool HasVolatile,
8141                                            bool HasRestrict) {
8142     QualType ParamTypes[2] = {
8143       S.Context.getLValueReferenceType(CandidateTy),
8144       S.Context.IntTy
8145     };
8146 
8147     // Non-volatile version.
8148     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8149 
8150     // Use a heuristic to reduce number of builtin candidates in the set:
8151     // add volatile version only if there are conversions to a volatile type.
8152     if (HasVolatile) {
8153       ParamTypes[0] =
8154         S.Context.getLValueReferenceType(
8155           S.Context.getVolatileType(CandidateTy));
8156       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8157     }
8158 
8159     // Add restrict version only if there are conversions to a restrict type
8160     // and our candidate type is a non-restrict-qualified pointer.
8161     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8162         !CandidateTy.isRestrictQualified()) {
8163       ParamTypes[0]
8164         = S.Context.getLValueReferenceType(
8165             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8166       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8167 
8168       if (HasVolatile) {
8169         ParamTypes[0]
8170           = S.Context.getLValueReferenceType(
8171               S.Context.getCVRQualifiedType(CandidateTy,
8172                                             (Qualifiers::Volatile |
8173                                              Qualifiers::Restrict)));
8174         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8175       }
8176     }
8177 
8178   }
8179 
8180   /// Helper to add an overload candidate for a binary builtin with types \p L
8181   /// and \p R.
AddCandidate(QualType L,QualType R)8182   void AddCandidate(QualType L, QualType R) {
8183     QualType LandR[2] = {L, R};
8184     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8185   }
8186 
8187 public:
BuiltinOperatorOverloadBuilder(Sema & S,ArrayRef<Expr * > Args,Qualifiers VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)8188   BuiltinOperatorOverloadBuilder(
8189     Sema &S, ArrayRef<Expr *> Args,
8190     Qualifiers VisibleTypeConversionsQuals,
8191     bool HasArithmeticOrEnumeralCandidateType,
8192     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8193     OverloadCandidateSet &CandidateSet)
8194     : S(S), Args(Args),
8195       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8196       HasArithmeticOrEnumeralCandidateType(
8197         HasArithmeticOrEnumeralCandidateType),
8198       CandidateTypes(CandidateTypes),
8199       CandidateSet(CandidateSet) {
8200 
8201     InitArithmeticTypes();
8202   }
8203 
8204   // Increment is deprecated for bool since C++17.
8205   //
8206   // C++ [over.built]p3:
8207   //
8208   //   For every pair (T, VQ), where T is an arithmetic type other
8209   //   than bool, and VQ is either volatile or empty, there exist
8210   //   candidate operator functions of the form
8211   //
8212   //       VQ T&      operator++(VQ T&);
8213   //       T          operator++(VQ T&, int);
8214   //
8215   // C++ [over.built]p4:
8216   //
8217   //   For every pair (T, VQ), where T is an arithmetic type other
8218   //   than bool, and VQ is either volatile or empty, there exist
8219   //   candidate operator functions of the form
8220   //
8221   //       VQ T&      operator--(VQ T&);
8222   //       T          operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)8223   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8224     if (!HasArithmeticOrEnumeralCandidateType)
8225       return;
8226 
8227     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8228       const auto TypeOfT = ArithmeticTypes[Arith];
8229       if (TypeOfT == S.Context.BoolTy) {
8230         if (Op == OO_MinusMinus)
8231           continue;
8232         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8233           continue;
8234       }
8235       addPlusPlusMinusMinusStyleOverloads(
8236         TypeOfT,
8237         VisibleTypeConversionsQuals.hasVolatile(),
8238         VisibleTypeConversionsQuals.hasRestrict());
8239     }
8240   }
8241 
8242   // C++ [over.built]p5:
8243   //
8244   //   For every pair (T, VQ), where T is a cv-qualified or
8245   //   cv-unqualified object type, and VQ is either volatile or
8246   //   empty, there exist candidate operator functions of the form
8247   //
8248   //       T*VQ&      operator++(T*VQ&);
8249   //       T*VQ&      operator--(T*VQ&);
8250   //       T*         operator++(T*VQ&, int);
8251   //       T*         operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()8252   void addPlusPlusMinusMinusPointerOverloads() {
8253     for (BuiltinCandidateTypeSet::iterator
8254               Ptr = CandidateTypes[0].pointer_begin(),
8255            PtrEnd = CandidateTypes[0].pointer_end();
8256          Ptr != PtrEnd; ++Ptr) {
8257       // Skip pointer types that aren't pointers to object types.
8258       if (!(*Ptr)->getPointeeType()->isObjectType())
8259         continue;
8260 
8261       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8262         (!(*Ptr).isVolatileQualified() &&
8263          VisibleTypeConversionsQuals.hasVolatile()),
8264         (!(*Ptr).isRestrictQualified() &&
8265          VisibleTypeConversionsQuals.hasRestrict()));
8266     }
8267   }
8268 
8269   // C++ [over.built]p6:
8270   //   For every cv-qualified or cv-unqualified object type T, there
8271   //   exist candidate operator functions of the form
8272   //
8273   //       T&         operator*(T*);
8274   //
8275   // C++ [over.built]p7:
8276   //   For every function type T that does not have cv-qualifiers or a
8277   //   ref-qualifier, there exist candidate operator functions of the form
8278   //       T&         operator*(T*);
addUnaryStarPointerOverloads()8279   void addUnaryStarPointerOverloads() {
8280     for (BuiltinCandidateTypeSet::iterator
8281               Ptr = CandidateTypes[0].pointer_begin(),
8282            PtrEnd = CandidateTypes[0].pointer_end();
8283          Ptr != PtrEnd; ++Ptr) {
8284       QualType ParamTy = *Ptr;
8285       QualType PointeeTy = ParamTy->getPointeeType();
8286       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8287         continue;
8288 
8289       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8290         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8291           continue;
8292 
8293       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8294     }
8295   }
8296 
8297   // C++ [over.built]p9:
8298   //  For every promoted arithmetic type T, there exist candidate
8299   //  operator functions of the form
8300   //
8301   //       T         operator+(T);
8302   //       T         operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()8303   void addUnaryPlusOrMinusArithmeticOverloads() {
8304     if (!HasArithmeticOrEnumeralCandidateType)
8305       return;
8306 
8307     for (unsigned Arith = FirstPromotedArithmeticType;
8308          Arith < LastPromotedArithmeticType; ++Arith) {
8309       QualType ArithTy = ArithmeticTypes[Arith];
8310       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8311     }
8312 
8313     // Extension: We also add these operators for vector types.
8314     for (QualType VecTy : CandidateTypes[0].vector_types())
8315       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8316   }
8317 
8318   // C++ [over.built]p8:
8319   //   For every type T, there exist candidate operator functions of
8320   //   the form
8321   //
8322   //       T*         operator+(T*);
addUnaryPlusPointerOverloads()8323   void addUnaryPlusPointerOverloads() {
8324     for (BuiltinCandidateTypeSet::iterator
8325               Ptr = CandidateTypes[0].pointer_begin(),
8326            PtrEnd = CandidateTypes[0].pointer_end();
8327          Ptr != PtrEnd; ++Ptr) {
8328       QualType ParamTy = *Ptr;
8329       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8330     }
8331   }
8332 
8333   // C++ [over.built]p10:
8334   //   For every promoted integral type T, there exist candidate
8335   //   operator functions of the form
8336   //
8337   //        T         operator~(T);
addUnaryTildePromotedIntegralOverloads()8338   void addUnaryTildePromotedIntegralOverloads() {
8339     if (!HasArithmeticOrEnumeralCandidateType)
8340       return;
8341 
8342     for (unsigned Int = FirstPromotedIntegralType;
8343          Int < LastPromotedIntegralType; ++Int) {
8344       QualType IntTy = ArithmeticTypes[Int];
8345       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8346     }
8347 
8348     // Extension: We also add this operator for vector types.
8349     for (QualType VecTy : CandidateTypes[0].vector_types())
8350       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8351   }
8352 
8353   // C++ [over.match.oper]p16:
8354   //   For every pointer to member type T or type std::nullptr_t, there
8355   //   exist candidate operator functions of the form
8356   //
8357   //        bool operator==(T,T);
8358   //        bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads()8359   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8360     /// Set of (canonical) types that we've already handled.
8361     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8362 
8363     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8364       for (BuiltinCandidateTypeSet::iterator
8365                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8366              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8367            MemPtr != MemPtrEnd;
8368            ++MemPtr) {
8369         // Don't add the same builtin candidate twice.
8370         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8371           continue;
8372 
8373         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8374         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8375       }
8376 
8377       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8378         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8379         if (AddedTypes.insert(NullPtrTy).second) {
8380           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8381           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8382         }
8383       }
8384     }
8385   }
8386 
8387   // C++ [over.built]p15:
8388   //
8389   //   For every T, where T is an enumeration type or a pointer type,
8390   //   there exist candidate operator functions of the form
8391   //
8392   //        bool       operator<(T, T);
8393   //        bool       operator>(T, T);
8394   //        bool       operator<=(T, T);
8395   //        bool       operator>=(T, T);
8396   //        bool       operator==(T, T);
8397   //        bool       operator!=(T, T);
8398   //           R       operator<=>(T, T)
addGenericBinaryPointerOrEnumeralOverloads()8399   void addGenericBinaryPointerOrEnumeralOverloads() {
8400     // C++ [over.match.oper]p3:
8401     //   [...]the built-in candidates include all of the candidate operator
8402     //   functions defined in 13.6 that, compared to the given operator, [...]
8403     //   do not have the same parameter-type-list as any non-template non-member
8404     //   candidate.
8405     //
8406     // Note that in practice, this only affects enumeration types because there
8407     // aren't any built-in candidates of record type, and a user-defined operator
8408     // must have an operand of record or enumeration type. Also, the only other
8409     // overloaded operator with enumeration arguments, operator=,
8410     // cannot be overloaded for enumeration types, so this is the only place
8411     // where we must suppress candidates like this.
8412     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8413       UserDefinedBinaryOperators;
8414 
8415     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8416       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8417           CandidateTypes[ArgIdx].enumeration_end()) {
8418         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8419                                          CEnd = CandidateSet.end();
8420              C != CEnd; ++C) {
8421           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8422             continue;
8423 
8424           if (C->Function->isFunctionTemplateSpecialization())
8425             continue;
8426 
8427           // We interpret "same parameter-type-list" as applying to the
8428           // "synthesized candidate, with the order of the two parameters
8429           // reversed", not to the original function.
8430           bool Reversed = C->isReversed();
8431           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8432                                         ->getType()
8433                                         .getUnqualifiedType();
8434           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8435                                          ->getType()
8436                                          .getUnqualifiedType();
8437 
8438           // Skip if either parameter isn't of enumeral type.
8439           if (!FirstParamType->isEnumeralType() ||
8440               !SecondParamType->isEnumeralType())
8441             continue;
8442 
8443           // Add this operator to the set of known user-defined operators.
8444           UserDefinedBinaryOperators.insert(
8445             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8446                            S.Context.getCanonicalType(SecondParamType)));
8447         }
8448       }
8449     }
8450 
8451     /// Set of (canonical) types that we've already handled.
8452     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8453 
8454     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8455       for (BuiltinCandidateTypeSet::iterator
8456                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8457              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8458            Ptr != PtrEnd; ++Ptr) {
8459         // Don't add the same builtin candidate twice.
8460         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8461           continue;
8462 
8463         QualType ParamTypes[2] = { *Ptr, *Ptr };
8464         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8465       }
8466       for (BuiltinCandidateTypeSet::iterator
8467                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8468              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8469            Enum != EnumEnd; ++Enum) {
8470         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8471 
8472         // Don't add the same builtin candidate twice, or if a user defined
8473         // candidate exists.
8474         if (!AddedTypes.insert(CanonType).second ||
8475             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8476                                                             CanonType)))
8477           continue;
8478         QualType ParamTypes[2] = { *Enum, *Enum };
8479         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8480       }
8481     }
8482   }
8483 
8484   // C++ [over.built]p13:
8485   //
8486   //   For every cv-qualified or cv-unqualified object type T
8487   //   there exist candidate operator functions of the form
8488   //
8489   //      T*         operator+(T*, ptrdiff_t);
8490   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8491   //      T*         operator-(T*, ptrdiff_t);
8492   //      T*         operator+(ptrdiff_t, T*);
8493   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8494   //
8495   // C++ [over.built]p14:
8496   //
8497   //   For every T, where T is a pointer to object type, there
8498   //   exist candidate operator functions of the form
8499   //
8500   //      ptrdiff_t  operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)8501   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8502     /// Set of (canonical) types that we've already handled.
8503     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8504 
8505     for (int Arg = 0; Arg < 2; ++Arg) {
8506       QualType AsymmetricParamTypes[2] = {
8507         S.Context.getPointerDiffType(),
8508         S.Context.getPointerDiffType(),
8509       };
8510       for (BuiltinCandidateTypeSet::iterator
8511                 Ptr = CandidateTypes[Arg].pointer_begin(),
8512              PtrEnd = CandidateTypes[Arg].pointer_end();
8513            Ptr != PtrEnd; ++Ptr) {
8514         QualType PointeeTy = (*Ptr)->getPointeeType();
8515         if (!PointeeTy->isObjectType())
8516           continue;
8517 
8518         AsymmetricParamTypes[Arg] = *Ptr;
8519         if (Arg == 0 || Op == OO_Plus) {
8520           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8521           // T* operator+(ptrdiff_t, T*);
8522           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8523         }
8524         if (Op == OO_Minus) {
8525           // ptrdiff_t operator-(T, T);
8526           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8527             continue;
8528 
8529           QualType ParamTypes[2] = { *Ptr, *Ptr };
8530           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8531         }
8532       }
8533     }
8534   }
8535 
8536   // C++ [over.built]p12:
8537   //
8538   //   For every pair of promoted arithmetic types L and R, there
8539   //   exist candidate operator functions of the form
8540   //
8541   //        LR         operator*(L, R);
8542   //        LR         operator/(L, R);
8543   //        LR         operator+(L, R);
8544   //        LR         operator-(L, R);
8545   //        bool       operator<(L, R);
8546   //        bool       operator>(L, R);
8547   //        bool       operator<=(L, R);
8548   //        bool       operator>=(L, R);
8549   //        bool       operator==(L, R);
8550   //        bool       operator!=(L, R);
8551   //
8552   //   where LR is the result of the usual arithmetic conversions
8553   //   between types L and R.
8554   //
8555   // C++ [over.built]p24:
8556   //
8557   //   For every pair of promoted arithmetic types L and R, there exist
8558   //   candidate operator functions of the form
8559   //
8560   //        LR       operator?(bool, L, R);
8561   //
8562   //   where LR is the result of the usual arithmetic conversions
8563   //   between types L and R.
8564   // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads()8565   void addGenericBinaryArithmeticOverloads() {
8566     if (!HasArithmeticOrEnumeralCandidateType)
8567       return;
8568     for (unsigned Left = FirstPromotedArithmeticType;
8569          Left < LastPromotedArithmeticType; ++Left) {
8570       for (unsigned Right = FirstPromotedArithmeticType;
8571            Right < LastPromotedArithmeticType; ++Right) {
8572         QualType LandR[2] = { ArithmeticTypes[Left],
8573                               ArithmeticTypes[Right] };
8574         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8575       }
8576     }
8577 
8578     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8579     // conditional operator for vector types.
8580     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8581       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8582         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8583         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8584       }
8585   }
8586 
8587   /// Add binary operator overloads for each candidate matrix type M1, M2:
8588   ///  * (M1, M1) -> M1
8589   ///  * (M1, M1.getElementType()) -> M1
8590   ///  * (M2.getElementType(), M2) -> M2
8591   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
addMatrixBinaryArithmeticOverloads()8592   void addMatrixBinaryArithmeticOverloads() {
8593     if (!HasArithmeticOrEnumeralCandidateType)
8594       return;
8595 
8596     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8597       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8598       AddCandidate(M1, M1);
8599     }
8600 
8601     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8602       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8603       if (!CandidateTypes[0].containsMatrixType(M2))
8604         AddCandidate(M2, M2);
8605     }
8606   }
8607 
8608   // C++2a [over.built]p14:
8609   //
8610   //   For every integral type T there exists a candidate operator function
8611   //   of the form
8612   //
8613   //        std::strong_ordering operator<=>(T, T)
8614   //
8615   // C++2a [over.built]p15:
8616   //
8617   //   For every pair of floating-point types L and R, there exists a candidate
8618   //   operator function of the form
8619   //
8620   //       std::partial_ordering operator<=>(L, R);
8621   //
8622   // FIXME: The current specification for integral types doesn't play nice with
8623   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8624   // comparisons. Under the current spec this can lead to ambiguity during
8625   // overload resolution. For example:
8626   //
8627   //   enum A : int {a};
8628   //   auto x = (a <=> (long)42);
8629   //
8630   //   error: call is ambiguous for arguments 'A' and 'long'.
8631   //   note: candidate operator<=>(int, int)
8632   //   note: candidate operator<=>(long, long)
8633   //
8634   // To avoid this error, this function deviates from the specification and adds
8635   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8636   // arithmetic types (the same as the generic relational overloads).
8637   //
8638   // For now this function acts as a placeholder.
addThreeWayArithmeticOverloads()8639   void addThreeWayArithmeticOverloads() {
8640     addGenericBinaryArithmeticOverloads();
8641   }
8642 
8643   // C++ [over.built]p17:
8644   //
8645   //   For every pair of promoted integral types L and R, there
8646   //   exist candidate operator functions of the form
8647   //
8648   //      LR         operator%(L, R);
8649   //      LR         operator&(L, R);
8650   //      LR         operator^(L, R);
8651   //      LR         operator|(L, R);
8652   //      L          operator<<(L, R);
8653   //      L          operator>>(L, R);
8654   //
8655   //   where LR is the result of the usual arithmetic conversions
8656   //   between types L and R.
addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op)8657   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8658     if (!HasArithmeticOrEnumeralCandidateType)
8659       return;
8660 
8661     unsigned LastType = S.Context.getTargetInfo().SupportsCapabilities()
8662                         ? LastCapabilityType : LastPromotedIntegralType;
8663     // XXXAR: allow any type as the RHS operand for a bitwise op with capabilities
8664     for (unsigned Left = FirstPromotedIntegralType;
8665          Left < LastType; ++Left) {
8666       for (unsigned Right = FirstPromotedIntegralType;
8667            Right < LastPromotedIntegralType; ++Right) {
8668         QualType LandR[2] = { ArithmeticTypes[Left],
8669                               ArithmeticTypes[Right] };
8670         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8671       }
8672     }
8673 
8674   }
8675 
8676   // C++ [over.built]p20:
8677   //
8678   //   For every pair (T, VQ), where T is an enumeration or
8679   //   pointer to member type and VQ is either volatile or
8680   //   empty, there exist candidate operator functions of the form
8681   //
8682   //        VQ T&      operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()8683   void addAssignmentMemberPointerOrEnumeralOverloads() {
8684     /// Set of (canonical) types that we've already handled.
8685     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8686 
8687     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8688       for (BuiltinCandidateTypeSet::iterator
8689                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8690              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8691            Enum != EnumEnd; ++Enum) {
8692         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8693           continue;
8694 
8695         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8696       }
8697 
8698       for (BuiltinCandidateTypeSet::iterator
8699                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8700              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8701            MemPtr != MemPtrEnd; ++MemPtr) {
8702         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8703           continue;
8704 
8705         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8706       }
8707     }
8708   }
8709 
8710   // C++ [over.built]p19:
8711   //
8712   //   For every pair (T, VQ), where T is any type and VQ is either
8713   //   volatile or empty, there exist candidate operator functions
8714   //   of the form
8715   //
8716   //        T*VQ&      operator=(T*VQ&, T*);
8717   //
8718   // C++ [over.built]p21:
8719   //
8720   //   For every pair (T, VQ), where T is a cv-qualified or
8721   //   cv-unqualified object type and VQ is either volatile or
8722   //   empty, there exist candidate operator functions of the form
8723   //
8724   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8725   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)8726   void addAssignmentPointerOverloads(bool isEqualOp) {
8727     /// Set of (canonical) types that we've already handled.
8728     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8729 
8730     for (BuiltinCandidateTypeSet::iterator
8731               Ptr = CandidateTypes[0].pointer_begin(),
8732            PtrEnd = CandidateTypes[0].pointer_end();
8733          Ptr != PtrEnd; ++Ptr) {
8734       // If this is operator=, keep track of the builtin candidates we added.
8735       if (isEqualOp)
8736         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8737       else if (!(*Ptr)->getPointeeType()->isObjectType())
8738         continue;
8739 
8740       // non-volatile version
8741       QualType ParamTypes[2] = {
8742         S.Context.getLValueReferenceType(*Ptr),
8743         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8744       };
8745       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8746                             /*IsAssignmentOperator=*/ isEqualOp);
8747 
8748       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8749                           VisibleTypeConversionsQuals.hasVolatile();
8750       if (NeedVolatile) {
8751         // volatile version
8752         ParamTypes[0] =
8753           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8754         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8755                               /*IsAssignmentOperator=*/isEqualOp);
8756       }
8757 
8758       if (!(*Ptr).isRestrictQualified() &&
8759           VisibleTypeConversionsQuals.hasRestrict()) {
8760         // restrict version
8761         ParamTypes[0]
8762           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8763         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8764                               /*IsAssignmentOperator=*/isEqualOp);
8765 
8766         if (NeedVolatile) {
8767           // volatile restrict version
8768           ParamTypes[0]
8769             = S.Context.getLValueReferenceType(
8770                 S.Context.getCVRQualifiedType(*Ptr,
8771                                               (Qualifiers::Volatile |
8772                                                Qualifiers::Restrict)));
8773           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8774                                 /*IsAssignmentOperator=*/isEqualOp);
8775         }
8776       }
8777     }
8778 
8779     if (isEqualOp) {
8780       for (BuiltinCandidateTypeSet::iterator
8781                 Ptr = CandidateTypes[1].pointer_begin(),
8782              PtrEnd = CandidateTypes[1].pointer_end();
8783            Ptr != PtrEnd; ++Ptr) {
8784         // Make sure we don't add the same candidate twice.
8785         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8786           continue;
8787 
8788         QualType ParamTypes[2] = {
8789           S.Context.getLValueReferenceType(*Ptr),
8790           *Ptr,
8791         };
8792 
8793         // non-volatile version
8794         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8795                               /*IsAssignmentOperator=*/true);
8796 
8797         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8798                            VisibleTypeConversionsQuals.hasVolatile();
8799         if (NeedVolatile) {
8800           // volatile version
8801           ParamTypes[0] =
8802             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8803           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8804                                 /*IsAssignmentOperator=*/true);
8805         }
8806 
8807         if (!(*Ptr).isRestrictQualified() &&
8808             VisibleTypeConversionsQuals.hasRestrict()) {
8809           // restrict version
8810           ParamTypes[0]
8811             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8812           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8813                                 /*IsAssignmentOperator=*/true);
8814 
8815           if (NeedVolatile) {
8816             // volatile restrict version
8817             ParamTypes[0]
8818               = S.Context.getLValueReferenceType(
8819                   S.Context.getCVRQualifiedType(*Ptr,
8820                                                 (Qualifiers::Volatile |
8821                                                  Qualifiers::Restrict)));
8822             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8823                                   /*IsAssignmentOperator=*/true);
8824           }
8825         }
8826       }
8827     }
8828   }
8829 
8830   // C++ [over.built]p18:
8831   //
8832   //   For every triple (L, VQ, R), where L is an arithmetic type,
8833   //   VQ is either volatile or empty, and R is a promoted
8834   //   arithmetic type, there exist candidate operator functions of
8835   //   the form
8836   //
8837   //        VQ L&      operator=(VQ L&, R);
8838   //        VQ L&      operator*=(VQ L&, R);
8839   //        VQ L&      operator/=(VQ L&, R);
8840   //        VQ L&      operator+=(VQ L&, R);
8841   //        VQ L&      operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)8842   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8843     if (!HasArithmeticOrEnumeralCandidateType)
8844       return;
8845 
8846     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8847       for (unsigned Right = FirstPromotedArithmeticType;
8848            Right < LastPromotedArithmeticType; ++Right) {
8849         QualType ParamTypes[2];
8850         ParamTypes[1] = ArithmeticTypes[Right];
8851         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8852             S, ArithmeticTypes[Left], Args[0]);
8853         // Add this built-in operator as a candidate (VQ is empty).
8854         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8855         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8856                               /*IsAssignmentOperator=*/isEqualOp);
8857 
8858         // Add this built-in operator as a candidate (VQ is 'volatile').
8859         if (VisibleTypeConversionsQuals.hasVolatile()) {
8860           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8861           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8862           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8863                                 /*IsAssignmentOperator=*/isEqualOp);
8864         }
8865       }
8866     }
8867 
8868     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8869     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8870       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8871         QualType ParamTypes[2];
8872         ParamTypes[1] = Vec2Ty;
8873         // Add this built-in operator as a candidate (VQ is empty).
8874         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8875         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8876                               /*IsAssignmentOperator=*/isEqualOp);
8877 
8878         // Add this built-in operator as a candidate (VQ is 'volatile').
8879         if (VisibleTypeConversionsQuals.hasVolatile()) {
8880           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8881           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8882           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8883                                 /*IsAssignmentOperator=*/isEqualOp);
8884         }
8885       }
8886   }
8887 
8888   // C++ [over.built]p22:
8889   //
8890   //   For every triple (L, VQ, R), where L is an integral type, VQ
8891   //   is either volatile or empty, and R is a promoted integral
8892   //   type, there exist candidate operator functions of the form
8893   //
8894   //        VQ L&       operator%=(VQ L&, R);
8895   //        VQ L&       operator<<=(VQ L&, R);
8896   //        VQ L&       operator>>=(VQ L&, R);
8897   //        VQ L&       operator&=(VQ L&, R);
8898   //        VQ L&       operator^=(VQ L&, R);
8899   //        VQ L&       operator|=(VQ L&, R);
addAssignmentIntegralOverloads()8900   void addAssignmentIntegralOverloads() {
8901     if (!HasArithmeticOrEnumeralCandidateType)
8902       return;
8903 
8904     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8905       for (unsigned Right = FirstPromotedIntegralType;
8906            Right < LastPromotedIntegralType; ++Right) {
8907         QualType ParamTypes[2];
8908         ParamTypes[1] = ArithmeticTypes[Right];
8909         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8910             S, ArithmeticTypes[Left], Args[0]);
8911         // Add this built-in operator as a candidate (VQ is empty).
8912         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8913         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8914         if (VisibleTypeConversionsQuals.hasVolatile()) {
8915           // Add this built-in operator as a candidate (VQ is 'volatile').
8916           ParamTypes[0] = LeftBaseTy;
8917           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8918           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8919           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8920         }
8921       }
8922     }
8923   }
8924 
8925   // C++ [over.operator]p23:
8926   //
8927   //   There also exist candidate operator functions of the form
8928   //
8929   //        bool        operator!(bool);
8930   //        bool        operator&&(bool, bool);
8931   //        bool        operator||(bool, bool);
addExclaimOverload()8932   void addExclaimOverload() {
8933     QualType ParamTy = S.Context.BoolTy;
8934     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8935                           /*IsAssignmentOperator=*/false,
8936                           /*NumContextualBoolArguments=*/1);
8937   }
addAmpAmpOrPipePipeOverload()8938   void addAmpAmpOrPipePipeOverload() {
8939     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8940     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8941                           /*IsAssignmentOperator=*/false,
8942                           /*NumContextualBoolArguments=*/2);
8943   }
8944 
8945   // C++ [over.built]p13:
8946   //
8947   //   For every cv-qualified or cv-unqualified object type T there
8948   //   exist candidate operator functions of the form
8949   //
8950   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8951   //        T&         operator[](T*, ptrdiff_t);
8952   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8953   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8954   //        T&         operator[](ptrdiff_t, T*);
addSubscriptOverloads()8955   void addSubscriptOverloads() {
8956     for (BuiltinCandidateTypeSet::iterator
8957               Ptr = CandidateTypes[0].pointer_begin(),
8958            PtrEnd = CandidateTypes[0].pointer_end();
8959          Ptr != PtrEnd; ++Ptr) {
8960       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8961       QualType PointeeType = (*Ptr)->getPointeeType();
8962       if (!PointeeType->isObjectType())
8963         continue;
8964 
8965       // T& operator[](T*, ptrdiff_t)
8966       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8967     }
8968 
8969     for (BuiltinCandidateTypeSet::iterator
8970               Ptr = CandidateTypes[1].pointer_begin(),
8971            PtrEnd = CandidateTypes[1].pointer_end();
8972          Ptr != PtrEnd; ++Ptr) {
8973       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8974       QualType PointeeType = (*Ptr)->getPointeeType();
8975       if (!PointeeType->isObjectType())
8976         continue;
8977 
8978       // T& operator[](ptrdiff_t, T*)
8979       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8980     }
8981   }
8982 
8983   // C++ [over.built]p11:
8984   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8985   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8986   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8987   //    there exist candidate operator functions of the form
8988   //
8989   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8990   //
8991   //    where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()8992   void addArrowStarOverloads() {
8993     for (BuiltinCandidateTypeSet::iterator
8994              Ptr = CandidateTypes[0].pointer_begin(),
8995            PtrEnd = CandidateTypes[0].pointer_end();
8996          Ptr != PtrEnd; ++Ptr) {
8997       QualType C1Ty = (*Ptr);
8998       QualType C1;
8999       QualifierCollector Q1;
9000       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9001       if (!isa<RecordType>(C1))
9002         continue;
9003       // heuristic to reduce number of builtin candidates in the set.
9004       // Add volatile/restrict version only if there are conversions to a
9005       // volatile/restrict type.
9006       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9007         continue;
9008       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9009         continue;
9010       for (BuiltinCandidateTypeSet::iterator
9011                 MemPtr = CandidateTypes[1].member_pointer_begin(),
9012              MemPtrEnd = CandidateTypes[1].member_pointer_end();
9013            MemPtr != MemPtrEnd; ++MemPtr) {
9014         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
9015         QualType C2 = QualType(mptr->getClass(), 0);
9016         C2 = C2.getUnqualifiedType();
9017         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9018           break;
9019         QualType ParamTypes[2] = { *Ptr, *MemPtr };
9020         // build CV12 T&
9021         QualType T = mptr->getPointeeType();
9022         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9023             T.isVolatileQualified())
9024           continue;
9025         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9026             T.isRestrictQualified())
9027           continue;
9028         T = Q1.apply(S.Context, T);
9029         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9030       }
9031     }
9032   }
9033 
9034   // Note that we don't consider the first argument, since it has been
9035   // contextually converted to bool long ago. The candidates below are
9036   // therefore added as binary.
9037   //
9038   // C++ [over.built]p25:
9039   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9040   //   enumeration type, there exist candidate operator functions of the form
9041   //
9042   //        T        operator?(bool, T, T);
9043   //
addConditionalOperatorOverloads()9044   void addConditionalOperatorOverloads() {
9045     /// Set of (canonical) types that we've already handled.
9046     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9047 
9048     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9049       for (BuiltinCandidateTypeSet::iterator
9050                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9051              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9052            Ptr != PtrEnd; ++Ptr) {
9053         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9054           continue;
9055 
9056         QualType ParamTypes[2] = { *Ptr, *Ptr };
9057         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9058       }
9059 
9060       for (BuiltinCandidateTypeSet::iterator
9061                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9062              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9063            MemPtr != MemPtrEnd; ++MemPtr) {
9064         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9065           continue;
9066 
9067         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9068         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9069       }
9070 
9071       if (S.getLangOpts().CPlusPlus11) {
9072         for (BuiltinCandidateTypeSet::iterator
9073                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9074                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9075              Enum != EnumEnd; ++Enum) {
9076           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9077             continue;
9078 
9079           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9080             continue;
9081 
9082           QualType ParamTypes[2] = { *Enum, *Enum };
9083           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9084         }
9085       }
9086     }
9087   }
9088 };
9089 
9090 } // end anonymous namespace
9091 
9092 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9093 /// operator overloads to the candidate set (C++ [over.built]), based
9094 /// on the operator @p Op and the arguments given. For example, if the
9095 /// operator is a binary '+', this routine might add "int
9096 /// operator+(int, int)" to cover integer addition.
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)9097 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9098                                         SourceLocation OpLoc,
9099                                         ArrayRef<Expr *> Args,
9100                                         OverloadCandidateSet &CandidateSet) {
9101   // Find all of the types that the arguments can convert to, but only
9102   // if the operator we're looking at has built-in operator candidates
9103   // that make use of these types. Also record whether we encounter non-record
9104   // candidate types or either arithmetic or enumeral candidate types.
9105   Qualifiers VisibleTypeConversionsQuals;
9106   VisibleTypeConversionsQuals.addConst();
9107   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9108     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9109 
9110   bool HasNonRecordCandidateType = false;
9111   bool HasArithmeticOrEnumeralCandidateType = false;
9112   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9113   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9114     CandidateTypes.emplace_back(*this);
9115     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9116                                                  OpLoc,
9117                                                  true,
9118                                                  (Op == OO_Exclaim ||
9119                                                   Op == OO_AmpAmp ||
9120                                                   Op == OO_PipePipe),
9121                                                  VisibleTypeConversionsQuals);
9122     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9123         CandidateTypes[ArgIdx].hasNonRecordTypes();
9124     HasArithmeticOrEnumeralCandidateType =
9125         HasArithmeticOrEnumeralCandidateType ||
9126         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9127   }
9128 
9129   // Exit early when no non-record types have been added to the candidate set
9130   // for any of the arguments to the operator.
9131   //
9132   // We can't exit early for !, ||, or &&, since there we have always have
9133   // 'bool' overloads.
9134   if (!HasNonRecordCandidateType &&
9135       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9136     return;
9137 
9138   // Setup an object to manage the common state for building overloads.
9139   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9140                                            VisibleTypeConversionsQuals,
9141                                            HasArithmeticOrEnumeralCandidateType,
9142                                            CandidateTypes, CandidateSet);
9143 
9144   // Dispatch over the operation to add in only those overloads which apply.
9145   switch (Op) {
9146   case OO_None:
9147   case NUM_OVERLOADED_OPERATORS:
9148     llvm_unreachable("Expected an overloaded operator");
9149 
9150   case OO_New:
9151   case OO_Delete:
9152   case OO_Array_New:
9153   case OO_Array_Delete:
9154   case OO_Call:
9155     llvm_unreachable(
9156                     "Special operators don't use AddBuiltinOperatorCandidates");
9157 
9158   case OO_Comma:
9159   case OO_Arrow:
9160   case OO_Coawait:
9161     // C++ [over.match.oper]p3:
9162     //   -- For the operator ',', the unary operator '&', the
9163     //      operator '->', or the operator 'co_await', the
9164     //      built-in candidates set is empty.
9165     break;
9166 
9167   case OO_Plus: // '+' is either unary or binary
9168     if (Args.size() == 1)
9169       OpBuilder.addUnaryPlusPointerOverloads();
9170     LLVM_FALLTHROUGH;
9171 
9172   case OO_Minus: // '-' is either unary or binary
9173     if (Args.size() == 1) {
9174       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9175     } else {
9176       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9177       OpBuilder.addGenericBinaryArithmeticOverloads();
9178       OpBuilder.addMatrixBinaryArithmeticOverloads();
9179     }
9180     break;
9181 
9182   case OO_Star: // '*' is either unary or binary
9183     if (Args.size() == 1)
9184       OpBuilder.addUnaryStarPointerOverloads();
9185     else {
9186       OpBuilder.addGenericBinaryArithmeticOverloads();
9187       OpBuilder.addMatrixBinaryArithmeticOverloads();
9188     }
9189     break;
9190 
9191   case OO_Slash:
9192     OpBuilder.addGenericBinaryArithmeticOverloads();
9193     break;
9194 
9195   case OO_PlusPlus:
9196   case OO_MinusMinus:
9197     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9198     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9199     break;
9200 
9201   case OO_EqualEqual:
9202   case OO_ExclaimEqual:
9203     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9204     LLVM_FALLTHROUGH;
9205 
9206   case OO_Less:
9207   case OO_Greater:
9208   case OO_LessEqual:
9209   case OO_GreaterEqual:
9210     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9211     OpBuilder.addGenericBinaryArithmeticOverloads();
9212     break;
9213 
9214   case OO_Spaceship:
9215     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9216     OpBuilder.addThreeWayArithmeticOverloads();
9217     break;
9218 
9219   case OO_Percent:
9220   case OO_Caret:
9221   case OO_Pipe:
9222   case OO_LessLess:
9223   case OO_GreaterGreater:
9224     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9225     break;
9226 
9227   case OO_Amp: // '&' is either unary or binary
9228     if (Args.size() == 1)
9229       // C++ [over.match.oper]p3:
9230       //   -- For the operator ',', the unary operator '&', or the
9231       //      operator '->', the built-in candidates set is empty.
9232       break;
9233 
9234     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9235     break;
9236 
9237   case OO_Tilde:
9238     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9239     break;
9240 
9241   case OO_Equal:
9242     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9243     LLVM_FALLTHROUGH;
9244 
9245   case OO_PlusEqual:
9246   case OO_MinusEqual:
9247     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9248     LLVM_FALLTHROUGH;
9249 
9250   case OO_StarEqual:
9251   case OO_SlashEqual:
9252     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9253     break;
9254 
9255   case OO_PercentEqual:
9256   case OO_LessLessEqual:
9257   case OO_GreaterGreaterEqual:
9258   case OO_AmpEqual:
9259   case OO_CaretEqual:
9260   case OO_PipeEqual:
9261     OpBuilder.addAssignmentIntegralOverloads();
9262     break;
9263 
9264   case OO_Exclaim:
9265     OpBuilder.addExclaimOverload();
9266     break;
9267 
9268   case OO_AmpAmp:
9269   case OO_PipePipe:
9270     OpBuilder.addAmpAmpOrPipePipeOverload();
9271     break;
9272 
9273   case OO_Subscript:
9274     OpBuilder.addSubscriptOverloads();
9275     break;
9276 
9277   case OO_ArrowStar:
9278     OpBuilder.addArrowStarOverloads();
9279     break;
9280 
9281   case OO_Conditional:
9282     OpBuilder.addConditionalOperatorOverloads();
9283     OpBuilder.addGenericBinaryArithmeticOverloads();
9284     break;
9285   }
9286 }
9287 
9288 /// Add function candidates found via argument-dependent lookup
9289 /// to the set of overloading candidates.
9290 ///
9291 /// This routine performs argument-dependent name lookup based on the
9292 /// given function name (which may also be an operator name) and adds
9293 /// all of the overload candidates found by ADL to the overload
9294 /// candidate set (C++ [basic.lookup.argdep]).
9295 void
AddArgumentDependentLookupCandidates(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading)9296 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9297                                            SourceLocation Loc,
9298                                            ArrayRef<Expr *> Args,
9299                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9300                                            OverloadCandidateSet& CandidateSet,
9301                                            bool PartialOverloading) {
9302   ADLResult Fns;
9303 
9304   // FIXME: This approach for uniquing ADL results (and removing
9305   // redundant candidates from the set) relies on pointer-equality,
9306   // which means we need to key off the canonical decl.  However,
9307   // always going back to the canonical decl might not get us the
9308   // right set of default arguments.  What default arguments are
9309   // we supposed to consider on ADL candidates, anyway?
9310 
9311   // FIXME: Pass in the explicit template arguments?
9312   ArgumentDependentLookup(Name, Loc, Args, Fns);
9313 
9314   // Erase all of the candidates we already knew about.
9315   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9316                                    CandEnd = CandidateSet.end();
9317        Cand != CandEnd; ++Cand)
9318     if (Cand->Function) {
9319       Fns.erase(Cand->Function);
9320       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9321         Fns.erase(FunTmpl);
9322     }
9323 
9324   // For each of the ADL candidates we found, add it to the overload
9325   // set.
9326   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9327     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9328 
9329     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9330       if (ExplicitTemplateArgs)
9331         continue;
9332 
9333       AddOverloadCandidate(
9334           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9335           PartialOverloading, /*AllowExplicit=*/true,
9336           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9337       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9338         AddOverloadCandidate(
9339             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9340             /*SuppressUserConversions=*/false, PartialOverloading,
9341             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9342             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9343       }
9344     } else {
9345       auto *FTD = cast<FunctionTemplateDecl>(*I);
9346       AddTemplateOverloadCandidate(
9347           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9348           /*SuppressUserConversions=*/false, PartialOverloading,
9349           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9350       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9351               Context, FTD->getTemplatedDecl())) {
9352         AddTemplateOverloadCandidate(
9353             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9354             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9355             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9356             OverloadCandidateParamOrder::Reversed);
9357       }
9358     }
9359   }
9360 }
9361 
9362 namespace {
9363 enum class Comparison { Equal, Better, Worse };
9364 }
9365 
9366 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9367 /// overload resolution.
9368 ///
9369 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9370 /// Cand1's first N enable_if attributes have precisely the same conditions as
9371 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9372 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9373 ///
9374 /// Note that you can have a pair of candidates such that Cand1's enable_if
9375 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9376 /// worse than Cand1's.
compareEnableIfAttrs(const Sema & S,const FunctionDecl * Cand1,const FunctionDecl * Cand2)9377 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9378                                        const FunctionDecl *Cand2) {
9379   // Common case: One (or both) decls don't have enable_if attrs.
9380   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9381   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9382   if (!Cand1Attr || !Cand2Attr) {
9383     if (Cand1Attr == Cand2Attr)
9384       return Comparison::Equal;
9385     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9386   }
9387 
9388   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9389   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9390 
9391   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9392   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9393     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9394     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9395 
9396     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9397     // has fewer enable_if attributes than Cand2, and vice versa.
9398     if (!Cand1A)
9399       return Comparison::Worse;
9400     if (!Cand2A)
9401       return Comparison::Better;
9402 
9403     Cand1ID.clear();
9404     Cand2ID.clear();
9405 
9406     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9407     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9408     if (Cand1ID != Cand2ID)
9409       return Comparison::Worse;
9410   }
9411 
9412   return Comparison::Equal;
9413 }
9414 
9415 static Comparison
isBetterMultiversionCandidate(const OverloadCandidate & Cand1,const OverloadCandidate & Cand2)9416 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9417                               const OverloadCandidate &Cand2) {
9418   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9419       !Cand2.Function->isMultiVersion())
9420     return Comparison::Equal;
9421 
9422   // If both are invalid, they are equal. If one of them is invalid, the other
9423   // is better.
9424   if (Cand1.Function->isInvalidDecl()) {
9425     if (Cand2.Function->isInvalidDecl())
9426       return Comparison::Equal;
9427     return Comparison::Worse;
9428   }
9429   if (Cand2.Function->isInvalidDecl())
9430     return Comparison::Better;
9431 
9432   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9433   // cpu_dispatch, else arbitrarily based on the identifiers.
9434   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9435   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9436   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9437   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9438 
9439   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9440     return Comparison::Equal;
9441 
9442   if (Cand1CPUDisp && !Cand2CPUDisp)
9443     return Comparison::Better;
9444   if (Cand2CPUDisp && !Cand1CPUDisp)
9445     return Comparison::Worse;
9446 
9447   if (Cand1CPUSpec && Cand2CPUSpec) {
9448     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9449       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9450                  ? Comparison::Better
9451                  : Comparison::Worse;
9452 
9453     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9454         FirstDiff = std::mismatch(
9455             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9456             Cand2CPUSpec->cpus_begin(),
9457             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9458               return LHS->getName() == RHS->getName();
9459             });
9460 
9461     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9462            "Two different cpu-specific versions should not have the same "
9463            "identifier list, otherwise they'd be the same decl!");
9464     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9465                ? Comparison::Better
9466                : Comparison::Worse;
9467   }
9468   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9469 }
9470 
9471 /// Compute the type of the implicit object parameter for the given function,
9472 /// if any. Returns None if there is no implicit object parameter, and a null
9473 /// QualType if there is a 'matches anything' implicit object parameter.
getImplicitObjectParamType(ASTContext & Context,const FunctionDecl * F)9474 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9475                                                      const FunctionDecl *F) {
9476   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9477     return llvm::None;
9478 
9479   auto *M = cast<CXXMethodDecl>(F);
9480   // Static member functions' object parameters match all types.
9481   if (M->isStatic())
9482     return QualType();
9483 
9484   QualType T = M->getThisObjectType();
9485   if (M->getRefQualifier() == RQ_RValue)
9486     return Context.getRValueReferenceType(T);
9487   return Context.getLValueReferenceType(T);
9488 }
9489 
haveSameParameterTypes(ASTContext & Context,const FunctionDecl * F1,const FunctionDecl * F2,unsigned NumParams)9490 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9491                                    const FunctionDecl *F2, unsigned NumParams) {
9492   if (declaresSameEntity(F1, F2))
9493     return true;
9494 
9495   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9496     if (First) {
9497       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9498         return *T;
9499     }
9500     assert(I < F->getNumParams());
9501     return F->getParamDecl(I++)->getType();
9502   };
9503 
9504   unsigned I1 = 0, I2 = 0;
9505   for (unsigned I = 0; I != NumParams; ++I) {
9506     QualType T1 = NextParam(F1, I1, I == 0);
9507     QualType T2 = NextParam(F2, I2, I == 0);
9508     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9509       return false;
9510   }
9511   return true;
9512 }
9513 
9514 /// isBetterOverloadCandidate - Determines whether the first overload
9515 /// candidate is a better candidate than the second (C++ 13.3.3p1).
isBetterOverloadCandidate(Sema & S,const OverloadCandidate & Cand1,const OverloadCandidate & Cand2,SourceLocation Loc,OverloadCandidateSet::CandidateSetKind Kind)9516 bool clang::isBetterOverloadCandidate(
9517     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9518     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9519   // Define viable functions to be better candidates than non-viable
9520   // functions.
9521   if (!Cand2.Viable)
9522     return Cand1.Viable;
9523   else if (!Cand1.Viable)
9524     return false;
9525 
9526   // C++ [over.match.best]p1:
9527   //
9528   //   -- if F is a static member function, ICS1(F) is defined such
9529   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9530   //      any function G, and, symmetrically, ICS1(G) is neither
9531   //      better nor worse than ICS1(F).
9532   unsigned StartArg = 0;
9533   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9534     StartArg = 1;
9535 
9536   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9537     // We don't allow incompatible pointer conversions in C++.
9538     if (!S.getLangOpts().CPlusPlus)
9539       return ICS.isStandard() &&
9540              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9541 
9542     // The only ill-formed conversion we allow in C++ is the string literal to
9543     // char* conversion, which is only considered ill-formed after C++11.
9544     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9545            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9546   };
9547 
9548   // Define functions that don't require ill-formed conversions for a given
9549   // argument to be better candidates than functions that do.
9550   unsigned NumArgs = Cand1.Conversions.size();
9551   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9552   bool HasBetterConversion = false;
9553   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9554     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9555     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9556     if (Cand1Bad != Cand2Bad) {
9557       if (Cand1Bad)
9558         return false;
9559       HasBetterConversion = true;
9560     }
9561   }
9562 
9563   if (HasBetterConversion)
9564     return true;
9565 
9566   // C++ [over.match.best]p1:
9567   //   A viable function F1 is defined to be a better function than another
9568   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9569   //   conversion sequence than ICSi(F2), and then...
9570   bool HasWorseConversion = false;
9571   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9572     switch (CompareImplicitConversionSequences(S, Loc,
9573                                                Cand1.Conversions[ArgIdx],
9574                                                Cand2.Conversions[ArgIdx])) {
9575     case ImplicitConversionSequence::Better:
9576       // Cand1 has a better conversion sequence.
9577       HasBetterConversion = true;
9578       break;
9579 
9580     case ImplicitConversionSequence::Worse:
9581       if (Cand1.Function && Cand2.Function &&
9582           Cand1.isReversed() != Cand2.isReversed() &&
9583           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9584                                  NumArgs)) {
9585         // Work around large-scale breakage caused by considering reversed
9586         // forms of operator== in C++20:
9587         //
9588         // When comparing a function against a reversed function with the same
9589         // parameter types, if we have a better conversion for one argument and
9590         // a worse conversion for the other, the implicit conversion sequences
9591         // are treated as being equally good.
9592         //
9593         // This prevents a comparison function from being considered ambiguous
9594         // with a reversed form that is written in the same way.
9595         //
9596         // We diagnose this as an extension from CreateOverloadedBinOp.
9597         HasWorseConversion = true;
9598         break;
9599       }
9600 
9601       // Cand1 can't be better than Cand2.
9602       return false;
9603 
9604     case ImplicitConversionSequence::Indistinguishable:
9605       // Do nothing.
9606       break;
9607     }
9608   }
9609 
9610   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9611   //       ICSj(F2), or, if not that,
9612   if (HasBetterConversion && !HasWorseConversion)
9613     return true;
9614 
9615   //   -- the context is an initialization by user-defined conversion
9616   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9617   //      from the return type of F1 to the destination type (i.e.,
9618   //      the type of the entity being initialized) is a better
9619   //      conversion sequence than the standard conversion sequence
9620   //      from the return type of F2 to the destination type.
9621   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9622       Cand1.Function && Cand2.Function &&
9623       isa<CXXConversionDecl>(Cand1.Function) &&
9624       isa<CXXConversionDecl>(Cand2.Function)) {
9625     // First check whether we prefer one of the conversion functions over the
9626     // other. This only distinguishes the results in non-standard, extension
9627     // cases such as the conversion from a lambda closure type to a function
9628     // pointer or block.
9629     ImplicitConversionSequence::CompareKind Result =
9630         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9631     if (Result == ImplicitConversionSequence::Indistinguishable)
9632       Result = CompareStandardConversionSequences(S, Loc,
9633                                                   Cand1.FinalConversion,
9634                                                   Cand2.FinalConversion);
9635 
9636     if (Result != ImplicitConversionSequence::Indistinguishable)
9637       return Result == ImplicitConversionSequence::Better;
9638 
9639     // FIXME: Compare kind of reference binding if conversion functions
9640     // convert to a reference type used in direct reference binding, per
9641     // C++14 [over.match.best]p1 section 2 bullet 3.
9642   }
9643 
9644   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9645   // as combined with the resolution to CWG issue 243.
9646   //
9647   // When the context is initialization by constructor ([over.match.ctor] or
9648   // either phase of [over.match.list]), a constructor is preferred over
9649   // a conversion function.
9650   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9651       Cand1.Function && Cand2.Function &&
9652       isa<CXXConstructorDecl>(Cand1.Function) !=
9653           isa<CXXConstructorDecl>(Cand2.Function))
9654     return isa<CXXConstructorDecl>(Cand1.Function);
9655 
9656   //    -- F1 is a non-template function and F2 is a function template
9657   //       specialization, or, if not that,
9658   bool Cand1IsSpecialization = Cand1.Function &&
9659                                Cand1.Function->getPrimaryTemplate();
9660   bool Cand2IsSpecialization = Cand2.Function &&
9661                                Cand2.Function->getPrimaryTemplate();
9662   if (Cand1IsSpecialization != Cand2IsSpecialization)
9663     return Cand2IsSpecialization;
9664 
9665   //   -- F1 and F2 are function template specializations, and the function
9666   //      template for F1 is more specialized than the template for F2
9667   //      according to the partial ordering rules described in 14.5.5.2, or,
9668   //      if not that,
9669   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9670     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9671             Cand1.Function->getPrimaryTemplate(),
9672             Cand2.Function->getPrimaryTemplate(), Loc,
9673             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9674                                                    : TPOC_Call,
9675             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9676             Cand1.isReversed() ^ Cand2.isReversed()))
9677       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9678   }
9679 
9680   //   -— F1 and F2 are non-template functions with the same
9681   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9682   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9683       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9684       Cand2.Function->hasPrototype()) {
9685     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9686     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9687     if (PT1->getNumParams() == PT2->getNumParams() &&
9688         PT1->isVariadic() == PT2->isVariadic() &&
9689         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9690       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9691       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9692       if (RC1 && RC2) {
9693         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9694         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9695                                      {RC2}, AtLeastAsConstrained1) ||
9696             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9697                                      {RC1}, AtLeastAsConstrained2))
9698           return false;
9699         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9700           return AtLeastAsConstrained1;
9701       } else if (RC1 || RC2) {
9702         return RC1 != nullptr;
9703       }
9704     }
9705   }
9706 
9707   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9708   //      class B of D, and for all arguments the corresponding parameters of
9709   //      F1 and F2 have the same type.
9710   // FIXME: Implement the "all parameters have the same type" check.
9711   bool Cand1IsInherited =
9712       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9713   bool Cand2IsInherited =
9714       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9715   if (Cand1IsInherited != Cand2IsInherited)
9716     return Cand2IsInherited;
9717   else if (Cand1IsInherited) {
9718     assert(Cand2IsInherited);
9719     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9720     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9721     if (Cand1Class->isDerivedFrom(Cand2Class))
9722       return true;
9723     if (Cand2Class->isDerivedFrom(Cand1Class))
9724       return false;
9725     // Inherited from sibling base classes: still ambiguous.
9726   }
9727 
9728   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9729   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9730   //      with reversed order of parameters and F1 is not
9731   //
9732   // We rank reversed + different operator as worse than just reversed, but
9733   // that comparison can never happen, because we only consider reversing for
9734   // the maximally-rewritten operator (== or <=>).
9735   if (Cand1.RewriteKind != Cand2.RewriteKind)
9736     return Cand1.RewriteKind < Cand2.RewriteKind;
9737 
9738   // Check C++17 tie-breakers for deduction guides.
9739   {
9740     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9741     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9742     if (Guide1 && Guide2) {
9743       //  -- F1 is generated from a deduction-guide and F2 is not
9744       if (Guide1->isImplicit() != Guide2->isImplicit())
9745         return Guide2->isImplicit();
9746 
9747       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9748       if (Guide1->isCopyDeductionCandidate())
9749         return true;
9750     }
9751   }
9752 
9753   // Check for enable_if value-based overload resolution.
9754   if (Cand1.Function && Cand2.Function) {
9755     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9756     if (Cmp != Comparison::Equal)
9757       return Cmp == Comparison::Better;
9758   }
9759 
9760   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9761     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9762     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9763            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9764   }
9765 
9766   bool HasPS1 = Cand1.Function != nullptr &&
9767                 functionHasPassObjectSizeParams(Cand1.Function);
9768   bool HasPS2 = Cand2.Function != nullptr &&
9769                 functionHasPassObjectSizeParams(Cand2.Function);
9770   if (HasPS1 != HasPS2 && HasPS1)
9771     return true;
9772 
9773   Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2);
9774   return MV == Comparison::Better;
9775 }
9776 
9777 /// Determine whether two declarations are "equivalent" for the purposes of
9778 /// name lookup and overload resolution. This applies when the same internal/no
9779 /// linkage entity is defined by two modules (probably by textually including
9780 /// the same header). In such a case, we don't consider the declarations to
9781 /// declare the same entity, but we also don't want lookups with both
9782 /// declarations visible to be ambiguous in some cases (this happens when using
9783 /// a modularized libstdc++).
isEquivalentInternalLinkageDeclaration(const NamedDecl * A,const NamedDecl * B)9784 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9785                                                   const NamedDecl *B) {
9786   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9787   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9788   if (!VA || !VB)
9789     return false;
9790 
9791   // The declarations must be declaring the same name as an internal linkage
9792   // entity in different modules.
9793   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9794           VB->getDeclContext()->getRedeclContext()) ||
9795       getOwningModule(VA) == getOwningModule(VB) ||
9796       VA->isExternallyVisible() || VB->isExternallyVisible())
9797     return false;
9798 
9799   // Check that the declarations appear to be equivalent.
9800   //
9801   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9802   // For constants and functions, we should check the initializer or body is
9803   // the same. For non-constant variables, we shouldn't allow it at all.
9804   if (Context.hasSameType(VA->getType(), VB->getType()))
9805     return true;
9806 
9807   // Enum constants within unnamed enumerations will have different types, but
9808   // may still be similar enough to be interchangeable for our purposes.
9809   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9810     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9811       // Only handle anonymous enums. If the enumerations were named and
9812       // equivalent, they would have been merged to the same type.
9813       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9814       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9815       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9816           !Context.hasSameType(EnumA->getIntegerType(),
9817                                EnumB->getIntegerType()))
9818         return false;
9819       // Allow this only if the value is the same for both enumerators.
9820       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9821     }
9822   }
9823 
9824   // Nothing else is sufficiently similar.
9825   return false;
9826 }
9827 
diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc,const NamedDecl * D,ArrayRef<const NamedDecl * > Equiv)9828 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9829     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9830   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9831 
9832   Module *M = getOwningModule(D);
9833   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9834       << !M << (M ? M->getFullModuleName() : "");
9835 
9836   for (auto *E : Equiv) {
9837     Module *M = getOwningModule(E);
9838     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9839         << !M << (M ? M->getFullModuleName() : "");
9840   }
9841 }
9842 
9843 /// Computes the best viable function (C++ 13.3.3)
9844 /// within an overload candidate set.
9845 ///
9846 /// \param Loc The location of the function name (or operator symbol) for
9847 /// which overload resolution occurs.
9848 ///
9849 /// \param Best If overload resolution was successful or found a deleted
9850 /// function, \p Best points to the candidate function found.
9851 ///
9852 /// \returns The result of overload resolution.
9853 OverloadingResult
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best)9854 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9855                                          iterator &Best) {
9856   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9857   std::transform(begin(), end(), std::back_inserter(Candidates),
9858                  [](OverloadCandidate &Cand) { return &Cand; });
9859 
9860   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9861   // are accepted by both clang and NVCC. However, during a particular
9862   // compilation mode only one call variant is viable. We need to
9863   // exclude non-viable overload candidates from consideration based
9864   // only on their host/device attributes. Specifically, if one
9865   // candidate call is WrongSide and the other is SameSide, we ignore
9866   // the WrongSide candidate.
9867   if (S.getLangOpts().CUDA) {
9868     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9869     bool ContainsSameSideCandidate =
9870         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9871           // Check viable function only.
9872           return Cand->Viable && Cand->Function &&
9873                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9874                      Sema::CFP_SameSide;
9875         });
9876     if (ContainsSameSideCandidate) {
9877       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9878         // Check viable function only to avoid unnecessary data copying/moving.
9879         return Cand->Viable && Cand->Function &&
9880                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9881                    Sema::CFP_WrongSide;
9882       };
9883       llvm::erase_if(Candidates, IsWrongSideCandidate);
9884     }
9885   }
9886 
9887   // Find the best viable function.
9888   Best = end();
9889   for (auto *Cand : Candidates) {
9890     Cand->Best = false;
9891     if (Cand->Viable)
9892       if (Best == end() ||
9893           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9894         Best = Cand;
9895   }
9896 
9897   // If we didn't find any viable functions, abort.
9898   if (Best == end())
9899     return OR_No_Viable_Function;
9900 
9901   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9902 
9903   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9904   PendingBest.push_back(&*Best);
9905   Best->Best = true;
9906 
9907   // Make sure that this function is better than every other viable
9908   // function. If not, we have an ambiguity.
9909   while (!PendingBest.empty()) {
9910     auto *Curr = PendingBest.pop_back_val();
9911     for (auto *Cand : Candidates) {
9912       if (Cand->Viable && !Cand->Best &&
9913           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9914         PendingBest.push_back(Cand);
9915         Cand->Best = true;
9916 
9917         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9918                                                      Curr->Function))
9919           EquivalentCands.push_back(Cand->Function);
9920         else
9921           Best = end();
9922       }
9923     }
9924   }
9925 
9926   // If we found more than one best candidate, this is ambiguous.
9927   if (Best == end())
9928     return OR_Ambiguous;
9929 
9930   // Best is the best viable function.
9931   if (Best->Function && Best->Function->isDeleted())
9932     return OR_Deleted;
9933 
9934   if (!EquivalentCands.empty())
9935     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9936                                                     EquivalentCands);
9937 
9938   return OR_Success;
9939 }
9940 
9941 namespace {
9942 
9943 enum OverloadCandidateKind {
9944   oc_function,
9945   oc_method,
9946   oc_reversed_binary_operator,
9947   oc_constructor,
9948   oc_implicit_default_constructor,
9949   oc_implicit_copy_constructor,
9950   oc_implicit_move_constructor,
9951   oc_implicit_copy_assignment,
9952   oc_implicit_move_assignment,
9953   oc_implicit_equality_comparison,
9954   oc_inherited_constructor
9955 };
9956 
9957 enum OverloadCandidateSelect {
9958   ocs_non_template,
9959   ocs_template,
9960   ocs_described_template,
9961 };
9962 
9963 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
ClassifyOverloadCandidate(Sema & S,NamedDecl * Found,FunctionDecl * Fn,OverloadCandidateRewriteKind CRK,std::string & Description)9964 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9965                           OverloadCandidateRewriteKind CRK,
9966                           std::string &Description) {
9967 
9968   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9969   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9970     isTemplate = true;
9971     Description = S.getTemplateArgumentBindingsText(
9972         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9973   }
9974 
9975   OverloadCandidateSelect Select = [&]() {
9976     if (!Description.empty())
9977       return ocs_described_template;
9978     return isTemplate ? ocs_template : ocs_non_template;
9979   }();
9980 
9981   OverloadCandidateKind Kind = [&]() {
9982     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9983       return oc_implicit_equality_comparison;
9984 
9985     if (CRK & CRK_Reversed)
9986       return oc_reversed_binary_operator;
9987 
9988     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9989       if (!Ctor->isImplicit()) {
9990         if (isa<ConstructorUsingShadowDecl>(Found))
9991           return oc_inherited_constructor;
9992         else
9993           return oc_constructor;
9994       }
9995 
9996       if (Ctor->isDefaultConstructor())
9997         return oc_implicit_default_constructor;
9998 
9999       if (Ctor->isMoveConstructor())
10000         return oc_implicit_move_constructor;
10001 
10002       assert(Ctor->isCopyConstructor() &&
10003              "unexpected sort of implicit constructor");
10004       return oc_implicit_copy_constructor;
10005     }
10006 
10007     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10008       // This actually gets spelled 'candidate function' for now, but
10009       // it doesn't hurt to split it out.
10010       if (!Meth->isImplicit())
10011         return oc_method;
10012 
10013       if (Meth->isMoveAssignmentOperator())
10014         return oc_implicit_move_assignment;
10015 
10016       if (Meth->isCopyAssignmentOperator())
10017         return oc_implicit_copy_assignment;
10018 
10019       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10020       return oc_method;
10021     }
10022 
10023     return oc_function;
10024   }();
10025 
10026   return std::make_pair(Kind, Select);
10027 }
10028 
MaybeEmitInheritedConstructorNote(Sema & S,Decl * FoundDecl)10029 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10030   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10031   // set.
10032   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10033     S.Diag(FoundDecl->getLocation(),
10034            diag::note_ovl_candidate_inherited_constructor)
10035       << Shadow->getNominatedBaseClass();
10036 }
10037 
10038 } // end anonymous namespace
10039 
isFunctionAlwaysEnabled(const ASTContext & Ctx,const FunctionDecl * FD)10040 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10041                                     const FunctionDecl *FD) {
10042   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10043     bool AlwaysTrue;
10044     if (EnableIf->getCond()->isValueDependent() ||
10045         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10046       return false;
10047     if (!AlwaysTrue)
10048       return false;
10049   }
10050   return true;
10051 }
10052 
10053 /// Returns true if we can take the address of the function.
10054 ///
10055 /// \param Complain - If true, we'll emit a diagnostic
10056 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10057 ///   we in overload resolution?
10058 /// \param Loc - The location of the statement we're complaining about. Ignored
10059 ///   if we're not complaining, or if we're in overload resolution.
checkAddressOfFunctionIsAvailable(Sema & S,const FunctionDecl * FD,bool Complain,bool InOverloadResolution,SourceLocation Loc)10060 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10061                                               bool Complain,
10062                                               bool InOverloadResolution,
10063                                               SourceLocation Loc) {
10064   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10065     if (Complain) {
10066       if (InOverloadResolution)
10067         S.Diag(FD->getBeginLoc(),
10068                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10069       else
10070         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10071     }
10072     return false;
10073   }
10074 
10075   if (FD->getTrailingRequiresClause()) {
10076     ConstraintSatisfaction Satisfaction;
10077     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10078       return false;
10079     if (!Satisfaction.IsSatisfied) {
10080       if (Complain) {
10081         if (InOverloadResolution)
10082           S.Diag(FD->getBeginLoc(),
10083                  diag::note_ovl_candidate_unsatisfied_constraints);
10084         else
10085           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10086               << FD;
10087         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10088       }
10089       return false;
10090     }
10091   }
10092 
10093   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10094     return P->hasAttr<PassObjectSizeAttr>();
10095   });
10096   if (I == FD->param_end())
10097     return true;
10098 
10099   if (Complain) {
10100     // Add one to ParamNo because it's user-facing
10101     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10102     if (InOverloadResolution)
10103       S.Diag(FD->getLocation(),
10104              diag::note_ovl_candidate_has_pass_object_size_params)
10105           << ParamNo;
10106     else
10107       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10108           << FD << ParamNo;
10109   }
10110   return false;
10111 }
10112 
checkAddressOfCandidateIsAvailable(Sema & S,const FunctionDecl * FD)10113 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10114                                                const FunctionDecl *FD) {
10115   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10116                                            /*InOverloadResolution=*/true,
10117                                            /*Loc=*/SourceLocation());
10118 }
10119 
checkAddressOfFunctionIsAvailable(const FunctionDecl * Function,bool Complain,SourceLocation Loc)10120 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10121                                              bool Complain,
10122                                              SourceLocation Loc) {
10123   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10124                                              /*InOverloadResolution=*/false,
10125                                              Loc);
10126 }
10127 
10128 // Notes the location of an overload candidate.
NoteOverloadCandidate(NamedDecl * Found,FunctionDecl * Fn,OverloadCandidateRewriteKind RewriteKind,QualType DestType,bool TakingAddress)10129 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10130                                  OverloadCandidateRewriteKind RewriteKind,
10131                                  QualType DestType, bool TakingAddress) {
10132   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10133     return;
10134   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10135       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10136     return;
10137 
10138   std::string FnDesc;
10139   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10140       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10141   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10142                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10143                          << Fn << FnDesc;
10144 
10145   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10146   Diag(Fn->getLocation(), PD);
10147   MaybeEmitInheritedConstructorNote(*this, Found);
10148 }
10149 
10150 static void
MaybeDiagnoseAmbiguousConstraints(Sema & S,ArrayRef<OverloadCandidate> Cands)10151 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10152   // Perhaps the ambiguity was caused by two atomic constraints that are
10153   // 'identical' but not equivalent:
10154   //
10155   // void foo() requires (sizeof(T) > 4) { } // #1
10156   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10157   //
10158   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10159   // #2 to subsume #1, but these constraint are not considered equivalent
10160   // according to the subsumption rules because they are not the same
10161   // source-level construct. This behavior is quite confusing and we should try
10162   // to help the user figure out what happened.
10163 
10164   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10165   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10166   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10167     if (!I->Function)
10168       continue;
10169     SmallVector<const Expr *, 3> AC;
10170     if (auto *Template = I->Function->getPrimaryTemplate())
10171       Template->getAssociatedConstraints(AC);
10172     else
10173       I->Function->getAssociatedConstraints(AC);
10174     if (AC.empty())
10175       continue;
10176     if (FirstCand == nullptr) {
10177       FirstCand = I->Function;
10178       FirstAC = AC;
10179     } else if (SecondCand == nullptr) {
10180       SecondCand = I->Function;
10181       SecondAC = AC;
10182     } else {
10183       // We have more than one pair of constrained functions - this check is
10184       // expensive and we'd rather not try to diagnose it.
10185       return;
10186     }
10187   }
10188   if (!SecondCand)
10189     return;
10190   // The diagnostic can only happen if there are associated constraints on
10191   // both sides (there needs to be some identical atomic constraint).
10192   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10193                                                       SecondCand, SecondAC))
10194     // Just show the user one diagnostic, they'll probably figure it out
10195     // from here.
10196     return;
10197 }
10198 
10199 // Notes the location of all overload candidates designated through
10200 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType,bool TakingAddress)10201 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10202                                      bool TakingAddress) {
10203   assert(OverloadedExpr->getType() == Context.OverloadTy);
10204 
10205   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10206   OverloadExpr *OvlExpr = Ovl.Expression;
10207 
10208   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10209                             IEnd = OvlExpr->decls_end();
10210        I != IEnd; ++I) {
10211     if (FunctionTemplateDecl *FunTmpl =
10212                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10213       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10214                             TakingAddress);
10215     } else if (FunctionDecl *Fun
10216                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10217       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10218     }
10219   }
10220 }
10221 
10222 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10223 /// "lead" diagnostic; it will be given two arguments, the source and
10224 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const10225 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10226                                  Sema &S,
10227                                  SourceLocation CaretLoc,
10228                                  const PartialDiagnostic &PDiag) const {
10229   S.Diag(CaretLoc, PDiag)
10230     << Ambiguous.getFromType() << Ambiguous.getToType();
10231   // FIXME: The note limiting machinery is borrowed from
10232   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10233   // refactoring here.
10234   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10235   unsigned CandsShown = 0;
10236   AmbiguousConversionSequence::const_iterator I, E;
10237   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10238     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10239       break;
10240     ++CandsShown;
10241     S.NoteOverloadCandidate(I->first, I->second);
10242   }
10243   if (I != E)
10244     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10245 }
10246 
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I,bool TakingCandidateAddress)10247 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10248                                   unsigned I, bool TakingCandidateAddress) {
10249   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10250   assert(Conv.isBad());
10251   assert(Cand->Function && "for now, candidate must be a function");
10252   FunctionDecl *Fn = Cand->Function;
10253 
10254   // There's a conversion slot for the object argument if this is a
10255   // non-constructor method.  Note that 'I' corresponds the
10256   // conversion-slot index.
10257   bool isObjectArgument = false;
10258   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10259     if (I == 0)
10260       isObjectArgument = true;
10261     else
10262       I--;
10263   }
10264 
10265   std::string FnDesc;
10266   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10267       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10268                                 FnDesc);
10269 
10270   Expr *FromExpr = Conv.Bad.FromExpr;
10271   QualType FromTy = Conv.Bad.getFromType();
10272   QualType ToTy = Conv.Bad.getToType();
10273 
10274   if (FromTy == S.Context.OverloadTy) {
10275     assert(FromExpr && "overload set argument came from implicit argument?");
10276     Expr *E = FromExpr->IgnoreParens();
10277     if (isa<UnaryOperator>(E))
10278       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10279     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10280 
10281     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10282         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10283         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10284         << Name << I + 1;
10285     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10286     return;
10287   }
10288 
10289   // Do some hand-waving analysis to see if the non-viability is due
10290   // to a qualifier mismatch.
10291   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10292   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10293   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10294     CToTy = RT->getPointeeType();
10295   else {
10296     // TODO: detect and diagnose the full richness of const mismatches.
10297     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10298       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10299         CFromTy = FromPT->getPointeeType();
10300         CToTy = ToPT->getPointeeType();
10301       }
10302   }
10303 
10304   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10305       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10306     Qualifiers FromQs = CFromTy.getQualifiers();
10307     Qualifiers ToQs = CToTy.getQualifiers();
10308 
10309     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10310       if (isObjectArgument)
10311         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10312             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10313             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10314             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10315       else
10316         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10317             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10318             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10319             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10320             << ToTy->isReferenceType() << I + 1;
10321       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10322       return;
10323     }
10324 
10325     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10326       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10327           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10328           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10329           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10330           << (unsigned)isObjectArgument << I + 1;
10331       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10332       return;
10333     }
10334 
10335     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10336       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10337           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10338           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10339           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10340           << (unsigned)isObjectArgument << I + 1;
10341       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10342       return;
10343     }
10344 
10345     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10346       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10347           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10348           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10349           << FromQs.hasUnaligned() << I + 1;
10350       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10351       return;
10352     }
10353 
10354     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10355     assert(CVR && "unexpected qualifiers mismatch");
10356 
10357     if (isObjectArgument) {
10358       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10359           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10360           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10361           << (CVR - 1);
10362     } else {
10363       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10364           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10365           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10366           << (CVR - 1) << I + 1;
10367     }
10368     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10369     return;
10370   }
10371 
10372   // Special diagnostic for failure to convert an initializer list, since
10373   // telling the user that it has type void is not useful.
10374   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10375     // XXXAR: it would be nice if we could somehow diagnose capability -> pointer
10376     // narrowing conversions here instead of just printing candidate not viable
10377     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10378         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10379         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10380         << ToTy << (unsigned)isObjectArgument << I + 1;
10381     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10382     return;
10383   }
10384 
10385   // Diagnose references or pointers to incomplete types differently,
10386   // since it's far from impossible that the incompleteness triggered
10387   // the failure.
10388   QualType TempFromTy = FromTy.getNonReferenceType();
10389   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10390     TempFromTy = PTy->getPointeeType();
10391   if (TempFromTy->isIncompleteType()) {
10392     // Emit the generic diagnostic and, optionally, add the hints to it.
10393     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10394         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10395         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10396         << ToTy << (unsigned)isObjectArgument << I + 1
10397         << (unsigned)(Cand->Fix.Kind);
10398 
10399     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10400     return;
10401   }
10402 
10403   // Diagnose base -> derived pointer conversions.
10404   unsigned BaseToDerivedConversion = 0;
10405   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10406     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10407       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10408                                                FromPtrTy->getPointeeType()) &&
10409           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10410           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10411           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10412                           FromPtrTy->getPointeeType()))
10413         BaseToDerivedConversion = 1;
10414     }
10415   } else if (const ObjCObjectPointerType *FromPtrTy
10416                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10417     if (const ObjCObjectPointerType *ToPtrTy
10418                                         = ToTy->getAs<ObjCObjectPointerType>())
10419       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10420         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10421           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10422                                                 FromPtrTy->getPointeeType()) &&
10423               FromIface->isSuperClassOf(ToIface))
10424             BaseToDerivedConversion = 2;
10425   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10426     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10427         !FromTy->isIncompleteType() &&
10428         !ToRefTy->getPointeeType()->isIncompleteType() &&
10429         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10430       BaseToDerivedConversion = 3;
10431     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10432                ToTy.getNonReferenceType().getCanonicalType() ==
10433                FromTy.getNonReferenceType().getCanonicalType()) {
10434       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10435           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10436           << (unsigned)isObjectArgument << I + 1
10437           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10438       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10439       return;
10440     }
10441   }
10442 
10443   if (BaseToDerivedConversion) {
10444     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10445         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10446         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10447         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10448     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10449     return;
10450   }
10451 
10452   if (isa<ObjCObjectPointerType>(CFromTy) &&
10453       isa<PointerType>(CToTy)) {
10454       Qualifiers FromQs = CFromTy.getQualifiers();
10455       Qualifiers ToQs = CToTy.getQualifiers();
10456       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10457         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10458             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10459             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10460             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10461         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10462         return;
10463       }
10464   }
10465 
10466   if (TakingCandidateAddress &&
10467       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10468     return;
10469 
10470   // Emit the generic diagnostic and, optionally, add the hints to it.
10471   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10472   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10473         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10474         << ToTy << (unsigned)isObjectArgument << I + 1
10475         << (unsigned)(Cand->Fix.Kind);
10476 
10477   // If we can fix the conversion, suggest the FixIts.
10478   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10479        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10480     FDiag << *HI;
10481   S.Diag(Fn->getLocation(), FDiag);
10482 
10483   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10484 }
10485 
10486 /// Additional arity mismatch diagnosis specific to a function overload
10487 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10488 /// over a candidate in any candidate set.
CheckArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)10489 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10490                                unsigned NumArgs) {
10491   FunctionDecl *Fn = Cand->Function;
10492   unsigned MinParams = Fn->getMinRequiredArguments();
10493 
10494   // With invalid overloaded operators, it's possible that we think we
10495   // have an arity mismatch when in fact it looks like we have the
10496   // right number of arguments, because only overloaded operators have
10497   // the weird behavior of overloading member and non-member functions.
10498   // Just don't report anything.
10499   if (Fn->isInvalidDecl() &&
10500       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10501     return true;
10502 
10503   if (NumArgs < MinParams) {
10504     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10505            (Cand->FailureKind == ovl_fail_bad_deduction &&
10506             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10507   } else {
10508     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10509            (Cand->FailureKind == ovl_fail_bad_deduction &&
10510             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10511   }
10512 
10513   return false;
10514 }
10515 
10516 /// General arity mismatch diagnosis over a candidate in a candidate set.
DiagnoseArityMismatch(Sema & S,NamedDecl * Found,Decl * D,unsigned NumFormalArgs)10517 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10518                                   unsigned NumFormalArgs) {
10519   assert(isa<FunctionDecl>(D) &&
10520       "The templated declaration should at least be a function"
10521       " when diagnosing bad template argument deduction due to too many"
10522       " or too few arguments");
10523 
10524   FunctionDecl *Fn = cast<FunctionDecl>(D);
10525 
10526   // TODO: treat calls to a missing default constructor as a special case
10527   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10528   unsigned MinParams = Fn->getMinRequiredArguments();
10529 
10530   // at least / at most / exactly
10531   unsigned mode, modeCount;
10532   if (NumFormalArgs < MinParams) {
10533     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10534         FnTy->isTemplateVariadic())
10535       mode = 0; // "at least"
10536     else
10537       mode = 2; // "exactly"
10538     modeCount = MinParams;
10539   } else {
10540     if (MinParams != FnTy->getNumParams())
10541       mode = 1; // "at most"
10542     else
10543       mode = 2; // "exactly"
10544     modeCount = FnTy->getNumParams();
10545   }
10546 
10547   std::string Description;
10548   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10549       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10550 
10551   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10552     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10553         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10554         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10555   else
10556     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10557         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10558         << Description << mode << modeCount << NumFormalArgs;
10559 
10560   MaybeEmitInheritedConstructorNote(S, Found);
10561 }
10562 
10563 /// Arity mismatch diagnosis specific to a function overload candidate.
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)10564 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10565                                   unsigned NumFormalArgs) {
10566   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10567     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10568 }
10569 
getDescribedTemplate(Decl * Templated)10570 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10571   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10572     return TD;
10573   llvm_unreachable("Unsupported: Getting the described template declaration"
10574                    " for bad deduction diagnosis");
10575 }
10576 
10577 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,NamedDecl * Found,Decl * Templated,DeductionFailureInfo & DeductionFailure,unsigned NumArgs,bool TakingCandidateAddress)10578 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10579                                  DeductionFailureInfo &DeductionFailure,
10580                                  unsigned NumArgs,
10581                                  bool TakingCandidateAddress) {
10582   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10583   NamedDecl *ParamD;
10584   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10585   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10586   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10587   switch (DeductionFailure.Result) {
10588   case Sema::TDK_Success:
10589     llvm_unreachable("TDK_success while diagnosing bad deduction");
10590 
10591   case Sema::TDK_Incomplete: {
10592     assert(ParamD && "no parameter found for incomplete deduction result");
10593     S.Diag(Templated->getLocation(),
10594            diag::note_ovl_candidate_incomplete_deduction)
10595         << ParamD->getDeclName();
10596     MaybeEmitInheritedConstructorNote(S, Found);
10597     return;
10598   }
10599 
10600   case Sema::TDK_IncompletePack: {
10601     assert(ParamD && "no parameter found for incomplete deduction result");
10602     S.Diag(Templated->getLocation(),
10603            diag::note_ovl_candidate_incomplete_deduction_pack)
10604         << ParamD->getDeclName()
10605         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10606         << *DeductionFailure.getFirstArg();
10607     MaybeEmitInheritedConstructorNote(S, Found);
10608     return;
10609   }
10610 
10611   case Sema::TDK_Underqualified: {
10612     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10613     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10614 
10615     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10616 
10617     // Param will have been canonicalized, but it should just be a
10618     // qualified version of ParamD, so move the qualifiers to that.
10619     QualifierCollector Qs;
10620     Qs.strip(Param);
10621     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10622     assert(S.Context.hasSameType(Param, NonCanonParam));
10623 
10624     // Arg has also been canonicalized, but there's nothing we can do
10625     // about that.  It also doesn't matter as much, because it won't
10626     // have any template parameters in it (because deduction isn't
10627     // done on dependent types).
10628     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10629 
10630     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10631         << ParamD->getDeclName() << Arg << NonCanonParam;
10632     MaybeEmitInheritedConstructorNote(S, Found);
10633     return;
10634   }
10635 
10636   case Sema::TDK_Inconsistent: {
10637     assert(ParamD && "no parameter found for inconsistent deduction result");
10638     int which = 0;
10639     if (isa<TemplateTypeParmDecl>(ParamD))
10640       which = 0;
10641     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10642       // Deduction might have failed because we deduced arguments of two
10643       // different types for a non-type template parameter.
10644       // FIXME: Use a different TDK value for this.
10645       QualType T1 =
10646           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10647       QualType T2 =
10648           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10649       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10650         S.Diag(Templated->getLocation(),
10651                diag::note_ovl_candidate_inconsistent_deduction_types)
10652           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10653           << *DeductionFailure.getSecondArg() << T2;
10654         MaybeEmitInheritedConstructorNote(S, Found);
10655         return;
10656       }
10657 
10658       which = 1;
10659     } else {
10660       which = 2;
10661     }
10662 
10663     // Tweak the diagnostic if the problem is that we deduced packs of
10664     // different arities. We'll print the actual packs anyway in case that
10665     // includes additional useful information.
10666     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10667         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10668         DeductionFailure.getFirstArg()->pack_size() !=
10669             DeductionFailure.getSecondArg()->pack_size()) {
10670       which = 3;
10671     }
10672 
10673     S.Diag(Templated->getLocation(),
10674            diag::note_ovl_candidate_inconsistent_deduction)
10675         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10676         << *DeductionFailure.getSecondArg();
10677     MaybeEmitInheritedConstructorNote(S, Found);
10678     return;
10679   }
10680 
10681   case Sema::TDK_InvalidExplicitArguments:
10682     assert(ParamD && "no parameter found for invalid explicit arguments");
10683     if (ParamD->getDeclName())
10684       S.Diag(Templated->getLocation(),
10685              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10686           << ParamD->getDeclName();
10687     else {
10688       int index = 0;
10689       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10690         index = TTP->getIndex();
10691       else if (NonTypeTemplateParmDecl *NTTP
10692                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10693         index = NTTP->getIndex();
10694       else
10695         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10696       S.Diag(Templated->getLocation(),
10697              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10698           << (index + 1);
10699     }
10700     MaybeEmitInheritedConstructorNote(S, Found);
10701     return;
10702 
10703   case Sema::TDK_ConstraintsNotSatisfied: {
10704     // Format the template argument list into the argument string.
10705     SmallString<128> TemplateArgString;
10706     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10707     TemplateArgString = " ";
10708     TemplateArgString += S.getTemplateArgumentBindingsText(
10709         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10710     if (TemplateArgString.size() == 1)
10711       TemplateArgString.clear();
10712     S.Diag(Templated->getLocation(),
10713            diag::note_ovl_candidate_unsatisfied_constraints)
10714         << TemplateArgString;
10715 
10716     S.DiagnoseUnsatisfiedConstraint(
10717         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10718     return;
10719   }
10720   case Sema::TDK_TooManyArguments:
10721   case Sema::TDK_TooFewArguments:
10722     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10723     return;
10724 
10725   case Sema::TDK_InstantiationDepth:
10726     S.Diag(Templated->getLocation(),
10727            diag::note_ovl_candidate_instantiation_depth);
10728     MaybeEmitInheritedConstructorNote(S, Found);
10729     return;
10730 
10731   case Sema::TDK_SubstitutionFailure: {
10732     // Format the template argument list into the argument string.
10733     SmallString<128> TemplateArgString;
10734     if (TemplateArgumentList *Args =
10735             DeductionFailure.getTemplateArgumentList()) {
10736       TemplateArgString = " ";
10737       TemplateArgString += S.getTemplateArgumentBindingsText(
10738           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10739       if (TemplateArgString.size() == 1)
10740         TemplateArgString.clear();
10741     }
10742 
10743     // If this candidate was disabled by enable_if, say so.
10744     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10745     if (PDiag && PDiag->second.getDiagID() ==
10746           diag::err_typename_nested_not_found_enable_if) {
10747       // FIXME: Use the source range of the condition, and the fully-qualified
10748       //        name of the enable_if template. These are both present in PDiag.
10749       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10750         << "'enable_if'" << TemplateArgString;
10751       return;
10752     }
10753 
10754     // We found a specific requirement that disabled the enable_if.
10755     if (PDiag && PDiag->second.getDiagID() ==
10756         diag::err_typename_nested_not_found_requirement) {
10757       S.Diag(Templated->getLocation(),
10758              diag::note_ovl_candidate_disabled_by_requirement)
10759         << PDiag->second.getStringArg(0) << TemplateArgString;
10760       return;
10761     }
10762 
10763     // Format the SFINAE diagnostic into the argument string.
10764     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10765     //        formatted message in another diagnostic.
10766     SmallString<128> SFINAEArgString;
10767     SourceRange R;
10768     if (PDiag) {
10769       SFINAEArgString = ": ";
10770       R = SourceRange(PDiag->first, PDiag->first);
10771       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10772     }
10773 
10774     S.Diag(Templated->getLocation(),
10775            diag::note_ovl_candidate_substitution_failure)
10776         << TemplateArgString << SFINAEArgString << R;
10777     MaybeEmitInheritedConstructorNote(S, Found);
10778     return;
10779   }
10780 
10781   case Sema::TDK_DeducedMismatch:
10782   case Sema::TDK_DeducedMismatchNested: {
10783     // Format the template argument list into the argument string.
10784     SmallString<128> TemplateArgString;
10785     if (TemplateArgumentList *Args =
10786             DeductionFailure.getTemplateArgumentList()) {
10787       TemplateArgString = " ";
10788       TemplateArgString += S.getTemplateArgumentBindingsText(
10789           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10790       if (TemplateArgString.size() == 1)
10791         TemplateArgString.clear();
10792     }
10793 
10794     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10795         << (*DeductionFailure.getCallArgIndex() + 1)
10796         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10797         << TemplateArgString
10798         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10799     break;
10800   }
10801 
10802   case Sema::TDK_NonDeducedMismatch: {
10803     // FIXME: Provide a source location to indicate what we couldn't match.
10804     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10805     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10806     if (FirstTA.getKind() == TemplateArgument::Template &&
10807         SecondTA.getKind() == TemplateArgument::Template) {
10808       TemplateName FirstTN = FirstTA.getAsTemplate();
10809       TemplateName SecondTN = SecondTA.getAsTemplate();
10810       if (FirstTN.getKind() == TemplateName::Template &&
10811           SecondTN.getKind() == TemplateName::Template) {
10812         if (FirstTN.getAsTemplateDecl()->getName() ==
10813             SecondTN.getAsTemplateDecl()->getName()) {
10814           // FIXME: This fixes a bad diagnostic where both templates are named
10815           // the same.  This particular case is a bit difficult since:
10816           // 1) It is passed as a string to the diagnostic printer.
10817           // 2) The diagnostic printer only attempts to find a better
10818           //    name for types, not decls.
10819           // Ideally, this should folded into the diagnostic printer.
10820           S.Diag(Templated->getLocation(),
10821                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10822               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10823           return;
10824         }
10825       }
10826     }
10827 
10828     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10829         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10830       return;
10831 
10832     // FIXME: For generic lambda parameters, check if the function is a lambda
10833     // call operator, and if so, emit a prettier and more informative
10834     // diagnostic that mentions 'auto' and lambda in addition to
10835     // (or instead of?) the canonical template type parameters.
10836     S.Diag(Templated->getLocation(),
10837            diag::note_ovl_candidate_non_deduced_mismatch)
10838         << FirstTA << SecondTA;
10839     return;
10840   }
10841   // TODO: diagnose these individually, then kill off
10842   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10843   case Sema::TDK_MiscellaneousDeductionFailure:
10844     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10845     MaybeEmitInheritedConstructorNote(S, Found);
10846     return;
10847   case Sema::TDK_CUDATargetMismatch:
10848     S.Diag(Templated->getLocation(),
10849            diag::note_cuda_ovl_candidate_target_mismatch);
10850     return;
10851   }
10852 }
10853 
10854 /// Diagnose a failed template-argument deduction, for function calls.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress)10855 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10856                                  unsigned NumArgs,
10857                                  bool TakingCandidateAddress) {
10858   unsigned TDK = Cand->DeductionFailure.Result;
10859   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10860     if (CheckArityMismatch(S, Cand, NumArgs))
10861       return;
10862   }
10863   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10864                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10865 }
10866 
10867 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)10868 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10869   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10870   FunctionDecl *Callee = Cand->Function;
10871 
10872   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10873                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10874 
10875   std::string FnDesc;
10876   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10877       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10878                                 Cand->getRewriteKind(), FnDesc);
10879 
10880   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10881       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10882       << FnDesc /* Ignored */
10883       << CalleeTarget << CallerTarget;
10884 
10885   // This could be an implicit constructor for which we could not infer the
10886   // target due to a collsion. Diagnose that case.
10887   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10888   if (Meth != nullptr && Meth->isImplicit()) {
10889     CXXRecordDecl *ParentClass = Meth->getParent();
10890     Sema::CXXSpecialMember CSM;
10891 
10892     switch (FnKindPair.first) {
10893     default:
10894       return;
10895     case oc_implicit_default_constructor:
10896       CSM = Sema::CXXDefaultConstructor;
10897       break;
10898     case oc_implicit_copy_constructor:
10899       CSM = Sema::CXXCopyConstructor;
10900       break;
10901     case oc_implicit_move_constructor:
10902       CSM = Sema::CXXMoveConstructor;
10903       break;
10904     case oc_implicit_copy_assignment:
10905       CSM = Sema::CXXCopyAssignment;
10906       break;
10907     case oc_implicit_move_assignment:
10908       CSM = Sema::CXXMoveAssignment;
10909       break;
10910     };
10911 
10912     bool ConstRHS = false;
10913     if (Meth->getNumParams()) {
10914       if (const ReferenceType *RT =
10915               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10916         ConstRHS = RT->getPointeeType().isConstQualified();
10917       }
10918     }
10919 
10920     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10921                                               /* ConstRHS */ ConstRHS,
10922                                               /* Diagnose */ true);
10923   }
10924 }
10925 
DiagnoseFailedEnableIfAttr(Sema & S,OverloadCandidate * Cand)10926 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10927   FunctionDecl *Callee = Cand->Function;
10928   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10929 
10930   S.Diag(Callee->getLocation(),
10931          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10932       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10933 }
10934 
DiagnoseFailedExplicitSpec(Sema & S,OverloadCandidate * Cand)10935 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10936   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10937   assert(ES.isExplicit() && "not an explicit candidate");
10938 
10939   unsigned Kind;
10940   switch (Cand->Function->getDeclKind()) {
10941   case Decl::Kind::CXXConstructor:
10942     Kind = 0;
10943     break;
10944   case Decl::Kind::CXXConversion:
10945     Kind = 1;
10946     break;
10947   case Decl::Kind::CXXDeductionGuide:
10948     Kind = Cand->Function->isImplicit() ? 0 : 2;
10949     break;
10950   default:
10951     llvm_unreachable("invalid Decl");
10952   }
10953 
10954   // Note the location of the first (in-class) declaration; a redeclaration
10955   // (particularly an out-of-class definition) will typically lack the
10956   // 'explicit' specifier.
10957   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10958   FunctionDecl *First = Cand->Function->getFirstDecl();
10959   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10960     First = Pattern->getFirstDecl();
10961 
10962   S.Diag(First->getLocation(),
10963          diag::note_ovl_candidate_explicit)
10964       << Kind << (ES.getExpr() ? 1 : 0)
10965       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10966 }
10967 
DiagnoseOpenCLExtensionDisabled(Sema & S,OverloadCandidate * Cand)10968 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10969   FunctionDecl *Callee = Cand->Function;
10970 
10971   S.Diag(Callee->getLocation(),
10972          diag::note_ovl_candidate_disabled_by_extension)
10973     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10974 }
10975 
10976 /// Generates a 'note' diagnostic for an overload candidate.  We've
10977 /// already generated a primary error at the call site.
10978 ///
10979 /// It really does need to be a single diagnostic with its caret
10980 /// pointed at the candidate declaration.  Yes, this creates some
10981 /// major challenges of technical writing.  Yes, this makes pointing
10982 /// out problems with specific arguments quite awkward.  It's still
10983 /// better than generating twenty screens of text for every failed
10984 /// overload.
10985 ///
10986 /// It would be great to be able to express per-candidate problems
10987 /// more richly for those diagnostic clients that cared, but we'd
10988 /// still have to be just as careful with the default diagnostics.
10989 /// \param CtorDestAS Addr space of object being constructed (for ctor
10990 /// candidates only).
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress,LangAS CtorDestAS=LangAS::Default)10991 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10992                                   unsigned NumArgs,
10993                                   bool TakingCandidateAddress,
10994                                   LangAS CtorDestAS = LangAS::Default) {
10995   FunctionDecl *Fn = Cand->Function;
10996 
10997   // Note deleted candidates, but only if they're viable.
10998   if (Cand->Viable) {
10999     if (Fn->isDeleted()) {
11000       std::string FnDesc;
11001       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11002           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11003                                     Cand->getRewriteKind(), FnDesc);
11004 
11005       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11006           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11007           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11008       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11009       return;
11010     }
11011 
11012     // We don't really have anything else to say about viable candidates.
11013     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11014     return;
11015   }
11016 
11017   switch (Cand->FailureKind) {
11018   case ovl_fail_too_many_arguments:
11019   case ovl_fail_too_few_arguments:
11020     return DiagnoseArityMismatch(S, Cand, NumArgs);
11021 
11022   case ovl_fail_bad_deduction:
11023     return DiagnoseBadDeduction(S, Cand, NumArgs,
11024                                 TakingCandidateAddress);
11025 
11026   case ovl_fail_illegal_constructor: {
11027     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11028       << (Fn->getPrimaryTemplate() ? 1 : 0);
11029     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11030     return;
11031   }
11032 
11033   case ovl_fail_object_addrspace_mismatch: {
11034     Qualifiers QualsForPrinting;
11035     QualsForPrinting.setAddressSpace(CtorDestAS);
11036     S.Diag(Fn->getLocation(),
11037            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11038         << QualsForPrinting;
11039     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11040     return;
11041   }
11042 
11043   case ovl_fail_trivial_conversion:
11044   case ovl_fail_bad_final_conversion:
11045   case ovl_fail_final_conversion_not_exact:
11046     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11047 
11048   case ovl_fail_bad_conversion: {
11049     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11050     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11051       if (Cand->Conversions[I].isBad())
11052         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11053 
11054     // FIXME: this currently happens when we're called from SemaInit
11055     // when user-conversion overload fails.  Figure out how to handle
11056     // those conditions and diagnose them well.
11057     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11058   }
11059 
11060   case ovl_fail_bad_target:
11061     return DiagnoseBadTarget(S, Cand);
11062 
11063   case ovl_fail_enable_if:
11064     return DiagnoseFailedEnableIfAttr(S, Cand);
11065 
11066   case ovl_fail_explicit:
11067     return DiagnoseFailedExplicitSpec(S, Cand);
11068 
11069   case ovl_fail_ext_disabled:
11070     return DiagnoseOpenCLExtensionDisabled(S, Cand);
11071 
11072   case ovl_fail_inhctor_slice:
11073     // It's generally not interesting to note copy/move constructors here.
11074     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11075       return;
11076     S.Diag(Fn->getLocation(),
11077            diag::note_ovl_candidate_inherited_constructor_slice)
11078       << (Fn->getPrimaryTemplate() ? 1 : 0)
11079       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11080     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11081     return;
11082 
11083   case ovl_fail_addr_not_available: {
11084     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11085     (void)Available;
11086     assert(!Available);
11087     break;
11088   }
11089   case ovl_non_default_multiversion_function:
11090     // Do nothing, these should simply be ignored.
11091     break;
11092 
11093   case ovl_fail_constraints_not_satisfied: {
11094     std::string FnDesc;
11095     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11096         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11097                                   Cand->getRewriteKind(), FnDesc);
11098 
11099     S.Diag(Fn->getLocation(),
11100            diag::note_ovl_candidate_constraints_not_satisfied)
11101         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11102         << FnDesc /* Ignored */;
11103     ConstraintSatisfaction Satisfaction;
11104     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11105       break;
11106     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11107   }
11108   }
11109 }
11110 
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)11111 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11112   // Desugar the type of the surrogate down to a function type,
11113   // retaining as many typedefs as possible while still showing
11114   // the function type (and, therefore, its parameter types).
11115   QualType FnType = Cand->Surrogate->getConversionType();
11116   bool isLValueReference = false;
11117   bool isRValueReference = false;
11118   bool isPointer = false;
11119   if (const LValueReferenceType *FnTypeRef =
11120         FnType->getAs<LValueReferenceType>()) {
11121     FnType = FnTypeRef->getPointeeType();
11122     isLValueReference = true;
11123   } else if (const RValueReferenceType *FnTypeRef =
11124                FnType->getAs<RValueReferenceType>()) {
11125     FnType = FnTypeRef->getPointeeType();
11126     isRValueReference = true;
11127   }
11128   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11129     FnType = FnTypePtr->getPointeeType();
11130     isPointer = true;
11131   }
11132   // Desugar down to a function type.
11133   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11134   // Reconstruct the pointer/reference as appropriate.
11135   if (isPointer) FnType = S.Context.getPointerType(FnType);
11136   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11137   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11138 
11139   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11140     << FnType;
11141 }
11142 
NoteBuiltinOperatorCandidate(Sema & S,StringRef Opc,SourceLocation OpLoc,OverloadCandidate * Cand)11143 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11144                                          SourceLocation OpLoc,
11145                                          OverloadCandidate *Cand) {
11146   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11147   std::string TypeStr("operator");
11148   TypeStr += Opc;
11149   TypeStr += "(";
11150   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11151   if (Cand->Conversions.size() == 1) {
11152     TypeStr += ")";
11153     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11154   } else {
11155     TypeStr += ", ";
11156     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11157     TypeStr += ")";
11158     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11159   }
11160 }
11161 
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)11162 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11163                                          OverloadCandidate *Cand) {
11164   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11165     if (ICS.isBad()) break; // all meaningless after first invalid
11166     if (!ICS.isAmbiguous()) continue;
11167 
11168     ICS.DiagnoseAmbiguousConversion(
11169         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11170   }
11171 }
11172 
GetLocationForCandidate(const OverloadCandidate * Cand)11173 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11174   if (Cand->Function)
11175     return Cand->Function->getLocation();
11176   if (Cand->IsSurrogate)
11177     return Cand->Surrogate->getLocation();
11178   return SourceLocation();
11179 }
11180 
RankDeductionFailure(const DeductionFailureInfo & DFI)11181 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11182   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11183   case Sema::TDK_Success:
11184   case Sema::TDK_NonDependentConversionFailure:
11185     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11186 
11187   case Sema::TDK_Invalid:
11188   case Sema::TDK_Incomplete:
11189   case Sema::TDK_IncompletePack:
11190     return 1;
11191 
11192   case Sema::TDK_Underqualified:
11193   case Sema::TDK_Inconsistent:
11194     return 2;
11195 
11196   case Sema::TDK_SubstitutionFailure:
11197   case Sema::TDK_DeducedMismatch:
11198   case Sema::TDK_ConstraintsNotSatisfied:
11199   case Sema::TDK_DeducedMismatchNested:
11200   case Sema::TDK_NonDeducedMismatch:
11201   case Sema::TDK_MiscellaneousDeductionFailure:
11202   case Sema::TDK_CUDATargetMismatch:
11203     return 3;
11204 
11205   case Sema::TDK_InstantiationDepth:
11206     return 4;
11207 
11208   case Sema::TDK_InvalidExplicitArguments:
11209     return 5;
11210 
11211   case Sema::TDK_TooManyArguments:
11212   case Sema::TDK_TooFewArguments:
11213     return 6;
11214   }
11215   llvm_unreachable("Unhandled deduction result");
11216 }
11217 
11218 namespace {
11219 struct CompareOverloadCandidatesForDisplay {
11220   Sema &S;
11221   SourceLocation Loc;
11222   size_t NumArgs;
11223   OverloadCandidateSet::CandidateSetKind CSK;
11224 
CompareOverloadCandidatesForDisplay__anon5fe2f31f1811::CompareOverloadCandidatesForDisplay11225   CompareOverloadCandidatesForDisplay(
11226       Sema &S, SourceLocation Loc, size_t NArgs,
11227       OverloadCandidateSet::CandidateSetKind CSK)
11228       : S(S), NumArgs(NArgs), CSK(CSK) {}
11229 
EffectiveFailureKind__anon5fe2f31f1811::CompareOverloadCandidatesForDisplay11230   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11231     // If there are too many or too few arguments, that's the high-order bit we
11232     // want to sort by, even if the immediate failure kind was something else.
11233     if (C->FailureKind == ovl_fail_too_many_arguments ||
11234         C->FailureKind == ovl_fail_too_few_arguments)
11235       return static_cast<OverloadFailureKind>(C->FailureKind);
11236 
11237     if (C->Function) {
11238       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11239         return ovl_fail_too_many_arguments;
11240       if (NumArgs < C->Function->getMinRequiredArguments())
11241         return ovl_fail_too_few_arguments;
11242     }
11243 
11244     return static_cast<OverloadFailureKind>(C->FailureKind);
11245   }
11246 
operator ()__anon5fe2f31f1811::CompareOverloadCandidatesForDisplay11247   bool operator()(const OverloadCandidate *L,
11248                   const OverloadCandidate *R) {
11249     // Fast-path this check.
11250     if (L == R) return false;
11251 
11252     // Order first by viability.
11253     if (L->Viable) {
11254       if (!R->Viable) return true;
11255 
11256       // TODO: introduce a tri-valued comparison for overload
11257       // candidates.  Would be more worthwhile if we had a sort
11258       // that could exploit it.
11259       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11260         return true;
11261       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11262         return false;
11263     } else if (R->Viable)
11264       return false;
11265 
11266     assert(L->Viable == R->Viable);
11267 
11268     // Criteria by which we can sort non-viable candidates:
11269     if (!L->Viable) {
11270       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11271       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11272 
11273       // 1. Arity mismatches come after other candidates.
11274       if (LFailureKind == ovl_fail_too_many_arguments ||
11275           LFailureKind == ovl_fail_too_few_arguments) {
11276         if (RFailureKind == ovl_fail_too_many_arguments ||
11277             RFailureKind == ovl_fail_too_few_arguments) {
11278           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11279           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11280           if (LDist == RDist) {
11281             if (LFailureKind == RFailureKind)
11282               // Sort non-surrogates before surrogates.
11283               return !L->IsSurrogate && R->IsSurrogate;
11284             // Sort candidates requiring fewer parameters than there were
11285             // arguments given after candidates requiring more parameters
11286             // than there were arguments given.
11287             return LFailureKind == ovl_fail_too_many_arguments;
11288           }
11289           return LDist < RDist;
11290         }
11291         return false;
11292       }
11293       if (RFailureKind == ovl_fail_too_many_arguments ||
11294           RFailureKind == ovl_fail_too_few_arguments)
11295         return true;
11296 
11297       // 2. Bad conversions come first and are ordered by the number
11298       // of bad conversions and quality of good conversions.
11299       if (LFailureKind == ovl_fail_bad_conversion) {
11300         if (RFailureKind != ovl_fail_bad_conversion)
11301           return true;
11302 
11303         // The conversion that can be fixed with a smaller number of changes,
11304         // comes first.
11305         unsigned numLFixes = L->Fix.NumConversionsFixed;
11306         unsigned numRFixes = R->Fix.NumConversionsFixed;
11307         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11308         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11309         if (numLFixes != numRFixes) {
11310           return numLFixes < numRFixes;
11311         }
11312 
11313         // If there's any ordering between the defined conversions...
11314         // FIXME: this might not be transitive.
11315         assert(L->Conversions.size() == R->Conversions.size());
11316 
11317         int leftBetter = 0;
11318         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11319         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11320           switch (CompareImplicitConversionSequences(S, Loc,
11321                                                      L->Conversions[I],
11322                                                      R->Conversions[I])) {
11323           case ImplicitConversionSequence::Better:
11324             leftBetter++;
11325             break;
11326 
11327           case ImplicitConversionSequence::Worse:
11328             leftBetter--;
11329             break;
11330 
11331           case ImplicitConversionSequence::Indistinguishable:
11332             break;
11333           }
11334         }
11335         if (leftBetter > 0) return true;
11336         if (leftBetter < 0) return false;
11337 
11338       } else if (RFailureKind == ovl_fail_bad_conversion)
11339         return false;
11340 
11341       if (LFailureKind == ovl_fail_bad_deduction) {
11342         if (RFailureKind != ovl_fail_bad_deduction)
11343           return true;
11344 
11345         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11346           return RankDeductionFailure(L->DeductionFailure)
11347                < RankDeductionFailure(R->DeductionFailure);
11348       } else if (RFailureKind == ovl_fail_bad_deduction)
11349         return false;
11350 
11351       // TODO: others?
11352     }
11353 
11354     // Sort everything else by location.
11355     SourceLocation LLoc = GetLocationForCandidate(L);
11356     SourceLocation RLoc = GetLocationForCandidate(R);
11357 
11358     // Put candidates without locations (e.g. builtins) at the end.
11359     if (LLoc.isInvalid()) return false;
11360     if (RLoc.isInvalid()) return true;
11361 
11362     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11363   }
11364 };
11365 }
11366 
11367 /// CompleteNonViableCandidate - Normally, overload resolution only
11368 /// computes up to the first bad conversion. Produces the FixIt set if
11369 /// possible.
11370 static void
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,ArrayRef<Expr * > Args,OverloadCandidateSet::CandidateSetKind CSK)11371 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11372                            ArrayRef<Expr *> Args,
11373                            OverloadCandidateSet::CandidateSetKind CSK) {
11374   assert(!Cand->Viable);
11375 
11376   // Don't do anything on failures other than bad conversion.
11377   if (Cand->FailureKind != ovl_fail_bad_conversion)
11378     return;
11379 
11380   // We only want the FixIts if all the arguments can be corrected.
11381   bool Unfixable = false;
11382   // Use a implicit copy initialization to check conversion fixes.
11383   Cand->Fix.setConversionChecker(TryCopyInitialization);
11384 
11385   // Attempt to fix the bad conversion.
11386   unsigned ConvCount = Cand->Conversions.size();
11387   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11388        ++ConvIdx) {
11389     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11390     if (Cand->Conversions[ConvIdx].isInitialized() &&
11391         Cand->Conversions[ConvIdx].isBad()) {
11392       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11393       break;
11394     }
11395   }
11396 
11397   // FIXME: this should probably be preserved from the overload
11398   // operation somehow.
11399   bool SuppressUserConversions = false;
11400 
11401   unsigned ConvIdx = 0;
11402   unsigned ArgIdx = 0;
11403   ArrayRef<QualType> ParamTypes;
11404   bool Reversed = Cand->isReversed();
11405 
11406   if (Cand->IsSurrogate) {
11407     QualType ConvType
11408       = Cand->Surrogate->getConversionType().getNonReferenceType();
11409     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11410       ConvType = ConvPtrType->getPointeeType();
11411     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11412     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11413     ConvIdx = 1;
11414   } else if (Cand->Function) {
11415     ParamTypes =
11416         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11417     if (isa<CXXMethodDecl>(Cand->Function) &&
11418         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11419       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11420       ConvIdx = 1;
11421       if (CSK == OverloadCandidateSet::CSK_Operator &&
11422           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11423         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11424         ArgIdx = 1;
11425     }
11426   } else {
11427     // Builtin operator.
11428     assert(ConvCount <= 3);
11429     ParamTypes = Cand->BuiltinParamTypes;
11430   }
11431 
11432   // Fill in the rest of the conversions.
11433   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11434        ConvIdx != ConvCount;
11435        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11436     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11437     if (Cand->Conversions[ConvIdx].isInitialized()) {
11438       // We've already checked this conversion.
11439     } else if (ParamIdx < ParamTypes.size()) {
11440       if (ParamTypes[ParamIdx]->isDependentType())
11441         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11442             Args[ArgIdx]->getType());
11443       else {
11444         Cand->Conversions[ConvIdx] =
11445             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11446                                   SuppressUserConversions,
11447                                   /*InOverloadResolution=*/true,
11448                                   /*AllowObjCWritebackConversion=*/
11449                                   S.getLangOpts().ObjCAutoRefCount);
11450         // Store the FixIt in the candidate if it exists.
11451         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11452           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11453       }
11454     } else
11455       Cand->Conversions[ConvIdx].setEllipsis();
11456   }
11457 }
11458 
CompleteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,SourceLocation OpLoc,llvm::function_ref<bool (OverloadCandidate &)> Filter)11459 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11460     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11461     SourceLocation OpLoc,
11462     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11463   // Sort the candidates by viability and position.  Sorting directly would
11464   // be prohibitive, so we make a set of pointers and sort those.
11465   SmallVector<OverloadCandidate*, 32> Cands;
11466   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11467   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11468     if (!Filter(*Cand))
11469       continue;
11470     switch (OCD) {
11471     case OCD_AllCandidates:
11472       if (!Cand->Viable) {
11473         if (!Cand->Function && !Cand->IsSurrogate) {
11474           // This a non-viable builtin candidate.  We do not, in general,
11475           // want to list every possible builtin candidate.
11476           continue;
11477         }
11478         CompleteNonViableCandidate(S, Cand, Args, Kind);
11479       }
11480       break;
11481 
11482     case OCD_ViableCandidates:
11483       if (!Cand->Viable)
11484         continue;
11485       break;
11486 
11487     case OCD_AmbiguousCandidates:
11488       if (!Cand->Best)
11489         continue;
11490       break;
11491     }
11492 
11493     Cands.push_back(Cand);
11494   }
11495 
11496   llvm::stable_sort(
11497       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11498 
11499   return Cands;
11500 }
11501 
11502 /// When overload resolution fails, prints diagnostic messages containing the
11503 /// candidates in the candidate set.
NoteCandidates(PartialDiagnosticAt PD,Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,StringRef Opc,SourceLocation OpLoc,llvm::function_ref<bool (OverloadCandidate &)> Filter)11504 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11505     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11506     StringRef Opc, SourceLocation OpLoc,
11507     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11508 
11509   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11510 
11511   S.Diag(PD.first, PD.second);
11512 
11513   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11514 
11515   if (OCD == OCD_AmbiguousCandidates)
11516     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11517 }
11518 
NoteCandidates(Sema & S,ArrayRef<Expr * > Args,ArrayRef<OverloadCandidate * > Cands,StringRef Opc,SourceLocation OpLoc)11519 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11520                                           ArrayRef<OverloadCandidate *> Cands,
11521                                           StringRef Opc, SourceLocation OpLoc) {
11522   bool ReportedAmbiguousConversions = false;
11523 
11524   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11525   unsigned CandsShown = 0;
11526   auto I = Cands.begin(), E = Cands.end();
11527   for (; I != E; ++I) {
11528     OverloadCandidate *Cand = *I;
11529 
11530     // Set an arbitrary limit on the number of candidate functions we'll spam
11531     // the user with.  FIXME: This limit should depend on details of the
11532     // candidate list.
11533     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11534       break;
11535     }
11536     ++CandsShown;
11537 
11538     if (Cand->Function)
11539       NoteFunctionCandidate(S, Cand, Args.size(),
11540                             /*TakingCandidateAddress=*/false, DestAS);
11541     else if (Cand->IsSurrogate)
11542       NoteSurrogateCandidate(S, Cand);
11543     else {
11544       assert(Cand->Viable &&
11545              "Non-viable built-in candidates are not added to Cands.");
11546       // Generally we only see ambiguities including viable builtin
11547       // operators if overload resolution got screwed up by an
11548       // ambiguous user-defined conversion.
11549       //
11550       // FIXME: It's quite possible for different conversions to see
11551       // different ambiguities, though.
11552       if (!ReportedAmbiguousConversions) {
11553         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11554         ReportedAmbiguousConversions = true;
11555       }
11556 
11557       // If this is a viable builtin, print it.
11558       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11559     }
11560   }
11561 
11562   if (I != E)
11563     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11564 }
11565 
11566 static SourceLocation
GetLocationForCandidate(const TemplateSpecCandidate * Cand)11567 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11568   return Cand->Specialization ? Cand->Specialization->getLocation()
11569                               : SourceLocation();
11570 }
11571 
11572 namespace {
11573 struct CompareTemplateSpecCandidatesForDisplay {
11574   Sema &S;
CompareTemplateSpecCandidatesForDisplay__anon5fe2f31f1911::CompareTemplateSpecCandidatesForDisplay11575   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11576 
operator ()__anon5fe2f31f1911::CompareTemplateSpecCandidatesForDisplay11577   bool operator()(const TemplateSpecCandidate *L,
11578                   const TemplateSpecCandidate *R) {
11579     // Fast-path this check.
11580     if (L == R)
11581       return false;
11582 
11583     // Assuming that both candidates are not matches...
11584 
11585     // Sort by the ranking of deduction failures.
11586     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11587       return RankDeductionFailure(L->DeductionFailure) <
11588              RankDeductionFailure(R->DeductionFailure);
11589 
11590     // Sort everything else by location.
11591     SourceLocation LLoc = GetLocationForCandidate(L);
11592     SourceLocation RLoc = GetLocationForCandidate(R);
11593 
11594     // Put candidates without locations (e.g. builtins) at the end.
11595     if (LLoc.isInvalid())
11596       return false;
11597     if (RLoc.isInvalid())
11598       return true;
11599 
11600     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11601   }
11602 };
11603 }
11604 
11605 /// Diagnose a template argument deduction failure.
11606 /// We are treating these failures as overload failures due to bad
11607 /// deductions.
NoteDeductionFailure(Sema & S,bool ForTakingAddress)11608 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11609                                                  bool ForTakingAddress) {
11610   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11611                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11612 }
11613 
destroyCandidates()11614 void TemplateSpecCandidateSet::destroyCandidates() {
11615   for (iterator i = begin(), e = end(); i != e; ++i) {
11616     i->DeductionFailure.Destroy();
11617   }
11618 }
11619 
clear()11620 void TemplateSpecCandidateSet::clear() {
11621   destroyCandidates();
11622   Candidates.clear();
11623 }
11624 
11625 /// NoteCandidates - When no template specialization match is found, prints
11626 /// diagnostic messages containing the non-matching specializations that form
11627 /// the candidate set.
11628 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11629 /// OCD == OCD_AllCandidates and Cand->Viable == false.
NoteCandidates(Sema & S,SourceLocation Loc)11630 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11631   // Sort the candidates by position (assuming no candidate is a match).
11632   // Sorting directly would be prohibitive, so we make a set of pointers
11633   // and sort those.
11634   SmallVector<TemplateSpecCandidate *, 32> Cands;
11635   Cands.reserve(size());
11636   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11637     if (Cand->Specialization)
11638       Cands.push_back(Cand);
11639     // Otherwise, this is a non-matching builtin candidate.  We do not,
11640     // in general, want to list every possible builtin candidate.
11641   }
11642 
11643   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11644 
11645   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11646   // for generalization purposes (?).
11647   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11648 
11649   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11650   unsigned CandsShown = 0;
11651   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11652     TemplateSpecCandidate *Cand = *I;
11653 
11654     // Set an arbitrary limit on the number of candidates we'll spam
11655     // the user with.  FIXME: This limit should depend on details of the
11656     // candidate list.
11657     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11658       break;
11659     ++CandsShown;
11660 
11661     assert(Cand->Specialization &&
11662            "Non-matching built-in candidates are not added to Cands.");
11663     Cand->NoteDeductionFailure(S, ForTakingAddress);
11664   }
11665 
11666   if (I != E)
11667     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11668 }
11669 
11670 // [PossiblyAFunctionType]  -->   [Return]
11671 // NonFunctionType --> NonFunctionType
11672 // R (A) --> R(A)
11673 // R (*)(A) --> R (A)
11674 // R (&)(A) --> R (A)
11675 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)11676 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11677   QualType Ret = PossiblyAFunctionType;
11678   if (const PointerType *ToTypePtr =
11679     PossiblyAFunctionType->getAs<PointerType>())
11680     Ret = ToTypePtr->getPointeeType();
11681   else if (const ReferenceType *ToTypeRef =
11682     PossiblyAFunctionType->getAs<ReferenceType>())
11683     Ret = ToTypeRef->getPointeeType();
11684   else if (const MemberPointerType *MemTypePtr =
11685     PossiblyAFunctionType->getAs<MemberPointerType>())
11686     Ret = MemTypePtr->getPointeeType();
11687   Ret =
11688     Context.getCanonicalType(Ret).getUnqualifiedType();
11689   return Ret;
11690 }
11691 
completeFunctionType(Sema & S,FunctionDecl * FD,SourceLocation Loc,bool Complain=true)11692 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11693                                  bool Complain = true) {
11694   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11695       S.DeduceReturnType(FD, Loc, Complain))
11696     return true;
11697 
11698   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11699   if (S.getLangOpts().CPlusPlus17 &&
11700       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11701       !S.ResolveExceptionSpec(Loc, FPT))
11702     return true;
11703 
11704   return false;
11705 }
11706 
11707 namespace {
11708 // A helper class to help with address of function resolution
11709 // - allows us to avoid passing around all those ugly parameters
11710 class AddressOfFunctionResolver {
11711   Sema& S;
11712   Expr* SourceExpr;
11713   const QualType& TargetType;
11714   QualType TargetFunctionType; // Extracted function type from target type
11715 
11716   bool Complain;
11717   //DeclAccessPair& ResultFunctionAccessPair;
11718   ASTContext& Context;
11719 
11720   bool TargetTypeIsNonStaticMemberFunction;
11721   bool FoundNonTemplateFunction;
11722   bool StaticMemberFunctionFromBoundPointer;
11723   bool HasComplained;
11724 
11725   OverloadExpr::FindResult OvlExprInfo;
11726   OverloadExpr *OvlExpr;
11727   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11728   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11729   TemplateSpecCandidateSet FailedCandidates;
11730 
11731 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)11732   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11733                             const QualType &TargetType, bool Complain)
11734       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11735         Complain(Complain), Context(S.getASTContext()),
11736         TargetTypeIsNonStaticMemberFunction(
11737             !!TargetType->getAs<MemberPointerType>()),
11738         FoundNonTemplateFunction(false),
11739         StaticMemberFunctionFromBoundPointer(false),
11740         HasComplained(false),
11741         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11742         OvlExpr(OvlExprInfo.Expression),
11743         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11744     ExtractUnqualifiedFunctionTypeFromTargetType();
11745 
11746     if (TargetFunctionType->isFunctionType()) {
11747       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11748         if (!UME->isImplicitAccess() &&
11749             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11750           StaticMemberFunctionFromBoundPointer = true;
11751     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11752       DeclAccessPair dap;
11753       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11754               OvlExpr, false, &dap)) {
11755         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11756           if (!Method->isStatic()) {
11757             // If the target type is a non-function type and the function found
11758             // is a non-static member function, pretend as if that was the
11759             // target, it's the only possible type to end up with.
11760             TargetTypeIsNonStaticMemberFunction = true;
11761 
11762             // And skip adding the function if its not in the proper form.
11763             // We'll diagnose this due to an empty set of functions.
11764             if (!OvlExprInfo.HasFormOfMemberPointer)
11765               return;
11766           }
11767 
11768         Matches.push_back(std::make_pair(dap, Fn));
11769       }
11770       return;
11771     }
11772 
11773     if (OvlExpr->hasExplicitTemplateArgs())
11774       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11775 
11776     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11777       // C++ [over.over]p4:
11778       //   If more than one function is selected, [...]
11779       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11780         if (FoundNonTemplateFunction)
11781           EliminateAllTemplateMatches();
11782         else
11783           EliminateAllExceptMostSpecializedTemplate();
11784       }
11785     }
11786 
11787     if (S.getLangOpts().CUDA && Matches.size() > 1)
11788       EliminateSuboptimalCudaMatches();
11789   }
11790 
hasComplained() const11791   bool hasComplained() const { return HasComplained; }
11792 
11793 private:
candidateHasExactlyCorrectType(const FunctionDecl * FD)11794   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11795     QualType Discard;
11796     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11797            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11798   }
11799 
11800   /// \return true if A is considered a better overload candidate for the
11801   /// desired type than B.
isBetterCandidate(const FunctionDecl * A,const FunctionDecl * B)11802   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11803     // If A doesn't have exactly the correct type, we don't want to classify it
11804     // as "better" than anything else. This way, the user is required to
11805     // disambiguate for us if there are multiple candidates and no exact match.
11806     return candidateHasExactlyCorrectType(A) &&
11807            (!candidateHasExactlyCorrectType(B) ||
11808             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11809   }
11810 
11811   /// \return true if we were able to eliminate all but one overload candidate,
11812   /// false otherwise.
eliminiateSuboptimalOverloadCandidates()11813   bool eliminiateSuboptimalOverloadCandidates() {
11814     // Same algorithm as overload resolution -- one pass to pick the "best",
11815     // another pass to be sure that nothing is better than the best.
11816     auto Best = Matches.begin();
11817     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11818       if (isBetterCandidate(I->second, Best->second))
11819         Best = I;
11820 
11821     const FunctionDecl *BestFn = Best->second;
11822     auto IsBestOrInferiorToBest = [this, BestFn](
11823         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11824       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11825     };
11826 
11827     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11828     // option, so we can potentially give the user a better error
11829     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11830       return false;
11831     Matches[0] = *Best;
11832     Matches.resize(1);
11833     return true;
11834   }
11835 
isTargetTypeAFunction() const11836   bool isTargetTypeAFunction() const {
11837     return TargetFunctionType->isFunctionType();
11838   }
11839 
11840   // [ToType]     [Return]
11841 
11842   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11843   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11844   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()11845   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11846     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11847   }
11848 
11849   // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)11850   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11851                                    const DeclAccessPair& CurAccessFunPair) {
11852     if (CXXMethodDecl *Method
11853               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11854       // Skip non-static function templates when converting to pointer, and
11855       // static when converting to member pointer.
11856       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11857         return false;
11858     }
11859     else if (TargetTypeIsNonStaticMemberFunction)
11860       return false;
11861 
11862     // C++ [over.over]p2:
11863     //   If the name is a function template, template argument deduction is
11864     //   done (14.8.2.2), and if the argument deduction succeeds, the
11865     //   resulting template argument list is used to generate a single
11866     //   function template specialization, which is added to the set of
11867     //   overloaded functions considered.
11868     FunctionDecl *Specialization = nullptr;
11869     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11870     if (Sema::TemplateDeductionResult Result
11871           = S.DeduceTemplateArguments(FunctionTemplate,
11872                                       &OvlExplicitTemplateArgs,
11873                                       TargetFunctionType, Specialization,
11874                                       Info, /*IsAddressOfFunction*/true)) {
11875       // Make a note of the failed deduction for diagnostics.
11876       FailedCandidates.addCandidate()
11877           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11878                MakeDeductionFailureInfo(Context, Result, Info));
11879       return false;
11880     }
11881 
11882     // Template argument deduction ensures that we have an exact match or
11883     // compatible pointer-to-function arguments that would be adjusted by ICS.
11884     // This function template specicalization works.
11885     assert(S.isSameOrCompatibleFunctionType(
11886               Context.getCanonicalType(Specialization->getType()),
11887               Context.getCanonicalType(TargetFunctionType)));
11888 
11889     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11890       return false;
11891 
11892     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11893     return true;
11894   }
11895 
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)11896   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11897                                       const DeclAccessPair& CurAccessFunPair) {
11898     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11899       // Skip non-static functions when converting to pointer, and static
11900       // when converting to member pointer.
11901       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11902         return false;
11903     }
11904     else if (TargetTypeIsNonStaticMemberFunction)
11905       return false;
11906 
11907     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11908       if (S.getLangOpts().CUDA)
11909         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11910           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11911             return false;
11912       if (FunDecl->isMultiVersion()) {
11913         const auto *TA = FunDecl->getAttr<TargetAttr>();
11914         if (TA && !TA->isDefaultVersion())
11915           return false;
11916       }
11917 
11918       // If any candidate has a placeholder return type, trigger its deduction
11919       // now.
11920       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11921                                Complain)) {
11922         HasComplained |= Complain;
11923         return false;
11924       }
11925 
11926       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11927         return false;
11928 
11929       // If we're in C, we need to support types that aren't exactly identical.
11930       if (!S.getLangOpts().CPlusPlus ||
11931           candidateHasExactlyCorrectType(FunDecl)) {
11932         Matches.push_back(std::make_pair(
11933             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11934         FoundNonTemplateFunction = true;
11935         return true;
11936       }
11937     }
11938 
11939     return false;
11940   }
11941 
FindAllFunctionsThatMatchTargetTypeExactly()11942   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11943     bool Ret = false;
11944 
11945     // If the overload expression doesn't have the form of a pointer to
11946     // member, don't try to convert it to a pointer-to-member type.
11947     if (IsInvalidFormOfPointerToMemberFunction())
11948       return false;
11949 
11950     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11951                                E = OvlExpr->decls_end();
11952          I != E; ++I) {
11953       // Look through any using declarations to find the underlying function.
11954       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11955 
11956       // C++ [over.over]p3:
11957       //   Non-member functions and static member functions match
11958       //   targets of type "pointer-to-function" or "reference-to-function."
11959       //   Nonstatic member functions match targets of
11960       //   type "pointer-to-member-function."
11961       // Note that according to DR 247, the containing class does not matter.
11962       if (FunctionTemplateDecl *FunctionTemplate
11963                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11964         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11965           Ret = true;
11966       }
11967       // If we have explicit template arguments supplied, skip non-templates.
11968       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11969                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11970         Ret = true;
11971     }
11972     assert(Ret || Matches.empty());
11973     return Ret;
11974   }
11975 
EliminateAllExceptMostSpecializedTemplate()11976   void EliminateAllExceptMostSpecializedTemplate() {
11977     //   [...] and any given function template specialization F1 is
11978     //   eliminated if the set contains a second function template
11979     //   specialization whose function template is more specialized
11980     //   than the function template of F1 according to the partial
11981     //   ordering rules of 14.5.5.2.
11982 
11983     // The algorithm specified above is quadratic. We instead use a
11984     // two-pass algorithm (similar to the one used to identify the
11985     // best viable function in an overload set) that identifies the
11986     // best function template (if it exists).
11987 
11988     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11989     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11990       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11991 
11992     // TODO: It looks like FailedCandidates does not serve much purpose
11993     // here, since the no_viable diagnostic has index 0.
11994     UnresolvedSetIterator Result = S.getMostSpecialized(
11995         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11996         SourceExpr->getBeginLoc(), S.PDiag(),
11997         S.PDiag(diag::err_addr_ovl_ambiguous)
11998             << Matches[0].second->getDeclName(),
11999         S.PDiag(diag::note_ovl_candidate)
12000             << (unsigned)oc_function << (unsigned)ocs_described_template,
12001         Complain, TargetFunctionType);
12002 
12003     if (Result != MatchesCopy.end()) {
12004       // Make it the first and only element
12005       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12006       Matches[0].second = cast<FunctionDecl>(*Result);
12007       Matches.resize(1);
12008     } else
12009       HasComplained |= Complain;
12010   }
12011 
EliminateAllTemplateMatches()12012   void EliminateAllTemplateMatches() {
12013     //   [...] any function template specializations in the set are
12014     //   eliminated if the set also contains a non-template function, [...]
12015     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12016       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12017         ++I;
12018       else {
12019         Matches[I] = Matches[--N];
12020         Matches.resize(N);
12021       }
12022     }
12023   }
12024 
EliminateSuboptimalCudaMatches()12025   void EliminateSuboptimalCudaMatches() {
12026     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12027   }
12028 
12029 public:
ComplainNoMatchesFound() const12030   void ComplainNoMatchesFound() const {
12031     assert(Matches.empty());
12032     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12033         << OvlExpr->getName() << TargetFunctionType
12034         << OvlExpr->getSourceRange();
12035     if (FailedCandidates.empty())
12036       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12037                                   /*TakingAddress=*/true);
12038     else {
12039       // We have some deduction failure messages. Use them to diagnose
12040       // the function templates, and diagnose the non-template candidates
12041       // normally.
12042       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12043                                  IEnd = OvlExpr->decls_end();
12044            I != IEnd; ++I)
12045         if (FunctionDecl *Fun =
12046                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12047           if (!functionHasPassObjectSizeParams(Fun))
12048             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12049                                     /*TakingAddress=*/true);
12050       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12051     }
12052   }
12053 
IsInvalidFormOfPointerToMemberFunction() const12054   bool IsInvalidFormOfPointerToMemberFunction() const {
12055     return TargetTypeIsNonStaticMemberFunction &&
12056       !OvlExprInfo.HasFormOfMemberPointer;
12057   }
12058 
ComplainIsInvalidFormOfPointerToMemberFunction() const12059   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12060       // TODO: Should we condition this on whether any functions might
12061       // have matched, or is it more appropriate to do that in callers?
12062       // TODO: a fixit wouldn't hurt.
12063       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12064         << TargetType << OvlExpr->getSourceRange();
12065   }
12066 
IsStaticMemberFunctionFromBoundPointer() const12067   bool IsStaticMemberFunctionFromBoundPointer() const {
12068     return StaticMemberFunctionFromBoundPointer;
12069   }
12070 
ComplainIsStaticMemberFunctionFromBoundPointer() const12071   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12072     S.Diag(OvlExpr->getBeginLoc(),
12073            diag::err_invalid_form_pointer_member_function)
12074         << OvlExpr->getSourceRange();
12075   }
12076 
ComplainOfInvalidConversion() const12077   void ComplainOfInvalidConversion() const {
12078     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12079         << OvlExpr->getName() << TargetType;
12080   }
12081 
ComplainMultipleMatchesFound() const12082   void ComplainMultipleMatchesFound() const {
12083     assert(Matches.size() > 1);
12084     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12085         << OvlExpr->getName() << OvlExpr->getSourceRange();
12086     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12087                                 /*TakingAddress=*/true);
12088   }
12089 
hadMultipleCandidates() const12090   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12091 
getNumMatches() const12092   int getNumMatches() const { return Matches.size(); }
12093 
getMatchingFunctionDecl() const12094   FunctionDecl* getMatchingFunctionDecl() const {
12095     if (Matches.size() != 1) return nullptr;
12096     return Matches[0].second;
12097   }
12098 
getMatchingFunctionAccessPair() const12099   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12100     if (Matches.size() != 1) return nullptr;
12101     return &Matches[0].first;
12102   }
12103 };
12104 }
12105 
12106 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12107 /// an overloaded function (C++ [over.over]), where @p From is an
12108 /// expression with overloaded function type and @p ToType is the type
12109 /// we're trying to resolve to. For example:
12110 ///
12111 /// @code
12112 /// int f(double);
12113 /// int f(int);
12114 ///
12115 /// int (*pfd)(double) = f; // selects f(double)
12116 /// @endcode
12117 ///
12118 /// This routine returns the resulting FunctionDecl if it could be
12119 /// resolved, and NULL otherwise. When @p Complain is true, this
12120 /// routine will emit diagnostics if there is an error.
12121 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)12122 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12123                                          QualType TargetType,
12124                                          bool Complain,
12125                                          DeclAccessPair &FoundResult,
12126                                          bool *pHadMultipleCandidates) {
12127   assert(AddressOfExpr->getType() == Context.OverloadTy);
12128 
12129   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12130                                      Complain);
12131   int NumMatches = Resolver.getNumMatches();
12132   FunctionDecl *Fn = nullptr;
12133   bool ShouldComplain = Complain && !Resolver.hasComplained();
12134   if (NumMatches == 0 && ShouldComplain) {
12135     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12136       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12137     else
12138       Resolver.ComplainNoMatchesFound();
12139   }
12140   else if (NumMatches > 1 && ShouldComplain)
12141     Resolver.ComplainMultipleMatchesFound();
12142   else if (NumMatches == 1) {
12143     Fn = Resolver.getMatchingFunctionDecl();
12144     assert(Fn);
12145     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12146       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12147     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12148     if (Complain) {
12149       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12150         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12151       else
12152         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12153     }
12154   }
12155 
12156   if (pHadMultipleCandidates)
12157     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12158   return Fn;
12159 }
12160 
12161 /// Given an expression that refers to an overloaded function, try to
12162 /// resolve that function to a single function that can have its address taken.
12163 /// This will modify `Pair` iff it returns non-null.
12164 ///
12165 /// This routine can only succeed if from all of the candidates in the overload
12166 /// set for SrcExpr that can have their addresses taken, there is one candidate
12167 /// that is more constrained than the rest.
12168 FunctionDecl *
resolveAddressOfSingleOverloadCandidate(Expr * E,DeclAccessPair & Pair)12169 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12170   OverloadExpr::FindResult R = OverloadExpr::find(E);
12171   OverloadExpr *Ovl = R.Expression;
12172   bool IsResultAmbiguous = false;
12173   FunctionDecl *Result = nullptr;
12174   DeclAccessPair DAP;
12175   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12176 
12177   auto CheckMoreConstrained =
12178       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12179         SmallVector<const Expr *, 1> AC1, AC2;
12180         FD1->getAssociatedConstraints(AC1);
12181         FD2->getAssociatedConstraints(AC2);
12182         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12183         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12184           return None;
12185         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12186           return None;
12187         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12188           return None;
12189         return AtLeastAsConstrained1;
12190       };
12191 
12192   // Don't use the AddressOfResolver because we're specifically looking for
12193   // cases where we have one overload candidate that lacks
12194   // enable_if/pass_object_size/...
12195   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12196     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12197     if (!FD)
12198       return nullptr;
12199 
12200     if (!checkAddressOfFunctionIsAvailable(FD))
12201       continue;
12202 
12203     // We have more than one result - see if it is more constrained than the
12204     // previous one.
12205     if (Result) {
12206       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12207                                                                         Result);
12208       if (!MoreConstrainedThanPrevious) {
12209         IsResultAmbiguous = true;
12210         AmbiguousDecls.push_back(FD);
12211         continue;
12212       }
12213       if (!*MoreConstrainedThanPrevious)
12214         continue;
12215       // FD is more constrained - replace Result with it.
12216     }
12217     IsResultAmbiguous = false;
12218     DAP = I.getPair();
12219     Result = FD;
12220   }
12221 
12222   if (IsResultAmbiguous)
12223     return nullptr;
12224 
12225   if (Result) {
12226     SmallVector<const Expr *, 1> ResultAC;
12227     // We skipped over some ambiguous declarations which might be ambiguous with
12228     // the selected result.
12229     for (FunctionDecl *Skipped : AmbiguousDecls)
12230       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12231         return nullptr;
12232     Pair = DAP;
12233   }
12234   return Result;
12235 }
12236 
12237 /// Given an overloaded function, tries to turn it into a non-overloaded
12238 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12239 /// will perform access checks, diagnose the use of the resultant decl, and, if
12240 /// requested, potentially perform a function-to-pointer decay.
12241 ///
12242 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12243 /// Otherwise, returns true. This may emit diagnostics and return true.
resolveAndFixAddressOfSingleOverloadCandidate(ExprResult & SrcExpr,bool DoFunctionPointerConverion)12244 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12245     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12246   Expr *E = SrcExpr.get();
12247   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12248 
12249   DeclAccessPair DAP;
12250   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12251   if (!Found || Found->isCPUDispatchMultiVersion() ||
12252       Found->isCPUSpecificMultiVersion())
12253     return false;
12254 
12255   // Emitting multiple diagnostics for a function that is both inaccessible and
12256   // unavailable is consistent with our behavior elsewhere. So, always check
12257   // for both.
12258   DiagnoseUseOfDecl(Found, E->getExprLoc());
12259   CheckAddressOfMemberAccess(E, DAP);
12260   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12261   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12262     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12263   else
12264     SrcExpr = Fixed;
12265   return true;
12266 }
12267 
12268 /// Given an expression that refers to an overloaded function, try to
12269 /// resolve that overloaded function expression down to a single function.
12270 ///
12271 /// This routine can only resolve template-ids that refer to a single function
12272 /// template, where that template-id refers to a single template whose template
12273 /// arguments are either provided by the template-id or have defaults,
12274 /// as described in C++0x [temp.arg.explicit]p3.
12275 ///
12276 /// If no template-ids are found, no diagnostics are emitted and NULL is
12277 /// returned.
12278 FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult)12279 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12280                                                   bool Complain,
12281                                                   DeclAccessPair *FoundResult) {
12282   // C++ [over.over]p1:
12283   //   [...] [Note: any redundant set of parentheses surrounding the
12284   //   overloaded function name is ignored (5.1). ]
12285   // C++ [over.over]p1:
12286   //   [...] The overloaded function name can be preceded by the &
12287   //   operator.
12288 
12289   // If we didn't actually find any template-ids, we're done.
12290   if (!ovl->hasExplicitTemplateArgs())
12291     return nullptr;
12292 
12293   TemplateArgumentListInfo ExplicitTemplateArgs;
12294   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12295   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12296 
12297   // Look through all of the overloaded functions, searching for one
12298   // whose type matches exactly.
12299   FunctionDecl *Matched = nullptr;
12300   for (UnresolvedSetIterator I = ovl->decls_begin(),
12301          E = ovl->decls_end(); I != E; ++I) {
12302     // C++0x [temp.arg.explicit]p3:
12303     //   [...] In contexts where deduction is done and fails, or in contexts
12304     //   where deduction is not done, if a template argument list is
12305     //   specified and it, along with any default template arguments,
12306     //   identifies a single function template specialization, then the
12307     //   template-id is an lvalue for the function template specialization.
12308     FunctionTemplateDecl *FunctionTemplate
12309       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12310 
12311     // C++ [over.over]p2:
12312     //   If the name is a function template, template argument deduction is
12313     //   done (14.8.2.2), and if the argument deduction succeeds, the
12314     //   resulting template argument list is used to generate a single
12315     //   function template specialization, which is added to the set of
12316     //   overloaded functions considered.
12317     FunctionDecl *Specialization = nullptr;
12318     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12319     if (TemplateDeductionResult Result
12320           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12321                                     Specialization, Info,
12322                                     /*IsAddressOfFunction*/true)) {
12323       // Make a note of the failed deduction for diagnostics.
12324       // TODO: Actually use the failed-deduction info?
12325       FailedCandidates.addCandidate()
12326           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12327                MakeDeductionFailureInfo(Context, Result, Info));
12328       continue;
12329     }
12330 
12331     assert(Specialization && "no specialization and no error?");
12332 
12333     // Multiple matches; we can't resolve to a single declaration.
12334     if (Matched) {
12335       if (Complain) {
12336         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12337           << ovl->getName();
12338         NoteAllOverloadCandidates(ovl);
12339       }
12340       return nullptr;
12341     }
12342 
12343     Matched = Specialization;
12344     if (FoundResult) *FoundResult = I.getPair();
12345   }
12346 
12347   if (Matched &&
12348       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12349     return nullptr;
12350 
12351   return Matched;
12352 }
12353 
12354 // Resolve and fix an overloaded expression that can be resolved
12355 // because it identifies a single function template specialization.
12356 //
12357 // Last three arguments should only be supplied if Complain = true
12358 //
12359 // Return true if it was logically possible to so resolve the
12360 // expression, regardless of whether or not it succeeded.  Always
12361 // returns true if 'complain' is set.
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConverion,bool complain,SourceRange OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)12362 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12363                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12364                       bool complain, SourceRange OpRangeForComplaining,
12365                                            QualType DestTypeForComplaining,
12366                                             unsigned DiagIDForComplaining) {
12367   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12368 
12369   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12370 
12371   DeclAccessPair found;
12372   ExprResult SingleFunctionExpression;
12373   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12374                            ovl.Expression, /*complain*/ false, &found)) {
12375     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12376       SrcExpr = ExprError();
12377       return true;
12378     }
12379 
12380     // It is only correct to resolve to an instance method if we're
12381     // resolving a form that's permitted to be a pointer to member.
12382     // Otherwise we'll end up making a bound member expression, which
12383     // is illegal in all the contexts we resolve like this.
12384     if (!ovl.HasFormOfMemberPointer &&
12385         isa<CXXMethodDecl>(fn) &&
12386         cast<CXXMethodDecl>(fn)->isInstance()) {
12387       if (!complain) return false;
12388 
12389       Diag(ovl.Expression->getExprLoc(),
12390            diag::err_bound_member_function)
12391         << 0 << ovl.Expression->getSourceRange();
12392 
12393       // TODO: I believe we only end up here if there's a mix of
12394       // static and non-static candidates (otherwise the expression
12395       // would have 'bound member' type, not 'overload' type).
12396       // Ideally we would note which candidate was chosen and why
12397       // the static candidates were rejected.
12398       SrcExpr = ExprError();
12399       return true;
12400     }
12401 
12402     // Fix the expression to refer to 'fn'.
12403     SingleFunctionExpression =
12404         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12405 
12406     // If desired, do function-to-pointer decay.
12407     if (doFunctionPointerConverion) {
12408       SingleFunctionExpression =
12409         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12410       if (SingleFunctionExpression.isInvalid()) {
12411         SrcExpr = ExprError();
12412         return true;
12413       }
12414     }
12415   }
12416 
12417   if (!SingleFunctionExpression.isUsable()) {
12418     if (complain) {
12419       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12420         << ovl.Expression->getName()
12421         << DestTypeForComplaining
12422         << OpRangeForComplaining
12423         << ovl.Expression->getQualifierLoc().getSourceRange();
12424       NoteAllOverloadCandidates(SrcExpr.get());
12425 
12426       SrcExpr = ExprError();
12427       return true;
12428     }
12429 
12430     return false;
12431   }
12432 
12433   SrcExpr = SingleFunctionExpression;
12434   return true;
12435 }
12436 
12437 /// Add a single candidate to the overload set.
AddOverloadedCallCandidate(Sema & S,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool KnownValid)12438 static void AddOverloadedCallCandidate(Sema &S,
12439                                        DeclAccessPair FoundDecl,
12440                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12441                                        ArrayRef<Expr *> Args,
12442                                        OverloadCandidateSet &CandidateSet,
12443                                        bool PartialOverloading,
12444                                        bool KnownValid) {
12445   NamedDecl *Callee = FoundDecl.getDecl();
12446   if (isa<UsingShadowDecl>(Callee))
12447     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12448 
12449   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12450     if (ExplicitTemplateArgs) {
12451       assert(!KnownValid && "Explicit template arguments?");
12452       return;
12453     }
12454     // Prevent ill-formed function decls to be added as overload candidates.
12455     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12456       return;
12457 
12458     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12459                            /*SuppressUserConversions=*/false,
12460                            PartialOverloading);
12461     return;
12462   }
12463 
12464   if (FunctionTemplateDecl *FuncTemplate
12465       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12466     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12467                                    ExplicitTemplateArgs, Args, CandidateSet,
12468                                    /*SuppressUserConversions=*/false,
12469                                    PartialOverloading);
12470     return;
12471   }
12472 
12473   assert(!KnownValid && "unhandled case in overloaded call candidate");
12474 }
12475 
12476 /// Add the overload candidates named by callee and/or found by argument
12477 /// dependent lookup to the given overload set.
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)12478 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12479                                        ArrayRef<Expr *> Args,
12480                                        OverloadCandidateSet &CandidateSet,
12481                                        bool PartialOverloading) {
12482 
12483 #ifndef NDEBUG
12484   // Verify that ArgumentDependentLookup is consistent with the rules
12485   // in C++0x [basic.lookup.argdep]p3:
12486   //
12487   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12488   //   and let Y be the lookup set produced by argument dependent
12489   //   lookup (defined as follows). If X contains
12490   //
12491   //     -- a declaration of a class member, or
12492   //
12493   //     -- a block-scope function declaration that is not a
12494   //        using-declaration, or
12495   //
12496   //     -- a declaration that is neither a function or a function
12497   //        template
12498   //
12499   //   then Y is empty.
12500 
12501   if (ULE->requiresADL()) {
12502     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12503            E = ULE->decls_end(); I != E; ++I) {
12504       assert(!(*I)->getDeclContext()->isRecord());
12505       assert(isa<UsingShadowDecl>(*I) ||
12506              !(*I)->getDeclContext()->isFunctionOrMethod());
12507       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12508     }
12509   }
12510 #endif
12511 
12512   // It would be nice to avoid this copy.
12513   TemplateArgumentListInfo TABuffer;
12514   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12515   if (ULE->hasExplicitTemplateArgs()) {
12516     ULE->copyTemplateArgumentsInto(TABuffer);
12517     ExplicitTemplateArgs = &TABuffer;
12518   }
12519 
12520   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12521          E = ULE->decls_end(); I != E; ++I)
12522     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12523                                CandidateSet, PartialOverloading,
12524                                /*KnownValid*/ true);
12525 
12526   if (ULE->requiresADL())
12527     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12528                                          Args, ExplicitTemplateArgs,
12529                                          CandidateSet, PartialOverloading);
12530 }
12531 
12532 /// Determine whether a declaration with the specified name could be moved into
12533 /// a different namespace.
canBeDeclaredInNamespace(const DeclarationName & Name)12534 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12535   switch (Name.getCXXOverloadedOperator()) {
12536   case OO_New: case OO_Array_New:
12537   case OO_Delete: case OO_Array_Delete:
12538     return false;
12539 
12540   default:
12541     return true;
12542   }
12543 }
12544 
12545 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12546 /// template, where the non-dependent name was declared after the template
12547 /// was defined. This is common in code written for a compilers which do not
12548 /// correctly implement two-stage name lookup.
12549 ///
12550 /// Returns true if a viable candidate was found and a diagnostic was issued.
12551 static bool
DiagnoseTwoPhaseLookup(Sema & SemaRef,SourceLocation FnLoc,const CXXScopeSpec & SS,LookupResult & R,OverloadCandidateSet::CandidateSetKind CSK,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,bool * DoDiagnoseEmptyLookup=nullptr)12552 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12553                        const CXXScopeSpec &SS, LookupResult &R,
12554                        OverloadCandidateSet::CandidateSetKind CSK,
12555                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12556                        ArrayRef<Expr *> Args,
12557                        bool *DoDiagnoseEmptyLookup = nullptr) {
12558   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12559     return false;
12560 
12561   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12562     if (DC->isTransparentContext())
12563       continue;
12564 
12565     SemaRef.LookupQualifiedName(R, DC);
12566 
12567     if (!R.empty()) {
12568       R.suppressDiagnostics();
12569 
12570       if (isa<CXXRecordDecl>(DC)) {
12571         // Don't diagnose names we find in classes; we get much better
12572         // diagnostics for these from DiagnoseEmptyLookup.
12573         R.clear();
12574         if (DoDiagnoseEmptyLookup)
12575           *DoDiagnoseEmptyLookup = true;
12576         return false;
12577       }
12578 
12579       OverloadCandidateSet Candidates(FnLoc, CSK);
12580       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12581         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12582                                    ExplicitTemplateArgs, Args,
12583                                    Candidates, false, /*KnownValid*/ false);
12584 
12585       OverloadCandidateSet::iterator Best;
12586       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12587         // No viable functions. Don't bother the user with notes for functions
12588         // which don't work and shouldn't be found anyway.
12589         R.clear();
12590         return false;
12591       }
12592 
12593       // Find the namespaces where ADL would have looked, and suggest
12594       // declaring the function there instead.
12595       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12596       Sema::AssociatedClassSet AssociatedClasses;
12597       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12598                                                  AssociatedNamespaces,
12599                                                  AssociatedClasses);
12600       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12601       if (canBeDeclaredInNamespace(R.getLookupName())) {
12602         DeclContext *Std = SemaRef.getStdNamespace();
12603         for (Sema::AssociatedNamespaceSet::iterator
12604                it = AssociatedNamespaces.begin(),
12605                end = AssociatedNamespaces.end(); it != end; ++it) {
12606           // Never suggest declaring a function within namespace 'std'.
12607           if (Std && Std->Encloses(*it))
12608             continue;
12609 
12610           // Never suggest declaring a function within a namespace with a
12611           // reserved name, like __gnu_cxx.
12612           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12613           if (NS &&
12614               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12615             continue;
12616 
12617           SuggestedNamespaces.insert(*it);
12618         }
12619       }
12620 
12621       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12622         << R.getLookupName();
12623       if (SuggestedNamespaces.empty()) {
12624         SemaRef.Diag(Best->Function->getLocation(),
12625                      diag::note_not_found_by_two_phase_lookup)
12626           << R.getLookupName() << 0;
12627       } else if (SuggestedNamespaces.size() == 1) {
12628         SemaRef.Diag(Best->Function->getLocation(),
12629                      diag::note_not_found_by_two_phase_lookup)
12630           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12631       } else {
12632         // FIXME: It would be useful to list the associated namespaces here,
12633         // but the diagnostics infrastructure doesn't provide a way to produce
12634         // a localized representation of a list of items.
12635         SemaRef.Diag(Best->Function->getLocation(),
12636                      diag::note_not_found_by_two_phase_lookup)
12637           << R.getLookupName() << 2;
12638       }
12639 
12640       // Try to recover by calling this function.
12641       return true;
12642     }
12643 
12644     R.clear();
12645   }
12646 
12647   return false;
12648 }
12649 
12650 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12651 /// template, where the non-dependent operator was declared after the template
12652 /// was defined.
12653 ///
12654 /// Returns true if a viable candidate was found and a diagnostic was issued.
12655 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args)12656 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12657                                SourceLocation OpLoc,
12658                                ArrayRef<Expr *> Args) {
12659   DeclarationName OpName =
12660     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12661   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12662   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12663                                 OverloadCandidateSet::CSK_Operator,
12664                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12665 }
12666 
12667 namespace {
12668 class BuildRecoveryCallExprRAII {
12669   Sema &SemaRef;
12670 public:
BuildRecoveryCallExprRAII(Sema & S)12671   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12672     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12673     SemaRef.IsBuildingRecoveryCallExpr = true;
12674   }
12675 
~BuildRecoveryCallExprRAII()12676   ~BuildRecoveryCallExprRAII() {
12677     SemaRef.IsBuildingRecoveryCallExpr = false;
12678   }
12679 };
12680 
12681 }
12682 
12683 /// Attempts to recover from a call where no functions were found.
12684 ///
12685 /// Returns true if new candidates were found.
12686 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)12687 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12688                       UnresolvedLookupExpr *ULE,
12689                       SourceLocation LParenLoc,
12690                       MutableArrayRef<Expr *> Args,
12691                       SourceLocation RParenLoc,
12692                       bool EmptyLookup, bool AllowTypoCorrection) {
12693   // Do not try to recover if it is already building a recovery call.
12694   // This stops infinite loops for template instantiations like
12695   //
12696   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12697   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12698   //
12699   if (SemaRef.IsBuildingRecoveryCallExpr)
12700     return ExprError();
12701   BuildRecoveryCallExprRAII RCE(SemaRef);
12702 
12703   CXXScopeSpec SS;
12704   SS.Adopt(ULE->getQualifierLoc());
12705   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12706 
12707   TemplateArgumentListInfo TABuffer;
12708   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12709   if (ULE->hasExplicitTemplateArgs()) {
12710     ULE->copyTemplateArgumentsInto(TABuffer);
12711     ExplicitTemplateArgs = &TABuffer;
12712   }
12713 
12714   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12715                  Sema::LookupOrdinaryName);
12716   bool DoDiagnoseEmptyLookup = EmptyLookup;
12717   if (!DiagnoseTwoPhaseLookup(
12718           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12719           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12720     NoTypoCorrectionCCC NoTypoValidator{};
12721     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12722                                                 ExplicitTemplateArgs != nullptr,
12723                                                 dyn_cast<MemberExpr>(Fn));
12724     CorrectionCandidateCallback &Validator =
12725         AllowTypoCorrection
12726             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12727             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12728     if (!DoDiagnoseEmptyLookup ||
12729         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12730                                     Args))
12731       return ExprError();
12732   }
12733 
12734   assert(!R.empty() && "lookup results empty despite recovery");
12735 
12736   // If recovery created an ambiguity, just bail out.
12737   if (R.isAmbiguous()) {
12738     R.suppressDiagnostics();
12739     return ExprError();
12740   }
12741 
12742   // Build an implicit member call if appropriate.  Just drop the
12743   // casts and such from the call, we don't really care.
12744   ExprResult NewFn = ExprError();
12745   if ((*R.begin())->isCXXClassMember())
12746     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12747                                                     ExplicitTemplateArgs, S);
12748   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12749     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12750                                         ExplicitTemplateArgs);
12751   else
12752     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12753 
12754   if (NewFn.isInvalid())
12755     return ExprError();
12756 
12757   // This shouldn't cause an infinite loop because we're giving it
12758   // an expression with viable lookup results, which should never
12759   // end up here.
12760   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12761                                MultiExprArg(Args.data(), Args.size()),
12762                                RParenLoc);
12763 }
12764 
12765 /// Constructs and populates an OverloadedCandidateSet from
12766 /// the given function.
12767 /// \returns true when an the ExprResult output parameter has been set.
buildOverloadedCallSet(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,MultiExprArg Args,SourceLocation RParenLoc,OverloadCandidateSet * CandidateSet,ExprResult * Result)12768 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12769                                   UnresolvedLookupExpr *ULE,
12770                                   MultiExprArg Args,
12771                                   SourceLocation RParenLoc,
12772                                   OverloadCandidateSet *CandidateSet,
12773                                   ExprResult *Result) {
12774 #ifndef NDEBUG
12775   if (ULE->requiresADL()) {
12776     // To do ADL, we must have found an unqualified name.
12777     assert(!ULE->getQualifier() && "qualified name with ADL");
12778 
12779     // We don't perform ADL for implicit declarations of builtins.
12780     // Verify that this was correctly set up.
12781     FunctionDecl *F;
12782     if (ULE->decls_begin() != ULE->decls_end() &&
12783         ULE->decls_begin() + 1 == ULE->decls_end() &&
12784         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12785         F->getBuiltinID() && F->isImplicit())
12786       llvm_unreachable("performing ADL for builtin");
12787 
12788     // We don't perform ADL in C.
12789     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12790   }
12791 #endif
12792 
12793   UnbridgedCastsSet UnbridgedCasts;
12794   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12795     *Result = ExprError();
12796     return true;
12797   }
12798 
12799   // Add the functions denoted by the callee to the set of candidate
12800   // functions, including those from argument-dependent lookup.
12801   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12802 
12803   if (getLangOpts().MSVCCompat &&
12804       CurContext->isDependentContext() && !isSFINAEContext() &&
12805       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12806 
12807     OverloadCandidateSet::iterator Best;
12808     if (CandidateSet->empty() ||
12809         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12810             OR_No_Viable_Function) {
12811       // In Microsoft mode, if we are inside a template class member function
12812       // then create a type dependent CallExpr. The goal is to postpone name
12813       // lookup to instantiation time to be able to search into type dependent
12814       // base classes.
12815       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12816                                       VK_RValue, RParenLoc);
12817       CE->markDependentForPostponedNameLookup();
12818       *Result = CE;
12819       return true;
12820     }
12821   }
12822 
12823   if (CandidateSet->empty())
12824     return false;
12825 
12826   UnbridgedCasts.restore();
12827   return false;
12828 }
12829 
12830 // Guess at what the return type for an unresolvable overload should be.
chooseRecoveryType(OverloadCandidateSet & CS,OverloadCandidateSet::iterator * Best)12831 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
12832                                    OverloadCandidateSet::iterator *Best) {
12833   llvm::Optional<QualType> Result;
12834   // Adjust Type after seeing a candidate.
12835   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
12836     if (!Candidate.Function)
12837       return;
12838     QualType T = Candidate.Function->getReturnType();
12839     if (T.isNull())
12840       return;
12841     if (!Result)
12842       Result = T;
12843     else if (Result != T)
12844       Result = QualType();
12845   };
12846 
12847   // Look for an unambiguous type from a progressively larger subset.
12848   // e.g. if types disagree, but all *viable* overloads return int, choose int.
12849   //
12850   // First, consider only the best candidate.
12851   if (Best && *Best != CS.end())
12852     ConsiderCandidate(**Best);
12853   // Next, consider only viable candidates.
12854   if (!Result)
12855     for (const auto &C : CS)
12856       if (C.Viable)
12857         ConsiderCandidate(C);
12858   // Finally, consider all candidates.
12859   if (!Result)
12860     for (const auto &C : CS)
12861       ConsiderCandidate(C);
12862 
12863   return Result.getValueOr(QualType());
12864 }
12865 
12866 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12867 /// the completed call expression. If overload resolution fails, emits
12868 /// diagnostics and returns ExprError()
FinishOverloadedCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,OverloadCandidateSet * CandidateSet,OverloadCandidateSet::iterator * Best,OverloadingResult OverloadResult,bool AllowTypoCorrection)12869 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12870                                            UnresolvedLookupExpr *ULE,
12871                                            SourceLocation LParenLoc,
12872                                            MultiExprArg Args,
12873                                            SourceLocation RParenLoc,
12874                                            Expr *ExecConfig,
12875                                            OverloadCandidateSet *CandidateSet,
12876                                            OverloadCandidateSet::iterator *Best,
12877                                            OverloadingResult OverloadResult,
12878                                            bool AllowTypoCorrection) {
12879   if (CandidateSet->empty())
12880     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12881                                  RParenLoc, /*EmptyLookup=*/true,
12882                                  AllowTypoCorrection);
12883 
12884   switch (OverloadResult) {
12885   case OR_Success: {
12886     FunctionDecl *FDecl = (*Best)->Function;
12887     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12888     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12889       return ExprError();
12890     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12891     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12892                                          ExecConfig, /*IsExecConfig=*/false,
12893                                          (*Best)->IsADLCandidate);
12894   }
12895 
12896   case OR_No_Viable_Function: {
12897     // Try to recover by looking for viable functions which the user might
12898     // have meant to call.
12899     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12900                                                 Args, RParenLoc,
12901                                                 /*EmptyLookup=*/false,
12902                                                 AllowTypoCorrection);
12903     if (!Recovery.isInvalid())
12904       return Recovery;
12905 
12906     // If the user passes in a function that we can't take the address of, we
12907     // generally end up emitting really bad error messages. Here, we attempt to
12908     // emit better ones.
12909     for (const Expr *Arg : Args) {
12910       if (!Arg->getType()->isFunctionType())
12911         continue;
12912       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12913         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12914         if (FD &&
12915             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12916                                                        Arg->getExprLoc()))
12917           return ExprError();
12918       }
12919     }
12920 
12921     CandidateSet->NoteCandidates(
12922         PartialDiagnosticAt(
12923             Fn->getBeginLoc(),
12924             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12925                 << ULE->getName() << Fn->getSourceRange()),
12926         SemaRef, OCD_AllCandidates, Args);
12927     break;
12928   }
12929 
12930   case OR_Ambiguous:
12931     CandidateSet->NoteCandidates(
12932         PartialDiagnosticAt(Fn->getBeginLoc(),
12933                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12934                                 << ULE->getName() << Fn->getSourceRange()),
12935         SemaRef, OCD_AmbiguousCandidates, Args);
12936     break;
12937 
12938   case OR_Deleted: {
12939     CandidateSet->NoteCandidates(
12940         PartialDiagnosticAt(Fn->getBeginLoc(),
12941                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12942                                 << ULE->getName() << Fn->getSourceRange()),
12943         SemaRef, OCD_AllCandidates, Args);
12944 
12945     // We emitted an error for the unavailable/deleted function call but keep
12946     // the call in the AST.
12947     FunctionDecl *FDecl = (*Best)->Function;
12948     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12949     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12950                                          ExecConfig, /*IsExecConfig=*/false,
12951                                          (*Best)->IsADLCandidate);
12952   }
12953   }
12954 
12955   // Overload resolution failed, try to recover.
12956   SmallVector<Expr *, 8> SubExprs = {Fn};
12957   SubExprs.append(Args.begin(), Args.end());
12958   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
12959                                     chooseRecoveryType(*CandidateSet, Best));
12960 }
12961 
markUnaddressableCandidatesUnviable(Sema & S,OverloadCandidateSet & CS)12962 static void markUnaddressableCandidatesUnviable(Sema &S,
12963                                                 OverloadCandidateSet &CS) {
12964   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12965     if (I->Viable &&
12966         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12967       I->Viable = false;
12968       I->FailureKind = ovl_fail_addr_not_available;
12969     }
12970   }
12971 }
12972 
12973 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12974 /// (which eventually refers to the declaration Func) and the call
12975 /// arguments Args/NumArgs, attempt to resolve the function call down
12976 /// to a specific function. If overload resolution succeeds, returns
12977 /// the call expression produced by overload resolution.
12978 /// Otherwise, emits diagnostics and returns ExprError.
BuildOverloadedCallExpr(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,bool AllowTypoCorrection,bool CalleesAddressIsTaken)12979 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12980                                          UnresolvedLookupExpr *ULE,
12981                                          SourceLocation LParenLoc,
12982                                          MultiExprArg Args,
12983                                          SourceLocation RParenLoc,
12984                                          Expr *ExecConfig,
12985                                          bool AllowTypoCorrection,
12986                                          bool CalleesAddressIsTaken) {
12987   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12988                                     OverloadCandidateSet::CSK_Normal);
12989   ExprResult result;
12990 
12991   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12992                              &result))
12993     return result;
12994 
12995   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12996   // functions that aren't addressible are considered unviable.
12997   if (CalleesAddressIsTaken)
12998     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12999 
13000   OverloadCandidateSet::iterator Best;
13001   OverloadingResult OverloadResult =
13002       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13003 
13004   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13005                                   ExecConfig, &CandidateSet, &Best,
13006                                   OverloadResult, AllowTypoCorrection);
13007 }
13008 
IsOverloaded(const UnresolvedSetImpl & Functions)13009 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13010   return Functions.size() > 1 ||
13011     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
13012 }
13013 
13014 /// Create a unary operation that may resolve to an overloaded
13015 /// operator.
13016 ///
13017 /// \param OpLoc The location of the operator itself (e.g., '*').
13018 ///
13019 /// \param Opc The UnaryOperatorKind that describes this operator.
13020 ///
13021 /// \param Fns The set of non-member functions that will be
13022 /// considered by overload resolution. The caller needs to build this
13023 /// set based on the context using, e.g.,
13024 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13025 /// set should not contain any member functions; those will be added
13026 /// by CreateOverloadedUnaryOp().
13027 ///
13028 /// \param Input The input argument.
13029 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * Input,bool PerformADL)13030 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13031                               const UnresolvedSetImpl &Fns,
13032                               Expr *Input, bool PerformADL) {
13033   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13034   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13035   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13036   // TODO: provide better source location info.
13037   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13038 
13039   if (checkPlaceholderForOverload(*this, Input))
13040     return ExprError();
13041 
13042   Expr *Args[2] = { Input, nullptr };
13043   unsigned NumArgs = 1;
13044 
13045   // For post-increment and post-decrement, add the implicit '0' as
13046   // the second argument, so that we know this is a post-increment or
13047   // post-decrement.
13048   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13049     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13050     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13051                                      SourceLocation());
13052     NumArgs = 2;
13053   }
13054 
13055   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13056 
13057   if (Input->isTypeDependent()) {
13058     if (Fns.empty())
13059       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13060                                    VK_RValue, OK_Ordinary, OpLoc, false,
13061                                    CurFPFeatureOverrides());
13062 
13063     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13064     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13065         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13066         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
13067     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
13068                                        Context.DependentTy, VK_RValue, OpLoc,
13069                                        CurFPFeatureOverrides());
13070   }
13071 
13072   // Build an empty overload set.
13073   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13074 
13075   // Add the candidates from the given function set.
13076   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13077 
13078   // Add operator candidates that are member functions.
13079   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13080 
13081   // Add candidates from ADL.
13082   if (PerformADL) {
13083     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13084                                          /*ExplicitTemplateArgs*/nullptr,
13085                                          CandidateSet);
13086   }
13087 
13088   // Add builtin operator candidates.
13089   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13090 
13091   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13092 
13093   // Perform overload resolution.
13094   OverloadCandidateSet::iterator Best;
13095   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13096   case OR_Success: {
13097     // We found a built-in operator or an overloaded operator.
13098     FunctionDecl *FnDecl = Best->Function;
13099 
13100     if (FnDecl) {
13101       Expr *Base = nullptr;
13102       // We matched an overloaded operator. Build a call to that
13103       // operator.
13104 
13105       // Convert the arguments.
13106       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13107         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13108 
13109         ExprResult InputRes =
13110           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13111                                               Best->FoundDecl, Method);
13112         if (InputRes.isInvalid())
13113           return ExprError();
13114         Base = Input = InputRes.get();
13115       } else {
13116         // Convert the arguments.
13117         ExprResult InputInit
13118           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13119                                                       Context,
13120                                                       FnDecl->getParamDecl(0)),
13121                                       SourceLocation(),
13122                                       Input);
13123         if (InputInit.isInvalid())
13124           return ExprError();
13125         Input = InputInit.get();
13126       }
13127 
13128       // Build the actual expression node.
13129       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13130                                                 Base, HadMultipleCandidates,
13131                                                 OpLoc);
13132       if (FnExpr.isInvalid())
13133         return ExprError();
13134 
13135       // Determine the result type.
13136       QualType ResultTy = FnDecl->getReturnType();
13137       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13138       ResultTy = ResultTy.getNonLValueExprType(Context);
13139 
13140       Args[0] = Input;
13141       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13142           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13143           CurFPFeatureOverrides(), Best->IsADLCandidate);
13144 
13145       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13146         return ExprError();
13147 
13148       if (CheckFunctionCall(FnDecl, TheCall,
13149                             FnDecl->getType()->castAs<FunctionProtoType>()))
13150         return ExprError();
13151       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13152     } else {
13153       // We matched a built-in operator. Convert the arguments, then
13154       // break out so that we will build the appropriate built-in
13155       // operator node.
13156       ExprResult InputRes = PerformImplicitConversion(
13157           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13158           CCK_ForBuiltinOverloadedOp);
13159       if (InputRes.isInvalid())
13160         return ExprError();
13161       Input = InputRes.get();
13162       break;
13163     }
13164   }
13165 
13166   case OR_No_Viable_Function:
13167     // This is an erroneous use of an operator which can be overloaded by
13168     // a non-member function. Check for non-member operators which were
13169     // defined too late to be candidates.
13170     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13171       // FIXME: Recover by calling the found function.
13172       return ExprError();
13173 
13174     // No viable function; fall through to handling this as a
13175     // built-in operator, which will produce an error message for us.
13176     break;
13177 
13178   case OR_Ambiguous:
13179     CandidateSet.NoteCandidates(
13180         PartialDiagnosticAt(OpLoc,
13181                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13182                                 << UnaryOperator::getOpcodeStr(Opc)
13183                                 << Input->getType() << Input->getSourceRange()),
13184         *this, OCD_AmbiguousCandidates, ArgsArray,
13185         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13186     return ExprError();
13187 
13188   case OR_Deleted:
13189     CandidateSet.NoteCandidates(
13190         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13191                                        << UnaryOperator::getOpcodeStr(Opc)
13192                                        << Input->getSourceRange()),
13193         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13194         OpLoc);
13195     return ExprError();
13196   }
13197 
13198   // Either we found no viable overloaded operator or we matched a
13199   // built-in operator. In either case, fall through to trying to
13200   // build a built-in operation.
13201   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13202 }
13203 
13204 /// Perform lookup for an overloaded binary operator.
LookupOverloadedBinOp(OverloadCandidateSet & CandidateSet,OverloadedOperatorKind Op,const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,bool PerformADL)13205 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13206                                  OverloadedOperatorKind Op,
13207                                  const UnresolvedSetImpl &Fns,
13208                                  ArrayRef<Expr *> Args, bool PerformADL) {
13209   SourceLocation OpLoc = CandidateSet.getLocation();
13210 
13211   OverloadedOperatorKind ExtraOp =
13212       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13213           ? getRewrittenOverloadedOperator(Op)
13214           : OO_None;
13215 
13216   // Add the candidates from the given function set. This also adds the
13217   // rewritten candidates using these functions if necessary.
13218   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13219 
13220   // Add operator candidates that are member functions.
13221   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13222   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13223     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13224                                 OverloadCandidateParamOrder::Reversed);
13225 
13226   // In C++20, also add any rewritten member candidates.
13227   if (ExtraOp) {
13228     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13229     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13230       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13231                                   CandidateSet,
13232                                   OverloadCandidateParamOrder::Reversed);
13233   }
13234 
13235   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13236   // performed for an assignment operator (nor for operator[] nor operator->,
13237   // which don't get here).
13238   if (Op != OO_Equal && PerformADL) {
13239     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13240     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13241                                          /*ExplicitTemplateArgs*/ nullptr,
13242                                          CandidateSet);
13243     if (ExtraOp) {
13244       DeclarationName ExtraOpName =
13245           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13246       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13247                                            /*ExplicitTemplateArgs*/ nullptr,
13248                                            CandidateSet);
13249     }
13250   }
13251 
13252   // Add builtin operator candidates.
13253   //
13254   // FIXME: We don't add any rewritten candidates here. This is strictly
13255   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13256   // resulting in our selecting a rewritten builtin candidate. For example:
13257   //
13258   //   enum class E { e };
13259   //   bool operator!=(E, E) requires false;
13260   //   bool k = E::e != E::e;
13261   //
13262   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13263   // it seems unreasonable to consider rewritten builtin candidates. A core
13264   // issue has been filed proposing to removed this requirement.
13265   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13266 }
13267 
13268 /// Create a binary operation that may resolve to an overloaded
13269 /// operator.
13270 ///
13271 /// \param OpLoc The location of the operator itself (e.g., '+').
13272 ///
13273 /// \param Opc The BinaryOperatorKind that describes this operator.
13274 ///
13275 /// \param Fns The set of non-member functions that will be
13276 /// considered by overload resolution. The caller needs to build this
13277 /// set based on the context using, e.g.,
13278 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13279 /// set should not contain any member functions; those will be added
13280 /// by CreateOverloadedBinOp().
13281 ///
13282 /// \param LHS Left-hand argument.
13283 /// \param RHS Right-hand argument.
13284 /// \param PerformADL Whether to consider operator candidates found by ADL.
13285 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13286 ///        C++20 operator rewrites.
13287 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13288 ///        the function in question. Such a function is never a candidate in
13289 ///        our overload resolution. This also enables synthesizing a three-way
13290 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
CreateOverloadedBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS,bool PerformADL,bool AllowRewrittenCandidates,FunctionDecl * DefaultedFn)13291 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13292                                        BinaryOperatorKind Opc,
13293                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13294                                        Expr *RHS, bool PerformADL,
13295                                        bool AllowRewrittenCandidates,
13296                                        FunctionDecl *DefaultedFn) {
13297   Expr *Args[2] = { LHS, RHS };
13298   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13299 
13300   if (!getLangOpts().CPlusPlus20)
13301     AllowRewrittenCandidates = false;
13302 
13303   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13304 
13305   // If either side is type-dependent, create an appropriate dependent
13306   // expression.
13307   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13308     if (Fns.empty()) {
13309       // If there are no functions to store, just build a dependent
13310       // BinaryOperator or CompoundAssignment.
13311       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13312         return BinaryOperator::Create(
13313             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_RValue,
13314             OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13315       return CompoundAssignOperator::Create(
13316           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13317           OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13318           Context.DependentTy);
13319     }
13320 
13321     // FIXME: save results of ADL from here?
13322     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13323     // TODO: provide better source location info in DNLoc component.
13324     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13325     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13326     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13327         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13328         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13329     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13330                                        Context.DependentTy, VK_RValue, OpLoc,
13331                                        CurFPFeatureOverrides());
13332   }
13333 
13334   // Always do placeholder-like conversions on the RHS.
13335   if (checkPlaceholderForOverload(*this, Args[1]))
13336     return ExprError();
13337 
13338   // Do placeholder-like conversion on the LHS; note that we should
13339   // not get here with a PseudoObject LHS.
13340   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13341   if (checkPlaceholderForOverload(*this, Args[0]))
13342     return ExprError();
13343 
13344   // If this is the assignment operator, we only perform overload resolution
13345   // if the left-hand side is a class or enumeration type. This is actually
13346   // a hack. The standard requires that we do overload resolution between the
13347   // various built-in candidates, but as DR507 points out, this can lead to
13348   // problems. So we do it this way, which pretty much follows what GCC does.
13349   // Note that we go the traditional code path for compound assignment forms.
13350   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13351     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13352 
13353   // If this is the .* operator, which is not overloadable, just
13354   // create a built-in binary operator.
13355   if (Opc == BO_PtrMemD)
13356     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13357 
13358   // Build the overload set.
13359   OverloadCandidateSet CandidateSet(
13360       OpLoc, OverloadCandidateSet::CSK_Operator,
13361       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13362   if (DefaultedFn)
13363     CandidateSet.exclude(DefaultedFn);
13364   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13365 
13366   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13367 
13368   // Perform overload resolution.
13369   OverloadCandidateSet::iterator Best;
13370   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13371     case OR_Success: {
13372       // We found a built-in operator or an overloaded operator.
13373       FunctionDecl *FnDecl = Best->Function;
13374 
13375       bool IsReversed = Best->isReversed();
13376       if (IsReversed)
13377         std::swap(Args[0], Args[1]);
13378 
13379       if (FnDecl) {
13380         Expr *Base = nullptr;
13381         // We matched an overloaded operator. Build a call to that
13382         // operator.
13383 
13384         OverloadedOperatorKind ChosenOp =
13385             FnDecl->getDeclName().getCXXOverloadedOperator();
13386 
13387         // C++2a [over.match.oper]p9:
13388         //   If a rewritten operator== candidate is selected by overload
13389         //   resolution for an operator@, its return type shall be cv bool
13390         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13391             !FnDecl->getReturnType()->isBooleanType()) {
13392           bool IsExtension =
13393               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13394           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13395                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13396               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13397               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13398           Diag(FnDecl->getLocation(), diag::note_declared_at);
13399           if (!IsExtension)
13400             return ExprError();
13401         }
13402 
13403         if (AllowRewrittenCandidates && !IsReversed &&
13404             CandidateSet.getRewriteInfo().isReversible()) {
13405           // We could have reversed this operator, but didn't. Check if some
13406           // reversed form was a viable candidate, and if so, if it had a
13407           // better conversion for either parameter. If so, this call is
13408           // formally ambiguous, and allowing it is an extension.
13409           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13410           for (OverloadCandidate &Cand : CandidateSet) {
13411             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13412                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13413               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13414                 if (CompareImplicitConversionSequences(
13415                         *this, OpLoc, Cand.Conversions[ArgIdx],
13416                         Best->Conversions[ArgIdx]) ==
13417                     ImplicitConversionSequence::Better) {
13418                   AmbiguousWith.push_back(Cand.Function);
13419                   break;
13420                 }
13421               }
13422             }
13423           }
13424 
13425           if (!AmbiguousWith.empty()) {
13426             bool AmbiguousWithSelf =
13427                 AmbiguousWith.size() == 1 &&
13428                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13429             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13430                 << BinaryOperator::getOpcodeStr(Opc)
13431                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13432                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13433             if (AmbiguousWithSelf) {
13434               Diag(FnDecl->getLocation(),
13435                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13436             } else {
13437               Diag(FnDecl->getLocation(),
13438                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13439               for (auto *F : AmbiguousWith)
13440                 Diag(F->getLocation(),
13441                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13442             }
13443           }
13444         }
13445 
13446         // Convert the arguments.
13447         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13448           // Best->Access is only meaningful for class members.
13449           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13450 
13451           ExprResult Arg1 =
13452             PerformCopyInitialization(
13453               InitializedEntity::InitializeParameter(Context,
13454                                                      FnDecl->getParamDecl(0)),
13455               SourceLocation(), Args[1]);
13456           if (Arg1.isInvalid())
13457             return ExprError();
13458 
13459           ExprResult Arg0 =
13460             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13461                                                 Best->FoundDecl, Method);
13462           if (Arg0.isInvalid())
13463             return ExprError();
13464           Base = Args[0] = Arg0.getAs<Expr>();
13465           Args[1] = RHS = Arg1.getAs<Expr>();
13466         } else {
13467           // Convert the arguments.
13468           ExprResult Arg0 = PerformCopyInitialization(
13469             InitializedEntity::InitializeParameter(Context,
13470                                                    FnDecl->getParamDecl(0)),
13471             SourceLocation(), Args[0]);
13472           if (Arg0.isInvalid())
13473             return ExprError();
13474 
13475           ExprResult Arg1 =
13476             PerformCopyInitialization(
13477               InitializedEntity::InitializeParameter(Context,
13478                                                      FnDecl->getParamDecl(1)),
13479               SourceLocation(), Args[1]);
13480           if (Arg1.isInvalid())
13481             return ExprError();
13482           Args[0] = LHS = Arg0.getAs<Expr>();
13483           Args[1] = RHS = Arg1.getAs<Expr>();
13484         }
13485 
13486         // Build the actual expression node.
13487         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13488                                                   Best->FoundDecl, Base,
13489                                                   HadMultipleCandidates, OpLoc);
13490         if (FnExpr.isInvalid())
13491           return ExprError();
13492 
13493         // Determine the result type.
13494         QualType ResultTy = FnDecl->getReturnType();
13495         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13496         ResultTy = ResultTy.getNonLValueExprType(Context);
13497 
13498         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13499             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13500             CurFPFeatureOverrides(), Best->IsADLCandidate);
13501 
13502         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13503                                 FnDecl))
13504           return ExprError();
13505 
13506         ArrayRef<const Expr *> ArgsArray(Args, 2);
13507         const Expr *ImplicitThis = nullptr;
13508         // Cut off the implicit 'this'.
13509         if (isa<CXXMethodDecl>(FnDecl)) {
13510           ImplicitThis = ArgsArray[0];
13511           ArgsArray = ArgsArray.slice(1);
13512         }
13513 
13514         // Check for a self move.
13515         if (Op == OO_Equal)
13516           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13517 
13518         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13519                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13520                   VariadicDoesNotApply);
13521 
13522         ExprResult R = MaybeBindToTemporary(TheCall);
13523         if (R.isInvalid())
13524           return ExprError();
13525 
13526         R = CheckForImmediateInvocation(R, FnDecl);
13527         if (R.isInvalid())
13528           return ExprError();
13529 
13530         // For a rewritten candidate, we've already reversed the arguments
13531         // if needed. Perform the rest of the rewrite now.
13532         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13533             (Op == OO_Spaceship && IsReversed)) {
13534           if (Op == OO_ExclaimEqual) {
13535             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13536             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13537           } else {
13538             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13539             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13540             Expr *ZeroLiteral =
13541                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13542 
13543             Sema::CodeSynthesisContext Ctx;
13544             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13545             Ctx.Entity = FnDecl;
13546             pushCodeSynthesisContext(Ctx);
13547 
13548             R = CreateOverloadedBinOp(
13549                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13550                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13551                 /*AllowRewrittenCandidates=*/false);
13552 
13553             popCodeSynthesisContext();
13554           }
13555           if (R.isInvalid())
13556             return ExprError();
13557         } else {
13558           assert(ChosenOp == Op && "unexpected operator name");
13559         }
13560 
13561         // Make a note in the AST if we did any rewriting.
13562         if (Best->RewriteKind != CRK_None)
13563           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13564 
13565         return R;
13566       } else {
13567         // We matched a built-in operator. Convert the arguments, then
13568         // break out so that we will build the appropriate built-in
13569         // operator node.
13570         ExprResult ArgsRes0 = PerformImplicitConversion(
13571             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13572             AA_Passing, CCK_ForBuiltinOverloadedOp);
13573         if (ArgsRes0.isInvalid())
13574           return ExprError();
13575         Args[0] = ArgsRes0.get();
13576 
13577         ExprResult ArgsRes1 = PerformImplicitConversion(
13578             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13579             AA_Passing, CCK_ForBuiltinOverloadedOp);
13580         if (ArgsRes1.isInvalid())
13581           return ExprError();
13582         Args[1] = ArgsRes1.get();
13583         break;
13584       }
13585     }
13586 
13587     case OR_No_Viable_Function: {
13588       // C++ [over.match.oper]p9:
13589       //   If the operator is the operator , [...] and there are no
13590       //   viable functions, then the operator is assumed to be the
13591       //   built-in operator and interpreted according to clause 5.
13592       if (Opc == BO_Comma)
13593         break;
13594 
13595       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13596       // compare result using '==' and '<'.
13597       if (DefaultedFn && Opc == BO_Cmp) {
13598         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13599                                                           Args[1], DefaultedFn);
13600         if (E.isInvalid() || E.isUsable())
13601           return E;
13602       }
13603 
13604       // For class as left operand for assignment or compound assignment
13605       // operator do not fall through to handling in built-in, but report that
13606       // no overloaded assignment operator found
13607       ExprResult Result = ExprError();
13608       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13609       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13610                                                    Args, OpLoc);
13611       if (Args[0]->getType()->isRecordType() &&
13612           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13613         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13614              << BinaryOperator::getOpcodeStr(Opc)
13615              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13616         if (Args[0]->getType()->isIncompleteType()) {
13617           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13618             << Args[0]->getType()
13619             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13620         }
13621       } else {
13622         // This is an erroneous use of an operator which can be overloaded by
13623         // a non-member function. Check for non-member operators which were
13624         // defined too late to be candidates.
13625         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13626           // FIXME: Recover by calling the found function.
13627           return ExprError();
13628 
13629         // No viable function; try to create a built-in operation, which will
13630         // produce an error. Then, show the non-viable candidates.
13631         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13632       }
13633       assert(Result.isInvalid() &&
13634              "C++ binary operator overloading is missing candidates!");
13635       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13636       return Result;
13637     }
13638 
13639     case OR_Ambiguous:
13640       CandidateSet.NoteCandidates(
13641           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13642                                          << BinaryOperator::getOpcodeStr(Opc)
13643                                          << Args[0]->getType()
13644                                          << Args[1]->getType()
13645                                          << Args[0]->getSourceRange()
13646                                          << Args[1]->getSourceRange()),
13647           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13648           OpLoc);
13649       return ExprError();
13650 
13651     case OR_Deleted:
13652       if (isImplicitlyDeleted(Best->Function)) {
13653         FunctionDecl *DeletedFD = Best->Function;
13654         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13655         if (DFK.isSpecialMember()) {
13656           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13657             << Args[0]->getType() << DFK.asSpecialMember();
13658         } else {
13659           assert(DFK.isComparison());
13660           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13661             << Args[0]->getType() << DeletedFD;
13662         }
13663 
13664         // The user probably meant to call this special member. Just
13665         // explain why it's deleted.
13666         NoteDeletedFunction(DeletedFD);
13667         return ExprError();
13668       }
13669       CandidateSet.NoteCandidates(
13670           PartialDiagnosticAt(
13671               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13672                          << getOperatorSpelling(Best->Function->getDeclName()
13673                                                     .getCXXOverloadedOperator())
13674                          << Args[0]->getSourceRange()
13675                          << Args[1]->getSourceRange()),
13676           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13677           OpLoc);
13678       return ExprError();
13679   }
13680 
13681   // We matched a built-in operator; build it.
13682   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13683 }
13684 
BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS,FunctionDecl * DefaultedFn)13685 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13686     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13687     FunctionDecl *DefaultedFn) {
13688   const ComparisonCategoryInfo *Info =
13689       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13690   // If we're not producing a known comparison category type, we can't
13691   // synthesize a three-way comparison. Let the caller diagnose this.
13692   if (!Info)
13693     return ExprResult((Expr*)nullptr);
13694 
13695   // If we ever want to perform this synthesis more generally, we will need to
13696   // apply the temporary materialization conversion to the operands.
13697   assert(LHS->isGLValue() && RHS->isGLValue() &&
13698          "cannot use prvalue expressions more than once");
13699   Expr *OrigLHS = LHS;
13700   Expr *OrigRHS = RHS;
13701 
13702   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13703   // each of them multiple times below.
13704   LHS = new (Context)
13705       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13706                       LHS->getObjectKind(), LHS);
13707   RHS = new (Context)
13708       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13709                       RHS->getObjectKind(), RHS);
13710 
13711   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13712                                         DefaultedFn);
13713   if (Eq.isInvalid())
13714     return ExprError();
13715 
13716   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13717                                           true, DefaultedFn);
13718   if (Less.isInvalid())
13719     return ExprError();
13720 
13721   ExprResult Greater;
13722   if (Info->isPartial()) {
13723     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13724                                     DefaultedFn);
13725     if (Greater.isInvalid())
13726       return ExprError();
13727   }
13728 
13729   // Form the list of comparisons we're going to perform.
13730   struct Comparison {
13731     ExprResult Cmp;
13732     ComparisonCategoryResult Result;
13733   } Comparisons[4] =
13734   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13735                           : ComparisonCategoryResult::Equivalent},
13736     {Less, ComparisonCategoryResult::Less},
13737     {Greater, ComparisonCategoryResult::Greater},
13738     {ExprResult(), ComparisonCategoryResult::Unordered},
13739   };
13740 
13741   int I = Info->isPartial() ? 3 : 2;
13742 
13743   // Combine the comparisons with suitable conditional expressions.
13744   ExprResult Result;
13745   for (; I >= 0; --I) {
13746     // Build a reference to the comparison category constant.
13747     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13748     // FIXME: Missing a constant for a comparison category. Diagnose this?
13749     if (!VI)
13750       return ExprResult((Expr*)nullptr);
13751     ExprResult ThisResult =
13752         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13753     if (ThisResult.isInvalid())
13754       return ExprError();
13755 
13756     // Build a conditional unless this is the final case.
13757     if (Result.get()) {
13758       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13759                                   ThisResult.get(), Result.get());
13760       if (Result.isInvalid())
13761         return ExprError();
13762     } else {
13763       Result = ThisResult;
13764     }
13765   }
13766 
13767   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13768   // bind the OpaqueValueExprs before they're (repeatedly) used.
13769   Expr *SyntacticForm = BinaryOperator::Create(
13770       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13771       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13772       CurFPFeatureOverrides());
13773   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13774   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13775 }
13776 
13777 ExprResult
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,Expr * Idx)13778 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13779                                          SourceLocation RLoc,
13780                                          Expr *Base, Expr *Idx) {
13781   Expr *Args[2] = { Base, Idx };
13782   DeclarationName OpName =
13783       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13784 
13785   // If either side is type-dependent, create an appropriate dependent
13786   // expression.
13787   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13788 
13789     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13790     // CHECKME: no 'operator' keyword?
13791     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13792     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13793     UnresolvedLookupExpr *Fn
13794       = UnresolvedLookupExpr::Create(Context, NamingClass,
13795                                      NestedNameSpecifierLoc(), OpNameInfo,
13796                                      /*ADL*/ true, /*Overloaded*/ false,
13797                                      UnresolvedSetIterator(),
13798                                      UnresolvedSetIterator());
13799     // Can't add any actual overloads yet
13800 
13801     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13802                                        Context.DependentTy, VK_RValue, RLoc,
13803                                        CurFPFeatureOverrides());
13804   }
13805 
13806   // Handle placeholders on both operands.
13807   if (checkPlaceholderForOverload(*this, Args[0]))
13808     return ExprError();
13809   if (checkPlaceholderForOverload(*this, Args[1]))
13810     return ExprError();
13811 
13812   // Build an empty overload set.
13813   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13814 
13815   // Subscript can only be overloaded as a member function.
13816 
13817   // Add operator candidates that are member functions.
13818   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13819 
13820   // Add builtin operator candidates.
13821   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13822 
13823   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13824 
13825   // Perform overload resolution.
13826   OverloadCandidateSet::iterator Best;
13827   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13828     case OR_Success: {
13829       // We found a built-in operator or an overloaded operator.
13830       FunctionDecl *FnDecl = Best->Function;
13831 
13832       if (FnDecl) {
13833         // We matched an overloaded operator. Build a call to that
13834         // operator.
13835 
13836         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13837 
13838         // Convert the arguments.
13839         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13840         ExprResult Arg0 =
13841           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13842                                               Best->FoundDecl, Method);
13843         if (Arg0.isInvalid())
13844           return ExprError();
13845         Args[0] = Arg0.get();
13846 
13847         // Convert the arguments.
13848         ExprResult InputInit
13849           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13850                                                       Context,
13851                                                       FnDecl->getParamDecl(0)),
13852                                       SourceLocation(),
13853                                       Args[1]);
13854         if (InputInit.isInvalid())
13855           return ExprError();
13856 
13857         Args[1] = InputInit.getAs<Expr>();
13858 
13859         // Build the actual expression node.
13860         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13861         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13862         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13863                                                   Best->FoundDecl,
13864                                                   Base,
13865                                                   HadMultipleCandidates,
13866                                                   OpLocInfo.getLoc(),
13867                                                   OpLocInfo.getInfo());
13868         if (FnExpr.isInvalid())
13869           return ExprError();
13870 
13871         // Determine the result type
13872         QualType ResultTy = FnDecl->getReturnType();
13873         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13874         ResultTy = ResultTy.getNonLValueExprType(Context);
13875 
13876         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13877             Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
13878             CurFPFeatureOverrides());
13879         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13880           return ExprError();
13881 
13882         if (CheckFunctionCall(Method, TheCall,
13883                               Method->getType()->castAs<FunctionProtoType>()))
13884           return ExprError();
13885 
13886         return MaybeBindToTemporary(TheCall);
13887       } else {
13888         // We matched a built-in operator. Convert the arguments, then
13889         // break out so that we will build the appropriate built-in
13890         // operator node.
13891         ExprResult ArgsRes0 = PerformImplicitConversion(
13892             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13893             AA_Passing, CCK_ForBuiltinOverloadedOp);
13894         if (ArgsRes0.isInvalid())
13895           return ExprError();
13896         Args[0] = ArgsRes0.get();
13897 
13898         ExprResult ArgsRes1 = PerformImplicitConversion(
13899             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13900             AA_Passing, CCK_ForBuiltinOverloadedOp);
13901         if (ArgsRes1.isInvalid())
13902           return ExprError();
13903         Args[1] = ArgsRes1.get();
13904 
13905         break;
13906       }
13907     }
13908 
13909     case OR_No_Viable_Function: {
13910       PartialDiagnostic PD = CandidateSet.empty()
13911           ? (PDiag(diag::err_ovl_no_oper)
13912              << Args[0]->getType() << /*subscript*/ 0
13913              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13914           : (PDiag(diag::err_ovl_no_viable_subscript)
13915              << Args[0]->getType() << Args[0]->getSourceRange()
13916              << Args[1]->getSourceRange());
13917       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13918                                   OCD_AllCandidates, Args, "[]", LLoc);
13919       return ExprError();
13920     }
13921 
13922     case OR_Ambiguous:
13923       CandidateSet.NoteCandidates(
13924           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13925                                         << "[]" << Args[0]->getType()
13926                                         << Args[1]->getType()
13927                                         << Args[0]->getSourceRange()
13928                                         << Args[1]->getSourceRange()),
13929           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13930       return ExprError();
13931 
13932     case OR_Deleted:
13933       CandidateSet.NoteCandidates(
13934           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13935                                         << "[]" << Args[0]->getSourceRange()
13936                                         << Args[1]->getSourceRange()),
13937           *this, OCD_AllCandidates, Args, "[]", LLoc);
13938       return ExprError();
13939     }
13940 
13941   // We matched a built-in operator; build it.
13942   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13943 }
13944 
13945 /// BuildCallToMemberFunction - Build a call to a member
13946 /// function. MemExpr is the expression that refers to the member
13947 /// function (and includes the object parameter), Args/NumArgs are the
13948 /// arguments to the function call (not including the object
13949 /// parameter). The caller needs to validate that the member
13950 /// expression refers to a non-static member function or an overloaded
13951 /// member function.
13952 ExprResult
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)13953 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13954                                 SourceLocation LParenLoc,
13955                                 MultiExprArg Args,
13956                                 SourceLocation RParenLoc) {
13957   assert(MemExprE->getType() == Context.BoundMemberTy ||
13958          MemExprE->getType() == Context.OverloadTy);
13959 
13960   // Dig out the member expression. This holds both the object
13961   // argument and the member function we're referring to.
13962   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13963 
13964   // Determine whether this is a call to a pointer-to-member function.
13965   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13966     assert(op->getType() == Context.BoundMemberTy);
13967     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13968 
13969     QualType fnType =
13970       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13971 
13972     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13973     QualType resultType = proto->getCallResultType(Context);
13974     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13975 
13976     // Check that the object type isn't more qualified than the
13977     // member function we're calling.
13978     Qualifiers funcQuals = proto->getMethodQuals();
13979 
13980     QualType objectType = op->getLHS()->getType();
13981     if (op->getOpcode() == BO_PtrMemI)
13982       objectType = objectType->castAs<PointerType>()->getPointeeType();
13983     Qualifiers objectQuals = objectType.getQualifiers();
13984 
13985     Qualifiers difference = objectQuals - funcQuals;
13986     difference.removeObjCGCAttr();
13987     difference.removeAddressSpace();
13988     if (difference) {
13989       std::string qualsString = difference.getAsString();
13990       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13991         << fnType.getUnqualifiedType()
13992         << qualsString
13993         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13994     }
13995 
13996     CXXMemberCallExpr *call =
13997         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13998                                   valueKind, RParenLoc, proto->getNumParams());
13999 
14000     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14001                             call, nullptr))
14002       return ExprError();
14003 
14004     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14005       return ExprError();
14006 
14007     if (CheckOtherCall(call, proto))
14008       return ExprError();
14009 
14010     return MaybeBindToTemporary(call);
14011   }
14012 
14013   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14014     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
14015                             RParenLoc);
14016 
14017   UnbridgedCastsSet UnbridgedCasts;
14018   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14019     return ExprError();
14020 
14021   MemberExpr *MemExpr;
14022   CXXMethodDecl *Method = nullptr;
14023   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14024   NestedNameSpecifier *Qualifier = nullptr;
14025   if (isa<MemberExpr>(NakedMemExpr)) {
14026     MemExpr = cast<MemberExpr>(NakedMemExpr);
14027     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14028     FoundDecl = MemExpr->getFoundDecl();
14029     Qualifier = MemExpr->getQualifier();
14030     UnbridgedCasts.restore();
14031   } else {
14032     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14033     Qualifier = UnresExpr->getQualifier();
14034 
14035     QualType ObjectType = UnresExpr->getBaseType();
14036     Expr::Classification ObjectClassification
14037       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14038                             : UnresExpr->getBase()->Classify(Context);
14039 
14040     // Add overload candidates
14041     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14042                                       OverloadCandidateSet::CSK_Normal);
14043 
14044     // FIXME: avoid copy.
14045     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14046     if (UnresExpr->hasExplicitTemplateArgs()) {
14047       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14048       TemplateArgs = &TemplateArgsBuffer;
14049     }
14050 
14051     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14052            E = UnresExpr->decls_end(); I != E; ++I) {
14053 
14054       NamedDecl *Func = *I;
14055       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14056       if (isa<UsingShadowDecl>(Func))
14057         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14058 
14059 
14060       // Microsoft supports direct constructor calls.
14061       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14062         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14063                              CandidateSet,
14064                              /*SuppressUserConversions*/ false);
14065       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14066         // If explicit template arguments were provided, we can't call a
14067         // non-template member function.
14068         if (TemplateArgs)
14069           continue;
14070 
14071         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14072                            ObjectClassification, Args, CandidateSet,
14073                            /*SuppressUserConversions=*/false);
14074       } else {
14075         AddMethodTemplateCandidate(
14076             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14077             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14078             /*SuppressUserConversions=*/false);
14079       }
14080     }
14081 
14082     DeclarationName DeclName = UnresExpr->getMemberName();
14083 
14084     UnbridgedCasts.restore();
14085 
14086     OverloadCandidateSet::iterator Best;
14087     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14088                                             Best)) {
14089     case OR_Success:
14090       Method = cast<CXXMethodDecl>(Best->Function);
14091       FoundDecl = Best->FoundDecl;
14092       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14093       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14094         return ExprError();
14095       // If FoundDecl is different from Method (such as if one is a template
14096       // and the other a specialization), make sure DiagnoseUseOfDecl is
14097       // called on both.
14098       // FIXME: This would be more comprehensively addressed by modifying
14099       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14100       // being used.
14101       if (Method != FoundDecl.getDecl() &&
14102                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14103         return ExprError();
14104       break;
14105 
14106     case OR_No_Viable_Function:
14107       CandidateSet.NoteCandidates(
14108           PartialDiagnosticAt(
14109               UnresExpr->getMemberLoc(),
14110               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14111                   << DeclName << MemExprE->getSourceRange()),
14112           *this, OCD_AllCandidates, Args);
14113       // FIXME: Leaking incoming expressions!
14114       return ExprError();
14115 
14116     case OR_Ambiguous:
14117       CandidateSet.NoteCandidates(
14118           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14119                               PDiag(diag::err_ovl_ambiguous_member_call)
14120                                   << DeclName << MemExprE->getSourceRange()),
14121           *this, OCD_AmbiguousCandidates, Args);
14122       // FIXME: Leaking incoming expressions!
14123       return ExprError();
14124 
14125     case OR_Deleted:
14126       CandidateSet.NoteCandidates(
14127           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14128                               PDiag(diag::err_ovl_deleted_member_call)
14129                                   << DeclName << MemExprE->getSourceRange()),
14130           *this, OCD_AllCandidates, Args);
14131       // FIXME: Leaking incoming expressions!
14132       return ExprError();
14133     }
14134 
14135     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14136 
14137     // If overload resolution picked a static member, build a
14138     // non-member call based on that function.
14139     if (Method->isStatic()) {
14140       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14141                                    RParenLoc);
14142     }
14143 
14144     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14145   }
14146 
14147   QualType ResultType = Method->getReturnType();
14148   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14149   ResultType = ResultType.getNonLValueExprType(Context);
14150 
14151   assert(Method && "Member call to something that isn't a method?");
14152   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14153   CXXMemberCallExpr *TheCall =
14154       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
14155                                 RParenLoc, Proto->getNumParams());
14156 
14157   // Check for a valid return type.
14158   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14159                           TheCall, Method))
14160     return ExprError();
14161 
14162   // Convert the object argument (for a non-static member function call).
14163   // We only need to do this if there was actually an overload; otherwise
14164   // it was done at lookup.
14165   if (!Method->isStatic()) {
14166     ExprResult ObjectArg =
14167       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14168                                           FoundDecl, Method);
14169     if (ObjectArg.isInvalid())
14170       return ExprError();
14171     MemExpr->setBase(ObjectArg.get());
14172   }
14173 
14174   // Convert the rest of the arguments
14175   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14176                               RParenLoc))
14177     return ExprError();
14178 
14179   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14180 
14181   if (CheckFunctionCall(Method, TheCall, Proto))
14182     return ExprError();
14183 
14184   // In the case the method to call was not selected by the overloading
14185   // resolution process, we still need to handle the enable_if attribute. Do
14186   // that here, so it will not hide previous -- and more relevant -- errors.
14187   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14188     if (const EnableIfAttr *Attr =
14189             CheckEnableIf(Method, LParenLoc, Args, true)) {
14190       Diag(MemE->getMemberLoc(),
14191            diag::err_ovl_no_viable_member_function_in_call)
14192           << Method << Method->getSourceRange();
14193       Diag(Method->getLocation(),
14194            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14195           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14196       return ExprError();
14197     }
14198   }
14199 
14200   if ((isa<CXXConstructorDecl>(CurContext) ||
14201        isa<CXXDestructorDecl>(CurContext)) &&
14202       TheCall->getMethodDecl()->isPure()) {
14203     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14204 
14205     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14206         MemExpr->performsVirtualDispatch(getLangOpts())) {
14207       Diag(MemExpr->getBeginLoc(),
14208            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14209           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14210           << MD->getParent()->getDeclName();
14211 
14212       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14213       if (getLangOpts().AppleKext)
14214         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14215             << MD->getParent()->getDeclName() << MD->getDeclName();
14216     }
14217   }
14218 
14219   if (CXXDestructorDecl *DD =
14220           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14221     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14222     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14223     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14224                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14225                          MemExpr->getMemberLoc());
14226   }
14227 
14228   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14229                                      TheCall->getMethodDecl());
14230 }
14231 
14232 /// BuildCallToObjectOfClassType - Build a call to an object of class
14233 /// type (C++ [over.call.object]), which can end up invoking an
14234 /// overloaded function call operator (@c operator()) or performing a
14235 /// user-defined conversion on the object argument.
14236 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)14237 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14238                                    SourceLocation LParenLoc,
14239                                    MultiExprArg Args,
14240                                    SourceLocation RParenLoc) {
14241   if (checkPlaceholderForOverload(*this, Obj))
14242     return ExprError();
14243   ExprResult Object = Obj;
14244 
14245   UnbridgedCastsSet UnbridgedCasts;
14246   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14247     return ExprError();
14248 
14249   assert(Object.get()->getType()->isRecordType() &&
14250          "Requires object type argument");
14251 
14252   // C++ [over.call.object]p1:
14253   //  If the primary-expression E in the function call syntax
14254   //  evaluates to a class object of type "cv T", then the set of
14255   //  candidate functions includes at least the function call
14256   //  operators of T. The function call operators of T are obtained by
14257   //  ordinary lookup of the name operator() in the context of
14258   //  (E).operator().
14259   OverloadCandidateSet CandidateSet(LParenLoc,
14260                                     OverloadCandidateSet::CSK_Operator);
14261   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14262 
14263   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14264                           diag::err_incomplete_object_call, Object.get()))
14265     return true;
14266 
14267   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14268   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14269   LookupQualifiedName(R, Record->getDecl());
14270   R.suppressDiagnostics();
14271 
14272   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14273        Oper != OperEnd; ++Oper) {
14274     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14275                        Object.get()->Classify(Context), Args, CandidateSet,
14276                        /*SuppressUserConversion=*/false);
14277   }
14278 
14279   // C++ [over.call.object]p2:
14280   //   In addition, for each (non-explicit in C++0x) conversion function
14281   //   declared in T of the form
14282   //
14283   //        operator conversion-type-id () cv-qualifier;
14284   //
14285   //   where cv-qualifier is the same cv-qualification as, or a
14286   //   greater cv-qualification than, cv, and where conversion-type-id
14287   //   denotes the type "pointer to function of (P1,...,Pn) returning
14288   //   R", or the type "reference to pointer to function of
14289   //   (P1,...,Pn) returning R", or the type "reference to function
14290   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14291   //   is also considered as a candidate function. Similarly,
14292   //   surrogate call functions are added to the set of candidate
14293   //   functions for each conversion function declared in an
14294   //   accessible base class provided the function is not hidden
14295   //   within T by another intervening declaration.
14296   const auto &Conversions =
14297       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14298   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14299     NamedDecl *D = *I;
14300     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14301     if (isa<UsingShadowDecl>(D))
14302       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14303 
14304     // Skip over templated conversion functions; they aren't
14305     // surrogates.
14306     if (isa<FunctionTemplateDecl>(D))
14307       continue;
14308 
14309     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14310     if (!Conv->isExplicit()) {
14311       // Strip the reference type (if any) and then the pointer type (if
14312       // any) to get down to what might be a function type.
14313       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14314       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14315         ConvType = ConvPtrType->getPointeeType();
14316 
14317       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14318       {
14319         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14320                               Object.get(), Args, CandidateSet);
14321       }
14322     }
14323   }
14324 
14325   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14326 
14327   // Perform overload resolution.
14328   OverloadCandidateSet::iterator Best;
14329   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14330                                           Best)) {
14331   case OR_Success:
14332     // Overload resolution succeeded; we'll build the appropriate call
14333     // below.
14334     break;
14335 
14336   case OR_No_Viable_Function: {
14337     PartialDiagnostic PD =
14338         CandidateSet.empty()
14339             ? (PDiag(diag::err_ovl_no_oper)
14340                << Object.get()->getType() << /*call*/ 1
14341                << Object.get()->getSourceRange())
14342             : (PDiag(diag::err_ovl_no_viable_object_call)
14343                << Object.get()->getType() << Object.get()->getSourceRange());
14344     CandidateSet.NoteCandidates(
14345         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14346         OCD_AllCandidates, Args);
14347     break;
14348   }
14349   case OR_Ambiguous:
14350     CandidateSet.NoteCandidates(
14351         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14352                             PDiag(diag::err_ovl_ambiguous_object_call)
14353                                 << Object.get()->getType()
14354                                 << Object.get()->getSourceRange()),
14355         *this, OCD_AmbiguousCandidates, Args);
14356     break;
14357 
14358   case OR_Deleted:
14359     CandidateSet.NoteCandidates(
14360         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14361                             PDiag(diag::err_ovl_deleted_object_call)
14362                                 << Object.get()->getType()
14363                                 << Object.get()->getSourceRange()),
14364         *this, OCD_AllCandidates, Args);
14365     break;
14366   }
14367 
14368   if (Best == CandidateSet.end())
14369     return true;
14370 
14371   UnbridgedCasts.restore();
14372 
14373   if (Best->Function == nullptr) {
14374     // Since there is no function declaration, this is one of the
14375     // surrogate candidates. Dig out the conversion function.
14376     CXXConversionDecl *Conv
14377       = cast<CXXConversionDecl>(
14378                          Best->Conversions[0].UserDefined.ConversionFunction);
14379 
14380     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14381                               Best->FoundDecl);
14382     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14383       return ExprError();
14384     assert(Conv == Best->FoundDecl.getDecl() &&
14385              "Found Decl & conversion-to-functionptr should be same, right?!");
14386     // We selected one of the surrogate functions that converts the
14387     // object parameter to a function pointer. Perform the conversion
14388     // on the object argument, then let BuildCallExpr finish the job.
14389 
14390     // Create an implicit member expr to refer to the conversion operator.
14391     // and then call it.
14392     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14393                                              Conv, HadMultipleCandidates);
14394     if (Call.isInvalid())
14395       return ExprError();
14396     // Record usage of conversion in an implicit cast.
14397     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14398                                     CK_UserDefinedConversion, Call.get(),
14399                                     nullptr, VK_RValue);
14400 
14401     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14402   }
14403 
14404   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14405 
14406   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14407   // that calls this method, using Object for the implicit object
14408   // parameter and passing along the remaining arguments.
14409   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14410 
14411   // An error diagnostic has already been printed when parsing the declaration.
14412   if (Method->isInvalidDecl())
14413     return ExprError();
14414 
14415   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14416   unsigned NumParams = Proto->getNumParams();
14417 
14418   DeclarationNameInfo OpLocInfo(
14419                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14420   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14421   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14422                                            Obj, HadMultipleCandidates,
14423                                            OpLocInfo.getLoc(),
14424                                            OpLocInfo.getInfo());
14425   if (NewFn.isInvalid())
14426     return true;
14427 
14428   // The number of argument slots to allocate in the call. If we have default
14429   // arguments we need to allocate space for them as well. We additionally
14430   // need one more slot for the object parameter.
14431   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14432 
14433   // Build the full argument list for the method call (the implicit object
14434   // parameter is placed at the beginning of the list).
14435   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14436 
14437   bool IsError = false;
14438 
14439   // Initialize the implicit object parameter.
14440   ExprResult ObjRes =
14441     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14442                                         Best->FoundDecl, Method);
14443   if (ObjRes.isInvalid())
14444     IsError = true;
14445   else
14446     Object = ObjRes;
14447   MethodArgs[0] = Object.get();
14448 
14449   // Check the argument types.
14450   for (unsigned i = 0; i != NumParams; i++) {
14451     Expr *Arg;
14452     if (i < Args.size()) {
14453       Arg = Args[i];
14454 
14455       // Pass the argument.
14456 
14457       ExprResult InputInit
14458         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14459                                                     Context,
14460                                                     Method->getParamDecl(i)),
14461                                     SourceLocation(), Arg);
14462 
14463       IsError |= InputInit.isInvalid();
14464       Arg = InputInit.getAs<Expr>();
14465     } else {
14466       ExprResult DefArg
14467         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14468       if (DefArg.isInvalid()) {
14469         IsError = true;
14470         break;
14471       }
14472 
14473       Arg = DefArg.getAs<Expr>();
14474     }
14475 
14476     MethodArgs[i + 1] = Arg;
14477   }
14478 
14479   // If this is a variadic call, handle args passed through "...".
14480   if (Proto->isVariadic()) {
14481     // Promote the arguments (C99 6.5.2.2p7).
14482     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14483       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14484                                                         nullptr);
14485       IsError |= Arg.isInvalid();
14486       MethodArgs[i + 1] = Arg.get();
14487     }
14488   }
14489 
14490   if (IsError)
14491     return true;
14492 
14493   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14494 
14495   // Once we've built TheCall, all of the expressions are properly owned.
14496   QualType ResultTy = Method->getReturnType();
14497   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14498   ResultTy = ResultTy.getNonLValueExprType(Context);
14499 
14500   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14501       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14502       CurFPFeatureOverrides());
14503 
14504   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14505     return true;
14506 
14507   if (CheckFunctionCall(Method, TheCall, Proto))
14508     return true;
14509 
14510   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14511 }
14512 
14513 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14514 ///  (if one exists), where @c Base is an expression of class type and
14515 /// @c Member is the name of the member we're trying to find.
14516 ExprResult
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc,bool * NoArrowOperatorFound)14517 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14518                                bool *NoArrowOperatorFound) {
14519   assert(Base->getType()->isRecordType() &&
14520          "left-hand side must have class type");
14521 
14522   if (checkPlaceholderForOverload(*this, Base))
14523     return ExprError();
14524 
14525   SourceLocation Loc = Base->getExprLoc();
14526 
14527   // C++ [over.ref]p1:
14528   //
14529   //   [...] An expression x->m is interpreted as (x.operator->())->m
14530   //   for a class object x of type T if T::operator->() exists and if
14531   //   the operator is selected as the best match function by the
14532   //   overload resolution mechanism (13.3).
14533   DeclarationName OpName =
14534     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14535   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14536 
14537   if (RequireCompleteType(Loc, Base->getType(),
14538                           diag::err_typecheck_incomplete_tag, Base))
14539     return ExprError();
14540 
14541   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14542   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14543   R.suppressDiagnostics();
14544 
14545   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14546        Oper != OperEnd; ++Oper) {
14547     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14548                        None, CandidateSet, /*SuppressUserConversion=*/false);
14549   }
14550 
14551   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14552 
14553   // Perform overload resolution.
14554   OverloadCandidateSet::iterator Best;
14555   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14556   case OR_Success:
14557     // Overload resolution succeeded; we'll build the call below.
14558     break;
14559 
14560   case OR_No_Viable_Function: {
14561     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14562     if (CandidateSet.empty()) {
14563       QualType BaseType = Base->getType();
14564       if (NoArrowOperatorFound) {
14565         // Report this specific error to the caller instead of emitting a
14566         // diagnostic, as requested.
14567         *NoArrowOperatorFound = true;
14568         return ExprError();
14569       }
14570       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14571         << BaseType << Base->getSourceRange();
14572       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14573         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14574           << FixItHint::CreateReplacement(OpLoc, ".");
14575       }
14576     } else
14577       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14578         << "operator->" << Base->getSourceRange();
14579     CandidateSet.NoteCandidates(*this, Base, Cands);
14580     return ExprError();
14581   }
14582   case OR_Ambiguous:
14583     CandidateSet.NoteCandidates(
14584         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14585                                        << "->" << Base->getType()
14586                                        << Base->getSourceRange()),
14587         *this, OCD_AmbiguousCandidates, Base);
14588     return ExprError();
14589 
14590   case OR_Deleted:
14591     CandidateSet.NoteCandidates(
14592         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14593                                        << "->" << Base->getSourceRange()),
14594         *this, OCD_AllCandidates, Base);
14595     return ExprError();
14596   }
14597 
14598   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14599 
14600   // Convert the object parameter.
14601   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14602   ExprResult BaseResult =
14603     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14604                                         Best->FoundDecl, Method);
14605   if (BaseResult.isInvalid())
14606     return ExprError();
14607   Base = BaseResult.get();
14608 
14609   // Build the operator call.
14610   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14611                                             Base, HadMultipleCandidates, OpLoc);
14612   if (FnExpr.isInvalid())
14613     return ExprError();
14614 
14615   QualType ResultTy = Method->getReturnType();
14616   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14617   ResultTy = ResultTy.getNonLValueExprType(Context);
14618   CXXOperatorCallExpr *TheCall =
14619       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14620                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14621 
14622   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14623     return ExprError();
14624 
14625   if (CheckFunctionCall(Method, TheCall,
14626                         Method->getType()->castAs<FunctionProtoType>()))
14627     return ExprError();
14628 
14629   return MaybeBindToTemporary(TheCall);
14630 }
14631 
14632 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14633 /// a literal operator described by the provided lookup results.
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)14634 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14635                                           DeclarationNameInfo &SuffixInfo,
14636                                           ArrayRef<Expr*> Args,
14637                                           SourceLocation LitEndLoc,
14638                                        TemplateArgumentListInfo *TemplateArgs) {
14639   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14640 
14641   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14642                                     OverloadCandidateSet::CSK_Normal);
14643   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14644                                  TemplateArgs);
14645 
14646   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14647 
14648   // Perform overload resolution. This will usually be trivial, but might need
14649   // to perform substitutions for a literal operator template.
14650   OverloadCandidateSet::iterator Best;
14651   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14652   case OR_Success:
14653   case OR_Deleted:
14654     break;
14655 
14656   case OR_No_Viable_Function:
14657     CandidateSet.NoteCandidates(
14658         PartialDiagnosticAt(UDSuffixLoc,
14659                             PDiag(diag::err_ovl_no_viable_function_in_call)
14660                                 << R.getLookupName()),
14661         *this, OCD_AllCandidates, Args);
14662     return ExprError();
14663 
14664   case OR_Ambiguous:
14665     CandidateSet.NoteCandidates(
14666         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14667                                                 << R.getLookupName()),
14668         *this, OCD_AmbiguousCandidates, Args);
14669     return ExprError();
14670   }
14671 
14672   FunctionDecl *FD = Best->Function;
14673   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14674                                         nullptr, HadMultipleCandidates,
14675                                         SuffixInfo.getLoc(),
14676                                         SuffixInfo.getInfo());
14677   if (Fn.isInvalid())
14678     return true;
14679 
14680   // Check the argument types. This should almost always be a no-op, except
14681   // that array-to-pointer decay is applied to string literals.
14682   Expr *ConvArgs[2];
14683   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14684     ExprResult InputInit = PerformCopyInitialization(
14685       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14686       SourceLocation(), Args[ArgIdx]);
14687     if (InputInit.isInvalid())
14688       return true;
14689     ConvArgs[ArgIdx] = InputInit.get();
14690   }
14691 
14692   QualType ResultTy = FD->getReturnType();
14693   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14694   ResultTy = ResultTy.getNonLValueExprType(Context);
14695 
14696   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14697       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14698       VK, LitEndLoc, UDSuffixLoc);
14699 
14700   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14701     return ExprError();
14702 
14703   if (CheckFunctionCall(FD, UDL, nullptr))
14704     return ExprError();
14705 
14706   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14707 }
14708 
14709 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14710 /// given LookupResult is non-empty, it is assumed to describe a member which
14711 /// will be invoked. Otherwise, the function will be found via argument
14712 /// dependent lookup.
14713 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14714 /// otherwise CallExpr is set to ExprError() and some non-success value
14715 /// is returned.
14716 Sema::ForRangeStatus
BuildForRangeBeginEndCall(SourceLocation Loc,SourceLocation RangeLoc,const DeclarationNameInfo & NameInfo,LookupResult & MemberLookup,OverloadCandidateSet * CandidateSet,Expr * Range,ExprResult * CallExpr)14717 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14718                                 SourceLocation RangeLoc,
14719                                 const DeclarationNameInfo &NameInfo,
14720                                 LookupResult &MemberLookup,
14721                                 OverloadCandidateSet *CandidateSet,
14722                                 Expr *Range, ExprResult *CallExpr) {
14723   Scope *S = nullptr;
14724 
14725   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14726   if (!MemberLookup.empty()) {
14727     ExprResult MemberRef =
14728         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14729                                  /*IsPtr=*/false, CXXScopeSpec(),
14730                                  /*TemplateKWLoc=*/SourceLocation(),
14731                                  /*FirstQualifierInScope=*/nullptr,
14732                                  MemberLookup,
14733                                  /*TemplateArgs=*/nullptr, S);
14734     if (MemberRef.isInvalid()) {
14735       *CallExpr = ExprError();
14736       return FRS_DiagnosticIssued;
14737     }
14738     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14739     if (CallExpr->isInvalid()) {
14740       *CallExpr = ExprError();
14741       return FRS_DiagnosticIssued;
14742     }
14743   } else {
14744     UnresolvedSet<0> FoundNames;
14745     UnresolvedLookupExpr *Fn =
14746       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14747                                    NestedNameSpecifierLoc(), NameInfo,
14748                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14749                                    FoundNames.begin(), FoundNames.end());
14750 
14751     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14752                                                     CandidateSet, CallExpr);
14753     if (CandidateSet->empty() || CandidateSetError) {
14754       *CallExpr = ExprError();
14755       return FRS_NoViableFunction;
14756     }
14757     OverloadCandidateSet::iterator Best;
14758     OverloadingResult OverloadResult =
14759         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14760 
14761     if (OverloadResult == OR_No_Viable_Function) {
14762       *CallExpr = ExprError();
14763       return FRS_NoViableFunction;
14764     }
14765     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14766                                          Loc, nullptr, CandidateSet, &Best,
14767                                          OverloadResult,
14768                                          /*AllowTypoCorrection=*/false);
14769     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14770       *CallExpr = ExprError();
14771       return FRS_DiagnosticIssued;
14772     }
14773   }
14774   return FRS_Success;
14775 }
14776 
14777 
14778 /// FixOverloadedFunctionReference - E is an expression that refers to
14779 /// a C++ overloaded function (possibly with some parentheses and
14780 /// perhaps a '&' around it). We have resolved the overloaded function
14781 /// to the function declaration Fn, so patch up the expression E to
14782 /// refer (possibly indirectly) to Fn. Returns the new expr.
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)14783 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14784                                            FunctionDecl *Fn) {
14785   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14786     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14787                                                    Found, Fn);
14788     if (SubExpr == PE->getSubExpr())
14789       return PE;
14790 
14791     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14792   }
14793 
14794   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14795     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14796                                                    Found, Fn);
14797     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14798                                SubExpr->getType()) &&
14799            "Implicit cast type cannot be determined from overload");
14800     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14801     if (SubExpr == ICE->getSubExpr())
14802       return ICE;
14803 
14804     return ImplicitCastExpr::Create(Context, ICE->getType(),
14805                                     ICE->getCastKind(),
14806                                     SubExpr, nullptr,
14807                                     ICE->getValueKind());
14808   }
14809 
14810   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14811     if (!GSE->isResultDependent()) {
14812       Expr *SubExpr =
14813           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14814       if (SubExpr == GSE->getResultExpr())
14815         return GSE;
14816 
14817       // Replace the resulting type information before rebuilding the generic
14818       // selection expression.
14819       ArrayRef<Expr *> A = GSE->getAssocExprs();
14820       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14821       unsigned ResultIdx = GSE->getResultIndex();
14822       AssocExprs[ResultIdx] = SubExpr;
14823 
14824       return GenericSelectionExpr::Create(
14825           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14826           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14827           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14828           ResultIdx);
14829     }
14830     // Rather than fall through to the unreachable, return the original generic
14831     // selection expression.
14832     return GSE;
14833   }
14834 
14835   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14836     assert(UnOp->getOpcode() == UO_AddrOf &&
14837            "Can only take the address of an overloaded function");
14838     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14839       if (Method->isStatic()) {
14840         // Do nothing: static member functions aren't any different
14841         // from non-member functions.
14842       } else {
14843         // Fix the subexpression, which really has to be an
14844         // UnresolvedLookupExpr holding an overloaded member function
14845         // or template.
14846         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14847                                                        Found, Fn);
14848         if (SubExpr == UnOp->getSubExpr())
14849           return UnOp;
14850 
14851         assert(isa<DeclRefExpr>(SubExpr)
14852                && "fixed to something other than a decl ref");
14853         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14854                && "fixed to a member ref with no nested name qualifier");
14855 
14856         // We have taken the address of a pointer to member
14857         // function. Perform the computation here so that we get the
14858         // appropriate pointer to member type.
14859         QualType ClassType
14860           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14861         QualType MemPtrType
14862           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14863         // Under the MS ABI, lock down the inheritance model now.
14864         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14865           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14866 
14867         return UnaryOperator::Create(
14868             Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
14869             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
14870       }
14871     }
14872     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14873                                                    Found, Fn);
14874     if (SubExpr == UnOp->getSubExpr())
14875       return UnOp;
14876 
14877     return UnaryOperator::Create(Context, SubExpr, UO_AddrOf,
14878                                  Context.getPointerType(SubExpr->getType()),
14879                                  VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(),
14880                                  false, CurFPFeatureOverrides());
14881   }
14882 
14883   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14884     // FIXME: avoid copy.
14885     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14886     if (ULE->hasExplicitTemplateArgs()) {
14887       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14888       TemplateArgs = &TemplateArgsBuffer;
14889     }
14890 
14891     DeclRefExpr *DRE =
14892         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14893                          ULE->getQualifierLoc(), Found.getDecl(),
14894                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14895     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14896     return DRE;
14897   }
14898 
14899   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14900     // FIXME: avoid copy.
14901     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14902     if (MemExpr->hasExplicitTemplateArgs()) {
14903       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14904       TemplateArgs = &TemplateArgsBuffer;
14905     }
14906 
14907     Expr *Base;
14908 
14909     // If we're filling in a static method where we used to have an
14910     // implicit member access, rewrite to a simple decl ref.
14911     if (MemExpr->isImplicitAccess()) {
14912       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14913         DeclRefExpr *DRE = BuildDeclRefExpr(
14914             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14915             MemExpr->getQualifierLoc(), Found.getDecl(),
14916             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14917         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14918         return DRE;
14919       } else {
14920         SourceLocation Loc = MemExpr->getMemberLoc();
14921         if (MemExpr->getQualifier())
14922           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14923         Base =
14924             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14925       }
14926     } else
14927       Base = MemExpr->getBase();
14928 
14929     ExprValueKind valueKind;
14930     QualType type;
14931     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14932       valueKind = VK_LValue;
14933       type = Fn->getType();
14934     } else {
14935       valueKind = VK_RValue;
14936       type = Context.BoundMemberTy;
14937     }
14938 
14939     return BuildMemberExpr(
14940         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14941         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14942         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14943         type, valueKind, OK_Ordinary, TemplateArgs);
14944   }
14945 
14946   llvm_unreachable("Invalid reference to overloaded function");
14947 }
14948 
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)14949 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14950                                                 DeclAccessPair Found,
14951                                                 FunctionDecl *Fn) {
14952   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14953 }
14954