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/ASTLambda.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DependenceFlags.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeOrdering.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/OperatorKinds.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/Support/Casting.h"
43 #include <algorithm>
44 #include <cstddef>
45 #include <cstdlib>
46 #include <optional>
47 
48 using namespace clang;
49 using namespace sema;
50 
51 using AllowedExplicit = Sema::AllowedExplicit;
52 
functionHasPassObjectSizeParams(const FunctionDecl * FD)53 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
54   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
55     return P->hasAttr<PassObjectSizeAttr>();
56   });
57 }
58 
59 /// A convenience routine for creating a decayed reference to a function.
CreateFunctionRefExpr(Sema & S,FunctionDecl * Fn,NamedDecl * FoundDecl,const Expr * Base,bool HadMultipleCandidates,SourceLocation Loc=SourceLocation (),const DeclarationNameLoc & LocInfo=DeclarationNameLoc ())60 static ExprResult CreateFunctionRefExpr(
61     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
62     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
63     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
64   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
65     return ExprError();
66   // If FoundDecl is different from Fn (such as if one is a template
67   // and the other a specialization), make sure DiagnoseUseOfDecl is
68   // called on both.
69   // FIXME: This would be more comprehensively addressed by modifying
70   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
71   // being used.
72   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
73     return ExprError();
74   DeclRefExpr *DRE = new (S.Context)
75       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
76   if (HadMultipleCandidates)
77     DRE->setHadMultipleCandidates(true);
78 
79   S.MarkDeclRefReferenced(DRE, Base);
80   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
81     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
82       S.ResolveExceptionSpec(Loc, FPT);
83       DRE->setType(Fn->getType());
84     }
85   }
86   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
87                              CK_FunctionToPointerDecay);
88 }
89 
90 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
91                                  bool InOverloadResolution,
92                                  StandardConversionSequence &SCS,
93                                  bool CStyle,
94                                  bool AllowObjCWritebackConversion);
95 
96 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
97                                                  QualType &ToType,
98                                                  bool InOverloadResolution,
99                                                  StandardConversionSequence &SCS,
100                                                  bool CStyle);
101 static OverloadingResult
102 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
103                         UserDefinedConversionSequence& User,
104                         OverloadCandidateSet& Conversions,
105                         AllowedExplicit AllowExplicit,
106                         bool AllowObjCConversionOnExplicit);
107 
108 static ImplicitConversionSequence::CompareKind
109 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
110                                    const StandardConversionSequence& SCS1,
111                                    const StandardConversionSequence& SCS2);
112 
113 static ImplicitConversionSequence::CompareKind
114 CompareQualificationConversions(Sema &S,
115                                 const StandardConversionSequence& SCS1,
116                                 const StandardConversionSequence& SCS2);
117 
118 static ImplicitConversionSequence::CompareKind
119 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
120                                 const StandardConversionSequence& SCS1,
121                                 const StandardConversionSequence& SCS2);
122 
123 /// GetConversionRank - Retrieve the implicit conversion rank
124 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)125 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
126   static const ImplicitConversionRank
127     Rank[] = {
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Exact_Match,
131     ICR_Exact_Match,
132     ICR_Exact_Match,
133     ICR_Exact_Match,
134     ICR_Promotion,
135     ICR_Promotion,
136     ICR_Promotion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Conversion,
147     ICR_Conversion,
148     ICR_Conversion,
149     ICR_OCL_Scalar_Widening,
150     ICR_Complex_Real_Conversion,
151     ICR_Conversion,
152     ICR_Conversion,
153     ICR_Writeback_Conversion,
154     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
155                      // it was omitted by the patch that added
156                      // ICK_Zero_Event_Conversion
157     ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
158                      // it was omitted by the patch that added
159                      // ICK_Zero_Queue_Conversion
160     ICR_C_Conversion,
161     ICR_C_Conversion_Extension,
162     ICR_Conversion,
163   };
164   static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
165   return Rank[(int)Kind];
166 }
167 
168 /// GetImplicitConversionName - Return the name of this kind of
169 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)170 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
171   static const char* const Name[] = {
172     "No conversion",
173     "Lvalue-to-rvalue",
174     "Array-to-pointer",
175     "Function-to-pointer",
176     "Function pointer conversion",
177     "Qualification",
178     "Integral promotion",
179     "Floating point promotion",
180     "Complex promotion",
181     "Integral conversion",
182     "Floating conversion",
183     "Complex conversion",
184     "Floating-integral conversion",
185     "Pointer conversion",
186     "Pointer-to-member conversion",
187     "Boolean conversion",
188     "Compatible-types conversion",
189     "Derived-to-base conversion",
190     "Vector conversion",
191     "SVE Vector conversion",
192     "RVV Vector conversion",
193     "Vector splat",
194     "Complex-real conversion",
195     "Block Pointer conversion",
196     "Transparent Union Conversion",
197     "Writeback conversion",
198     "OpenCL Zero Event Conversion",
199     "OpenCL Zero Queue Conversion",
200     "C specific type conversion",
201     "Incompatible pointer conversion",
202     "Fixed point conversion",
203   };
204   static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
205   return Name[Kind];
206 }
207 
208 /// StandardConversionSequence - Set the standard conversion
209 /// sequence to the identity conversion.
setAsIdentityConversion()210 void StandardConversionSequence::setAsIdentityConversion() {
211   First = ICK_Identity;
212   Second = ICK_Identity;
213   Third = ICK_Identity;
214   DeprecatedStringLiteralToCharPtr = false;
215   QualificationIncludesObjCLifetime = false;
216   ReferenceBinding = false;
217   DirectBinding = false;
218   IsLvalueReference = true;
219   BindsToFunctionLvalue = false;
220   BindsToRvalue = false;
221   BindsImplicitObjectArgumentWithoutRefQualifier = false;
222   ObjCLifetimeConversionBinding = false;
223   CopyConstructor = nullptr;
224 }
225 
226 /// getRank - Retrieve the rank of this standard conversion sequence
227 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
228 /// implicit conversions.
getRank() const229 ImplicitConversionRank StandardConversionSequence::getRank() const {
230   ImplicitConversionRank Rank = ICR_Exact_Match;
231   if  (GetConversionRank(First) > Rank)
232     Rank = GetConversionRank(First);
233   if  (GetConversionRank(Second) > Rank)
234     Rank = GetConversionRank(Second);
235   if  (GetConversionRank(Third) > Rank)
236     Rank = GetConversionRank(Third);
237   return Rank;
238 }
239 
240 /// isPointerConversionToBool - Determines whether this conversion is
241 /// a conversion of a pointer or pointer-to-member to bool. This is
242 /// used as part of the ranking of standard conversion sequences
243 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const244 bool StandardConversionSequence::isPointerConversionToBool() const {
245   // Note that FromType has not necessarily been transformed by the
246   // array-to-pointer or function-to-pointer implicit conversions, so
247   // check for their presence as well as checking whether FromType is
248   // a pointer.
249   if (getToType(1)->isBooleanType() &&
250       (getFromType()->isPointerType() ||
251        getFromType()->isMemberPointerType() ||
252        getFromType()->isObjCObjectPointerType() ||
253        getFromType()->isBlockPointerType() ||
254        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
255     return true;
256 
257   return false;
258 }
259 
260 /// isPointerConversionToVoidPointer - Determines whether this
261 /// conversion is a conversion of a pointer to a void pointer. This is
262 /// used as part of the ranking of standard conversion sequences (C++
263 /// 13.3.3.2p4).
264 bool
265 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const266 isPointerConversionToVoidPointer(ASTContext& Context) const {
267   QualType FromType = getFromType();
268   QualType ToType = getToType(1);
269 
270   // Note that FromType has not necessarily been transformed by the
271   // array-to-pointer implicit conversion, so check for its presence
272   // and redo the conversion to get a pointer.
273   if (First == ICK_Array_To_Pointer)
274     FromType = Context.getArrayDecayedType(FromType);
275 
276   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
277     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
278       return ToPtrType->getPointeeType()->isVoidType();
279 
280   return false;
281 }
282 
283 /// Skip any implicit casts which could be either part of a narrowing conversion
284 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(ASTContext & Ctx,const Expr * Converted)285 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
286                                              const Expr *Converted) {
287   // We can have cleanups wrapping the converted expression; these need to be
288   // preserved so that destructors run if necessary.
289   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
290     Expr *Inner =
291         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
292     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
293                                     EWC->getObjects());
294   }
295 
296   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
297     switch (ICE->getCastKind()) {
298     case CK_NoOp:
299     case CK_IntegralCast:
300     case CK_IntegralToBoolean:
301     case CK_IntegralToFloating:
302     case CK_BooleanToSignedIntegral:
303     case CK_FloatingToIntegral:
304     case CK_FloatingToBoolean:
305     case CK_FloatingCast:
306       Converted = ICE->getSubExpr();
307       continue;
308 
309     default:
310       return Converted;
311     }
312   }
313 
314   return Converted;
315 }
316 
317 /// Check if this standard conversion sequence represents a narrowing
318 /// conversion, according to C++11 [dcl.init.list]p7.
319 ///
320 /// \param Ctx  The AST context.
321 /// \param Converted  The result of applying this standard conversion sequence.
322 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
323 ///        value of the expression prior to the narrowing conversion.
324 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
325 ///        type of the expression prior to the narrowing conversion.
326 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
327 ///        from floating point types to integral types should be ignored.
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType,bool IgnoreFloatToIntegralConversion) const328 NarrowingKind StandardConversionSequence::getNarrowingKind(
329     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
330     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
331   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
332 
333   // C++11 [dcl.init.list]p7:
334   //   A narrowing conversion is an implicit conversion ...
335   QualType FromType = getToType(0);
336   QualType ToType = getToType(1);
337 
338   // A conversion to an enumeration type is narrowing if the conversion to
339   // the underlying type is narrowing. This only arises for expressions of
340   // the form 'Enum{init}'.
341   if (auto *ET = ToType->getAs<EnumType>())
342     ToType = ET->getDecl()->getIntegerType();
343 
344   switch (Second) {
345   // 'bool' is an integral type; dispatch to the right place to handle it.
346   case ICK_Boolean_Conversion:
347     if (FromType->isRealFloatingType())
348       goto FloatingIntegralConversion;
349     if (FromType->isIntegralOrUnscopedEnumerationType())
350       goto IntegralConversion;
351     // -- from a pointer type or pointer-to-member type to bool, or
352     return NK_Type_Narrowing;
353 
354   // -- from a floating-point type to an integer type, or
355   //
356   // -- from an integer type or unscoped enumeration type to a floating-point
357   //    type, except where the source is a constant expression and the actual
358   //    value after conversion will fit into the target type and will produce
359   //    the original value when converted back to the original type, or
360   case ICK_Floating_Integral:
361   FloatingIntegralConversion:
362     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
363       return NK_Type_Narrowing;
364     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
365                ToType->isRealFloatingType()) {
366       if (IgnoreFloatToIntegralConversion)
367         return NK_Not_Narrowing;
368       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
369       assert(Initializer && "Unknown conversion expression");
370 
371       // If it's value-dependent, we can't tell whether it's narrowing.
372       if (Initializer->isValueDependent())
373         return NK_Dependent_Narrowing;
374 
375       if (std::optional<llvm::APSInt> IntConstantValue =
376               Initializer->getIntegerConstantExpr(Ctx)) {
377         // Convert the integer to the floating type.
378         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
379         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
380                                 llvm::APFloat::rmNearestTiesToEven);
381         // And back.
382         llvm::APSInt ConvertedValue = *IntConstantValue;
383         bool ignored;
384         Result.convertToInteger(ConvertedValue,
385                                 llvm::APFloat::rmTowardZero, &ignored);
386         // If the resulting value is different, this was a narrowing conversion.
387         if (*IntConstantValue != ConvertedValue) {
388           ConstantValue = APValue(*IntConstantValue);
389           ConstantType = Initializer->getType();
390           return NK_Constant_Narrowing;
391         }
392       } else {
393         // Variables are always narrowings.
394         return NK_Variable_Narrowing;
395       }
396     }
397     return NK_Not_Narrowing;
398 
399   // -- from long double to double or float, or from double to float, except
400   //    where the source is a constant expression and the actual value after
401   //    conversion is within the range of values that can be represented (even
402   //    if it cannot be represented exactly), or
403   case ICK_Floating_Conversion:
404     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
405         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
406       // FromType is larger than ToType.
407       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
408 
409       // If it's value-dependent, we can't tell whether it's narrowing.
410       if (Initializer->isValueDependent())
411         return NK_Dependent_Narrowing;
412 
413       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
414         // Constant!
415         assert(ConstantValue.isFloat());
416         llvm::APFloat FloatVal = ConstantValue.getFloat();
417         // Convert the source value into the target type.
418         bool ignored;
419         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
420           Ctx.getFloatTypeSemantics(ToType),
421           llvm::APFloat::rmNearestTiesToEven, &ignored);
422         // If there was no overflow, the source value is within the range of
423         // values that can be represented.
424         if (ConvertStatus & llvm::APFloat::opOverflow) {
425           ConstantType = Initializer->getType();
426           return NK_Constant_Narrowing;
427         }
428       } else {
429         return NK_Variable_Narrowing;
430       }
431     }
432     return NK_Not_Narrowing;
433 
434   // -- from an integer type or unscoped enumeration type to an integer type
435   //    that cannot represent all the values of the original type, except where
436   //    the source is a constant expression and the actual value after
437   //    conversion will fit into the target type and will produce the original
438   //    value when converted back to the original type.
439   case ICK_Integral_Conversion:
440   IntegralConversion: {
441     assert(FromType->isIntegralOrUnscopedEnumerationType());
442     assert(ToType->isIntegralOrUnscopedEnumerationType());
443     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
444     const unsigned FromWidth = Ctx.getIntWidth(FromType);
445     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
446     const unsigned ToWidth = Ctx.getIntWidth(ToType);
447 
448     if (FromWidth > ToWidth ||
449         (FromWidth == ToWidth && FromSigned != ToSigned) ||
450         (FromSigned && !ToSigned)) {
451       // Not all values of FromType can be represented in ToType.
452       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
453 
454       // If it's value-dependent, we can't tell whether it's narrowing.
455       if (Initializer->isValueDependent())
456         return NK_Dependent_Narrowing;
457 
458       std::optional<llvm::APSInt> OptInitializerValue;
459       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
460         // Such conversions on variables are always narrowing.
461         return NK_Variable_Narrowing;
462       }
463       llvm::APSInt &InitializerValue = *OptInitializerValue;
464       bool Narrowing = false;
465       if (FromWidth < ToWidth) {
466         // Negative -> unsigned is narrowing. Otherwise, more bits is never
467         // narrowing.
468         if (InitializerValue.isSigned() && InitializerValue.isNegative())
469           Narrowing = true;
470       } else {
471         // Add a bit to the InitializerValue so we don't have to worry about
472         // signed vs. unsigned comparisons.
473         InitializerValue = InitializerValue.extend(
474           InitializerValue.getBitWidth() + 1);
475         // Convert the initializer to and from the target width and signed-ness.
476         llvm::APSInt ConvertedValue = InitializerValue;
477         ConvertedValue = ConvertedValue.trunc(ToWidth);
478         ConvertedValue.setIsSigned(ToSigned);
479         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
480         ConvertedValue.setIsSigned(InitializerValue.isSigned());
481         // If the result is different, this was a narrowing conversion.
482         if (ConvertedValue != InitializerValue)
483           Narrowing = true;
484       }
485       if (Narrowing) {
486         ConstantType = Initializer->getType();
487         ConstantValue = APValue(InitializerValue);
488         return NK_Constant_Narrowing;
489       }
490     }
491     return NK_Not_Narrowing;
492   }
493 
494   default:
495     // Other kinds of conversions are not narrowings.
496     return NK_Not_Narrowing;
497   }
498 }
499 
500 /// dump - Print this standard conversion sequence to standard
501 /// error. Useful for debugging overloading issues.
dump() const502 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
503   raw_ostream &OS = llvm::errs();
504   bool PrintedSomething = false;
505   if (First != ICK_Identity) {
506     OS << GetImplicitConversionName(First);
507     PrintedSomething = true;
508   }
509 
510   if (Second != ICK_Identity) {
511     if (PrintedSomething) {
512       OS << " -> ";
513     }
514     OS << GetImplicitConversionName(Second);
515 
516     if (CopyConstructor) {
517       OS << " (by copy constructor)";
518     } else if (DirectBinding) {
519       OS << " (direct reference binding)";
520     } else if (ReferenceBinding) {
521       OS << " (reference binding)";
522     }
523     PrintedSomething = true;
524   }
525 
526   if (Third != ICK_Identity) {
527     if (PrintedSomething) {
528       OS << " -> ";
529     }
530     OS << GetImplicitConversionName(Third);
531     PrintedSomething = true;
532   }
533 
534   if (!PrintedSomething) {
535     OS << "No conversions required";
536   }
537 }
538 
539 /// dump - Print this user-defined conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
dump() const541 void UserDefinedConversionSequence::dump() const {
542   raw_ostream &OS = llvm::errs();
543   if (Before.First || Before.Second || Before.Third) {
544     Before.dump();
545     OS << " -> ";
546   }
547   if (ConversionFunction)
548     OS << '\'' << *ConversionFunction << '\'';
549   else
550     OS << "aggregate initialization";
551   if (After.First || After.Second || After.Third) {
552     OS << " -> ";
553     After.dump();
554   }
555 }
556 
557 /// dump - Print this implicit conversion sequence to standard
558 /// error. Useful for debugging overloading issues.
dump() const559 void ImplicitConversionSequence::dump() const {
560   raw_ostream &OS = llvm::errs();
561   if (hasInitializerListContainerType())
562     OS << "Worst list element conversion: ";
563   switch (ConversionKind) {
564   case StandardConversion:
565     OS << "Standard conversion: ";
566     Standard.dump();
567     break;
568   case UserDefinedConversion:
569     OS << "User-defined conversion: ";
570     UserDefined.dump();
571     break;
572   case EllipsisConversion:
573     OS << "Ellipsis conversion";
574     break;
575   case AmbiguousConversion:
576     OS << "Ambiguous conversion";
577     break;
578   case BadConversion:
579     OS << "Bad conversion";
580     break;
581   }
582 
583   OS << "\n";
584 }
585 
construct()586 void AmbiguousConversionSequence::construct() {
587   new (&conversions()) ConversionSet();
588 }
589 
destruct()590 void AmbiguousConversionSequence::destruct() {
591   conversions().~ConversionSet();
592 }
593 
594 void
copyFrom(const AmbiguousConversionSequence & O)595 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
596   FromTypePtr = O.FromTypePtr;
597   ToTypePtr = O.ToTypePtr;
598   new (&conversions()) ConversionSet(O.conversions());
599 }
600 
601 namespace {
602   // Structure used by DeductionFailureInfo to store
603   // template argument information.
604   struct DFIArguments {
605     TemplateArgument FirstArg;
606     TemplateArgument SecondArg;
607   };
608   // Structure used by DeductionFailureInfo to store
609   // template parameter and template argument information.
610   struct DFIParamWithArguments : DFIArguments {
611     TemplateParameter Param;
612   };
613   // Structure used by DeductionFailureInfo to store template argument
614   // information and the index of the problematic call argument.
615   struct DFIDeducedMismatchArgs : DFIArguments {
616     TemplateArgumentList *TemplateArgs;
617     unsigned CallArgIndex;
618   };
619   // Structure used by DeductionFailureInfo to store information about
620   // unsatisfied constraints.
621   struct CNSInfo {
622     TemplateArgumentList *TemplateArgs;
623     ConstraintSatisfaction Satisfaction;
624   };
625 }
626 
627 /// Convert from Sema's representation of template deduction information
628 /// to the form used in overload-candidate information.
629 DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext & Context,Sema::TemplateDeductionResult TDK,TemplateDeductionInfo & Info)630 clang::MakeDeductionFailureInfo(ASTContext &Context,
631                                 Sema::TemplateDeductionResult TDK,
632                                 TemplateDeductionInfo &Info) {
633   DeductionFailureInfo Result;
634   Result.Result = static_cast<unsigned>(TDK);
635   Result.HasDiagnostic = false;
636   switch (TDK) {
637   case Sema::TDK_Invalid:
638   case Sema::TDK_InstantiationDepth:
639   case Sema::TDK_TooManyArguments:
640   case Sema::TDK_TooFewArguments:
641   case Sema::TDK_MiscellaneousDeductionFailure:
642   case Sema::TDK_CUDATargetMismatch:
643     Result.Data = nullptr;
644     break;
645 
646   case Sema::TDK_Incomplete:
647   case Sema::TDK_InvalidExplicitArguments:
648     Result.Data = Info.Param.getOpaqueValue();
649     break;
650 
651   case Sema::TDK_DeducedMismatch:
652   case Sema::TDK_DeducedMismatchNested: {
653     // FIXME: Should allocate from normal heap so that we can free this later.
654     auto *Saved = new (Context) DFIDeducedMismatchArgs;
655     Saved->FirstArg = Info.FirstArg;
656     Saved->SecondArg = Info.SecondArg;
657     Saved->TemplateArgs = Info.takeSugared();
658     Saved->CallArgIndex = Info.CallArgIndex;
659     Result.Data = Saved;
660     break;
661   }
662 
663   case Sema::TDK_NonDeducedMismatch: {
664     // FIXME: Should allocate from normal heap so that we can free this later.
665     DFIArguments *Saved = new (Context) DFIArguments;
666     Saved->FirstArg = Info.FirstArg;
667     Saved->SecondArg = Info.SecondArg;
668     Result.Data = Saved;
669     break;
670   }
671 
672   case Sema::TDK_IncompletePack:
673     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
674   case Sema::TDK_Inconsistent:
675   case Sema::TDK_Underqualified: {
676     // FIXME: Should allocate from normal heap so that we can free this later.
677     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
678     Saved->Param = Info.Param;
679     Saved->FirstArg = Info.FirstArg;
680     Saved->SecondArg = Info.SecondArg;
681     Result.Data = Saved;
682     break;
683   }
684 
685   case Sema::TDK_SubstitutionFailure:
686     Result.Data = Info.takeSugared();
687     if (Info.hasSFINAEDiagnostic()) {
688       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
689           SourceLocation(), PartialDiagnostic::NullDiagnostic());
690       Info.takeSFINAEDiagnostic(*Diag);
691       Result.HasDiagnostic = true;
692     }
693     break;
694 
695   case Sema::TDK_ConstraintsNotSatisfied: {
696     CNSInfo *Saved = new (Context) CNSInfo;
697     Saved->TemplateArgs = Info.takeSugared();
698     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
699     Result.Data = Saved;
700     break;
701   }
702 
703   case Sema::TDK_Success:
704   case Sema::TDK_NonDependentConversionFailure:
705   case Sema::TDK_AlreadyDiagnosed:
706     llvm_unreachable("not a deduction failure");
707   }
708 
709   return Result;
710 }
711 
Destroy()712 void DeductionFailureInfo::Destroy() {
713   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
714   case Sema::TDK_Success:
715   case Sema::TDK_Invalid:
716   case Sema::TDK_InstantiationDepth:
717   case Sema::TDK_Incomplete:
718   case Sema::TDK_TooManyArguments:
719   case Sema::TDK_TooFewArguments:
720   case Sema::TDK_InvalidExplicitArguments:
721   case Sema::TDK_CUDATargetMismatch:
722   case Sema::TDK_NonDependentConversionFailure:
723     break;
724 
725   case Sema::TDK_IncompletePack:
726   case Sema::TDK_Inconsistent:
727   case Sema::TDK_Underqualified:
728   case Sema::TDK_DeducedMismatch:
729   case Sema::TDK_DeducedMismatchNested:
730   case Sema::TDK_NonDeducedMismatch:
731     // FIXME: Destroy the data?
732     Data = nullptr;
733     break;
734 
735   case Sema::TDK_SubstitutionFailure:
736     // FIXME: Destroy the template argument list?
737     Data = nullptr;
738     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
739       Diag->~PartialDiagnosticAt();
740       HasDiagnostic = false;
741     }
742     break;
743 
744   case Sema::TDK_ConstraintsNotSatisfied:
745     // FIXME: Destroy the template argument list?
746     Data = nullptr;
747     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
748       Diag->~PartialDiagnosticAt();
749       HasDiagnostic = false;
750     }
751     break;
752 
753   // Unhandled
754   case Sema::TDK_MiscellaneousDeductionFailure:
755   case Sema::TDK_AlreadyDiagnosed:
756     break;
757   }
758 }
759 
getSFINAEDiagnostic()760 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
761   if (HasDiagnostic)
762     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
763   return nullptr;
764 }
765 
getTemplateParameter()766 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
767   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
768   case Sema::TDK_Success:
769   case Sema::TDK_Invalid:
770   case Sema::TDK_InstantiationDepth:
771   case Sema::TDK_TooManyArguments:
772   case Sema::TDK_TooFewArguments:
773   case Sema::TDK_SubstitutionFailure:
774   case Sema::TDK_DeducedMismatch:
775   case Sema::TDK_DeducedMismatchNested:
776   case Sema::TDK_NonDeducedMismatch:
777   case Sema::TDK_CUDATargetMismatch:
778   case Sema::TDK_NonDependentConversionFailure:
779   case Sema::TDK_ConstraintsNotSatisfied:
780     return TemplateParameter();
781 
782   case Sema::TDK_Incomplete:
783   case Sema::TDK_InvalidExplicitArguments:
784     return TemplateParameter::getFromOpaqueValue(Data);
785 
786   case Sema::TDK_IncompletePack:
787   case Sema::TDK_Inconsistent:
788   case Sema::TDK_Underqualified:
789     return static_cast<DFIParamWithArguments*>(Data)->Param;
790 
791   // Unhandled
792   case Sema::TDK_MiscellaneousDeductionFailure:
793   case Sema::TDK_AlreadyDiagnosed:
794     break;
795   }
796 
797   return TemplateParameter();
798 }
799 
getTemplateArgumentList()800 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
801   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
802   case Sema::TDK_Success:
803   case Sema::TDK_Invalid:
804   case Sema::TDK_InstantiationDepth:
805   case Sema::TDK_TooManyArguments:
806   case Sema::TDK_TooFewArguments:
807   case Sema::TDK_Incomplete:
808   case Sema::TDK_IncompletePack:
809   case Sema::TDK_InvalidExplicitArguments:
810   case Sema::TDK_Inconsistent:
811   case Sema::TDK_Underqualified:
812   case Sema::TDK_NonDeducedMismatch:
813   case Sema::TDK_CUDATargetMismatch:
814   case Sema::TDK_NonDependentConversionFailure:
815     return nullptr;
816 
817   case Sema::TDK_DeducedMismatch:
818   case Sema::TDK_DeducedMismatchNested:
819     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
820 
821   case Sema::TDK_SubstitutionFailure:
822     return static_cast<TemplateArgumentList*>(Data);
823 
824   case Sema::TDK_ConstraintsNotSatisfied:
825     return static_cast<CNSInfo*>(Data)->TemplateArgs;
826 
827   // Unhandled
828   case Sema::TDK_MiscellaneousDeductionFailure:
829   case Sema::TDK_AlreadyDiagnosed:
830     break;
831   }
832 
833   return nullptr;
834 }
835 
getFirstArg()836 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
837   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
838   case Sema::TDK_Success:
839   case Sema::TDK_Invalid:
840   case Sema::TDK_InstantiationDepth:
841   case Sema::TDK_Incomplete:
842   case Sema::TDK_TooManyArguments:
843   case Sema::TDK_TooFewArguments:
844   case Sema::TDK_InvalidExplicitArguments:
845   case Sema::TDK_SubstitutionFailure:
846   case Sema::TDK_CUDATargetMismatch:
847   case Sema::TDK_NonDependentConversionFailure:
848   case Sema::TDK_ConstraintsNotSatisfied:
849     return nullptr;
850 
851   case Sema::TDK_IncompletePack:
852   case Sema::TDK_Inconsistent:
853   case Sema::TDK_Underqualified:
854   case Sema::TDK_DeducedMismatch:
855   case Sema::TDK_DeducedMismatchNested:
856   case Sema::TDK_NonDeducedMismatch:
857     return &static_cast<DFIArguments*>(Data)->FirstArg;
858 
859   // Unhandled
860   case Sema::TDK_MiscellaneousDeductionFailure:
861   case Sema::TDK_AlreadyDiagnosed:
862     break;
863   }
864 
865   return nullptr;
866 }
867 
getSecondArg()868 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
869   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
870   case Sema::TDK_Success:
871   case Sema::TDK_Invalid:
872   case Sema::TDK_InstantiationDepth:
873   case Sema::TDK_Incomplete:
874   case Sema::TDK_IncompletePack:
875   case Sema::TDK_TooManyArguments:
876   case Sema::TDK_TooFewArguments:
877   case Sema::TDK_InvalidExplicitArguments:
878   case Sema::TDK_SubstitutionFailure:
879   case Sema::TDK_CUDATargetMismatch:
880   case Sema::TDK_NonDependentConversionFailure:
881   case Sema::TDK_ConstraintsNotSatisfied:
882     return nullptr;
883 
884   case Sema::TDK_Inconsistent:
885   case Sema::TDK_Underqualified:
886   case Sema::TDK_DeducedMismatch:
887   case Sema::TDK_DeducedMismatchNested:
888   case Sema::TDK_NonDeducedMismatch:
889     return &static_cast<DFIArguments*>(Data)->SecondArg;
890 
891   // Unhandled
892   case Sema::TDK_MiscellaneousDeductionFailure:
893   case Sema::TDK_AlreadyDiagnosed:
894     break;
895   }
896 
897   return nullptr;
898 }
899 
getCallArgIndex()900 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
901   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
902   case Sema::TDK_DeducedMismatch:
903   case Sema::TDK_DeducedMismatchNested:
904     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
905 
906   default:
907     return std::nullopt;
908   }
909 }
910 
FunctionsCorrespond(ASTContext & Ctx,const FunctionDecl * X,const FunctionDecl * Y)911 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
912                                 const FunctionDecl *Y) {
913   if (!X || !Y)
914     return false;
915   if (X->getNumParams() != Y->getNumParams())
916     return false;
917   // FIXME: when do rewritten comparison operators
918   // with explicit object parameters correspond?
919   // https://cplusplus.github.io/CWG/issues/2797.html
920   for (unsigned I = 0; I < X->getNumParams(); ++I)
921     if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
922                                     Y->getParamDecl(I)->getType()))
923       return false;
924   if (auto *FTX = X->getDescribedFunctionTemplate()) {
925     auto *FTY = Y->getDescribedFunctionTemplate();
926     if (!FTY)
927       return false;
928     if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
929                                          FTY->getTemplateParameters()))
930       return false;
931   }
932   return true;
933 }
934 
shouldAddReversedEqEq(Sema & S,SourceLocation OpLoc,Expr * FirstOperand,FunctionDecl * EqFD)935 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
936                                   Expr *FirstOperand, FunctionDecl *EqFD) {
937   assert(EqFD->getOverloadedOperator() ==
938          OverloadedOperatorKind::OO_EqualEqual);
939   // C++2a [over.match.oper]p4:
940   // A non-template function or function template F named operator== is a
941   // rewrite target with first operand o unless a search for the name operator!=
942   // in the scope S from the instantiation context of the operator expression
943   // finds a function or function template that would correspond
944   // ([basic.scope.scope]) to F if its name were operator==, where S is the
945   // scope of the class type of o if F is a class member, and the namespace
946   // scope of which F is a member otherwise. A function template specialization
947   // named operator== is a rewrite target if its function template is a rewrite
948   // target.
949   DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
950       OverloadedOperatorKind::OO_ExclaimEqual);
951   if (isa<CXXMethodDecl>(EqFD)) {
952     // If F is a class member, search scope is class type of first operand.
953     QualType RHS = FirstOperand->getType();
954     auto *RHSRec = RHS->getAs<RecordType>();
955     if (!RHSRec)
956       return true;
957     LookupResult Members(S, NotEqOp, OpLoc,
958                          Sema::LookupNameKind::LookupMemberName);
959     S.LookupQualifiedName(Members, RHSRec->getDecl());
960     Members.suppressAccessDiagnostics();
961     for (NamedDecl *Op : Members)
962       if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
963         return false;
964     return true;
965   }
966   // Otherwise the search scope is the namespace scope of which F is a member.
967   for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
968     auto *NotEqFD = Op->getAsFunction();
969     if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
970       NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
971     if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
972         declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
973                            cast<Decl>(Op->getLexicalDeclContext())))
974       return false;
975   }
976   return true;
977 }
978 
allowsReversed(OverloadedOperatorKind Op)979 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
980     OverloadedOperatorKind Op) {
981   if (!AllowRewrittenCandidates)
982     return false;
983   return Op == OO_EqualEqual || Op == OO_Spaceship;
984 }
985 
shouldAddReversed(Sema & S,ArrayRef<Expr * > OriginalArgs,FunctionDecl * FD)986 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
987     Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
988   auto Op = FD->getOverloadedOperator();
989   if (!allowsReversed(Op))
990     return false;
991   if (Op == OverloadedOperatorKind::OO_EqualEqual) {
992     assert(OriginalArgs.size() == 2);
993     if (!shouldAddReversedEqEq(
994             S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
995       return false;
996   }
997   // Don't bother adding a reversed candidate that can never be a better
998   // match than the non-reversed version.
999   return FD->getNumNonObjectParams() != 2 ||
1000          !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
1001                                            FD->getParamDecl(1)->getType()) ||
1002          FD->hasAttr<EnableIfAttr>();
1003 }
1004 
destroyCandidates()1005 void OverloadCandidateSet::destroyCandidates() {
1006   for (iterator i = begin(), e = end(); i != e; ++i) {
1007     for (auto &C : i->Conversions)
1008       C.~ImplicitConversionSequence();
1009     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1010       i->DeductionFailure.Destroy();
1011   }
1012 }
1013 
clear(CandidateSetKind CSK)1014 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1015   destroyCandidates();
1016   SlabAllocator.Reset();
1017   NumInlineBytesUsed = 0;
1018   Candidates.clear();
1019   Functions.clear();
1020   Kind = CSK;
1021 }
1022 
1023 namespace {
1024   class UnbridgedCastsSet {
1025     struct Entry {
1026       Expr **Addr;
1027       Expr *Saved;
1028     };
1029     SmallVector<Entry, 2> Entries;
1030 
1031   public:
save(Sema & S,Expr * & E)1032     void save(Sema &S, Expr *&E) {
1033       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1034       Entry entry = { &E, E };
1035       Entries.push_back(entry);
1036       E = S.stripARCUnbridgedCast(E);
1037     }
1038 
restore()1039     void restore() {
1040       for (SmallVectorImpl<Entry>::iterator
1041              i = Entries.begin(), e = Entries.end(); i != e; ++i)
1042         *i->Addr = i->Saved;
1043     }
1044   };
1045 }
1046 
1047 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1048 /// preprocessing on the given expression.
1049 ///
1050 /// \param unbridgedCasts a collection to which to add unbridged casts;
1051 ///   without this, they will be immediately diagnosed as errors
1052 ///
1053 /// Return true on unrecoverable error.
1054 static bool
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=nullptr)1055 checkPlaceholderForOverload(Sema &S, Expr *&E,
1056                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
1057   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
1058     // We can't handle overloaded expressions here because overload
1059     // resolution might reasonably tweak them.
1060     if (placeholder->getKind() == BuiltinType::Overload) return false;
1061 
1062     // If the context potentially accepts unbridged ARC casts, strip
1063     // the unbridged cast and add it to the collection for later restoration.
1064     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1065         unbridgedCasts) {
1066       unbridgedCasts->save(S, E);
1067       return false;
1068     }
1069 
1070     // Go ahead and check everything else.
1071     ExprResult result = S.CheckPlaceholderExpr(E);
1072     if (result.isInvalid())
1073       return true;
1074 
1075     E = result.get();
1076     return false;
1077   }
1078 
1079   // Nothing to do.
1080   return false;
1081 }
1082 
1083 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1084 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,MultiExprArg Args,UnbridgedCastsSet & unbridged)1085 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1086                                             UnbridgedCastsSet &unbridged) {
1087   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1088     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1089       return true;
1090 
1091   return false;
1092 }
1093 
1094 /// Determine whether the given New declaration is an overload of the
1095 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1096 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1097 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1098 /// functions (or function templates) at all. When it does return Ovl_Match or
1099 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1100 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1101 /// declaration.
1102 ///
1103 /// Example: Given the following input:
1104 ///
1105 ///   void f(int, float); // #1
1106 ///   void f(int, int); // #2
1107 ///   int f(int, int); // #3
1108 ///
1109 /// When we process #1, there is no previous declaration of "f", so IsOverload
1110 /// will not be used.
1111 ///
1112 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1113 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1114 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1115 /// unchanged.
1116 ///
1117 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1118 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1119 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1120 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1121 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1122 ///
1123 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1124 /// by a using declaration. The rules for whether to hide shadow declarations
1125 /// ignore some properties which otherwise figure into a function template's
1126 /// signature.
1127 Sema::OverloadKind
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)1128 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1129                     NamedDecl *&Match, bool NewIsUsingDecl) {
1130   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1131          I != E; ++I) {
1132     NamedDecl *OldD = *I;
1133 
1134     bool OldIsUsingDecl = false;
1135     if (isa<UsingShadowDecl>(OldD)) {
1136       OldIsUsingDecl = true;
1137 
1138       // We can always introduce two using declarations into the same
1139       // context, even if they have identical signatures.
1140       if (NewIsUsingDecl) continue;
1141 
1142       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1143     }
1144 
1145     // A using-declaration does not conflict with another declaration
1146     // if one of them is hidden.
1147     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1148       continue;
1149 
1150     // If either declaration was introduced by a using declaration,
1151     // we'll need to use slightly different rules for matching.
1152     // Essentially, these rules are the normal rules, except that
1153     // function templates hide function templates with different
1154     // return types or template parameter lists.
1155     bool UseMemberUsingDeclRules =
1156       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1157       !New->getFriendObjectKind();
1158 
1159     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1160       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1161         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1162           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1163           continue;
1164         }
1165 
1166         if (!isa<FunctionTemplateDecl>(OldD) &&
1167             !shouldLinkPossiblyHiddenDecl(*I, New))
1168           continue;
1169 
1170         Match = *I;
1171         return Ovl_Match;
1172       }
1173 
1174       // Builtins that have custom typechecking or have a reference should
1175       // not be overloadable or redeclarable.
1176       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1177         Match = *I;
1178         return Ovl_NonFunction;
1179       }
1180     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1181       // We can overload with these, which can show up when doing
1182       // redeclaration checks for UsingDecls.
1183       assert(Old.getLookupKind() == LookupUsingDeclName);
1184     } else if (isa<TagDecl>(OldD)) {
1185       // We can always overload with tags by hiding them.
1186     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1187       // Optimistically assume that an unresolved using decl will
1188       // overload; if it doesn't, we'll have to diagnose during
1189       // template instantiation.
1190       //
1191       // Exception: if the scope is dependent and this is not a class
1192       // member, the using declaration can only introduce an enumerator.
1193       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1194         Match = *I;
1195         return Ovl_NonFunction;
1196       }
1197     } else {
1198       // (C++ 13p1):
1199       //   Only function declarations can be overloaded; object and type
1200       //   declarations cannot be overloaded.
1201       Match = *I;
1202       return Ovl_NonFunction;
1203     }
1204   }
1205 
1206   // C++ [temp.friend]p1:
1207   //   For a friend function declaration that is not a template declaration:
1208   //    -- if the name of the friend is a qualified or unqualified template-id,
1209   //       [...], otherwise
1210   //    -- if the name of the friend is a qualified-id and a matching
1211   //       non-template function is found in the specified class or namespace,
1212   //       the friend declaration refers to that function, otherwise,
1213   //    -- if the name of the friend is a qualified-id and a matching function
1214   //       template is found in the specified class or namespace, the friend
1215   //       declaration refers to the deduced specialization of that function
1216   //       template, otherwise
1217   //    -- the name shall be an unqualified-id [...]
1218   // If we get here for a qualified friend declaration, we've just reached the
1219   // third bullet. If the type of the friend is dependent, skip this lookup
1220   // until instantiation.
1221   if (New->getFriendObjectKind() && New->getQualifier() &&
1222       !New->getDescribedFunctionTemplate() &&
1223       !New->getDependentSpecializationInfo() &&
1224       !New->getType()->isDependentType()) {
1225     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1226     TemplateSpecResult.addAllDecls(Old);
1227     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1228                                             /*QualifiedFriend*/true)) {
1229       New->setInvalidDecl();
1230       return Ovl_Overload;
1231     }
1232 
1233     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1234     return Ovl_Match;
1235   }
1236 
1237   return Ovl_Overload;
1238 }
1239 
IsOverloadOrOverrideImpl(Sema & SemaRef,FunctionDecl * New,FunctionDecl * Old,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs,bool UseOverrideRules=false)1240 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1241                                      FunctionDecl *Old,
1242                                      bool UseMemberUsingDeclRules,
1243                                      bool ConsiderCudaAttrs,
1244                                      bool UseOverrideRules = false) {
1245   // C++ [basic.start.main]p2: This function shall not be overloaded.
1246   if (New->isMain())
1247     return false;
1248 
1249   // MSVCRT user defined entry points cannot be overloaded.
1250   if (New->isMSVCRTEntryPoint())
1251     return false;
1252 
1253   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1254   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1255 
1256   // C++ [temp.fct]p2:
1257   //   A function template can be overloaded with other function templates
1258   //   and with normal (non-template) functions.
1259   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1260     return true;
1261 
1262   // Is the function New an overload of the function Old?
1263   QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1264   QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1265 
1266   // Compare the signatures (C++ 1.3.10) of the two functions to
1267   // determine whether they are overloads. If we find any mismatch
1268   // in the signature, they are overloads.
1269 
1270   // If either of these functions is a K&R-style function (no
1271   // prototype), then we consider them to have matching signatures.
1272   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1273       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1274     return false;
1275 
1276   const auto *OldType = cast<FunctionProtoType>(OldQType);
1277   const auto *NewType = cast<FunctionProtoType>(NewQType);
1278 
1279   // The signature of a function includes the types of its
1280   // parameters (C++ 1.3.10), which includes the presence or absence
1281   // of the ellipsis; see C++ DR 357).
1282   if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1283     return true;
1284 
1285   // For member-like friends, the enclosing class is part of the signature.
1286   if ((New->isMemberLikeConstrainedFriend() ||
1287        Old->isMemberLikeConstrainedFriend()) &&
1288       !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1289     return true;
1290 
1291   // Compare the parameter lists.
1292   // This can only be done once we have establish that friend functions
1293   // inhabit the same context, otherwise we might tried to instantiate
1294   // references to non-instantiated entities during constraint substitution.
1295   // GH78101.
1296   if (NewTemplate) {
1297     // C++ [temp.over.link]p4:
1298     //   The signature of a function template consists of its function
1299     //   signature, its return type and its template parameter list. The names
1300     //   of the template parameters are significant only for establishing the
1301     //   relationship between the template parameters and the rest of the
1302     //   signature.
1303     //
1304     // We check the return type and template parameter lists for function
1305     // templates first; the remaining checks follow.
1306     bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1307         NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1308         OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1309     bool SameReturnType = SemaRef.Context.hasSameType(
1310         Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1311     // FIXME(GH58571): Match template parameter list even for non-constrained
1312     // template heads. This currently ensures that the code prior to C++20 is
1313     // not newly broken.
1314     bool ConstraintsInTemplateHead =
1315         NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1316         OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1317     // C++ [namespace.udecl]p11:
1318     //   The set of declarations named by a using-declarator that inhabits a
1319     //   class C does not include member functions and member function
1320     //   templates of a base class that "correspond" to (and thus would
1321     //   conflict with) a declaration of a function or function template in
1322     //   C.
1323     // Comparing return types is not required for the "correspond" check to
1324     // decide whether a member introduced by a shadow declaration is hidden.
1325     if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1326         !SameTemplateParameterList)
1327       return true;
1328     if (!UseMemberUsingDeclRules &&
1329         (!SameTemplateParameterList || !SameReturnType))
1330       return true;
1331   }
1332 
1333   const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1334   const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1335 
1336   int OldParamsOffset = 0;
1337   int NewParamsOffset = 0;
1338 
1339   // When determining if a method is an overload from a base class, act as if
1340   // the implicit object parameter are of the same type.
1341 
1342   auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1343     if (M->isExplicitObjectMemberFunction())
1344       return Q;
1345 
1346     // We do not allow overloading based off of '__restrict'.
1347     Q.removeRestrict();
1348 
1349     // We may not have applied the implicit const for a constexpr member
1350     // function yet (because we haven't yet resolved whether this is a static
1351     // or non-static member function). Add it now, on the assumption that this
1352     // is a redeclaration of OldMethod.
1353     if (!SemaRef.getLangOpts().CPlusPlus14 &&
1354         (M->isConstexpr() || M->isConsteval()) &&
1355         !isa<CXXConstructorDecl>(NewMethod))
1356       Q.addConst();
1357     return Q;
1358   };
1359 
1360   auto CompareType = [&](QualType Base, QualType D) {
1361     auto BS = Base.getNonReferenceType().getCanonicalType().split();
1362     BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1363 
1364     auto DS = D.getNonReferenceType().getCanonicalType().split();
1365     DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1366 
1367     if (BS.Quals != DS.Quals)
1368       return false;
1369 
1370     if (OldMethod->isImplicitObjectMemberFunction() &&
1371         OldMethod->getParent() != NewMethod->getParent()) {
1372       QualType ParentType =
1373           SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1374               .getCanonicalType();
1375       if (ParentType.getTypePtr() != BS.Ty)
1376         return false;
1377       BS.Ty = DS.Ty;
1378     }
1379 
1380     // FIXME: should we ignore some type attributes here?
1381     if (BS.Ty != DS.Ty)
1382       return false;
1383 
1384     if (Base->isLValueReferenceType())
1385       return D->isLValueReferenceType();
1386     return Base->isRValueReferenceType() == D->isRValueReferenceType();
1387   };
1388 
1389   // If the function is a class member, its signature includes the
1390   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1391   auto DiagnoseInconsistentRefQualifiers = [&]() {
1392     if (SemaRef.LangOpts.CPlusPlus23)
1393       return false;
1394     if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1395       return false;
1396     if (OldMethod->isExplicitObjectMemberFunction() ||
1397         NewMethod->isExplicitObjectMemberFunction())
1398       return false;
1399     if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1400                                      NewMethod->getRefQualifier() == RQ_None)) {
1401       SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1402           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1403       SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1404       return true;
1405     }
1406     return false;
1407   };
1408 
1409   if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1410     OldParamsOffset++;
1411   if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1412     NewParamsOffset++;
1413 
1414   if (OldType->getNumParams() - OldParamsOffset !=
1415           NewType->getNumParams() - NewParamsOffset ||
1416       !SemaRef.FunctionParamTypesAreEqual(
1417           {OldType->param_type_begin() + OldParamsOffset,
1418            OldType->param_type_end()},
1419           {NewType->param_type_begin() + NewParamsOffset,
1420            NewType->param_type_end()},
1421           nullptr)) {
1422     return true;
1423   }
1424 
1425   if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1426       !OldMethod->isStatic()) {
1427     bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1428                                                  const CXXMethodDecl *New) {
1429       auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1430       auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1431 
1432       auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1433         return F->getRefQualifier() == RQ_None &&
1434                !F->isExplicitObjectMemberFunction();
1435       };
1436 
1437       if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1438           CompareType(OldObjectType.getNonReferenceType(),
1439                       NewObjectType.getNonReferenceType()))
1440         return true;
1441       return CompareType(OldObjectType, NewObjectType);
1442     }(OldMethod, NewMethod);
1443 
1444     if (!HaveCorrespondingObjectParameters) {
1445       if (DiagnoseInconsistentRefQualifiers())
1446         return true;
1447       // CWG2554
1448       // and, if at least one is an explicit object member function, ignoring
1449       // object parameters
1450       if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1451                                 !OldMethod->isExplicitObjectMemberFunction()))
1452         return true;
1453     }
1454   }
1455 
1456   if (!UseOverrideRules) {
1457     Expr *NewRC = New->getTrailingRequiresClause(),
1458          *OldRC = Old->getTrailingRequiresClause();
1459     if ((NewRC != nullptr) != (OldRC != nullptr))
1460       return true;
1461 
1462     if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1463       return true;
1464   }
1465 
1466   if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1467       NewMethod->isImplicitObjectMemberFunction()) {
1468     if (DiagnoseInconsistentRefQualifiers())
1469       return true;
1470   }
1471 
1472   // Though pass_object_size is placed on parameters and takes an argument, we
1473   // consider it to be a function-level modifier for the sake of function
1474   // identity. Either the function has one or more parameters with
1475   // pass_object_size or it doesn't.
1476   if (functionHasPassObjectSizeParams(New) !=
1477       functionHasPassObjectSizeParams(Old))
1478     return true;
1479 
1480   // enable_if attributes are an order-sensitive part of the signature.
1481   for (specific_attr_iterator<EnableIfAttr>
1482          NewI = New->specific_attr_begin<EnableIfAttr>(),
1483          NewE = New->specific_attr_end<EnableIfAttr>(),
1484          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1485          OldE = Old->specific_attr_end<EnableIfAttr>();
1486        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1487     if (NewI == NewE || OldI == OldE)
1488       return true;
1489     llvm::FoldingSetNodeID NewID, OldID;
1490     NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1491     OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1492     if (NewID != OldID)
1493       return true;
1494   }
1495 
1496   if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1497     // Don't allow overloading of destructors.  (In theory we could, but it
1498     // would be a giant change to clang.)
1499     if (!isa<CXXDestructorDecl>(New)) {
1500       Sema::CUDAFunctionTarget NewTarget = SemaRef.IdentifyCUDATarget(New),
1501                                OldTarget = SemaRef.IdentifyCUDATarget(Old);
1502       if (NewTarget != Sema::CFT_InvalidTarget) {
1503         assert((OldTarget != Sema::CFT_InvalidTarget) &&
1504                "Unexpected invalid target.");
1505 
1506         // Allow overloading of functions with same signature and different CUDA
1507         // target attributes.
1508         if (NewTarget != OldTarget)
1509           return true;
1510       }
1511     }
1512   }
1513 
1514   // The signatures match; this is not an overload.
1515   return false;
1516 }
1517 
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs)1518 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1519                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1520   return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1521                                   ConsiderCudaAttrs);
1522 }
1523 
IsOverride(FunctionDecl * MD,FunctionDecl * BaseMD,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs)1524 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1525                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1526   return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1527                                   /*UseMemberUsingDeclRules=*/false,
1528                                   /*ConsiderCudaAttrs=*/true,
1529                                   /*UseOverrideRules=*/true);
1530 }
1531 
1532 /// Tries a user-defined conversion from From to ToType.
1533 ///
1534 /// Produces an implicit conversion sequence for when a standard conversion
1535 /// is not an option. See TryImplicitConversion for more information.
1536 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1537 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1538                          bool SuppressUserConversions,
1539                          AllowedExplicit AllowExplicit,
1540                          bool InOverloadResolution,
1541                          bool CStyle,
1542                          bool AllowObjCWritebackConversion,
1543                          bool AllowObjCConversionOnExplicit) {
1544   ImplicitConversionSequence ICS;
1545 
1546   if (SuppressUserConversions) {
1547     // We're not in the case above, so there is no conversion that
1548     // we can perform.
1549     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1550     return ICS;
1551   }
1552 
1553   // Attempt user-defined conversion.
1554   OverloadCandidateSet Conversions(From->getExprLoc(),
1555                                    OverloadCandidateSet::CSK_Normal);
1556   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1557                                   Conversions, AllowExplicit,
1558                                   AllowObjCConversionOnExplicit)) {
1559   case OR_Success:
1560   case OR_Deleted:
1561     ICS.setUserDefined();
1562     // C++ [over.ics.user]p4:
1563     //   A conversion of an expression of class type to the same class
1564     //   type is given Exact Match rank, and a conversion of an
1565     //   expression of class type to a base class of that type is
1566     //   given Conversion rank, in spite of the fact that a copy
1567     //   constructor (i.e., a user-defined conversion function) is
1568     //   called for those cases.
1569     if (CXXConstructorDecl *Constructor
1570           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1571       QualType FromCanon
1572         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1573       QualType ToCanon
1574         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1575       if (Constructor->isCopyConstructor() &&
1576           (FromCanon == ToCanon ||
1577            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1578         // Turn this into a "standard" conversion sequence, so that it
1579         // gets ranked with standard conversion sequences.
1580         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1581         ICS.setStandard();
1582         ICS.Standard.setAsIdentityConversion();
1583         ICS.Standard.setFromType(From->getType());
1584         ICS.Standard.setAllToTypes(ToType);
1585         ICS.Standard.CopyConstructor = Constructor;
1586         ICS.Standard.FoundCopyConstructor = Found;
1587         if (ToCanon != FromCanon)
1588           ICS.Standard.Second = ICK_Derived_To_Base;
1589       }
1590     }
1591     break;
1592 
1593   case OR_Ambiguous:
1594     ICS.setAmbiguous();
1595     ICS.Ambiguous.setFromType(From->getType());
1596     ICS.Ambiguous.setToType(ToType);
1597     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1598          Cand != Conversions.end(); ++Cand)
1599       if (Cand->Best)
1600         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1601     break;
1602 
1603     // Fall through.
1604   case OR_No_Viable_Function:
1605     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1606     break;
1607   }
1608 
1609   return ICS;
1610 }
1611 
1612 /// TryImplicitConversion - Attempt to perform an implicit conversion
1613 /// from the given expression (Expr) to the given type (ToType). This
1614 /// function returns an implicit conversion sequence that can be used
1615 /// to perform the initialization. Given
1616 ///
1617 ///   void f(float f);
1618 ///   void g(int i) { f(i); }
1619 ///
1620 /// this routine would produce an implicit conversion sequence to
1621 /// describe the initialization of f from i, which will be a standard
1622 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1623 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1624 //
1625 /// Note that this routine only determines how the conversion can be
1626 /// performed; it does not actually perform the conversion. As such,
1627 /// it will not produce any diagnostics if no conversion is available,
1628 /// but will instead return an implicit conversion sequence of kind
1629 /// "BadConversion".
1630 ///
1631 /// If @p SuppressUserConversions, then user-defined conversions are
1632 /// not permitted.
1633 /// If @p AllowExplicit, then explicit user-defined conversions are
1634 /// permitted.
1635 ///
1636 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1637 /// writeback conversion, which allows __autoreleasing id* parameters to
1638 /// be initialized with __strong id* or __weak id* arguments.
1639 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1640 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1641                       bool SuppressUserConversions,
1642                       AllowedExplicit AllowExplicit,
1643                       bool InOverloadResolution,
1644                       bool CStyle,
1645                       bool AllowObjCWritebackConversion,
1646                       bool AllowObjCConversionOnExplicit) {
1647   ImplicitConversionSequence ICS;
1648   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1649                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1650     ICS.setStandard();
1651     return ICS;
1652   }
1653 
1654   if (!S.getLangOpts().CPlusPlus) {
1655     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1656     return ICS;
1657   }
1658 
1659   // C++ [over.ics.user]p4:
1660   //   A conversion of an expression of class type to the same class
1661   //   type is given Exact Match rank, and a conversion of an
1662   //   expression of class type to a base class of that type is
1663   //   given Conversion rank, in spite of the fact that a copy/move
1664   //   constructor (i.e., a user-defined conversion function) is
1665   //   called for those cases.
1666   QualType FromType = From->getType();
1667   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1668       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1669        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1670     ICS.setStandard();
1671     ICS.Standard.setAsIdentityConversion();
1672     ICS.Standard.setFromType(FromType);
1673     ICS.Standard.setAllToTypes(ToType);
1674 
1675     // We don't actually check at this point whether there is a valid
1676     // copy/move constructor, since overloading just assumes that it
1677     // exists. When we actually perform initialization, we'll find the
1678     // appropriate constructor to copy the returned object, if needed.
1679     ICS.Standard.CopyConstructor = nullptr;
1680 
1681     // Determine whether this is considered a derived-to-base conversion.
1682     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1683       ICS.Standard.Second = ICK_Derived_To_Base;
1684 
1685     return ICS;
1686   }
1687 
1688   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1689                                   AllowExplicit, InOverloadResolution, CStyle,
1690                                   AllowObjCWritebackConversion,
1691                                   AllowObjCConversionOnExplicit);
1692 }
1693 
1694 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1695 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1696                             bool SuppressUserConversions,
1697                             AllowedExplicit AllowExplicit,
1698                             bool InOverloadResolution,
1699                             bool CStyle,
1700                             bool AllowObjCWritebackConversion) {
1701   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1702                                  AllowExplicit, InOverloadResolution, CStyle,
1703                                  AllowObjCWritebackConversion,
1704                                  /*AllowObjCConversionOnExplicit=*/false);
1705 }
1706 
1707 /// PerformImplicitConversion - Perform an implicit conversion of the
1708 /// expression From to the type ToType. Returns the
1709 /// converted expression. Flavor is the kind of conversion we're
1710 /// performing, used in the error message. If @p AllowExplicit,
1711 /// explicit user-defined conversions are permitted.
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1712 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1713                                            AssignmentAction Action,
1714                                            bool AllowExplicit) {
1715   if (checkPlaceholderForOverload(*this, From))
1716     return ExprError();
1717 
1718   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1719   bool AllowObjCWritebackConversion
1720     = getLangOpts().ObjCAutoRefCount &&
1721       (Action == AA_Passing || Action == AA_Sending);
1722   if (getLangOpts().ObjC)
1723     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1724                                       From->getType(), From);
1725   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1726       *this, From, ToType,
1727       /*SuppressUserConversions=*/false,
1728       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1729       /*InOverloadResolution=*/false,
1730       /*CStyle=*/false, AllowObjCWritebackConversion,
1731       /*AllowObjCConversionOnExplicit=*/false);
1732   return PerformImplicitConversion(From, ToType, ICS, Action);
1733 }
1734 
1735 /// Determine whether the conversion from FromType to ToType is a valid
1736 /// conversion that strips "noexcept" or "noreturn" off the nested function
1737 /// type.
IsFunctionConversion(QualType FromType,QualType ToType,QualType & ResultTy)1738 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1739                                 QualType &ResultTy) {
1740   if (Context.hasSameUnqualifiedType(FromType, ToType))
1741     return false;
1742 
1743   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1744   //                    or F(t noexcept) -> F(t)
1745   // where F adds one of the following at most once:
1746   //   - a pointer
1747   //   - a member pointer
1748   //   - a block pointer
1749   // Changes here need matching changes in FindCompositePointerType.
1750   CanQualType CanTo = Context.getCanonicalType(ToType);
1751   CanQualType CanFrom = Context.getCanonicalType(FromType);
1752   Type::TypeClass TyClass = CanTo->getTypeClass();
1753   if (TyClass != CanFrom->getTypeClass()) return false;
1754   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1755     if (TyClass == Type::Pointer) {
1756       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1757       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1758     } else if (TyClass == Type::BlockPointer) {
1759       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1760       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1761     } else if (TyClass == Type::MemberPointer) {
1762       auto ToMPT = CanTo.castAs<MemberPointerType>();
1763       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1764       // A function pointer conversion cannot change the class of the function.
1765       if (ToMPT->getClass() != FromMPT->getClass())
1766         return false;
1767       CanTo = ToMPT->getPointeeType();
1768       CanFrom = FromMPT->getPointeeType();
1769     } else {
1770       return false;
1771     }
1772 
1773     TyClass = CanTo->getTypeClass();
1774     if (TyClass != CanFrom->getTypeClass()) return false;
1775     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1776       return false;
1777   }
1778 
1779   const auto *FromFn = cast<FunctionType>(CanFrom);
1780   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1781 
1782   const auto *ToFn = cast<FunctionType>(CanTo);
1783   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1784 
1785   bool Changed = false;
1786 
1787   // Drop 'noreturn' if not present in target type.
1788   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1789     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1790     Changed = true;
1791   }
1792 
1793   // Drop 'noexcept' if not present in target type.
1794   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1795     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1796     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1797       FromFn = cast<FunctionType>(
1798           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1799                                                    EST_None)
1800                  .getTypePtr());
1801       Changed = true;
1802     }
1803 
1804     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1805     // only if the ExtParameterInfo lists of the two function prototypes can be
1806     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1807     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1808     bool CanUseToFPT, CanUseFromFPT;
1809     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1810                                       CanUseFromFPT, NewParamInfos) &&
1811         CanUseToFPT && !CanUseFromFPT) {
1812       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1813       ExtInfo.ExtParameterInfos =
1814           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1815       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1816                                             FromFPT->getParamTypes(), ExtInfo);
1817       FromFn = QT->getAs<FunctionType>();
1818       Changed = true;
1819     }
1820   }
1821 
1822   if (!Changed)
1823     return false;
1824 
1825   assert(QualType(FromFn, 0).isCanonical());
1826   if (QualType(FromFn, 0) != CanTo) return false;
1827 
1828   ResultTy = ToType;
1829   return true;
1830 }
1831 
1832 /// Determine whether the conversion from FromType to ToType is a valid
1833 /// vector conversion.
1834 ///
1835 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1836 /// conversion.
IsVectorConversion(Sema & S,QualType FromType,QualType ToType,ImplicitConversionKind & ICK,Expr * From,bool InOverloadResolution,bool CStyle)1837 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1838                                ImplicitConversionKind &ICK, Expr *From,
1839                                bool InOverloadResolution, bool CStyle) {
1840   // We need at least one of these types to be a vector type to have a vector
1841   // conversion.
1842   if (!ToType->isVectorType() && !FromType->isVectorType())
1843     return false;
1844 
1845   // Identical types require no conversions.
1846   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1847     return false;
1848 
1849   // There are no conversions between extended vector types, only identity.
1850   if (ToType->isExtVectorType()) {
1851     // There are no conversions between extended vector types other than the
1852     // identity conversion.
1853     if (FromType->isExtVectorType())
1854       return false;
1855 
1856     // Vector splat from any arithmetic type to a vector.
1857     if (FromType->isArithmeticType()) {
1858       ICK = ICK_Vector_Splat;
1859       return true;
1860     }
1861   }
1862 
1863   if (ToType->isSVESizelessBuiltinType() ||
1864       FromType->isSVESizelessBuiltinType())
1865     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1866         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1867       ICK = ICK_SVE_Vector_Conversion;
1868       return true;
1869     }
1870 
1871   if (ToType->isRVVSizelessBuiltinType() ||
1872       FromType->isRVVSizelessBuiltinType())
1873     if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
1874         S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
1875       ICK = ICK_RVV_Vector_Conversion;
1876       return true;
1877     }
1878 
1879   // We can perform the conversion between vector types in the following cases:
1880   // 1)vector types are equivalent AltiVec and GCC vector types
1881   // 2)lax vector conversions are permitted and the vector types are of the
1882   //   same size
1883   // 3)the destination type does not have the ARM MVE strict-polymorphism
1884   //   attribute, which inhibits lax vector conversion for overload resolution
1885   //   only
1886   if (ToType->isVectorType() && FromType->isVectorType()) {
1887     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1888         (S.isLaxVectorConversion(FromType, ToType) &&
1889          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1890       if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
1891           S.isLaxVectorConversion(FromType, ToType) &&
1892           S.anyAltivecTypes(FromType, ToType) &&
1893           !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
1894           !InOverloadResolution && !CStyle) {
1895         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1896             << FromType << ToType;
1897       }
1898       ICK = ICK_Vector_Conversion;
1899       return true;
1900     }
1901   }
1902 
1903   return false;
1904 }
1905 
1906 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1907                                 bool InOverloadResolution,
1908                                 StandardConversionSequence &SCS,
1909                                 bool CStyle);
1910 
1911 /// IsStandardConversion - Determines whether there is a standard
1912 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1913 /// expression From to the type ToType. Standard conversion sequences
1914 /// only consider non-class types; for conversions that involve class
1915 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1916 /// contain the standard conversion sequence required to perform this
1917 /// conversion and this routine will return true. Otherwise, this
1918 /// 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)1919 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1920                                  bool InOverloadResolution,
1921                                  StandardConversionSequence &SCS,
1922                                  bool CStyle,
1923                                  bool AllowObjCWritebackConversion) {
1924   QualType FromType = From->getType();
1925 
1926   // Standard conversions (C++ [conv])
1927   SCS.setAsIdentityConversion();
1928   SCS.IncompatibleObjC = false;
1929   SCS.setFromType(FromType);
1930   SCS.CopyConstructor = nullptr;
1931 
1932   // There are no standard conversions for class types in C++, so
1933   // abort early. When overloading in C, however, we do permit them.
1934   if (S.getLangOpts().CPlusPlus &&
1935       (FromType->isRecordType() || ToType->isRecordType()))
1936     return false;
1937 
1938   // The first conversion can be an lvalue-to-rvalue conversion,
1939   // array-to-pointer conversion, or function-to-pointer conversion
1940   // (C++ 4p1).
1941 
1942   if (FromType == S.Context.OverloadTy) {
1943     DeclAccessPair AccessPair;
1944     if (FunctionDecl *Fn
1945           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1946                                                  AccessPair)) {
1947       // We were able to resolve the address of the overloaded function,
1948       // so we can convert to the type of that function.
1949       FromType = Fn->getType();
1950       SCS.setFromType(FromType);
1951 
1952       // we can sometimes resolve &foo<int> regardless of ToType, so check
1953       // if the type matches (identity) or we are converting to bool
1954       if (!S.Context.hasSameUnqualifiedType(
1955                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1956         QualType resultTy;
1957         // if the function type matches except for [[noreturn]], it's ok
1958         if (!S.IsFunctionConversion(FromType,
1959               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1960           // otherwise, only a boolean conversion is standard
1961           if (!ToType->isBooleanType())
1962             return false;
1963       }
1964 
1965       // Check if the "from" expression is taking the address of an overloaded
1966       // function and recompute the FromType accordingly. Take advantage of the
1967       // fact that non-static member functions *must* have such an address-of
1968       // expression.
1969       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1970       if (Method && !Method->isStatic() &&
1971           !Method->isExplicitObjectMemberFunction()) {
1972         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1973                "Non-unary operator on non-static member address");
1974         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1975                == UO_AddrOf &&
1976                "Non-address-of operator on non-static member address");
1977         const Type *ClassType
1978           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1979         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1980       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1981         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1982                UO_AddrOf &&
1983                "Non-address-of operator for overloaded function expression");
1984         FromType = S.Context.getPointerType(FromType);
1985       }
1986     } else {
1987       return false;
1988     }
1989   }
1990   // Lvalue-to-rvalue conversion (C++11 4.1):
1991   //   A glvalue (3.10) of a non-function, non-array type T can
1992   //   be converted to a prvalue.
1993   bool argIsLValue = From->isGLValue();
1994   if (argIsLValue &&
1995       !FromType->isFunctionType() && !FromType->isArrayType() &&
1996       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1997     SCS.First = ICK_Lvalue_To_Rvalue;
1998 
1999     // C11 6.3.2.1p2:
2000     //   ... if the lvalue has atomic type, the value has the non-atomic version
2001     //   of the type of the lvalue ...
2002     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2003       FromType = Atomic->getValueType();
2004 
2005     // If T is a non-class type, the type of the rvalue is the
2006     // cv-unqualified version of T. Otherwise, the type of the rvalue
2007     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2008     // just strip the qualifiers because they don't matter.
2009     FromType = FromType.getUnqualifiedType();
2010   } else if (FromType->isArrayType()) {
2011     // Array-to-pointer conversion (C++ 4.2)
2012     SCS.First = ICK_Array_To_Pointer;
2013 
2014     // An lvalue or rvalue of type "array of N T" or "array of unknown
2015     // bound of T" can be converted to an rvalue of type "pointer to
2016     // T" (C++ 4.2p1).
2017     FromType = S.Context.getArrayDecayedType(FromType);
2018 
2019     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2020       // This conversion is deprecated in C++03 (D.4)
2021       SCS.DeprecatedStringLiteralToCharPtr = true;
2022 
2023       // For the purpose of ranking in overload resolution
2024       // (13.3.3.1.1), this conversion is considered an
2025       // array-to-pointer conversion followed by a qualification
2026       // conversion (4.4). (C++ 4.2p2)
2027       SCS.Second = ICK_Identity;
2028       SCS.Third = ICK_Qualification;
2029       SCS.QualificationIncludesObjCLifetime = false;
2030       SCS.setAllToTypes(FromType);
2031       return true;
2032     }
2033   } else if (FromType->isFunctionType() && argIsLValue) {
2034     // Function-to-pointer conversion (C++ 4.3).
2035     SCS.First = ICK_Function_To_Pointer;
2036 
2037     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2038       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2039         if (!S.checkAddressOfFunctionIsAvailable(FD))
2040           return false;
2041 
2042     // An lvalue of function type T can be converted to an rvalue of
2043     // type "pointer to T." The result is a pointer to the
2044     // function. (C++ 4.3p1).
2045     FromType = S.Context.getPointerType(FromType);
2046   } else {
2047     // We don't require any conversions for the first step.
2048     SCS.First = ICK_Identity;
2049   }
2050   SCS.setToType(0, FromType);
2051 
2052   // The second conversion can be an integral promotion, floating
2053   // point promotion, integral conversion, floating point conversion,
2054   // floating-integral conversion, pointer conversion,
2055   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2056   // For overloading in C, this can also be a "compatible-type"
2057   // conversion.
2058   bool IncompatibleObjC = false;
2059   ImplicitConversionKind SecondICK = ICK_Identity;
2060   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2061     // The unqualified versions of the types are the same: there's no
2062     // conversion to do.
2063     SCS.Second = ICK_Identity;
2064   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2065     // Integral promotion (C++ 4.5).
2066     SCS.Second = ICK_Integral_Promotion;
2067     FromType = ToType.getUnqualifiedType();
2068   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2069     // Floating point promotion (C++ 4.6).
2070     SCS.Second = ICK_Floating_Promotion;
2071     FromType = ToType.getUnqualifiedType();
2072   } else if (S.IsComplexPromotion(FromType, ToType)) {
2073     // Complex promotion (Clang extension)
2074     SCS.Second = ICK_Complex_Promotion;
2075     FromType = ToType.getUnqualifiedType();
2076   } else if (ToType->isBooleanType() &&
2077              (FromType->isArithmeticType() ||
2078               FromType->isAnyPointerType() ||
2079               FromType->isBlockPointerType() ||
2080               FromType->isMemberPointerType())) {
2081     // Boolean conversions (C++ 4.12).
2082     SCS.Second = ICK_Boolean_Conversion;
2083     FromType = S.Context.BoolTy;
2084   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2085              ToType->isIntegralType(S.Context)) {
2086     // Integral conversions (C++ 4.7).
2087     SCS.Second = ICK_Integral_Conversion;
2088     FromType = ToType.getUnqualifiedType();
2089   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2090     // Complex conversions (C99 6.3.1.6)
2091     SCS.Second = ICK_Complex_Conversion;
2092     FromType = ToType.getUnqualifiedType();
2093   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2094              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2095     // Complex-real conversions (C99 6.3.1.7)
2096     SCS.Second = ICK_Complex_Real;
2097     FromType = ToType.getUnqualifiedType();
2098   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
2099     // FIXME: disable conversions between long double, __ibm128 and __float128
2100     // if their representation is different until there is back end support
2101     // We of course allow this conversion if long double is really double.
2102 
2103     // Conversions between bfloat16 and float16 are currently not supported.
2104     if ((FromType->isBFloat16Type() &&
2105          (ToType->isFloat16Type() || ToType->isHalfType())) ||
2106         (ToType->isBFloat16Type() &&
2107          (FromType->isFloat16Type() || FromType->isHalfType())))
2108       return false;
2109 
2110     // Conversions between IEEE-quad and IBM-extended semantics are not
2111     // permitted.
2112     const llvm::fltSemantics &FromSem =
2113         S.Context.getFloatTypeSemantics(FromType);
2114     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2115     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2116          &ToSem == &llvm::APFloat::IEEEquad()) ||
2117         (&FromSem == &llvm::APFloat::IEEEquad() &&
2118          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2119       return false;
2120 
2121     // Floating point conversions (C++ 4.8).
2122     SCS.Second = ICK_Floating_Conversion;
2123     FromType = ToType.getUnqualifiedType();
2124   } else if ((FromType->isRealFloatingType() &&
2125               ToType->isIntegralType(S.Context)) ||
2126              (FromType->isIntegralOrUnscopedEnumerationType() &&
2127               ToType->isRealFloatingType())) {
2128 
2129     // Floating-integral conversions (C++ 4.9).
2130     SCS.Second = ICK_Floating_Integral;
2131     FromType = ToType.getUnqualifiedType();
2132   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2133     SCS.Second = ICK_Block_Pointer_Conversion;
2134   } else if (AllowObjCWritebackConversion &&
2135              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2136     SCS.Second = ICK_Writeback_Conversion;
2137   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2138                                    FromType, IncompatibleObjC)) {
2139     // Pointer conversions (C++ 4.10).
2140     SCS.Second = ICK_Pointer_Conversion;
2141     SCS.IncompatibleObjC = IncompatibleObjC;
2142     FromType = FromType.getUnqualifiedType();
2143   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2144                                          InOverloadResolution, FromType)) {
2145     // Pointer to member conversions (4.11).
2146     SCS.Second = ICK_Pointer_Member;
2147   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
2148                                 InOverloadResolution, CStyle)) {
2149     SCS.Second = SecondICK;
2150     FromType = ToType.getUnqualifiedType();
2151   } else if (!S.getLangOpts().CPlusPlus &&
2152              S.Context.typesAreCompatible(ToType, FromType)) {
2153     // Compatible conversions (Clang extension for C function overloading)
2154     SCS.Second = ICK_Compatible_Conversion;
2155     FromType = ToType.getUnqualifiedType();
2156   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
2157                                              InOverloadResolution,
2158                                              SCS, CStyle)) {
2159     SCS.Second = ICK_TransparentUnionConversion;
2160     FromType = ToType;
2161   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2162                                  CStyle)) {
2163     // tryAtomicConversion has updated the standard conversion sequence
2164     // appropriately.
2165     return true;
2166   } else if (ToType->isEventT() &&
2167              From->isIntegerConstantExpr(S.getASTContext()) &&
2168              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2169     SCS.Second = ICK_Zero_Event_Conversion;
2170     FromType = ToType;
2171   } else if (ToType->isQueueT() &&
2172              From->isIntegerConstantExpr(S.getASTContext()) &&
2173              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2174     SCS.Second = ICK_Zero_Queue_Conversion;
2175     FromType = ToType;
2176   } else if (ToType->isSamplerT() &&
2177              From->isIntegerConstantExpr(S.getASTContext())) {
2178     SCS.Second = ICK_Compatible_Conversion;
2179     FromType = ToType;
2180   } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) {
2181     SCS.Second = ICK_Fixed_Point_Conversion;
2182     FromType = ToType;
2183   } else {
2184     // No second conversion required.
2185     SCS.Second = ICK_Identity;
2186   }
2187   SCS.setToType(1, FromType);
2188 
2189   // The third conversion can be a function pointer conversion or a
2190   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2191   bool ObjCLifetimeConversion;
2192   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2193     // Function pointer conversions (removing 'noexcept') including removal of
2194     // 'noreturn' (Clang extension).
2195     SCS.Third = ICK_Function_Conversion;
2196   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2197                                          ObjCLifetimeConversion)) {
2198     SCS.Third = ICK_Qualification;
2199     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2200     FromType = ToType;
2201   } else {
2202     // No conversion required
2203     SCS.Third = ICK_Identity;
2204   }
2205 
2206   // C++ [over.best.ics]p6:
2207   //   [...] Any difference in top-level cv-qualification is
2208   //   subsumed by the initialization itself and does not constitute
2209   //   a conversion. [...]
2210   QualType CanonFrom = S.Context.getCanonicalType(FromType);
2211   QualType CanonTo = S.Context.getCanonicalType(ToType);
2212   if (CanonFrom.getLocalUnqualifiedType()
2213                                      == CanonTo.getLocalUnqualifiedType() &&
2214       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2215     FromType = ToType;
2216     CanonFrom = CanonTo;
2217   }
2218 
2219   SCS.setToType(2, FromType);
2220 
2221   if (CanonFrom == CanonTo)
2222     return true;
2223 
2224   // If we have not converted the argument type to the parameter type,
2225   // this is a bad conversion sequence, unless we're resolving an overload in C.
2226   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2227     return false;
2228 
2229   ExprResult ER = ExprResult{From};
2230   Sema::AssignConvertType Conv =
2231       S.CheckSingleAssignmentConstraints(ToType, ER,
2232                                          /*Diagnose=*/false,
2233                                          /*DiagnoseCFAudited=*/false,
2234                                          /*ConvertRHS=*/false);
2235   ImplicitConversionKind SecondConv;
2236   switch (Conv) {
2237   case Sema::Compatible:
2238     SecondConv = ICK_C_Only_Conversion;
2239     break;
2240   // For our purposes, discarding qualifiers is just as bad as using an
2241   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2242   // qualifiers, as well.
2243   case Sema::CompatiblePointerDiscardsQualifiers:
2244   case Sema::IncompatiblePointer:
2245   case Sema::IncompatiblePointerSign:
2246     SecondConv = ICK_Incompatible_Pointer_Conversion;
2247     break;
2248   default:
2249     return false;
2250   }
2251 
2252   // First can only be an lvalue conversion, so we pretend that this was the
2253   // second conversion. First should already be valid from earlier in the
2254   // function.
2255   SCS.Second = SecondConv;
2256   SCS.setToType(1, ToType);
2257 
2258   // Third is Identity, because Second should rank us worse than any other
2259   // conversion. This could also be ICK_Qualification, but it's simpler to just
2260   // lump everything in with the second conversion, and we don't gain anything
2261   // from making this ICK_Qualification.
2262   SCS.Third = ICK_Identity;
2263   SCS.setToType(2, ToType);
2264   return true;
2265 }
2266 
2267 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)2268 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2269                                      QualType &ToType,
2270                                      bool InOverloadResolution,
2271                                      StandardConversionSequence &SCS,
2272                                      bool CStyle) {
2273 
2274   const RecordType *UT = ToType->getAsUnionType();
2275   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2276     return false;
2277   // The field to initialize within the transparent union.
2278   RecordDecl *UD = UT->getDecl();
2279   // It's compatible if the expression matches any of the fields.
2280   for (const auto *it : UD->fields()) {
2281     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2282                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2283       ToType = it->getType();
2284       return true;
2285     }
2286   }
2287   return false;
2288 }
2289 
2290 /// IsIntegralPromotion - Determines whether the conversion from the
2291 /// expression From (whose potentially-adjusted type is FromType) to
2292 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2293 /// sets PromotedType to the promoted type.
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)2294 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2295   const BuiltinType *To = ToType->getAs<BuiltinType>();
2296   // All integers are built-in.
2297   if (!To) {
2298     return false;
2299   }
2300 
2301   // An rvalue of type char, signed char, unsigned char, short int, or
2302   // unsigned short int can be converted to an rvalue of type int if
2303   // int can represent all the values of the source type; otherwise,
2304   // the source rvalue can be converted to an rvalue of type unsigned
2305   // int (C++ 4.5p1).
2306   if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2307       !FromType->isEnumeralType()) {
2308     if ( // We can promote any signed, promotable integer type to an int
2309         (FromType->isSignedIntegerType() ||
2310          // We can promote any unsigned integer type whose size is
2311          // less than int to an int.
2312          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2313       return To->getKind() == BuiltinType::Int;
2314     }
2315 
2316     return To->getKind() == BuiltinType::UInt;
2317   }
2318 
2319   // C++11 [conv.prom]p3:
2320   //   A prvalue of an unscoped enumeration type whose underlying type is not
2321   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2322   //   following types that can represent all the values of the enumeration
2323   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2324   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2325   //   long long int. If none of the types in that list can represent all the
2326   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2327   //   type can be converted to an rvalue a prvalue of the extended integer type
2328   //   with lowest integer conversion rank (4.13) greater than the rank of long
2329   //   long in which all the values of the enumeration can be represented. If
2330   //   there are two such extended types, the signed one is chosen.
2331   // C++11 [conv.prom]p4:
2332   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2333   //   can be converted to a prvalue of its underlying type. Moreover, if
2334   //   integral promotion can be applied to its underlying type, a prvalue of an
2335   //   unscoped enumeration type whose underlying type is fixed can also be
2336   //   converted to a prvalue of the promoted underlying type.
2337   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2338     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2339     // provided for a scoped enumeration.
2340     if (FromEnumType->getDecl()->isScoped())
2341       return false;
2342 
2343     // We can perform an integral promotion to the underlying type of the enum,
2344     // even if that's not the promoted type. Note that the check for promoting
2345     // the underlying type is based on the type alone, and does not consider
2346     // the bitfield-ness of the actual source expression.
2347     if (FromEnumType->getDecl()->isFixed()) {
2348       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2349       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2350              IsIntegralPromotion(nullptr, Underlying, ToType);
2351     }
2352 
2353     // We have already pre-calculated the promotion type, so this is trivial.
2354     if (ToType->isIntegerType() &&
2355         isCompleteType(From->getBeginLoc(), FromType))
2356       return Context.hasSameUnqualifiedType(
2357           ToType, FromEnumType->getDecl()->getPromotionType());
2358 
2359     // C++ [conv.prom]p5:
2360     //   If the bit-field has an enumerated type, it is treated as any other
2361     //   value of that type for promotion purposes.
2362     //
2363     // ... so do not fall through into the bit-field checks below in C++.
2364     if (getLangOpts().CPlusPlus)
2365       return false;
2366   }
2367 
2368   // C++0x [conv.prom]p2:
2369   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2370   //   to an rvalue a prvalue of the first of the following types that can
2371   //   represent all the values of its underlying type: int, unsigned int,
2372   //   long int, unsigned long int, long long int, or unsigned long long int.
2373   //   If none of the types in that list can represent all the values of its
2374   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2375   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2376   //   type.
2377   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2378       ToType->isIntegerType()) {
2379     // Determine whether the type we're converting from is signed or
2380     // unsigned.
2381     bool FromIsSigned = FromType->isSignedIntegerType();
2382     uint64_t FromSize = Context.getTypeSize(FromType);
2383 
2384     // The types we'll try to promote to, in the appropriate
2385     // order. Try each of these types.
2386     QualType PromoteTypes[6] = {
2387       Context.IntTy, Context.UnsignedIntTy,
2388       Context.LongTy, Context.UnsignedLongTy ,
2389       Context.LongLongTy, Context.UnsignedLongLongTy
2390     };
2391     for (int Idx = 0; Idx < 6; ++Idx) {
2392       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2393       if (FromSize < ToSize ||
2394           (FromSize == ToSize &&
2395            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2396         // We found the type that we can promote to. If this is the
2397         // type we wanted, we have a promotion. Otherwise, no
2398         // promotion.
2399         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2400       }
2401     }
2402   }
2403 
2404   // An rvalue for an integral bit-field (9.6) can be converted to an
2405   // rvalue of type int if int can represent all the values of the
2406   // bit-field; otherwise, it can be converted to unsigned int if
2407   // unsigned int can represent all the values of the bit-field. If
2408   // the bit-field is larger yet, no integral promotion applies to
2409   // it. If the bit-field has an enumerated type, it is treated as any
2410   // other value of that type for promotion purposes (C++ 4.5p3).
2411   // FIXME: We should delay checking of bit-fields until we actually perform the
2412   // conversion.
2413   //
2414   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2415   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2416   // bit-fields and those whose underlying type is larger than int) for GCC
2417   // compatibility.
2418   if (From) {
2419     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2420       std::optional<llvm::APSInt> BitWidth;
2421       if (FromType->isIntegralType(Context) &&
2422           (BitWidth =
2423                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2424         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2425         ToSize = Context.getTypeSize(ToType);
2426 
2427         // Are we promoting to an int from a bitfield that fits in an int?
2428         if (*BitWidth < ToSize ||
2429             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2430           return To->getKind() == BuiltinType::Int;
2431         }
2432 
2433         // Are we promoting to an unsigned int from an unsigned bitfield
2434         // that fits into an unsigned int?
2435         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2436           return To->getKind() == BuiltinType::UInt;
2437         }
2438 
2439         return false;
2440       }
2441     }
2442   }
2443 
2444   // An rvalue of type bool can be converted to an rvalue of type int,
2445   // with false becoming zero and true becoming one (C++ 4.5p4).
2446   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2447     return true;
2448   }
2449 
2450   return false;
2451 }
2452 
2453 /// IsFloatingPointPromotion - Determines whether the conversion from
2454 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2455 /// returns true and sets PromotedType to the promoted type.
IsFloatingPointPromotion(QualType FromType,QualType ToType)2456 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2457   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2458     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2459       /// An rvalue of type float can be converted to an rvalue of type
2460       /// double. (C++ 4.6p1).
2461       if (FromBuiltin->getKind() == BuiltinType::Float &&
2462           ToBuiltin->getKind() == BuiltinType::Double)
2463         return true;
2464 
2465       // C99 6.3.1.5p1:
2466       //   When a float is promoted to double or long double, or a
2467       //   double is promoted to long double [...].
2468       if (!getLangOpts().CPlusPlus &&
2469           (FromBuiltin->getKind() == BuiltinType::Float ||
2470            FromBuiltin->getKind() == BuiltinType::Double) &&
2471           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2472            ToBuiltin->getKind() == BuiltinType::Float128 ||
2473            ToBuiltin->getKind() == BuiltinType::Ibm128))
2474         return true;
2475 
2476       // Half can be promoted to float.
2477       if (!getLangOpts().NativeHalfType &&
2478            FromBuiltin->getKind() == BuiltinType::Half &&
2479           ToBuiltin->getKind() == BuiltinType::Float)
2480         return true;
2481     }
2482 
2483   return false;
2484 }
2485 
2486 /// Determine if a conversion is a complex promotion.
2487 ///
2488 /// A complex promotion is defined as a complex -> complex conversion
2489 /// where the conversion between the underlying real types is a
2490 /// floating-point or integral promotion.
IsComplexPromotion(QualType FromType,QualType ToType)2491 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2492   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2493   if (!FromComplex)
2494     return false;
2495 
2496   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2497   if (!ToComplex)
2498     return false;
2499 
2500   return IsFloatingPointPromotion(FromComplex->getElementType(),
2501                                   ToComplex->getElementType()) ||
2502     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2503                         ToComplex->getElementType());
2504 }
2505 
2506 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2507 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2508 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2509 /// if non-empty, will be a pointer to ToType that may or may not have
2510 /// the right set of qualifiers on its pointee.
2511 ///
2512 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)2513 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2514                                    QualType ToPointee, QualType ToType,
2515                                    ASTContext &Context,
2516                                    bool StripObjCLifetime = false) {
2517   assert((FromPtr->getTypeClass() == Type::Pointer ||
2518           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2519          "Invalid similarly-qualified pointer type");
2520 
2521   /// Conversions to 'id' subsume cv-qualifier conversions.
2522   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2523     return ToType.getUnqualifiedType();
2524 
2525   QualType CanonFromPointee
2526     = Context.getCanonicalType(FromPtr->getPointeeType());
2527   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2528   Qualifiers Quals = CanonFromPointee.getQualifiers();
2529 
2530   if (StripObjCLifetime)
2531     Quals.removeObjCLifetime();
2532 
2533   // Exact qualifier match -> return the pointer type we're converting to.
2534   if (CanonToPointee.getLocalQualifiers() == Quals) {
2535     // ToType is exactly what we need. Return it.
2536     if (!ToType.isNull())
2537       return ToType.getUnqualifiedType();
2538 
2539     // Build a pointer to ToPointee. It has the right qualifiers
2540     // already.
2541     if (isa<ObjCObjectPointerType>(ToType))
2542       return Context.getObjCObjectPointerType(ToPointee);
2543     return Context.getPointerType(ToPointee);
2544   }
2545 
2546   // Just build a canonical type that has the right qualifiers.
2547   QualType QualifiedCanonToPointee
2548     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2549 
2550   if (isa<ObjCObjectPointerType>(ToType))
2551     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2552   return Context.getPointerType(QualifiedCanonToPointee);
2553 }
2554 
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)2555 static bool isNullPointerConstantForConversion(Expr *Expr,
2556                                                bool InOverloadResolution,
2557                                                ASTContext &Context) {
2558   // Handle value-dependent integral null pointer constants correctly.
2559   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2560   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2561       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2562     return !InOverloadResolution;
2563 
2564   return Expr->isNullPointerConstant(Context,
2565                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2566                                         : Expr::NPC_ValueDependentIsNull);
2567 }
2568 
2569 /// IsPointerConversion - Determines whether the conversion of the
2570 /// expression From, which has the (possibly adjusted) type FromType,
2571 /// can be converted to the type ToType via a pointer conversion (C++
2572 /// 4.10). If so, returns true and places the converted type (that
2573 /// might differ from ToType in its cv-qualifiers at some level) into
2574 /// ConvertedType.
2575 ///
2576 /// This routine also supports conversions to and from block pointers
2577 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2578 /// pointers to interfaces. FIXME: Once we've determined the
2579 /// appropriate overloading rules for Objective-C, we may want to
2580 /// split the Objective-C checks into a different routine; however,
2581 /// GCC seems to consider all of these conversions to be pointer
2582 /// conversions, so for now they live here. IncompatibleObjC will be
2583 /// set if the conversion is an allowed Objective-C conversion that
2584 /// should result in a warning.
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)2585 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2586                                bool InOverloadResolution,
2587                                QualType& ConvertedType,
2588                                bool &IncompatibleObjC) {
2589   IncompatibleObjC = false;
2590   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2591                               IncompatibleObjC))
2592     return true;
2593 
2594   // Conversion from a null pointer constant to any Objective-C pointer type.
2595   if (ToType->isObjCObjectPointerType() &&
2596       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2597     ConvertedType = ToType;
2598     return true;
2599   }
2600 
2601   // Blocks: Block pointers can be converted to void*.
2602   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2603       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2604     ConvertedType = ToType;
2605     return true;
2606   }
2607   // Blocks: A null pointer constant can be converted to a block
2608   // pointer type.
2609   if (ToType->isBlockPointerType() &&
2610       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2611     ConvertedType = ToType;
2612     return true;
2613   }
2614 
2615   // If the left-hand-side is nullptr_t, the right side can be a null
2616   // pointer constant.
2617   if (ToType->isNullPtrType() &&
2618       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2619     ConvertedType = ToType;
2620     return true;
2621   }
2622 
2623   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2624   if (!ToTypePtr)
2625     return false;
2626 
2627   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2628   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2629     ConvertedType = ToType;
2630     return true;
2631   }
2632 
2633   // Beyond this point, both types need to be pointers
2634   // , including objective-c pointers.
2635   QualType ToPointeeType = ToTypePtr->getPointeeType();
2636   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2637       !getLangOpts().ObjCAutoRefCount) {
2638     ConvertedType = BuildSimilarlyQualifiedPointerType(
2639         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2640         Context);
2641     return true;
2642   }
2643   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2644   if (!FromTypePtr)
2645     return false;
2646 
2647   QualType FromPointeeType = FromTypePtr->getPointeeType();
2648 
2649   // If the unqualified pointee types are the same, this can't be a
2650   // pointer conversion, so don't do all of the work below.
2651   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2652     return false;
2653 
2654   // An rvalue of type "pointer to cv T," where T is an object type,
2655   // can be converted to an rvalue of type "pointer to cv void" (C++
2656   // 4.10p2).
2657   if (FromPointeeType->isIncompleteOrObjectType() &&
2658       ToPointeeType->isVoidType()) {
2659     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2660                                                        ToPointeeType,
2661                                                        ToType, Context,
2662                                                    /*StripObjCLifetime=*/true);
2663     return true;
2664   }
2665 
2666   // MSVC allows implicit function to void* type conversion.
2667   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2668       ToPointeeType->isVoidType()) {
2669     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2670                                                        ToPointeeType,
2671                                                        ToType, Context);
2672     return true;
2673   }
2674 
2675   // When we're overloading in C, we allow a special kind of pointer
2676   // conversion for compatible-but-not-identical pointee types.
2677   if (!getLangOpts().CPlusPlus &&
2678       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2679     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2680                                                        ToPointeeType,
2681                                                        ToType, Context);
2682     return true;
2683   }
2684 
2685   // C++ [conv.ptr]p3:
2686   //
2687   //   An rvalue of type "pointer to cv D," where D is a class type,
2688   //   can be converted to an rvalue of type "pointer to cv B," where
2689   //   B is a base class (clause 10) of D. If B is an inaccessible
2690   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2691   //   necessitates this conversion is ill-formed. The result of the
2692   //   conversion is a pointer to the base class sub-object of the
2693   //   derived class object. The null pointer value is converted to
2694   //   the null pointer value of the destination type.
2695   //
2696   // Note that we do not check for ambiguity or inaccessibility
2697   // here. That is handled by CheckPointerConversion.
2698   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2699       ToPointeeType->isRecordType() &&
2700       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2701       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2702     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2703                                                        ToPointeeType,
2704                                                        ToType, Context);
2705     return true;
2706   }
2707 
2708   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2709       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2710     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2711                                                        ToPointeeType,
2712                                                        ToType, Context);
2713     return true;
2714   }
2715 
2716   return false;
2717 }
2718 
2719 /// Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)2720 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2721   Qualifiers TQs = T.getQualifiers();
2722 
2723   // Check whether qualifiers already match.
2724   if (TQs == Qs)
2725     return T;
2726 
2727   if (Qs.compatiblyIncludes(TQs))
2728     return Context.getQualifiedType(T, Qs);
2729 
2730   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2731 }
2732 
2733 /// isObjCPointerConversion - Determines whether this is an
2734 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2735 /// with the same arguments and return values.
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)2736 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2737                                    QualType& ConvertedType,
2738                                    bool &IncompatibleObjC) {
2739   if (!getLangOpts().ObjC)
2740     return false;
2741 
2742   // The set of qualifiers on the type we're converting from.
2743   Qualifiers FromQualifiers = FromType.getQualifiers();
2744 
2745   // First, we handle all conversions on ObjC object pointer types.
2746   const ObjCObjectPointerType* ToObjCPtr =
2747     ToType->getAs<ObjCObjectPointerType>();
2748   const ObjCObjectPointerType *FromObjCPtr =
2749     FromType->getAs<ObjCObjectPointerType>();
2750 
2751   if (ToObjCPtr && FromObjCPtr) {
2752     // If the pointee types are the same (ignoring qualifications),
2753     // then this is not a pointer conversion.
2754     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2755                                        FromObjCPtr->getPointeeType()))
2756       return false;
2757 
2758     // Conversion between Objective-C pointers.
2759     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2760       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2761       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2762       if (getLangOpts().CPlusPlus && LHS && RHS &&
2763           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2764                                                 FromObjCPtr->getPointeeType()))
2765         return false;
2766       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2767                                                    ToObjCPtr->getPointeeType(),
2768                                                          ToType, Context);
2769       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2770       return true;
2771     }
2772 
2773     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2774       // Okay: this is some kind of implicit downcast of Objective-C
2775       // interfaces, which is permitted. However, we're going to
2776       // complain about it.
2777       IncompatibleObjC = true;
2778       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2779                                                    ToObjCPtr->getPointeeType(),
2780                                                          ToType, Context);
2781       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2782       return true;
2783     }
2784   }
2785   // Beyond this point, both types need to be C pointers or block pointers.
2786   QualType ToPointeeType;
2787   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2788     ToPointeeType = ToCPtr->getPointeeType();
2789   else if (const BlockPointerType *ToBlockPtr =
2790             ToType->getAs<BlockPointerType>()) {
2791     // Objective C++: We're able to convert from a pointer to any object
2792     // to a block pointer type.
2793     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2794       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2795       return true;
2796     }
2797     ToPointeeType = ToBlockPtr->getPointeeType();
2798   }
2799   else if (FromType->getAs<BlockPointerType>() &&
2800            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2801     // Objective C++: We're able to convert from a block pointer type to a
2802     // pointer to any object.
2803     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2804     return true;
2805   }
2806   else
2807     return false;
2808 
2809   QualType FromPointeeType;
2810   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2811     FromPointeeType = FromCPtr->getPointeeType();
2812   else if (const BlockPointerType *FromBlockPtr =
2813            FromType->getAs<BlockPointerType>())
2814     FromPointeeType = FromBlockPtr->getPointeeType();
2815   else
2816     return false;
2817 
2818   // If we have pointers to pointers, recursively check whether this
2819   // is an Objective-C conversion.
2820   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2821       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2822                               IncompatibleObjC)) {
2823     // We always complain about this conversion.
2824     IncompatibleObjC = true;
2825     ConvertedType = Context.getPointerType(ConvertedType);
2826     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2827     return true;
2828   }
2829   // Allow conversion of pointee being objective-c pointer to another one;
2830   // as in I* to id.
2831   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2832       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2833       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2834                               IncompatibleObjC)) {
2835 
2836     ConvertedType = Context.getPointerType(ConvertedType);
2837     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2838     return true;
2839   }
2840 
2841   // If we have pointers to functions or blocks, check whether the only
2842   // differences in the argument and result types are in Objective-C
2843   // pointer conversions. If so, we permit the conversion (but
2844   // complain about it).
2845   const FunctionProtoType *FromFunctionType
2846     = FromPointeeType->getAs<FunctionProtoType>();
2847   const FunctionProtoType *ToFunctionType
2848     = ToPointeeType->getAs<FunctionProtoType>();
2849   if (FromFunctionType && ToFunctionType) {
2850     // If the function types are exactly the same, this isn't an
2851     // Objective-C pointer conversion.
2852     if (Context.getCanonicalType(FromPointeeType)
2853           == Context.getCanonicalType(ToPointeeType))
2854       return false;
2855 
2856     // Perform the quick checks that will tell us whether these
2857     // function types are obviously different.
2858     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2859         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2860         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2861       return false;
2862 
2863     bool HasObjCConversion = false;
2864     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2865         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2866       // Okay, the types match exactly. Nothing to do.
2867     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2868                                        ToFunctionType->getReturnType(),
2869                                        ConvertedType, IncompatibleObjC)) {
2870       // Okay, we have an Objective-C pointer conversion.
2871       HasObjCConversion = true;
2872     } else {
2873       // Function types are too different. Abort.
2874       return false;
2875     }
2876 
2877     // Check argument types.
2878     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2879          ArgIdx != NumArgs; ++ArgIdx) {
2880       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2881       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2882       if (Context.getCanonicalType(FromArgType)
2883             == Context.getCanonicalType(ToArgType)) {
2884         // Okay, the types match exactly. Nothing to do.
2885       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2886                                          ConvertedType, IncompatibleObjC)) {
2887         // Okay, we have an Objective-C pointer conversion.
2888         HasObjCConversion = true;
2889       } else {
2890         // Argument types are too different. Abort.
2891         return false;
2892       }
2893     }
2894 
2895     if (HasObjCConversion) {
2896       // We had an Objective-C conversion. Allow this pointer
2897       // conversion, but complain about it.
2898       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2899       IncompatibleObjC = true;
2900       return true;
2901     }
2902   }
2903 
2904   return false;
2905 }
2906 
2907 /// Determine whether this is an Objective-C writeback conversion,
2908 /// used for parameter passing when performing automatic reference counting.
2909 ///
2910 /// \param FromType The type we're converting form.
2911 ///
2912 /// \param ToType The type we're converting to.
2913 ///
2914 /// \param ConvertedType The type that will be produced after applying
2915 /// this conversion.
isObjCWritebackConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2916 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2917                                      QualType &ConvertedType) {
2918   if (!getLangOpts().ObjCAutoRefCount ||
2919       Context.hasSameUnqualifiedType(FromType, ToType))
2920     return false;
2921 
2922   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2923   QualType ToPointee;
2924   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2925     ToPointee = ToPointer->getPointeeType();
2926   else
2927     return false;
2928 
2929   Qualifiers ToQuals = ToPointee.getQualifiers();
2930   if (!ToPointee->isObjCLifetimeType() ||
2931       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2932       !ToQuals.withoutObjCLifetime().empty())
2933     return false;
2934 
2935   // Argument must be a pointer to __strong to __weak.
2936   QualType FromPointee;
2937   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2938     FromPointee = FromPointer->getPointeeType();
2939   else
2940     return false;
2941 
2942   Qualifiers FromQuals = FromPointee.getQualifiers();
2943   if (!FromPointee->isObjCLifetimeType() ||
2944       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2945        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2946     return false;
2947 
2948   // Make sure that we have compatible qualifiers.
2949   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2950   if (!ToQuals.compatiblyIncludes(FromQuals))
2951     return false;
2952 
2953   // Remove qualifiers from the pointee type we're converting from; they
2954   // aren't used in the compatibility check belong, and we'll be adding back
2955   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2956   FromPointee = FromPointee.getUnqualifiedType();
2957 
2958   // The unqualified form of the pointee types must be compatible.
2959   ToPointee = ToPointee.getUnqualifiedType();
2960   bool IncompatibleObjC;
2961   if (Context.typesAreCompatible(FromPointee, ToPointee))
2962     FromPointee = ToPointee;
2963   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2964                                     IncompatibleObjC))
2965     return false;
2966 
2967   /// Construct the type we're converting to, which is a pointer to
2968   /// __autoreleasing pointee.
2969   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2970   ConvertedType = Context.getPointerType(FromPointee);
2971   return true;
2972 }
2973 
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2974 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2975                                     QualType& ConvertedType) {
2976   QualType ToPointeeType;
2977   if (const BlockPointerType *ToBlockPtr =
2978         ToType->getAs<BlockPointerType>())
2979     ToPointeeType = ToBlockPtr->getPointeeType();
2980   else
2981     return false;
2982 
2983   QualType FromPointeeType;
2984   if (const BlockPointerType *FromBlockPtr =
2985       FromType->getAs<BlockPointerType>())
2986     FromPointeeType = FromBlockPtr->getPointeeType();
2987   else
2988     return false;
2989   // We have pointer to blocks, check whether the only
2990   // differences in the argument and result types are in Objective-C
2991   // pointer conversions. If so, we permit the conversion.
2992 
2993   const FunctionProtoType *FromFunctionType
2994     = FromPointeeType->getAs<FunctionProtoType>();
2995   const FunctionProtoType *ToFunctionType
2996     = ToPointeeType->getAs<FunctionProtoType>();
2997 
2998   if (!FromFunctionType || !ToFunctionType)
2999     return false;
3000 
3001   if (Context.hasSameType(FromPointeeType, ToPointeeType))
3002     return true;
3003 
3004   // Perform the quick checks that will tell us whether these
3005   // function types are obviously different.
3006   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3007       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3008     return false;
3009 
3010   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3011   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3012   if (FromEInfo != ToEInfo)
3013     return false;
3014 
3015   bool IncompatibleObjC = false;
3016   if (Context.hasSameType(FromFunctionType->getReturnType(),
3017                           ToFunctionType->getReturnType())) {
3018     // Okay, the types match exactly. Nothing to do.
3019   } else {
3020     QualType RHS = FromFunctionType->getReturnType();
3021     QualType LHS = ToFunctionType->getReturnType();
3022     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3023         !RHS.hasQualifiers() && LHS.hasQualifiers())
3024        LHS = LHS.getUnqualifiedType();
3025 
3026      if (Context.hasSameType(RHS,LHS)) {
3027        // OK exact match.
3028      } else if (isObjCPointerConversion(RHS, LHS,
3029                                         ConvertedType, IncompatibleObjC)) {
3030      if (IncompatibleObjC)
3031        return false;
3032      // Okay, we have an Objective-C pointer conversion.
3033      }
3034      else
3035        return false;
3036    }
3037 
3038    // Check argument types.
3039    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3040         ArgIdx != NumArgs; ++ArgIdx) {
3041      IncompatibleObjC = false;
3042      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3043      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3044      if (Context.hasSameType(FromArgType, ToArgType)) {
3045        // Okay, the types match exactly. Nothing to do.
3046      } else if (isObjCPointerConversion(ToArgType, FromArgType,
3047                                         ConvertedType, IncompatibleObjC)) {
3048        if (IncompatibleObjC)
3049          return false;
3050        // Okay, we have an Objective-C pointer conversion.
3051      } else
3052        // Argument types are too different. Abort.
3053        return false;
3054    }
3055 
3056    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3057    bool CanUseToFPT, CanUseFromFPT;
3058    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3059                                       CanUseToFPT, CanUseFromFPT,
3060                                       NewParamInfos))
3061      return false;
3062 
3063    ConvertedType = ToType;
3064    return true;
3065 }
3066 
3067 enum {
3068   ft_default,
3069   ft_different_class,
3070   ft_parameter_arity,
3071   ft_parameter_mismatch,
3072   ft_return_type,
3073   ft_qualifer_mismatch,
3074   ft_noexcept
3075 };
3076 
3077 /// Attempts to get the FunctionProtoType from a Type. Handles
3078 /// MemberFunctionPointers properly.
tryGetFunctionProtoType(QualType FromType)3079 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3080   if (auto *FPT = FromType->getAs<FunctionProtoType>())
3081     return FPT;
3082 
3083   if (auto *MPT = FromType->getAs<MemberPointerType>())
3084     return MPT->getPointeeType()->getAs<FunctionProtoType>();
3085 
3086   return nullptr;
3087 }
3088 
3089 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3090 /// function types.  Catches different number of parameter, mismatch in
3091 /// parameter types, and different return types.
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)3092 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3093                                       QualType FromType, QualType ToType) {
3094   // If either type is not valid, include no extra info.
3095   if (FromType.isNull() || ToType.isNull()) {
3096     PDiag << ft_default;
3097     return;
3098   }
3099 
3100   // Get the function type from the pointers.
3101   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3102     const auto *FromMember = FromType->castAs<MemberPointerType>(),
3103                *ToMember = ToType->castAs<MemberPointerType>();
3104     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3105       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3106             << QualType(FromMember->getClass(), 0);
3107       return;
3108     }
3109     FromType = FromMember->getPointeeType();
3110     ToType = ToMember->getPointeeType();
3111   }
3112 
3113   if (FromType->isPointerType())
3114     FromType = FromType->getPointeeType();
3115   if (ToType->isPointerType())
3116     ToType = ToType->getPointeeType();
3117 
3118   // Remove references.
3119   FromType = FromType.getNonReferenceType();
3120   ToType = ToType.getNonReferenceType();
3121 
3122   // Don't print extra info for non-specialized template functions.
3123   if (FromType->isInstantiationDependentType() &&
3124       !FromType->getAs<TemplateSpecializationType>()) {
3125     PDiag << ft_default;
3126     return;
3127   }
3128 
3129   // No extra info for same types.
3130   if (Context.hasSameType(FromType, ToType)) {
3131     PDiag << ft_default;
3132     return;
3133   }
3134 
3135   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3136                           *ToFunction = tryGetFunctionProtoType(ToType);
3137 
3138   // Both types need to be function types.
3139   if (!FromFunction || !ToFunction) {
3140     PDiag << ft_default;
3141     return;
3142   }
3143 
3144   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3145     PDiag << ft_parameter_arity << ToFunction->getNumParams()
3146           << FromFunction->getNumParams();
3147     return;
3148   }
3149 
3150   // Handle different parameter types.
3151   unsigned ArgPos;
3152   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3153     PDiag << ft_parameter_mismatch << ArgPos + 1
3154           << ToFunction->getParamType(ArgPos)
3155           << FromFunction->getParamType(ArgPos);
3156     return;
3157   }
3158 
3159   // Handle different return type.
3160   if (!Context.hasSameType(FromFunction->getReturnType(),
3161                            ToFunction->getReturnType())) {
3162     PDiag << ft_return_type << ToFunction->getReturnType()
3163           << FromFunction->getReturnType();
3164     return;
3165   }
3166 
3167   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3168     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3169           << FromFunction->getMethodQuals();
3170     return;
3171   }
3172 
3173   // Handle exception specification differences on canonical type (in C++17
3174   // onwards).
3175   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3176           ->isNothrow() !=
3177       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3178           ->isNothrow()) {
3179     PDiag << ft_noexcept;
3180     return;
3181   }
3182 
3183   // Unable to find a difference, so add no extra info.
3184   PDiag << ft_default;
3185 }
3186 
3187 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3188 /// for equality of their parameter types. Caller has already checked that
3189 /// they have same number of parameters.  If the parameters are different,
3190 /// ArgPos will have the parameter index of the first different parameter.
3191 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3192 /// reverse order. That's useful if one of the functions is being used as a C++20
3193 /// synthesized operator overload with a reversed parameter order.
FunctionParamTypesAreEqual(ArrayRef<QualType> Old,ArrayRef<QualType> New,unsigned * ArgPos,bool Reversed)3194 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3195                                       ArrayRef<QualType> New, unsigned *ArgPos,
3196                                       bool Reversed) {
3197   assert(llvm::size(Old) == llvm::size(New) &&
3198          "Can't compare parameters of functions with different number of "
3199          "parameters!");
3200 
3201   for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3202     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3203     size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3204 
3205     // Ignore address spaces in pointee type. This is to disallow overloading
3206     // on __ptr32/__ptr64 address spaces.
3207     QualType OldType =
3208         Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3209     QualType NewType =
3210         Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3211 
3212     if (!Context.hasSameType(OldType, NewType)) {
3213       if (ArgPos)
3214         *ArgPos = Idx;
3215       return false;
3216     }
3217   }
3218   return true;
3219 }
3220 
FunctionParamTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos,bool Reversed)3221 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3222                                       const FunctionProtoType *NewType,
3223                                       unsigned *ArgPos, bool Reversed) {
3224   return FunctionParamTypesAreEqual(OldType->param_types(),
3225                                     NewType->param_types(), ArgPos, Reversed);
3226 }
3227 
FunctionNonObjectParamTypesAreEqual(const FunctionDecl * OldFunction,const FunctionDecl * NewFunction,unsigned * ArgPos,bool Reversed)3228 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3229                                                const FunctionDecl *NewFunction,
3230                                                unsigned *ArgPos,
3231                                                bool Reversed) {
3232 
3233   if (OldFunction->getNumNonObjectParams() !=
3234       NewFunction->getNumNonObjectParams())
3235     return false;
3236 
3237   unsigned OldIgnore =
3238       unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3239   unsigned NewIgnore =
3240       unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3241 
3242   auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3243   auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3244 
3245   return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3246                                     NewPT->param_types().slice(NewIgnore),
3247                                     ArgPos, Reversed);
3248 }
3249 
3250 /// CheckPointerConversion - Check the pointer conversion from the
3251 /// expression From to the type ToType. This routine checks for
3252 /// ambiguous or inaccessible derived-to-base pointer
3253 /// conversions for which IsPointerConversion has already returned
3254 /// true. It returns true and produces a diagnostic if there was an
3255 /// error, or returns false otherwise.
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess,bool Diagnose)3256 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3257                                   CastKind &Kind,
3258                                   CXXCastPath& BasePath,
3259                                   bool IgnoreBaseAccess,
3260                                   bool Diagnose) {
3261   QualType FromType = From->getType();
3262   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3263 
3264   Kind = CK_BitCast;
3265 
3266   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3267       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3268           Expr::NPCK_ZeroExpression) {
3269     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3270       DiagRuntimeBehavior(From->getExprLoc(), From,
3271                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3272                             << ToType << From->getSourceRange());
3273     else if (!isUnevaluatedContext())
3274       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3275         << ToType << From->getSourceRange();
3276   }
3277   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3278     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3279       QualType FromPointeeType = FromPtrType->getPointeeType(),
3280                ToPointeeType   = ToPtrType->getPointeeType();
3281 
3282       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3283           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3284         // We must have a derived-to-base conversion. Check an
3285         // ambiguous or inaccessible conversion.
3286         unsigned InaccessibleID = 0;
3287         unsigned AmbiguousID = 0;
3288         if (Diagnose) {
3289           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3290           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3291         }
3292         if (CheckDerivedToBaseConversion(
3293                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3294                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3295                 &BasePath, IgnoreBaseAccess))
3296           return true;
3297 
3298         // The conversion was successful.
3299         Kind = CK_DerivedToBase;
3300       }
3301 
3302       if (Diagnose && !IsCStyleOrFunctionalCast &&
3303           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3304         assert(getLangOpts().MSVCCompat &&
3305                "this should only be possible with MSVCCompat!");
3306         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3307             << From->getSourceRange();
3308       }
3309     }
3310   } else if (const ObjCObjectPointerType *ToPtrType =
3311                ToType->getAs<ObjCObjectPointerType>()) {
3312     if (const ObjCObjectPointerType *FromPtrType =
3313           FromType->getAs<ObjCObjectPointerType>()) {
3314       // Objective-C++ conversions are always okay.
3315       // FIXME: We should have a different class of conversions for the
3316       // Objective-C++ implicit conversions.
3317       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3318         return false;
3319     } else if (FromType->isBlockPointerType()) {
3320       Kind = CK_BlockPointerToObjCPointerCast;
3321     } else {
3322       Kind = CK_CPointerToObjCPointerCast;
3323     }
3324   } else if (ToType->isBlockPointerType()) {
3325     if (!FromType->isBlockPointerType())
3326       Kind = CK_AnyPointerToBlockPointerCast;
3327   }
3328 
3329   // We shouldn't fall into this case unless it's valid for other
3330   // reasons.
3331   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3332     Kind = CK_NullToPointer;
3333 
3334   return false;
3335 }
3336 
3337 /// IsMemberPointerConversion - Determines whether the conversion of the
3338 /// expression From, which has the (possibly adjusted) type FromType, can be
3339 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3340 /// If so, returns true and places the converted type (that might differ from
3341 /// ToType in its cv-qualifiers at some level) into ConvertedType.
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)3342 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3343                                      QualType ToType,
3344                                      bool InOverloadResolution,
3345                                      QualType &ConvertedType) {
3346   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3347   if (!ToTypePtr)
3348     return false;
3349 
3350   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3351   if (From->isNullPointerConstant(Context,
3352                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3353                                         : Expr::NPC_ValueDependentIsNull)) {
3354     ConvertedType = ToType;
3355     return true;
3356   }
3357 
3358   // Otherwise, both types have to be member pointers.
3359   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3360   if (!FromTypePtr)
3361     return false;
3362 
3363   // A pointer to member of B can be converted to a pointer to member of D,
3364   // where D is derived from B (C++ 4.11p2).
3365   QualType FromClass(FromTypePtr->getClass(), 0);
3366   QualType ToClass(ToTypePtr->getClass(), 0);
3367 
3368   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3369       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3370     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3371                                                  ToClass.getTypePtr());
3372     return true;
3373   }
3374 
3375   return false;
3376 }
3377 
3378 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3379 /// expression From to the type ToType. This routine checks for ambiguous or
3380 /// virtual or inaccessible base-to-derived member pointer conversions
3381 /// for which IsMemberPointerConversion has already returned true. It returns
3382 /// true and produces a diagnostic if there was an error, or returns false
3383 /// otherwise.
CheckMemberPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)3384 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3385                                         CastKind &Kind,
3386                                         CXXCastPath &BasePath,
3387                                         bool IgnoreBaseAccess) {
3388   QualType FromType = From->getType();
3389   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3390   if (!FromPtrType) {
3391     // This must be a null pointer to member pointer conversion
3392     assert(From->isNullPointerConstant(Context,
3393                                        Expr::NPC_ValueDependentIsNull) &&
3394            "Expr must be null pointer constant!");
3395     Kind = CK_NullToMemberPointer;
3396     return false;
3397   }
3398 
3399   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3400   assert(ToPtrType && "No member pointer cast has a target type "
3401                       "that is not a member pointer.");
3402 
3403   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3404   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3405 
3406   // FIXME: What about dependent types?
3407   assert(FromClass->isRecordType() && "Pointer into non-class.");
3408   assert(ToClass->isRecordType() && "Pointer into non-class.");
3409 
3410   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3411                      /*DetectVirtual=*/true);
3412   bool DerivationOkay =
3413       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3414   assert(DerivationOkay &&
3415          "Should not have been called if derivation isn't OK.");
3416   (void)DerivationOkay;
3417 
3418   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3419                                   getUnqualifiedType())) {
3420     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3421     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3422       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3423     return true;
3424   }
3425 
3426   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3427     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3428       << FromClass << ToClass << QualType(VBase, 0)
3429       << From->getSourceRange();
3430     return true;
3431   }
3432 
3433   if (!IgnoreBaseAccess)
3434     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3435                          Paths.front(),
3436                          diag::err_downcast_from_inaccessible_base);
3437 
3438   // Must be a base to derived member conversion.
3439   BuildBasePathArray(Paths, BasePath);
3440   Kind = CK_BaseToDerivedMemberPointer;
3441   return false;
3442 }
3443 
3444 /// Determine whether the lifetime conversion between the two given
3445 /// qualifiers sets is nontrivial.
isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,Qualifiers ToQuals)3446 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3447                                                Qualifiers ToQuals) {
3448   // Converting anything to const __unsafe_unretained is trivial.
3449   if (ToQuals.hasConst() &&
3450       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3451     return false;
3452 
3453   return true;
3454 }
3455 
3456 /// Perform a single iteration of the loop for checking if a qualification
3457 /// conversion is valid.
3458 ///
3459 /// Specifically, check whether any change between the qualifiers of \p
3460 /// FromType and \p ToType is permissible, given knowledge about whether every
3461 /// outer layer is const-qualified.
isQualificationConversionStep(QualType FromType,QualType ToType,bool CStyle,bool IsTopLevel,bool & PreviousToQualsIncludeConst,bool & ObjCLifetimeConversion)3462 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3463                                           bool CStyle, bool IsTopLevel,
3464                                           bool &PreviousToQualsIncludeConst,
3465                                           bool &ObjCLifetimeConversion) {
3466   Qualifiers FromQuals = FromType.getQualifiers();
3467   Qualifiers ToQuals = ToType.getQualifiers();
3468 
3469   // Ignore __unaligned qualifier.
3470   FromQuals.removeUnaligned();
3471 
3472   // Objective-C ARC:
3473   //   Check Objective-C lifetime conversions.
3474   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3475     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3476       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3477         ObjCLifetimeConversion = true;
3478       FromQuals.removeObjCLifetime();
3479       ToQuals.removeObjCLifetime();
3480     } else {
3481       // Qualification conversions cannot cast between different
3482       // Objective-C lifetime qualifiers.
3483       return false;
3484     }
3485   }
3486 
3487   // Allow addition/removal of GC attributes but not changing GC attributes.
3488   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3489       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3490     FromQuals.removeObjCGCAttr();
3491     ToQuals.removeObjCGCAttr();
3492   }
3493 
3494   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3495   //      2,j, and similarly for volatile.
3496   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3497     return false;
3498 
3499   // If address spaces mismatch:
3500   //  - in top level it is only valid to convert to addr space that is a
3501   //    superset in all cases apart from C-style casts where we allow
3502   //    conversions between overlapping address spaces.
3503   //  - in non-top levels it is not a valid conversion.
3504   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3505       (!IsTopLevel ||
3506        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3507          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3508     return false;
3509 
3510   //   -- if the cv 1,j and cv 2,j are different, then const is in
3511   //      every cv for 0 < k < j.
3512   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3513       !PreviousToQualsIncludeConst)
3514     return false;
3515 
3516   // The following wording is from C++20, where the result of the conversion
3517   // is T3, not T2.
3518   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3519   //      "array of unknown bound of"
3520   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3521     return false;
3522 
3523   //   -- if the resulting P3,i is different from P1,i [...], then const is
3524   //      added to every cv 3_k for 0 < k < i.
3525   if (!CStyle && FromType->isConstantArrayType() &&
3526       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3527     return false;
3528 
3529   // Keep track of whether all prior cv-qualifiers in the "to" type
3530   // include const.
3531   PreviousToQualsIncludeConst =
3532       PreviousToQualsIncludeConst && ToQuals.hasConst();
3533   return true;
3534 }
3535 
3536 /// IsQualificationConversion - Determines whether the conversion from
3537 /// an rvalue of type FromType to ToType is a qualification conversion
3538 /// (C++ 4.4).
3539 ///
3540 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3541 /// when the qualification conversion involves a change in the Objective-C
3542 /// object lifetime.
3543 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)3544 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3545                                 bool CStyle, bool &ObjCLifetimeConversion) {
3546   FromType = Context.getCanonicalType(FromType);
3547   ToType = Context.getCanonicalType(ToType);
3548   ObjCLifetimeConversion = false;
3549 
3550   // If FromType and ToType are the same type, this is not a
3551   // qualification conversion.
3552   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3553     return false;
3554 
3555   // (C++ 4.4p4):
3556   //   A conversion can add cv-qualifiers at levels other than the first
3557   //   in multi-level pointers, subject to the following rules: [...]
3558   bool PreviousToQualsIncludeConst = true;
3559   bool UnwrappedAnyPointer = false;
3560   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3561     if (!isQualificationConversionStep(
3562             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3563             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3564       return false;
3565     UnwrappedAnyPointer = true;
3566   }
3567 
3568   // We are left with FromType and ToType being the pointee types
3569   // after unwrapping the original FromType and ToType the same number
3570   // of times. If we unwrapped any pointers, and if FromType and
3571   // ToType have the same unqualified type (since we checked
3572   // qualifiers above), then this is a qualification conversion.
3573   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3574 }
3575 
3576 /// - Determine whether this is a conversion from a scalar type to an
3577 /// atomic type.
3578 ///
3579 /// If successful, updates \c SCS's second and third steps in the conversion
3580 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)3581 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3582                                 bool InOverloadResolution,
3583                                 StandardConversionSequence &SCS,
3584                                 bool CStyle) {
3585   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3586   if (!ToAtomic)
3587     return false;
3588 
3589   StandardConversionSequence InnerSCS;
3590   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3591                             InOverloadResolution, InnerSCS,
3592                             CStyle, /*AllowObjCWritebackConversion=*/false))
3593     return false;
3594 
3595   SCS.Second = InnerSCS.Second;
3596   SCS.setToType(1, InnerSCS.getToType(1));
3597   SCS.Third = InnerSCS.Third;
3598   SCS.QualificationIncludesObjCLifetime
3599     = InnerSCS.QualificationIncludesObjCLifetime;
3600   SCS.setToType(2, InnerSCS.getToType(2));
3601   return true;
3602 }
3603 
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)3604 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3605                                               CXXConstructorDecl *Constructor,
3606                                               QualType Type) {
3607   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3608   if (CtorType->getNumParams() > 0) {
3609     QualType FirstArg = CtorType->getParamType(0);
3610     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3611       return true;
3612   }
3613   return false;
3614 }
3615 
3616 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)3617 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3618                                        CXXRecordDecl *To,
3619                                        UserDefinedConversionSequence &User,
3620                                        OverloadCandidateSet &CandidateSet,
3621                                        bool AllowExplicit) {
3622   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3623   for (auto *D : S.LookupConstructors(To)) {
3624     auto Info = getConstructorInfo(D);
3625     if (!Info)
3626       continue;
3627 
3628     bool Usable = !Info.Constructor->isInvalidDecl() &&
3629                   S.isInitListConstructor(Info.Constructor);
3630     if (Usable) {
3631       bool SuppressUserConversions = false;
3632       if (Info.ConstructorTmpl)
3633         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3634                                        /*ExplicitArgs*/ nullptr, From,
3635                                        CandidateSet, SuppressUserConversions,
3636                                        /*PartialOverloading*/ false,
3637                                        AllowExplicit);
3638       else
3639         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3640                                CandidateSet, SuppressUserConversions,
3641                                /*PartialOverloading*/ false, AllowExplicit);
3642     }
3643   }
3644 
3645   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3646 
3647   OverloadCandidateSet::iterator Best;
3648   switch (auto Result =
3649               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3650   case OR_Deleted:
3651   case OR_Success: {
3652     // Record the standard conversion we used and the conversion function.
3653     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3654     QualType ThisType = Constructor->getFunctionObjectParameterType();
3655     // Initializer lists don't have conversions as such.
3656     User.Before.setAsIdentityConversion();
3657     User.HadMultipleCandidates = HadMultipleCandidates;
3658     User.ConversionFunction = Constructor;
3659     User.FoundConversionFunction = Best->FoundDecl;
3660     User.After.setAsIdentityConversion();
3661     User.After.setFromType(ThisType);
3662     User.After.setAllToTypes(ToType);
3663     return Result;
3664   }
3665 
3666   case OR_No_Viable_Function:
3667     return OR_No_Viable_Function;
3668   case OR_Ambiguous:
3669     return OR_Ambiguous;
3670   }
3671 
3672   llvm_unreachable("Invalid OverloadResult!");
3673 }
3674 
3675 /// Determines whether there is a user-defined conversion sequence
3676 /// (C++ [over.ics.user]) that converts expression From to the type
3677 /// ToType. If such a conversion exists, User will contain the
3678 /// user-defined conversion sequence that performs such a conversion
3679 /// and this routine will return true. Otherwise, this routine returns
3680 /// false and User is unspecified.
3681 ///
3682 /// \param AllowExplicit  true if the conversion should consider C++0x
3683 /// "explicit" conversion functions as well as non-explicit conversion
3684 /// functions (C++0x [class.conv.fct]p2).
3685 ///
3686 /// \param AllowObjCConversionOnExplicit true if the conversion should
3687 /// allow an extra Objective-C pointer conversion on uses of explicit
3688 /// constructors. Requires \c AllowExplicit to also be set.
3689 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,AllowedExplicit AllowExplicit,bool AllowObjCConversionOnExplicit)3690 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3691                         UserDefinedConversionSequence &User,
3692                         OverloadCandidateSet &CandidateSet,
3693                         AllowedExplicit AllowExplicit,
3694                         bool AllowObjCConversionOnExplicit) {
3695   assert(AllowExplicit != AllowedExplicit::None ||
3696          !AllowObjCConversionOnExplicit);
3697   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3698 
3699   // Whether we will only visit constructors.
3700   bool ConstructorsOnly = false;
3701 
3702   // If the type we are conversion to is a class type, enumerate its
3703   // constructors.
3704   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3705     // C++ [over.match.ctor]p1:
3706     //   When objects of class type are direct-initialized (8.5), or
3707     //   copy-initialized from an expression of the same or a
3708     //   derived class type (8.5), overload resolution selects the
3709     //   constructor. [...] For copy-initialization, the candidate
3710     //   functions are all the converting constructors (12.3.1) of
3711     //   that class. The argument list is the expression-list within
3712     //   the parentheses of the initializer.
3713     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3714         (From->getType()->getAs<RecordType>() &&
3715          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3716       ConstructorsOnly = true;
3717 
3718     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3719       // We're not going to find any constructors.
3720     } else if (CXXRecordDecl *ToRecordDecl
3721                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3722 
3723       Expr **Args = &From;
3724       unsigned NumArgs = 1;
3725       bool ListInitializing = false;
3726       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3727         // But first, see if there is an init-list-constructor that will work.
3728         OverloadingResult Result = IsInitializerListConstructorConversion(
3729             S, From, ToType, ToRecordDecl, User, CandidateSet,
3730             AllowExplicit == AllowedExplicit::All);
3731         if (Result != OR_No_Viable_Function)
3732           return Result;
3733         // Never mind.
3734         CandidateSet.clear(
3735             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3736 
3737         // If we're list-initializing, we pass the individual elements as
3738         // arguments, not the entire list.
3739         Args = InitList->getInits();
3740         NumArgs = InitList->getNumInits();
3741         ListInitializing = true;
3742       }
3743 
3744       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3745         auto Info = getConstructorInfo(D);
3746         if (!Info)
3747           continue;
3748 
3749         bool Usable = !Info.Constructor->isInvalidDecl();
3750         if (!ListInitializing)
3751           Usable = Usable && Info.Constructor->isConvertingConstructor(
3752                                  /*AllowExplicit*/ true);
3753         if (Usable) {
3754           bool SuppressUserConversions = !ConstructorsOnly;
3755           // C++20 [over.best.ics.general]/4.5:
3756           //   if the target is the first parameter of a constructor [of class
3757           //   X] and the constructor [...] is a candidate by [...] the second
3758           //   phase of [over.match.list] when the initializer list has exactly
3759           //   one element that is itself an initializer list, [...] and the
3760           //   conversion is to X or reference to cv X, user-defined conversion
3761           //   sequences are not cnosidered.
3762           if (SuppressUserConversions && ListInitializing) {
3763             SuppressUserConversions =
3764                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3765                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3766                                                   ToType);
3767           }
3768           if (Info.ConstructorTmpl)
3769             S.AddTemplateOverloadCandidate(
3770                 Info.ConstructorTmpl, Info.FoundDecl,
3771                 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3772                 CandidateSet, SuppressUserConversions,
3773                 /*PartialOverloading*/ false,
3774                 AllowExplicit == AllowedExplicit::All);
3775           else
3776             // Allow one user-defined conversion when user specifies a
3777             // From->ToType conversion via an static cast (c-style, etc).
3778             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3779                                    llvm::ArrayRef(Args, NumArgs), CandidateSet,
3780                                    SuppressUserConversions,
3781                                    /*PartialOverloading*/ false,
3782                                    AllowExplicit == AllowedExplicit::All);
3783         }
3784       }
3785     }
3786   }
3787 
3788   // Enumerate conversion functions, if we're allowed to.
3789   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3790   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3791     // No conversion functions from incomplete types.
3792   } else if (const RecordType *FromRecordType =
3793                  From->getType()->getAs<RecordType>()) {
3794     if (CXXRecordDecl *FromRecordDecl
3795          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3796       // Add all of the conversion functions as candidates.
3797       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3798       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3799         DeclAccessPair FoundDecl = I.getPair();
3800         NamedDecl *D = FoundDecl.getDecl();
3801         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3802         if (isa<UsingShadowDecl>(D))
3803           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3804 
3805         CXXConversionDecl *Conv;
3806         FunctionTemplateDecl *ConvTemplate;
3807         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3808           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3809         else
3810           Conv = cast<CXXConversionDecl>(D);
3811 
3812         if (ConvTemplate)
3813           S.AddTemplateConversionCandidate(
3814               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3815               CandidateSet, AllowObjCConversionOnExplicit,
3816               AllowExplicit != AllowedExplicit::None);
3817         else
3818           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3819                                    CandidateSet, AllowObjCConversionOnExplicit,
3820                                    AllowExplicit != AllowedExplicit::None);
3821       }
3822     }
3823   }
3824 
3825   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3826 
3827   OverloadCandidateSet::iterator Best;
3828   switch (auto Result =
3829               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3830   case OR_Success:
3831   case OR_Deleted:
3832     // Record the standard conversion we used and the conversion function.
3833     if (CXXConstructorDecl *Constructor
3834           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3835       // C++ [over.ics.user]p1:
3836       //   If the user-defined conversion is specified by a
3837       //   constructor (12.3.1), the initial standard conversion
3838       //   sequence converts the source type to the type required by
3839       //   the argument of the constructor.
3840       //
3841       if (isa<InitListExpr>(From)) {
3842         // Initializer lists don't have conversions as such.
3843         User.Before.setAsIdentityConversion();
3844       } else {
3845         if (Best->Conversions[0].isEllipsis())
3846           User.EllipsisConversion = true;
3847         else {
3848           User.Before = Best->Conversions[0].Standard;
3849           User.EllipsisConversion = false;
3850         }
3851       }
3852       User.HadMultipleCandidates = HadMultipleCandidates;
3853       User.ConversionFunction = Constructor;
3854       User.FoundConversionFunction = Best->FoundDecl;
3855       User.After.setAsIdentityConversion();
3856       User.After.setFromType(Constructor->getFunctionObjectParameterType());
3857       User.After.setAllToTypes(ToType);
3858       return Result;
3859     }
3860     if (CXXConversionDecl *Conversion
3861                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3862       // C++ [over.ics.user]p1:
3863       //
3864       //   [...] If the user-defined conversion is specified by a
3865       //   conversion function (12.3.2), the initial standard
3866       //   conversion sequence converts the source type to the
3867       //   implicit object parameter of the conversion function.
3868       User.Before = Best->Conversions[0].Standard;
3869       User.HadMultipleCandidates = HadMultipleCandidates;
3870       User.ConversionFunction = Conversion;
3871       User.FoundConversionFunction = Best->FoundDecl;
3872       User.EllipsisConversion = false;
3873 
3874       // C++ [over.ics.user]p2:
3875       //   The second standard conversion sequence converts the
3876       //   result of the user-defined conversion to the target type
3877       //   for the sequence. Since an implicit conversion sequence
3878       //   is an initialization, the special rules for
3879       //   initialization by user-defined conversion apply when
3880       //   selecting the best user-defined conversion for a
3881       //   user-defined conversion sequence (see 13.3.3 and
3882       //   13.3.3.1).
3883       User.After = Best->FinalConversion;
3884       return Result;
3885     }
3886     llvm_unreachable("Not a constructor or conversion function?");
3887 
3888   case OR_No_Viable_Function:
3889     return OR_No_Viable_Function;
3890 
3891   case OR_Ambiguous:
3892     return OR_Ambiguous;
3893   }
3894 
3895   llvm_unreachable("Invalid OverloadResult!");
3896 }
3897 
3898 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)3899 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3900   ImplicitConversionSequence ICS;
3901   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3902                                     OverloadCandidateSet::CSK_Normal);
3903   OverloadingResult OvResult =
3904     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3905                             CandidateSet, AllowedExplicit::None, false);
3906 
3907   if (!(OvResult == OR_Ambiguous ||
3908         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3909     return false;
3910 
3911   auto Cands = CandidateSet.CompleteCandidates(
3912       *this,
3913       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3914       From);
3915   if (OvResult == OR_Ambiguous)
3916     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3917         << From->getType() << ToType << From->getSourceRange();
3918   else { // OR_No_Viable_Function && !CandidateSet.empty()
3919     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3920                              diag::err_typecheck_nonviable_condition_incomplete,
3921                              From->getType(), From->getSourceRange()))
3922       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3923           << false << From->getType() << From->getSourceRange() << ToType;
3924   }
3925 
3926   CandidateSet.NoteCandidates(
3927                               *this, From, Cands);
3928   return true;
3929 }
3930 
3931 // Helper for compareConversionFunctions that gets the FunctionType that the
3932 // conversion-operator return  value 'points' to, or nullptr.
3933 static const FunctionType *
getConversionOpReturnTyAsFunction(CXXConversionDecl * Conv)3934 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3935   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3936   const PointerType *RetPtrTy =
3937       ConvFuncTy->getReturnType()->getAs<PointerType>();
3938 
3939   if (!RetPtrTy)
3940     return nullptr;
3941 
3942   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3943 }
3944 
3945 /// Compare the user-defined conversion functions or constructors
3946 /// of two user-defined conversion sequences to determine whether any ordering
3947 /// is possible.
3948 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)3949 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3950                            FunctionDecl *Function2) {
3951   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3952   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3953   if (!Conv1 || !Conv2)
3954     return ImplicitConversionSequence::Indistinguishable;
3955 
3956   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3957     return ImplicitConversionSequence::Indistinguishable;
3958 
3959   // Objective-C++:
3960   //   If both conversion functions are implicitly-declared conversions from
3961   //   a lambda closure type to a function pointer and a block pointer,
3962   //   respectively, always prefer the conversion to a function pointer,
3963   //   because the function pointer is more lightweight and is more likely
3964   //   to keep code working.
3965   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3966     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3967     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3968     if (Block1 != Block2)
3969       return Block1 ? ImplicitConversionSequence::Worse
3970                     : ImplicitConversionSequence::Better;
3971   }
3972 
3973   // In order to support multiple calling conventions for the lambda conversion
3974   // operator (such as when the free and member function calling convention is
3975   // different), prefer the 'free' mechanism, followed by the calling-convention
3976   // of operator(). The latter is in place to support the MSVC-like solution of
3977   // defining ALL of the possible conversions in regards to calling-convention.
3978   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3979   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3980 
3981   if (Conv1FuncRet && Conv2FuncRet &&
3982       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3983     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3984     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3985 
3986     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3987     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3988 
3989     CallingConv CallOpCC =
3990         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3991     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3992         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3993     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3994         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3995 
3996     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3997     for (CallingConv CC : PrefOrder) {
3998       if (Conv1CC == CC)
3999         return ImplicitConversionSequence::Better;
4000       if (Conv2CC == CC)
4001         return ImplicitConversionSequence::Worse;
4002     }
4003   }
4004 
4005   return ImplicitConversionSequence::Indistinguishable;
4006 }
4007 
hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence & ICS)4008 static bool hasDeprecatedStringLiteralToCharPtrConversion(
4009     const ImplicitConversionSequence &ICS) {
4010   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4011          (ICS.isUserDefined() &&
4012           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4013 }
4014 
4015 /// CompareImplicitConversionSequences - Compare two implicit
4016 /// conversion sequences to determine whether one is better than the
4017 /// other or if they are indistinguishable (C++ 13.3.3.2).
4018 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,SourceLocation Loc,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)4019 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4020                                    const ImplicitConversionSequence& ICS1,
4021                                    const ImplicitConversionSequence& ICS2)
4022 {
4023   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4024   // conversion sequences (as defined in 13.3.3.1)
4025   //   -- a standard conversion sequence (13.3.3.1.1) is a better
4026   //      conversion sequence than a user-defined conversion sequence or
4027   //      an ellipsis conversion sequence, and
4028   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
4029   //      conversion sequence than an ellipsis conversion sequence
4030   //      (13.3.3.1.3).
4031   //
4032   // C++0x [over.best.ics]p10:
4033   //   For the purpose of ranking implicit conversion sequences as
4034   //   described in 13.3.3.2, the ambiguous conversion sequence is
4035   //   treated as a user-defined sequence that is indistinguishable
4036   //   from any other user-defined conversion sequence.
4037 
4038   // String literal to 'char *' conversion has been deprecated in C++03. It has
4039   // been removed from C++11. We still accept this conversion, if it happens at
4040   // the best viable function. Otherwise, this conversion is considered worse
4041   // than ellipsis conversion. Consider this as an extension; this is not in the
4042   // standard. For example:
4043   //
4044   // int &f(...);    // #1
4045   // void f(char*);  // #2
4046   // void g() { int &r = f("foo"); }
4047   //
4048   // In C++03, we pick #2 as the best viable function.
4049   // In C++11, we pick #1 as the best viable function, because ellipsis
4050   // conversion is better than string-literal to char* conversion (since there
4051   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4052   // convert arguments, #2 would be the best viable function in C++11.
4053   // If the best viable function has this conversion, a warning will be issued
4054   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4055 
4056   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4057       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
4058           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
4059       // Ill-formedness must not differ
4060       ICS1.isBad() == ICS2.isBad())
4061     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
4062                ? ImplicitConversionSequence::Worse
4063                : ImplicitConversionSequence::Better;
4064 
4065   if (ICS1.getKindRank() < ICS2.getKindRank())
4066     return ImplicitConversionSequence::Better;
4067   if (ICS2.getKindRank() < ICS1.getKindRank())
4068     return ImplicitConversionSequence::Worse;
4069 
4070   // The following checks require both conversion sequences to be of
4071   // the same kind.
4072   if (ICS1.getKind() != ICS2.getKind())
4073     return ImplicitConversionSequence::Indistinguishable;
4074 
4075   ImplicitConversionSequence::CompareKind Result =
4076       ImplicitConversionSequence::Indistinguishable;
4077 
4078   // Two implicit conversion sequences of the same form are
4079   // indistinguishable conversion sequences unless one of the
4080   // following rules apply: (C++ 13.3.3.2p3):
4081 
4082   // List-initialization sequence L1 is a better conversion sequence than
4083   // list-initialization sequence L2 if:
4084   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4085   //   if not that,
4086   // — L1 and L2 convert to arrays of the same element type, and either the
4087   //   number of elements n_1 initialized by L1 is less than the number of
4088   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4089   //   an array of unknown bound and L1 does not,
4090   // even if one of the other rules in this paragraph would otherwise apply.
4091   if (!ICS1.isBad()) {
4092     bool StdInit1 = false, StdInit2 = false;
4093     if (ICS1.hasInitializerListContainerType())
4094       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
4095                                         nullptr);
4096     if (ICS2.hasInitializerListContainerType())
4097       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
4098                                         nullptr);
4099     if (StdInit1 != StdInit2)
4100       return StdInit1 ? ImplicitConversionSequence::Better
4101                       : ImplicitConversionSequence::Worse;
4102 
4103     if (ICS1.hasInitializerListContainerType() &&
4104         ICS2.hasInitializerListContainerType())
4105       if (auto *CAT1 = S.Context.getAsConstantArrayType(
4106               ICS1.getInitializerListContainerType()))
4107         if (auto *CAT2 = S.Context.getAsConstantArrayType(
4108                 ICS2.getInitializerListContainerType())) {
4109           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4110                                                CAT2->getElementType())) {
4111             // Both to arrays of the same element type
4112             if (CAT1->getSize() != CAT2->getSize())
4113               // Different sized, the smaller wins
4114               return CAT1->getSize().ult(CAT2->getSize())
4115                          ? ImplicitConversionSequence::Better
4116                          : ImplicitConversionSequence::Worse;
4117             if (ICS1.isInitializerListOfIncompleteArray() !=
4118                 ICS2.isInitializerListOfIncompleteArray())
4119               // One is incomplete, it loses
4120               return ICS2.isInitializerListOfIncompleteArray()
4121                          ? ImplicitConversionSequence::Better
4122                          : ImplicitConversionSequence::Worse;
4123           }
4124         }
4125   }
4126 
4127   if (ICS1.isStandard())
4128     // Standard conversion sequence S1 is a better conversion sequence than
4129     // standard conversion sequence S2 if [...]
4130     Result = CompareStandardConversionSequences(S, Loc,
4131                                                 ICS1.Standard, ICS2.Standard);
4132   else if (ICS1.isUserDefined()) {
4133     // User-defined conversion sequence U1 is a better conversion
4134     // sequence than another user-defined conversion sequence U2 if
4135     // they contain the same user-defined conversion function or
4136     // constructor and if the second standard conversion sequence of
4137     // U1 is better than the second standard conversion sequence of
4138     // U2 (C++ 13.3.3.2p3).
4139     if (ICS1.UserDefined.ConversionFunction ==
4140           ICS2.UserDefined.ConversionFunction)
4141       Result = CompareStandardConversionSequences(S, Loc,
4142                                                   ICS1.UserDefined.After,
4143                                                   ICS2.UserDefined.After);
4144     else
4145       Result = compareConversionFunctions(S,
4146                                           ICS1.UserDefined.ConversionFunction,
4147                                           ICS2.UserDefined.ConversionFunction);
4148   }
4149 
4150   return Result;
4151 }
4152 
4153 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4154 // determine if one is a proper subset of the other.
4155 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4156 compareStandardConversionSubsets(ASTContext &Context,
4157                                  const StandardConversionSequence& SCS1,
4158                                  const StandardConversionSequence& SCS2) {
4159   ImplicitConversionSequence::CompareKind Result
4160     = ImplicitConversionSequence::Indistinguishable;
4161 
4162   // the identity conversion sequence is considered to be a subsequence of
4163   // any non-identity conversion sequence
4164   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4165     return ImplicitConversionSequence::Better;
4166   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4167     return ImplicitConversionSequence::Worse;
4168 
4169   if (SCS1.Second != SCS2.Second) {
4170     if (SCS1.Second == ICK_Identity)
4171       Result = ImplicitConversionSequence::Better;
4172     else if (SCS2.Second == ICK_Identity)
4173       Result = ImplicitConversionSequence::Worse;
4174     else
4175       return ImplicitConversionSequence::Indistinguishable;
4176   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4177     return ImplicitConversionSequence::Indistinguishable;
4178 
4179   if (SCS1.Third == SCS2.Third) {
4180     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4181                              : ImplicitConversionSequence::Indistinguishable;
4182   }
4183 
4184   if (SCS1.Third == ICK_Identity)
4185     return Result == ImplicitConversionSequence::Worse
4186              ? ImplicitConversionSequence::Indistinguishable
4187              : ImplicitConversionSequence::Better;
4188 
4189   if (SCS2.Third == ICK_Identity)
4190     return Result == ImplicitConversionSequence::Better
4191              ? ImplicitConversionSequence::Indistinguishable
4192              : ImplicitConversionSequence::Worse;
4193 
4194   return ImplicitConversionSequence::Indistinguishable;
4195 }
4196 
4197 /// Determine whether one of the given reference bindings is better
4198 /// than the other based on what kind of bindings they are.
4199 static bool
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4200 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4201                              const StandardConversionSequence &SCS2) {
4202   // C++0x [over.ics.rank]p3b4:
4203   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4204   //      implicit object parameter of a non-static member function declared
4205   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
4206   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
4207   //      lvalue reference to a function lvalue and S2 binds an rvalue
4208   //      reference*.
4209   //
4210   // FIXME: Rvalue references. We're going rogue with the above edits,
4211   // because the semantics in the current C++0x working paper (N3225 at the
4212   // time of this writing) break the standard definition of std::forward
4213   // and std::reference_wrapper when dealing with references to functions.
4214   // Proposed wording changes submitted to CWG for consideration.
4215   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4216       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4217     return false;
4218 
4219   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4220           SCS2.IsLvalueReference) ||
4221          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4222           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4223 }
4224 
4225 enum class FixedEnumPromotion {
4226   None,
4227   ToUnderlyingType,
4228   ToPromotedUnderlyingType
4229 };
4230 
4231 /// Returns kind of fixed enum promotion the \a SCS uses.
4232 static FixedEnumPromotion
getFixedEnumPromtion(Sema & S,const StandardConversionSequence & SCS)4233 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4234 
4235   if (SCS.Second != ICK_Integral_Promotion)
4236     return FixedEnumPromotion::None;
4237 
4238   QualType FromType = SCS.getFromType();
4239   if (!FromType->isEnumeralType())
4240     return FixedEnumPromotion::None;
4241 
4242   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4243   if (!Enum->isFixed())
4244     return FixedEnumPromotion::None;
4245 
4246   QualType UnderlyingType = Enum->getIntegerType();
4247   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4248     return FixedEnumPromotion::ToUnderlyingType;
4249 
4250   return FixedEnumPromotion::ToPromotedUnderlyingType;
4251 }
4252 
4253 /// CompareStandardConversionSequences - Compare two standard
4254 /// conversion sequences to determine whether one is better than the
4255 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4256 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4257 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4258                                    const StandardConversionSequence& SCS1,
4259                                    const StandardConversionSequence& SCS2)
4260 {
4261   // Standard conversion sequence S1 is a better conversion sequence
4262   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4263 
4264   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4265   //     sequences in the canonical form defined by 13.3.3.1.1,
4266   //     excluding any Lvalue Transformation; the identity conversion
4267   //     sequence is considered to be a subsequence of any
4268   //     non-identity conversion sequence) or, if not that,
4269   if (ImplicitConversionSequence::CompareKind CK
4270         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4271     return CK;
4272 
4273   //  -- the rank of S1 is better than the rank of S2 (by the rules
4274   //     defined below), or, if not that,
4275   ImplicitConversionRank Rank1 = SCS1.getRank();
4276   ImplicitConversionRank Rank2 = SCS2.getRank();
4277   if (Rank1 < Rank2)
4278     return ImplicitConversionSequence::Better;
4279   else if (Rank2 < Rank1)
4280     return ImplicitConversionSequence::Worse;
4281 
4282   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4283   // are indistinguishable unless one of the following rules
4284   // applies:
4285 
4286   //   A conversion that is not a conversion of a pointer, or
4287   //   pointer to member, to bool is better than another conversion
4288   //   that is such a conversion.
4289   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4290     return SCS2.isPointerConversionToBool()
4291              ? ImplicitConversionSequence::Better
4292              : ImplicitConversionSequence::Worse;
4293 
4294   // C++14 [over.ics.rank]p4b2:
4295   // This is retroactively applied to C++11 by CWG 1601.
4296   //
4297   //   A conversion that promotes an enumeration whose underlying type is fixed
4298   //   to its underlying type is better than one that promotes to the promoted
4299   //   underlying type, if the two are different.
4300   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4301   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4302   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4303       FEP1 != FEP2)
4304     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4305                ? ImplicitConversionSequence::Better
4306                : ImplicitConversionSequence::Worse;
4307 
4308   // C++ [over.ics.rank]p4b2:
4309   //
4310   //   If class B is derived directly or indirectly from class A,
4311   //   conversion of B* to A* is better than conversion of B* to
4312   //   void*, and conversion of A* to void* is better than conversion
4313   //   of B* to void*.
4314   bool SCS1ConvertsToVoid
4315     = SCS1.isPointerConversionToVoidPointer(S.Context);
4316   bool SCS2ConvertsToVoid
4317     = SCS2.isPointerConversionToVoidPointer(S.Context);
4318   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4319     // Exactly one of the conversion sequences is a conversion to
4320     // a void pointer; it's the worse conversion.
4321     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4322                               : ImplicitConversionSequence::Worse;
4323   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4324     // Neither conversion sequence converts to a void pointer; compare
4325     // their derived-to-base conversions.
4326     if (ImplicitConversionSequence::CompareKind DerivedCK
4327           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4328       return DerivedCK;
4329   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4330              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4331     // Both conversion sequences are conversions to void
4332     // pointers. Compare the source types to determine if there's an
4333     // inheritance relationship in their sources.
4334     QualType FromType1 = SCS1.getFromType();
4335     QualType FromType2 = SCS2.getFromType();
4336 
4337     // Adjust the types we're converting from via the array-to-pointer
4338     // conversion, if we need to.
4339     if (SCS1.First == ICK_Array_To_Pointer)
4340       FromType1 = S.Context.getArrayDecayedType(FromType1);
4341     if (SCS2.First == ICK_Array_To_Pointer)
4342       FromType2 = S.Context.getArrayDecayedType(FromType2);
4343 
4344     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4345     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4346 
4347     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4348       return ImplicitConversionSequence::Better;
4349     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4350       return ImplicitConversionSequence::Worse;
4351 
4352     // Objective-C++: If one interface is more specific than the
4353     // other, it is the better one.
4354     const ObjCObjectPointerType* FromObjCPtr1
4355       = FromType1->getAs<ObjCObjectPointerType>();
4356     const ObjCObjectPointerType* FromObjCPtr2
4357       = FromType2->getAs<ObjCObjectPointerType>();
4358     if (FromObjCPtr1 && FromObjCPtr2) {
4359       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4360                                                           FromObjCPtr2);
4361       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4362                                                            FromObjCPtr1);
4363       if (AssignLeft != AssignRight) {
4364         return AssignLeft? ImplicitConversionSequence::Better
4365                          : ImplicitConversionSequence::Worse;
4366       }
4367     }
4368   }
4369 
4370   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4371     // Check for a better reference binding based on the kind of bindings.
4372     if (isBetterReferenceBindingKind(SCS1, SCS2))
4373       return ImplicitConversionSequence::Better;
4374     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4375       return ImplicitConversionSequence::Worse;
4376   }
4377 
4378   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4379   // bullet 3).
4380   if (ImplicitConversionSequence::CompareKind QualCK
4381         = CompareQualificationConversions(S, SCS1, SCS2))
4382     return QualCK;
4383 
4384   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4385     // C++ [over.ics.rank]p3b4:
4386     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4387     //      which the references refer are the same type except for
4388     //      top-level cv-qualifiers, and the type to which the reference
4389     //      initialized by S2 refers is more cv-qualified than the type
4390     //      to which the reference initialized by S1 refers.
4391     QualType T1 = SCS1.getToType(2);
4392     QualType T2 = SCS2.getToType(2);
4393     T1 = S.Context.getCanonicalType(T1);
4394     T2 = S.Context.getCanonicalType(T2);
4395     Qualifiers T1Quals, T2Quals;
4396     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4397     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4398     if (UnqualT1 == UnqualT2) {
4399       // Objective-C++ ARC: If the references refer to objects with different
4400       // lifetimes, prefer bindings that don't change lifetime.
4401       if (SCS1.ObjCLifetimeConversionBinding !=
4402                                           SCS2.ObjCLifetimeConversionBinding) {
4403         return SCS1.ObjCLifetimeConversionBinding
4404                                            ? ImplicitConversionSequence::Worse
4405                                            : ImplicitConversionSequence::Better;
4406       }
4407 
4408       // If the type is an array type, promote the element qualifiers to the
4409       // type for comparison.
4410       if (isa<ArrayType>(T1) && T1Quals)
4411         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4412       if (isa<ArrayType>(T2) && T2Quals)
4413         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4414       if (T2.isMoreQualifiedThan(T1))
4415         return ImplicitConversionSequence::Better;
4416       if (T1.isMoreQualifiedThan(T2))
4417         return ImplicitConversionSequence::Worse;
4418     }
4419   }
4420 
4421   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4422   // floating-to-integral conversion if the integral conversion
4423   // is between types of the same size.
4424   // For example:
4425   // void f(float);
4426   // void f(int);
4427   // int main {
4428   //    long a;
4429   //    f(a);
4430   // }
4431   // Here, MSVC will call f(int) instead of generating a compile error
4432   // as clang will do in standard mode.
4433   if (S.getLangOpts().MSVCCompat &&
4434       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4435       SCS1.Second == ICK_Integral_Conversion &&
4436       SCS2.Second == ICK_Floating_Integral &&
4437       S.Context.getTypeSize(SCS1.getFromType()) ==
4438           S.Context.getTypeSize(SCS1.getToType(2)))
4439     return ImplicitConversionSequence::Better;
4440 
4441   // Prefer a compatible vector conversion over a lax vector conversion
4442   // For example:
4443   //
4444   // typedef float __v4sf __attribute__((__vector_size__(16)));
4445   // void f(vector float);
4446   // void f(vector signed int);
4447   // int main() {
4448   //   __v4sf a;
4449   //   f(a);
4450   // }
4451   // Here, we'd like to choose f(vector float) and not
4452   // report an ambiguous call error
4453   if (SCS1.Second == ICK_Vector_Conversion &&
4454       SCS2.Second == ICK_Vector_Conversion) {
4455     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4456         SCS1.getFromType(), SCS1.getToType(2));
4457     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4458         SCS2.getFromType(), SCS2.getToType(2));
4459 
4460     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4461       return SCS1IsCompatibleVectorConversion
4462                  ? ImplicitConversionSequence::Better
4463                  : ImplicitConversionSequence::Worse;
4464   }
4465 
4466   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4467       SCS2.Second == ICK_SVE_Vector_Conversion) {
4468     bool SCS1IsCompatibleSVEVectorConversion =
4469         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4470     bool SCS2IsCompatibleSVEVectorConversion =
4471         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4472 
4473     if (SCS1IsCompatibleSVEVectorConversion !=
4474         SCS2IsCompatibleSVEVectorConversion)
4475       return SCS1IsCompatibleSVEVectorConversion
4476                  ? ImplicitConversionSequence::Better
4477                  : ImplicitConversionSequence::Worse;
4478   }
4479 
4480   if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4481       SCS2.Second == ICK_RVV_Vector_Conversion) {
4482     bool SCS1IsCompatibleRVVVectorConversion =
4483         S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4484     bool SCS2IsCompatibleRVVVectorConversion =
4485         S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4486 
4487     if (SCS1IsCompatibleRVVVectorConversion !=
4488         SCS2IsCompatibleRVVVectorConversion)
4489       return SCS1IsCompatibleRVVVectorConversion
4490                  ? ImplicitConversionSequence::Better
4491                  : ImplicitConversionSequence::Worse;
4492   }
4493 
4494   return ImplicitConversionSequence::Indistinguishable;
4495 }
4496 
4497 /// CompareQualificationConversions - Compares two standard conversion
4498 /// sequences to determine whether they can be ranked based on their
4499 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4500 static ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4501 CompareQualificationConversions(Sema &S,
4502                                 const StandardConversionSequence& SCS1,
4503                                 const StandardConversionSequence& SCS2) {
4504   // C++ [over.ics.rank]p3:
4505   //  -- S1 and S2 differ only in their qualification conversion and
4506   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4507   // [C++98]
4508   //     [...] and the cv-qualification signature of type T1 is a proper subset
4509   //     of the cv-qualification signature of type T2, and S1 is not the
4510   //     deprecated string literal array-to-pointer conversion (4.2).
4511   // [C++2a]
4512   //     [...] where T1 can be converted to T2 by a qualification conversion.
4513   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4514       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4515     return ImplicitConversionSequence::Indistinguishable;
4516 
4517   // FIXME: the example in the standard doesn't use a qualification
4518   // conversion (!)
4519   QualType T1 = SCS1.getToType(2);
4520   QualType T2 = SCS2.getToType(2);
4521   T1 = S.Context.getCanonicalType(T1);
4522   T2 = S.Context.getCanonicalType(T2);
4523   assert(!T1->isReferenceType() && !T2->isReferenceType());
4524   Qualifiers T1Quals, T2Quals;
4525   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4526   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4527 
4528   // If the types are the same, we won't learn anything by unwrapping
4529   // them.
4530   if (UnqualT1 == UnqualT2)
4531     return ImplicitConversionSequence::Indistinguishable;
4532 
4533   // Don't ever prefer a standard conversion sequence that uses the deprecated
4534   // string literal array to pointer conversion.
4535   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4536   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4537 
4538   // Objective-C++ ARC:
4539   //   Prefer qualification conversions not involving a change in lifetime
4540   //   to qualification conversions that do change lifetime.
4541   if (SCS1.QualificationIncludesObjCLifetime &&
4542       !SCS2.QualificationIncludesObjCLifetime)
4543     CanPick1 = false;
4544   if (SCS2.QualificationIncludesObjCLifetime &&
4545       !SCS1.QualificationIncludesObjCLifetime)
4546     CanPick2 = false;
4547 
4548   bool ObjCLifetimeConversion;
4549   if (CanPick1 &&
4550       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4551     CanPick1 = false;
4552   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4553   // directions, so we can't short-cut this second check in general.
4554   if (CanPick2 &&
4555       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4556     CanPick2 = false;
4557 
4558   if (CanPick1 != CanPick2)
4559     return CanPick1 ? ImplicitConversionSequence::Better
4560                     : ImplicitConversionSequence::Worse;
4561   return ImplicitConversionSequence::Indistinguishable;
4562 }
4563 
4564 /// CompareDerivedToBaseConversions - Compares two standard conversion
4565 /// sequences to determine whether they can be ranked based on their
4566 /// various kinds of derived-to-base conversions (C++
4567 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4568 /// conversions between Objective-C interface types.
4569 static ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4570 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4571                                 const StandardConversionSequence& SCS1,
4572                                 const StandardConversionSequence& SCS2) {
4573   QualType FromType1 = SCS1.getFromType();
4574   QualType ToType1 = SCS1.getToType(1);
4575   QualType FromType2 = SCS2.getFromType();
4576   QualType ToType2 = SCS2.getToType(1);
4577 
4578   // Adjust the types we're converting from via the array-to-pointer
4579   // conversion, if we need to.
4580   if (SCS1.First == ICK_Array_To_Pointer)
4581     FromType1 = S.Context.getArrayDecayedType(FromType1);
4582   if (SCS2.First == ICK_Array_To_Pointer)
4583     FromType2 = S.Context.getArrayDecayedType(FromType2);
4584 
4585   // Canonicalize all of the types.
4586   FromType1 = S.Context.getCanonicalType(FromType1);
4587   ToType1 = S.Context.getCanonicalType(ToType1);
4588   FromType2 = S.Context.getCanonicalType(FromType2);
4589   ToType2 = S.Context.getCanonicalType(ToType2);
4590 
4591   // C++ [over.ics.rank]p4b3:
4592   //
4593   //   If class B is derived directly or indirectly from class A and
4594   //   class C is derived directly or indirectly from B,
4595   //
4596   // Compare based on pointer conversions.
4597   if (SCS1.Second == ICK_Pointer_Conversion &&
4598       SCS2.Second == ICK_Pointer_Conversion &&
4599       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4600       FromType1->isPointerType() && FromType2->isPointerType() &&
4601       ToType1->isPointerType() && ToType2->isPointerType()) {
4602     QualType FromPointee1 =
4603         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4604     QualType ToPointee1 =
4605         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4606     QualType FromPointee2 =
4607         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4608     QualType ToPointee2 =
4609         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4610 
4611     //   -- conversion of C* to B* is better than conversion of C* to A*,
4612     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4613       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4614         return ImplicitConversionSequence::Better;
4615       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4616         return ImplicitConversionSequence::Worse;
4617     }
4618 
4619     //   -- conversion of B* to A* is better than conversion of C* to A*,
4620     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4621       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4622         return ImplicitConversionSequence::Better;
4623       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4624         return ImplicitConversionSequence::Worse;
4625     }
4626   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4627              SCS2.Second == ICK_Pointer_Conversion) {
4628     const ObjCObjectPointerType *FromPtr1
4629       = FromType1->getAs<ObjCObjectPointerType>();
4630     const ObjCObjectPointerType *FromPtr2
4631       = FromType2->getAs<ObjCObjectPointerType>();
4632     const ObjCObjectPointerType *ToPtr1
4633       = ToType1->getAs<ObjCObjectPointerType>();
4634     const ObjCObjectPointerType *ToPtr2
4635       = ToType2->getAs<ObjCObjectPointerType>();
4636 
4637     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4638       // Apply the same conversion ranking rules for Objective-C pointer types
4639       // that we do for C++ pointers to class types. However, we employ the
4640       // Objective-C pseudo-subtyping relationship used for assignment of
4641       // Objective-C pointer types.
4642       bool FromAssignLeft
4643         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4644       bool FromAssignRight
4645         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4646       bool ToAssignLeft
4647         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4648       bool ToAssignRight
4649         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4650 
4651       // A conversion to an a non-id object pointer type or qualified 'id'
4652       // type is better than a conversion to 'id'.
4653       if (ToPtr1->isObjCIdType() &&
4654           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4655         return ImplicitConversionSequence::Worse;
4656       if (ToPtr2->isObjCIdType() &&
4657           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4658         return ImplicitConversionSequence::Better;
4659 
4660       // A conversion to a non-id object pointer type is better than a
4661       // conversion to a qualified 'id' type
4662       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4663         return ImplicitConversionSequence::Worse;
4664       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4665         return ImplicitConversionSequence::Better;
4666 
4667       // A conversion to an a non-Class object pointer type or qualified 'Class'
4668       // type is better than a conversion to 'Class'.
4669       if (ToPtr1->isObjCClassType() &&
4670           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4671         return ImplicitConversionSequence::Worse;
4672       if (ToPtr2->isObjCClassType() &&
4673           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4674         return ImplicitConversionSequence::Better;
4675 
4676       // A conversion to a non-Class object pointer type is better than a
4677       // conversion to a qualified 'Class' type.
4678       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4679         return ImplicitConversionSequence::Worse;
4680       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4681         return ImplicitConversionSequence::Better;
4682 
4683       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4684       if (S.Context.hasSameType(FromType1, FromType2) &&
4685           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4686           (ToAssignLeft != ToAssignRight)) {
4687         if (FromPtr1->isSpecialized()) {
4688           // "conversion of B<A> * to B * is better than conversion of B * to
4689           // C *.
4690           bool IsFirstSame =
4691               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4692           bool IsSecondSame =
4693               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4694           if (IsFirstSame) {
4695             if (!IsSecondSame)
4696               return ImplicitConversionSequence::Better;
4697           } else if (IsSecondSame)
4698             return ImplicitConversionSequence::Worse;
4699         }
4700         return ToAssignLeft? ImplicitConversionSequence::Worse
4701                            : ImplicitConversionSequence::Better;
4702       }
4703 
4704       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4705       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4706           (FromAssignLeft != FromAssignRight))
4707         return FromAssignLeft? ImplicitConversionSequence::Better
4708         : ImplicitConversionSequence::Worse;
4709     }
4710   }
4711 
4712   // Ranking of member-pointer types.
4713   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4714       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4715       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4716     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4717     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4718     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4719     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4720     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4721     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4722     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4723     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4724     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4725     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4726     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4727     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4728     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4729     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4730       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4731         return ImplicitConversionSequence::Worse;
4732       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4733         return ImplicitConversionSequence::Better;
4734     }
4735     // conversion of B::* to C::* is better than conversion of A::* to C::*
4736     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4737       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4738         return ImplicitConversionSequence::Better;
4739       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4740         return ImplicitConversionSequence::Worse;
4741     }
4742   }
4743 
4744   if (SCS1.Second == ICK_Derived_To_Base) {
4745     //   -- conversion of C to B is better than conversion of C to A,
4746     //   -- binding of an expression of type C to a reference of type
4747     //      B& is better than binding an expression of type C to a
4748     //      reference of type A&,
4749     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4750         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4751       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4752         return ImplicitConversionSequence::Better;
4753       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4754         return ImplicitConversionSequence::Worse;
4755     }
4756 
4757     //   -- conversion of B to A is better than conversion of C to A.
4758     //   -- binding of an expression of type B to a reference of type
4759     //      A& is better than binding an expression of type C to a
4760     //      reference of type A&,
4761     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4762         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4763       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4764         return ImplicitConversionSequence::Better;
4765       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4766         return ImplicitConversionSequence::Worse;
4767     }
4768   }
4769 
4770   return ImplicitConversionSequence::Indistinguishable;
4771 }
4772 
withoutUnaligned(ASTContext & Ctx,QualType T)4773 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4774   if (!T.getQualifiers().hasUnaligned())
4775     return T;
4776 
4777   Qualifiers Q;
4778   T = Ctx.getUnqualifiedArrayType(T, Q);
4779   Q.removeUnaligned();
4780   return Ctx.getQualifiedType(T, Q);
4781 }
4782 
4783 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4784 /// determine whether they are reference-compatible,
4785 /// reference-related, or incompatible, for use in C++ initialization by
4786 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4787 /// type, and the first type (T1) is the pointee type of the reference
4788 /// type being initialized.
4789 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,ReferenceConversions * ConvOut)4790 Sema::CompareReferenceRelationship(SourceLocation Loc,
4791                                    QualType OrigT1, QualType OrigT2,
4792                                    ReferenceConversions *ConvOut) {
4793   assert(!OrigT1->isReferenceType() &&
4794     "T1 must be the pointee type of the reference type");
4795   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4796 
4797   QualType T1 = Context.getCanonicalType(OrigT1);
4798   QualType T2 = Context.getCanonicalType(OrigT2);
4799   Qualifiers T1Quals, T2Quals;
4800   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4801   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4802 
4803   ReferenceConversions ConvTmp;
4804   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4805   Conv = ReferenceConversions();
4806 
4807   // C++2a [dcl.init.ref]p4:
4808   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4809   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4810   //   T1 is a base class of T2.
4811   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4812   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4813   //   "pointer to cv1 T1" via a standard conversion sequence.
4814 
4815   // Check for standard conversions we can apply to pointers: derived-to-base
4816   // conversions, ObjC pointer conversions, and function pointer conversions.
4817   // (Qualification conversions are checked last.)
4818   QualType ConvertedT2;
4819   if (UnqualT1 == UnqualT2) {
4820     // Nothing to do.
4821   } else if (isCompleteType(Loc, OrigT2) &&
4822              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4823     Conv |= ReferenceConversions::DerivedToBase;
4824   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4825            UnqualT2->isObjCObjectOrInterfaceType() &&
4826            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4827     Conv |= ReferenceConversions::ObjC;
4828   else if (UnqualT2->isFunctionType() &&
4829            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4830     Conv |= ReferenceConversions::Function;
4831     // No need to check qualifiers; function types don't have them.
4832     return Ref_Compatible;
4833   }
4834   bool ConvertedReferent = Conv != 0;
4835 
4836   // We can have a qualification conversion. Compute whether the types are
4837   // similar at the same time.
4838   bool PreviousToQualsIncludeConst = true;
4839   bool TopLevel = true;
4840   do {
4841     if (T1 == T2)
4842       break;
4843 
4844     // We will need a qualification conversion.
4845     Conv |= ReferenceConversions::Qualification;
4846 
4847     // Track whether we performed a qualification conversion anywhere other
4848     // than the top level. This matters for ranking reference bindings in
4849     // overload resolution.
4850     if (!TopLevel)
4851       Conv |= ReferenceConversions::NestedQualification;
4852 
4853     // MS compiler ignores __unaligned qualifier for references; do the same.
4854     T1 = withoutUnaligned(Context, T1);
4855     T2 = withoutUnaligned(Context, T2);
4856 
4857     // If we find a qualifier mismatch, the types are not reference-compatible,
4858     // but are still be reference-related if they're similar.
4859     bool ObjCLifetimeConversion = false;
4860     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4861                                        PreviousToQualsIncludeConst,
4862                                        ObjCLifetimeConversion))
4863       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4864                  ? Ref_Related
4865                  : Ref_Incompatible;
4866 
4867     // FIXME: Should we track this for any level other than the first?
4868     if (ObjCLifetimeConversion)
4869       Conv |= ReferenceConversions::ObjCLifetime;
4870 
4871     TopLevel = false;
4872   } while (Context.UnwrapSimilarTypes(T1, T2));
4873 
4874   // At this point, if the types are reference-related, we must either have the
4875   // same inner type (ignoring qualifiers), or must have already worked out how
4876   // to convert the referent.
4877   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4878              ? Ref_Compatible
4879              : Ref_Incompatible;
4880 }
4881 
4882 /// Look for a user-defined conversion to a value reference-compatible
4883 ///        with DeclType. Return true if something definite is found.
4884 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)4885 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4886                          QualType DeclType, SourceLocation DeclLoc,
4887                          Expr *Init, QualType T2, bool AllowRvalues,
4888                          bool AllowExplicit) {
4889   assert(T2->isRecordType() && "Can only find conversions of record types.");
4890   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4891 
4892   OverloadCandidateSet CandidateSet(
4893       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4894   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4895   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4896     NamedDecl *D = *I;
4897     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4898     if (isa<UsingShadowDecl>(D))
4899       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4900 
4901     FunctionTemplateDecl *ConvTemplate
4902       = dyn_cast<FunctionTemplateDecl>(D);
4903     CXXConversionDecl *Conv;
4904     if (ConvTemplate)
4905       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4906     else
4907       Conv = cast<CXXConversionDecl>(D);
4908 
4909     if (AllowRvalues) {
4910       // If we are initializing an rvalue reference, don't permit conversion
4911       // functions that return lvalues.
4912       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4913         const ReferenceType *RefType
4914           = Conv->getConversionType()->getAs<LValueReferenceType>();
4915         if (RefType && !RefType->getPointeeType()->isFunctionType())
4916           continue;
4917       }
4918 
4919       if (!ConvTemplate &&
4920           S.CompareReferenceRelationship(
4921               DeclLoc,
4922               Conv->getConversionType()
4923                   .getNonReferenceType()
4924                   .getUnqualifiedType(),
4925               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4926               Sema::Ref_Incompatible)
4927         continue;
4928     } else {
4929       // If the conversion function doesn't return a reference type,
4930       // it can't be considered for this conversion. An rvalue reference
4931       // is only acceptable if its referencee is a function type.
4932 
4933       const ReferenceType *RefType =
4934         Conv->getConversionType()->getAs<ReferenceType>();
4935       if (!RefType ||
4936           (!RefType->isLValueReferenceType() &&
4937            !RefType->getPointeeType()->isFunctionType()))
4938         continue;
4939     }
4940 
4941     if (ConvTemplate)
4942       S.AddTemplateConversionCandidate(
4943           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4944           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4945     else
4946       S.AddConversionCandidate(
4947           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4948           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4949   }
4950 
4951   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4952 
4953   OverloadCandidateSet::iterator Best;
4954   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4955   case OR_Success:
4956     // C++ [over.ics.ref]p1:
4957     //
4958     //   [...] If the parameter binds directly to the result of
4959     //   applying a conversion function to the argument
4960     //   expression, the implicit conversion sequence is a
4961     //   user-defined conversion sequence (13.3.3.1.2), with the
4962     //   second standard conversion sequence either an identity
4963     //   conversion or, if the conversion function returns an
4964     //   entity of a type that is a derived class of the parameter
4965     //   type, a derived-to-base Conversion.
4966     if (!Best->FinalConversion.DirectBinding)
4967       return false;
4968 
4969     ICS.setUserDefined();
4970     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4971     ICS.UserDefined.After = Best->FinalConversion;
4972     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4973     ICS.UserDefined.ConversionFunction = Best->Function;
4974     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4975     ICS.UserDefined.EllipsisConversion = false;
4976     assert(ICS.UserDefined.After.ReferenceBinding &&
4977            ICS.UserDefined.After.DirectBinding &&
4978            "Expected a direct reference binding!");
4979     return true;
4980 
4981   case OR_Ambiguous:
4982     ICS.setAmbiguous();
4983     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4984          Cand != CandidateSet.end(); ++Cand)
4985       if (Cand->Best)
4986         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4987     return true;
4988 
4989   case OR_No_Viable_Function:
4990   case OR_Deleted:
4991     // There was no suitable conversion, or we found a deleted
4992     // conversion; continue with other checks.
4993     return false;
4994   }
4995 
4996   llvm_unreachable("Invalid OverloadResult!");
4997 }
4998 
4999 /// Compute an implicit conversion sequence for reference
5000 /// initialization.
5001 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)5002 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5003                  SourceLocation DeclLoc,
5004                  bool SuppressUserConversions,
5005                  bool AllowExplicit) {
5006   assert(DeclType->isReferenceType() && "Reference init needs a reference");
5007 
5008   // Most paths end in a failed conversion.
5009   ImplicitConversionSequence ICS;
5010   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5011 
5012   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5013   QualType T2 = Init->getType();
5014 
5015   // If the initializer is the address of an overloaded function, try
5016   // to resolve the overloaded function. If all goes well, T2 is the
5017   // type of the resulting function.
5018   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5019     DeclAccessPair Found;
5020     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
5021                                                                 false, Found))
5022       T2 = Fn->getType();
5023   }
5024 
5025   // Compute some basic properties of the types and the initializer.
5026   bool isRValRef = DeclType->isRValueReferenceType();
5027   Expr::Classification InitCategory = Init->Classify(S.Context);
5028 
5029   Sema::ReferenceConversions RefConv;
5030   Sema::ReferenceCompareResult RefRelationship =
5031       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5032 
5033   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5034     ICS.setStandard();
5035     ICS.Standard.First = ICK_Identity;
5036     // FIXME: A reference binding can be a function conversion too. We should
5037     // consider that when ordering reference-to-function bindings.
5038     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5039                               ? ICK_Derived_To_Base
5040                               : (RefConv & Sema::ReferenceConversions::ObjC)
5041                                     ? ICK_Compatible_Conversion
5042                                     : ICK_Identity;
5043     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5044     // a reference binding that performs a non-top-level qualification
5045     // conversion as a qualification conversion, not as an identity conversion.
5046     ICS.Standard.Third = (RefConv &
5047                               Sema::ReferenceConversions::NestedQualification)
5048                              ? ICK_Qualification
5049                              : ICK_Identity;
5050     ICS.Standard.setFromType(T2);
5051     ICS.Standard.setToType(0, T2);
5052     ICS.Standard.setToType(1, T1);
5053     ICS.Standard.setToType(2, T1);
5054     ICS.Standard.ReferenceBinding = true;
5055     ICS.Standard.DirectBinding = BindsDirectly;
5056     ICS.Standard.IsLvalueReference = !isRValRef;
5057     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5058     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5059     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5060     ICS.Standard.ObjCLifetimeConversionBinding =
5061         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5062     ICS.Standard.CopyConstructor = nullptr;
5063     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5064   };
5065 
5066   // C++0x [dcl.init.ref]p5:
5067   //   A reference to type "cv1 T1" is initialized by an expression
5068   //   of type "cv2 T2" as follows:
5069 
5070   //     -- If reference is an lvalue reference and the initializer expression
5071   if (!isRValRef) {
5072     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5073     //        reference-compatible with "cv2 T2," or
5074     //
5075     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5076     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5077       // C++ [over.ics.ref]p1:
5078       //   When a parameter of reference type binds directly (8.5.3)
5079       //   to an argument expression, the implicit conversion sequence
5080       //   is the identity conversion, unless the argument expression
5081       //   has a type that is a derived class of the parameter type,
5082       //   in which case the implicit conversion sequence is a
5083       //   derived-to-base Conversion (13.3.3.1).
5084       SetAsReferenceBinding(/*BindsDirectly=*/true);
5085 
5086       // Nothing more to do: the inaccessibility/ambiguity check for
5087       // derived-to-base conversions is suppressed when we're
5088       // computing the implicit conversion sequence (C++
5089       // [over.best.ics]p2).
5090       return ICS;
5091     }
5092 
5093     //       -- has a class type (i.e., T2 is a class type), where T1 is
5094     //          not reference-related to T2, and can be implicitly
5095     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
5096     //          is reference-compatible with "cv3 T3" 92) (this
5097     //          conversion is selected by enumerating the applicable
5098     //          conversion functions (13.3.1.6) and choosing the best
5099     //          one through overload resolution (13.3)),
5100     if (!SuppressUserConversions && T2->isRecordType() &&
5101         S.isCompleteType(DeclLoc, T2) &&
5102         RefRelationship == Sema::Ref_Incompatible) {
5103       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5104                                    Init, T2, /*AllowRvalues=*/false,
5105                                    AllowExplicit))
5106         return ICS;
5107     }
5108   }
5109 
5110   //     -- Otherwise, the reference shall be an lvalue reference to a
5111   //        non-volatile const type (i.e., cv1 shall be const), or the reference
5112   //        shall be an rvalue reference.
5113   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5114     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5115       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
5116     return ICS;
5117   }
5118 
5119   //       -- If the initializer expression
5120   //
5121   //            -- is an xvalue, class prvalue, array prvalue or function
5122   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5123   if (RefRelationship == Sema::Ref_Compatible &&
5124       (InitCategory.isXValue() ||
5125        (InitCategory.isPRValue() &&
5126           (T2->isRecordType() || T2->isArrayType())) ||
5127        (InitCategory.isLValue() && T2->isFunctionType()))) {
5128     // In C++11, this is always a direct binding. In C++98/03, it's a direct
5129     // binding unless we're binding to a class prvalue.
5130     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5131     // allow the use of rvalue references in C++98/03 for the benefit of
5132     // standard library implementors; therefore, we need the xvalue check here.
5133     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5134                           !(InitCategory.isPRValue() || T2->isRecordType()));
5135     return ICS;
5136   }
5137 
5138   //            -- has a class type (i.e., T2 is a class type), where T1 is not
5139   //               reference-related to T2, and can be implicitly converted to
5140   //               an xvalue, class prvalue, or function lvalue of type
5141   //               "cv3 T3", where "cv1 T1" is reference-compatible with
5142   //               "cv3 T3",
5143   //
5144   //          then the reference is bound to the value of the initializer
5145   //          expression in the first case and to the result of the conversion
5146   //          in the second case (or, in either case, to an appropriate base
5147   //          class subobject).
5148   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5149       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5150       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5151                                Init, T2, /*AllowRvalues=*/true,
5152                                AllowExplicit)) {
5153     // In the second case, if the reference is an rvalue reference
5154     // and the second standard conversion sequence of the
5155     // user-defined conversion sequence includes an lvalue-to-rvalue
5156     // conversion, the program is ill-formed.
5157     if (ICS.isUserDefined() && isRValRef &&
5158         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5159       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5160 
5161     return ICS;
5162   }
5163 
5164   // A temporary of function type cannot be created; don't even try.
5165   if (T1->isFunctionType())
5166     return ICS;
5167 
5168   //       -- Otherwise, a temporary of type "cv1 T1" is created and
5169   //          initialized from the initializer expression using the
5170   //          rules for a non-reference copy initialization (8.5). The
5171   //          reference is then bound to the temporary. If T1 is
5172   //          reference-related to T2, cv1 must be the same
5173   //          cv-qualification as, or greater cv-qualification than,
5174   //          cv2; otherwise, the program is ill-formed.
5175   if (RefRelationship == Sema::Ref_Related) {
5176     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5177     // we would be reference-compatible or reference-compatible with
5178     // added qualification. But that wasn't the case, so the reference
5179     // initialization fails.
5180     //
5181     // Note that we only want to check address spaces and cvr-qualifiers here.
5182     // ObjC GC, lifetime and unaligned qualifiers aren't important.
5183     Qualifiers T1Quals = T1.getQualifiers();
5184     Qualifiers T2Quals = T2.getQualifiers();
5185     T1Quals.removeObjCGCAttr();
5186     T1Quals.removeObjCLifetime();
5187     T2Quals.removeObjCGCAttr();
5188     T2Quals.removeObjCLifetime();
5189     // MS compiler ignores __unaligned qualifier for references; do the same.
5190     T1Quals.removeUnaligned();
5191     T2Quals.removeUnaligned();
5192     if (!T1Quals.compatiblyIncludes(T2Quals))
5193       return ICS;
5194   }
5195 
5196   // If at least one of the types is a class type, the types are not
5197   // related, and we aren't allowed any user conversions, the
5198   // reference binding fails. This case is important for breaking
5199   // recursion, since TryImplicitConversion below will attempt to
5200   // create a temporary through the use of a copy constructor.
5201   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5202       (T1->isRecordType() || T2->isRecordType()))
5203     return ICS;
5204 
5205   // If T1 is reference-related to T2 and the reference is an rvalue
5206   // reference, the initializer expression shall not be an lvalue.
5207   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5208       Init->Classify(S.Context).isLValue()) {
5209     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5210     return ICS;
5211   }
5212 
5213   // C++ [over.ics.ref]p2:
5214   //   When a parameter of reference type is not bound directly to
5215   //   an argument expression, the conversion sequence is the one
5216   //   required to convert the argument expression to the
5217   //   underlying type of the reference according to
5218   //   13.3.3.1. Conceptually, this conversion sequence corresponds
5219   //   to copy-initializing a temporary of the underlying type with
5220   //   the argument expression. Any difference in top-level
5221   //   cv-qualification is subsumed by the initialization itself
5222   //   and does not constitute a conversion.
5223   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5224                               AllowedExplicit::None,
5225                               /*InOverloadResolution=*/false,
5226                               /*CStyle=*/false,
5227                               /*AllowObjCWritebackConversion=*/false,
5228                               /*AllowObjCConversionOnExplicit=*/false);
5229 
5230   // Of course, that's still a reference binding.
5231   if (ICS.isStandard()) {
5232     ICS.Standard.ReferenceBinding = true;
5233     ICS.Standard.IsLvalueReference = !isRValRef;
5234     ICS.Standard.BindsToFunctionLvalue = false;
5235     ICS.Standard.BindsToRvalue = true;
5236     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5237     ICS.Standard.ObjCLifetimeConversionBinding = false;
5238   } else if (ICS.isUserDefined()) {
5239     const ReferenceType *LValRefType =
5240         ICS.UserDefined.ConversionFunction->getReturnType()
5241             ->getAs<LValueReferenceType>();
5242 
5243     // C++ [over.ics.ref]p3:
5244     //   Except for an implicit object parameter, for which see 13.3.1, a
5245     //   standard conversion sequence cannot be formed if it requires [...]
5246     //   binding an rvalue reference to an lvalue other than a function
5247     //   lvalue.
5248     // Note that the function case is not possible here.
5249     if (isRValRef && LValRefType) {
5250       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5251       return ICS;
5252     }
5253 
5254     ICS.UserDefined.After.ReferenceBinding = true;
5255     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5256     ICS.UserDefined.After.BindsToFunctionLvalue = false;
5257     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5258     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5259     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5260   }
5261 
5262   return ICS;
5263 }
5264 
5265 static ImplicitConversionSequence
5266 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5267                       bool SuppressUserConversions,
5268                       bool InOverloadResolution,
5269                       bool AllowObjCWritebackConversion,
5270                       bool AllowExplicit = false);
5271 
5272 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5273 /// initializer list From.
5274 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)5275 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5276                   bool SuppressUserConversions,
5277                   bool InOverloadResolution,
5278                   bool AllowObjCWritebackConversion) {
5279   // C++11 [over.ics.list]p1:
5280   //   When an argument is an initializer list, it is not an expression and
5281   //   special rules apply for converting it to a parameter type.
5282 
5283   ImplicitConversionSequence Result;
5284   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5285 
5286   // We need a complete type for what follows.  With one C++20 exception,
5287   // incomplete types can never be initialized from init lists.
5288   QualType InitTy = ToType;
5289   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5290   if (AT && S.getLangOpts().CPlusPlus20)
5291     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5292       // C++20 allows list initialization of an incomplete array type.
5293       InitTy = IAT->getElementType();
5294   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5295     return Result;
5296 
5297   // C++20 [over.ics.list]/2:
5298   //   If the initializer list is a designated-initializer-list, a conversion
5299   //   is only possible if the parameter has an aggregate type
5300   //
5301   // FIXME: The exception for reference initialization here is not part of the
5302   // language rules, but follow other compilers in adding it as a tentative DR
5303   // resolution.
5304   bool IsDesignatedInit = From->hasDesignatedInit();
5305   if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5306       IsDesignatedInit)
5307     return Result;
5308 
5309   // Per DR1467:
5310   //   If the parameter type is a class X and the initializer list has a single
5311   //   element of type cv U, where U is X or a class derived from X, the
5312   //   implicit conversion sequence is the one required to convert the element
5313   //   to the parameter type.
5314   //
5315   //   Otherwise, if the parameter type is a character array [... ]
5316   //   and the initializer list has a single element that is an
5317   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5318   //   implicit conversion sequence is the identity conversion.
5319   if (From->getNumInits() == 1 && !IsDesignatedInit) {
5320     if (ToType->isRecordType()) {
5321       QualType InitType = From->getInit(0)->getType();
5322       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5323           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5324         return TryCopyInitialization(S, From->getInit(0), ToType,
5325                                      SuppressUserConversions,
5326                                      InOverloadResolution,
5327                                      AllowObjCWritebackConversion);
5328     }
5329 
5330     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5331       InitializedEntity Entity =
5332           InitializedEntity::InitializeParameter(S.Context, ToType,
5333                                                  /*Consumed=*/false);
5334       if (S.CanPerformCopyInitialization(Entity, From)) {
5335         Result.setStandard();
5336         Result.Standard.setAsIdentityConversion();
5337         Result.Standard.setFromType(ToType);
5338         Result.Standard.setAllToTypes(ToType);
5339         return Result;
5340       }
5341     }
5342   }
5343 
5344   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5345   // C++11 [over.ics.list]p2:
5346   //   If the parameter type is std::initializer_list<X> or "array of X" and
5347   //   all the elements can be implicitly converted to X, the implicit
5348   //   conversion sequence is the worst conversion necessary to convert an
5349   //   element of the list to X.
5350   //
5351   // C++14 [over.ics.list]p3:
5352   //   Otherwise, if the parameter type is "array of N X", if the initializer
5353   //   list has exactly N elements or if it has fewer than N elements and X is
5354   //   default-constructible, and if all the elements of the initializer list
5355   //   can be implicitly converted to X, the implicit conversion sequence is
5356   //   the worst conversion necessary to convert an element of the list to X.
5357   if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5358     unsigned e = From->getNumInits();
5359     ImplicitConversionSequence DfltElt;
5360     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5361                    QualType());
5362     QualType ContTy = ToType;
5363     bool IsUnbounded = false;
5364     if (AT) {
5365       InitTy = AT->getElementType();
5366       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5367         if (CT->getSize().ult(e)) {
5368           // Too many inits, fatally bad
5369           Result.setBad(BadConversionSequence::too_many_initializers, From,
5370                         ToType);
5371           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5372           return Result;
5373         }
5374         if (CT->getSize().ugt(e)) {
5375           // Need an init from empty {}, is there one?
5376           InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5377                                  From->getEndLoc());
5378           EmptyList.setType(S.Context.VoidTy);
5379           DfltElt = TryListConversion(
5380               S, &EmptyList, InitTy, SuppressUserConversions,
5381               InOverloadResolution, AllowObjCWritebackConversion);
5382           if (DfltElt.isBad()) {
5383             // No {} init, fatally bad
5384             Result.setBad(BadConversionSequence::too_few_initializers, From,
5385                           ToType);
5386             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5387             return Result;
5388           }
5389         }
5390       } else {
5391         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5392         IsUnbounded = true;
5393         if (!e) {
5394           // Cannot convert to zero-sized.
5395           Result.setBad(BadConversionSequence::too_few_initializers, From,
5396                         ToType);
5397           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5398           return Result;
5399         }
5400         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5401         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5402                                                 ArraySizeModifier::Normal, 0);
5403       }
5404     }
5405 
5406     Result.setStandard();
5407     Result.Standard.setAsIdentityConversion();
5408     Result.Standard.setFromType(InitTy);
5409     Result.Standard.setAllToTypes(InitTy);
5410     for (unsigned i = 0; i < e; ++i) {
5411       Expr *Init = From->getInit(i);
5412       ImplicitConversionSequence ICS = TryCopyInitialization(
5413           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5414           AllowObjCWritebackConversion);
5415 
5416       // Keep the worse conversion seen so far.
5417       // FIXME: Sequences are not totally ordered, so 'worse' can be
5418       // ambiguous. CWG has been informed.
5419       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5420                                              Result) ==
5421           ImplicitConversionSequence::Worse) {
5422         Result = ICS;
5423         // Bail as soon as we find something unconvertible.
5424         if (Result.isBad()) {
5425           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5426           return Result;
5427         }
5428       }
5429     }
5430 
5431     // If we needed any implicit {} initialization, compare that now.
5432     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5433     // has been informed that this might not be the best thing.
5434     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5435                                 S, From->getEndLoc(), DfltElt, Result) ==
5436                                 ImplicitConversionSequence::Worse)
5437       Result = DfltElt;
5438     // Record the type being initialized so that we may compare sequences
5439     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5440     return Result;
5441   }
5442 
5443   // C++14 [over.ics.list]p4:
5444   // C++11 [over.ics.list]p3:
5445   //   Otherwise, if the parameter is a non-aggregate class X and overload
5446   //   resolution chooses a single best constructor [...] the implicit
5447   //   conversion sequence is a user-defined conversion sequence. If multiple
5448   //   constructors are viable but none is better than the others, the
5449   //   implicit conversion sequence is a user-defined conversion sequence.
5450   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5451     // This function can deal with initializer lists.
5452     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5453                                     AllowedExplicit::None,
5454                                     InOverloadResolution, /*CStyle=*/false,
5455                                     AllowObjCWritebackConversion,
5456                                     /*AllowObjCConversionOnExplicit=*/false);
5457   }
5458 
5459   // C++14 [over.ics.list]p5:
5460   // C++11 [over.ics.list]p4:
5461   //   Otherwise, if the parameter has an aggregate type which can be
5462   //   initialized from the initializer list [...] the implicit conversion
5463   //   sequence is a user-defined conversion sequence.
5464   if (ToType->isAggregateType()) {
5465     // Type is an aggregate, argument is an init list. At this point it comes
5466     // down to checking whether the initialization works.
5467     // FIXME: Find out whether this parameter is consumed or not.
5468     InitializedEntity Entity =
5469         InitializedEntity::InitializeParameter(S.Context, ToType,
5470                                                /*Consumed=*/false);
5471     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5472                                                                  From)) {
5473       Result.setUserDefined();
5474       Result.UserDefined.Before.setAsIdentityConversion();
5475       // Initializer lists don't have a type.
5476       Result.UserDefined.Before.setFromType(QualType());
5477       Result.UserDefined.Before.setAllToTypes(QualType());
5478 
5479       Result.UserDefined.After.setAsIdentityConversion();
5480       Result.UserDefined.After.setFromType(ToType);
5481       Result.UserDefined.After.setAllToTypes(ToType);
5482       Result.UserDefined.ConversionFunction = nullptr;
5483     }
5484     return Result;
5485   }
5486 
5487   // C++14 [over.ics.list]p6:
5488   // C++11 [over.ics.list]p5:
5489   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5490   if (ToType->isReferenceType()) {
5491     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5492     // mention initializer lists in any way. So we go by what list-
5493     // initialization would do and try to extrapolate from that.
5494 
5495     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5496 
5497     // If the initializer list has a single element that is reference-related
5498     // to the parameter type, we initialize the reference from that.
5499     if (From->getNumInits() == 1 && !IsDesignatedInit) {
5500       Expr *Init = From->getInit(0);
5501 
5502       QualType T2 = Init->getType();
5503 
5504       // If the initializer is the address of an overloaded function, try
5505       // to resolve the overloaded function. If all goes well, T2 is the
5506       // type of the resulting function.
5507       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5508         DeclAccessPair Found;
5509         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5510                                    Init, ToType, false, Found))
5511           T2 = Fn->getType();
5512       }
5513 
5514       // Compute some basic properties of the types and the initializer.
5515       Sema::ReferenceCompareResult RefRelationship =
5516           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5517 
5518       if (RefRelationship >= Sema::Ref_Related) {
5519         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5520                                 SuppressUserConversions,
5521                                 /*AllowExplicit=*/false);
5522       }
5523     }
5524 
5525     // Otherwise, we bind the reference to a temporary created from the
5526     // initializer list.
5527     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5528                                InOverloadResolution,
5529                                AllowObjCWritebackConversion);
5530     if (Result.isFailure())
5531       return Result;
5532     assert(!Result.isEllipsis() &&
5533            "Sub-initialization cannot result in ellipsis conversion.");
5534 
5535     // Can we even bind to a temporary?
5536     if (ToType->isRValueReferenceType() ||
5537         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5538       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5539                                             Result.UserDefined.After;
5540       SCS.ReferenceBinding = true;
5541       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5542       SCS.BindsToRvalue = true;
5543       SCS.BindsToFunctionLvalue = false;
5544       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5545       SCS.ObjCLifetimeConversionBinding = false;
5546     } else
5547       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5548                     From, ToType);
5549     return Result;
5550   }
5551 
5552   // C++14 [over.ics.list]p7:
5553   // C++11 [over.ics.list]p6:
5554   //   Otherwise, if the parameter type is not a class:
5555   if (!ToType->isRecordType()) {
5556     //    - if the initializer list has one element that is not itself an
5557     //      initializer list, the implicit conversion sequence is the one
5558     //      required to convert the element to the parameter type.
5559     unsigned NumInits = From->getNumInits();
5560     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5561       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5562                                      SuppressUserConversions,
5563                                      InOverloadResolution,
5564                                      AllowObjCWritebackConversion);
5565     //    - if the initializer list has no elements, the implicit conversion
5566     //      sequence is the identity conversion.
5567     else if (NumInits == 0) {
5568       Result.setStandard();
5569       Result.Standard.setAsIdentityConversion();
5570       Result.Standard.setFromType(ToType);
5571       Result.Standard.setAllToTypes(ToType);
5572     }
5573     return Result;
5574   }
5575 
5576   // C++14 [over.ics.list]p8:
5577   // C++11 [over.ics.list]p7:
5578   //   In all cases other than those enumerated above, no conversion is possible
5579   return Result;
5580 }
5581 
5582 /// TryCopyInitialization - Try to copy-initialize a value of type
5583 /// ToType from the expression From. Return the implicit conversion
5584 /// sequence required to pass this argument, which may be a bad
5585 /// conversion sequence (meaning that the argument cannot be passed to
5586 /// a parameter of this type). If @p SuppressUserConversions, then we
5587 /// do not permit any user-defined conversion sequences.
5588 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)5589 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5590                       bool SuppressUserConversions,
5591                       bool InOverloadResolution,
5592                       bool AllowObjCWritebackConversion,
5593                       bool AllowExplicit) {
5594   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5595     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5596                              InOverloadResolution,AllowObjCWritebackConversion);
5597 
5598   if (ToType->isReferenceType())
5599     return TryReferenceInit(S, From, ToType,
5600                             /*FIXME:*/ From->getBeginLoc(),
5601                             SuppressUserConversions, AllowExplicit);
5602 
5603   return TryImplicitConversion(S, From, ToType,
5604                                SuppressUserConversions,
5605                                AllowedExplicit::None,
5606                                InOverloadResolution,
5607                                /*CStyle=*/false,
5608                                AllowObjCWritebackConversion,
5609                                /*AllowObjCConversionOnExplicit=*/false);
5610 }
5611 
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)5612 static bool TryCopyInitialization(const CanQualType FromQTy,
5613                                   const CanQualType ToQTy,
5614                                   Sema &S,
5615                                   SourceLocation Loc,
5616                                   ExprValueKind FromVK) {
5617   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5618   ImplicitConversionSequence ICS =
5619     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5620 
5621   return !ICS.isBad();
5622 }
5623 
5624 /// TryObjectArgumentInitialization - Try to initialize the object
5625 /// parameter of the given member function (@c Method) from the
5626 /// expression @p From.
TryObjectArgumentInitialization(Sema & S,SourceLocation Loc,QualType FromType,Expr::Classification FromClassification,CXXMethodDecl * Method,const CXXRecordDecl * ActingContext,bool InOverloadResolution=false,QualType ExplicitParameterType=QualType (),bool SuppressUserConversion=false)5627 static ImplicitConversionSequence TryObjectArgumentInitialization(
5628     Sema &S, SourceLocation Loc, QualType FromType,
5629     Expr::Classification FromClassification, CXXMethodDecl *Method,
5630     const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5631     QualType ExplicitParameterType = QualType(),
5632     bool SuppressUserConversion = false) {
5633 
5634   // We need to have an object of class type.
5635   if (const auto *PT = FromType->getAs<PointerType>()) {
5636     FromType = PT->getPointeeType();
5637 
5638     // When we had a pointer, it's implicitly dereferenced, so we
5639     // better have an lvalue.
5640     assert(FromClassification.isLValue());
5641   }
5642 
5643   auto ValueKindFromClassification = [](Expr::Classification C) {
5644     if (C.isPRValue())
5645       return clang::VK_PRValue;
5646     if (C.isXValue())
5647       return VK_XValue;
5648     return clang::VK_LValue;
5649   };
5650 
5651   if (Method->isExplicitObjectMemberFunction()) {
5652     if (ExplicitParameterType.isNull())
5653       ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5654     OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5655                             ValueKindFromClassification(FromClassification));
5656     ImplicitConversionSequence ICS = TryCopyInitialization(
5657         S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5658         /*InOverloadResolution=*/true, false);
5659     if (ICS.isBad())
5660       ICS.Bad.FromExpr = nullptr;
5661     return ICS;
5662   }
5663 
5664   assert(FromType->isRecordType());
5665 
5666   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5667   // C++98 [class.dtor]p2:
5668   //   A destructor can be invoked for a const, volatile or const volatile
5669   //   object.
5670   // C++98 [over.match.funcs]p4:
5671   //   For static member functions, the implicit object parameter is considered
5672   //   to match any object (since if the function is selected, the object is
5673   //   discarded).
5674   Qualifiers Quals = Method->getMethodQualifiers();
5675   if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5676     Quals.addConst();
5677     Quals.addVolatile();
5678   }
5679 
5680   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5681 
5682   // Set up the conversion sequence as a "bad" conversion, to allow us
5683   // to exit early.
5684   ImplicitConversionSequence ICS;
5685 
5686   // C++0x [over.match.funcs]p4:
5687   //   For non-static member functions, the type of the implicit object
5688   //   parameter is
5689   //
5690   //     - "lvalue reference to cv X" for functions declared without a
5691   //        ref-qualifier or with the & ref-qualifier
5692   //     - "rvalue reference to cv X" for functions declared with the &&
5693   //        ref-qualifier
5694   //
5695   // where X is the class of which the function is a member and cv is the
5696   // cv-qualification on the member function declaration.
5697   //
5698   // However, when finding an implicit conversion sequence for the argument, we
5699   // are not allowed to perform user-defined conversions
5700   // (C++ [over.match.funcs]p5). We perform a simplified version of
5701   // reference binding here, that allows class rvalues to bind to
5702   // non-constant references.
5703 
5704   // First check the qualifiers.
5705   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5706   // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5707   if (ImplicitParamType.getCVRQualifiers() !=
5708           FromTypeCanon.getLocalCVRQualifiers() &&
5709       !ImplicitParamType.isAtLeastAsQualifiedAs(
5710           withoutUnaligned(S.Context, FromTypeCanon))) {
5711     ICS.setBad(BadConversionSequence::bad_qualifiers,
5712                FromType, ImplicitParamType);
5713     return ICS;
5714   }
5715 
5716   if (FromTypeCanon.hasAddressSpace()) {
5717     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5718     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5719     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5720       ICS.setBad(BadConversionSequence::bad_qualifiers,
5721                  FromType, ImplicitParamType);
5722       return ICS;
5723     }
5724   }
5725 
5726   // Check that we have either the same type or a derived type. It
5727   // affects the conversion rank.
5728   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5729   ImplicitConversionKind SecondKind;
5730   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5731     SecondKind = ICK_Identity;
5732   } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5733     SecondKind = ICK_Derived_To_Base;
5734   } else if (!Method->isExplicitObjectMemberFunction()) {
5735     ICS.setBad(BadConversionSequence::unrelated_class,
5736                FromType, ImplicitParamType);
5737     return ICS;
5738   }
5739 
5740   // Check the ref-qualifier.
5741   switch (Method->getRefQualifier()) {
5742   case RQ_None:
5743     // Do nothing; we don't care about lvalueness or rvalueness.
5744     break;
5745 
5746   case RQ_LValue:
5747     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5748       // non-const lvalue reference cannot bind to an rvalue
5749       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5750                  ImplicitParamType);
5751       return ICS;
5752     }
5753     break;
5754 
5755   case RQ_RValue:
5756     if (!FromClassification.isRValue()) {
5757       // rvalue reference cannot bind to an lvalue
5758       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5759                  ImplicitParamType);
5760       return ICS;
5761     }
5762     break;
5763   }
5764 
5765   // Success. Mark this as a reference binding.
5766   ICS.setStandard();
5767   ICS.Standard.setAsIdentityConversion();
5768   ICS.Standard.Second = SecondKind;
5769   ICS.Standard.setFromType(FromType);
5770   ICS.Standard.setAllToTypes(ImplicitParamType);
5771   ICS.Standard.ReferenceBinding = true;
5772   ICS.Standard.DirectBinding = true;
5773   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5774   ICS.Standard.BindsToFunctionLvalue = false;
5775   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5776   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5777     = (Method->getRefQualifier() == RQ_None);
5778   return ICS;
5779 }
5780 
5781 /// PerformObjectArgumentInitialization - Perform initialization of
5782 /// the implicit object parameter for the given Method with the given
5783 /// expression.
PerformImplicitObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)5784 ExprResult Sema::PerformImplicitObjectArgumentInitialization(
5785     Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5786     CXXMethodDecl *Method) {
5787   QualType FromRecordType, DestType;
5788   QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5789 
5790   Expr::Classification FromClassification;
5791   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5792     FromRecordType = PT->getPointeeType();
5793     DestType = Method->getThisType();
5794     FromClassification = Expr::Classification::makeSimpleLValue();
5795   } else {
5796     FromRecordType = From->getType();
5797     DestType = ImplicitParamRecordType;
5798     FromClassification = From->Classify(Context);
5799 
5800     // When performing member access on a prvalue, materialize a temporary.
5801     if (From->isPRValue()) {
5802       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5803                                             Method->getRefQualifier() !=
5804                                                 RefQualifierKind::RQ_RValue);
5805     }
5806   }
5807 
5808   // Note that we always use the true parent context when performing
5809   // the actual argument initialization.
5810   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5811       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5812       Method->getParent());
5813   if (ICS.isBad()) {
5814     switch (ICS.Bad.Kind) {
5815     case BadConversionSequence::bad_qualifiers: {
5816       Qualifiers FromQs = FromRecordType.getQualifiers();
5817       Qualifiers ToQs = DestType.getQualifiers();
5818       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5819       if (CVR) {
5820         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5821             << Method->getDeclName() << FromRecordType << (CVR - 1)
5822             << From->getSourceRange();
5823         Diag(Method->getLocation(), diag::note_previous_decl)
5824           << Method->getDeclName();
5825         return ExprError();
5826       }
5827       break;
5828     }
5829 
5830     case BadConversionSequence::lvalue_ref_to_rvalue:
5831     case BadConversionSequence::rvalue_ref_to_lvalue: {
5832       bool IsRValueQualified =
5833         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5834       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5835           << Method->getDeclName() << FromClassification.isRValue()
5836           << IsRValueQualified;
5837       Diag(Method->getLocation(), diag::note_previous_decl)
5838         << Method->getDeclName();
5839       return ExprError();
5840     }
5841 
5842     case BadConversionSequence::no_conversion:
5843     case BadConversionSequence::unrelated_class:
5844       break;
5845 
5846     case BadConversionSequence::too_few_initializers:
5847     case BadConversionSequence::too_many_initializers:
5848       llvm_unreachable("Lists are not objects");
5849     }
5850 
5851     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5852            << ImplicitParamRecordType << FromRecordType
5853            << From->getSourceRange();
5854   }
5855 
5856   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5857     ExprResult FromRes =
5858       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5859     if (FromRes.isInvalid())
5860       return ExprError();
5861     From = FromRes.get();
5862   }
5863 
5864   if (!Context.hasSameType(From->getType(), DestType)) {
5865     CastKind CK;
5866     QualType PteeTy = DestType->getPointeeType();
5867     LangAS DestAS =
5868         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5869     if (FromRecordType.getAddressSpace() != DestAS)
5870       CK = CK_AddressSpaceConversion;
5871     else
5872       CK = CK_NoOp;
5873     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5874   }
5875   return From;
5876 }
5877 
5878 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5879 /// expression From to bool (C++0x [conv]p3).
5880 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)5881 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5882   // C++ [dcl.init]/17.8:
5883   //   - Otherwise, if the initialization is direct-initialization, the source
5884   //     type is std::nullptr_t, and the destination type is bool, the initial
5885   //     value of the object being initialized is false.
5886   if (From->getType()->isNullPtrType())
5887     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5888                                                         S.Context.BoolTy,
5889                                                         From->isGLValue());
5890 
5891   // All other direct-initialization of bool is equivalent to an implicit
5892   // conversion to bool in which explicit conversions are permitted.
5893   return TryImplicitConversion(S, From, S.Context.BoolTy,
5894                                /*SuppressUserConversions=*/false,
5895                                AllowedExplicit::Conversions,
5896                                /*InOverloadResolution=*/false,
5897                                /*CStyle=*/false,
5898                                /*AllowObjCWritebackConversion=*/false,
5899                                /*AllowObjCConversionOnExplicit=*/false);
5900 }
5901 
5902 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5903 /// of the expression From to bool (C++0x [conv]p3).
PerformContextuallyConvertToBool(Expr * From)5904 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5905   if (checkPlaceholderForOverload(*this, From))
5906     return ExprError();
5907 
5908   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5909   if (!ICS.isBad())
5910     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5911 
5912   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5913     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5914            << From->getType() << From->getSourceRange();
5915   return ExprError();
5916 }
5917 
5918 /// Check that the specified conversion is permitted in a converted constant
5919 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5920 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)5921 static bool CheckConvertedConstantConversions(Sema &S,
5922                                               StandardConversionSequence &SCS) {
5923   // Since we know that the target type is an integral or unscoped enumeration
5924   // type, most conversion kinds are impossible. All possible First and Third
5925   // conversions are fine.
5926   switch (SCS.Second) {
5927   case ICK_Identity:
5928   case ICK_Integral_Promotion:
5929   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5930   case ICK_Zero_Queue_Conversion:
5931     return true;
5932 
5933   case ICK_Boolean_Conversion:
5934     // Conversion from an integral or unscoped enumeration type to bool is
5935     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5936     // conversion, so we allow it in a converted constant expression.
5937     //
5938     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5939     // a lot of popular code. We should at least add a warning for this
5940     // (non-conforming) extension.
5941     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5942            SCS.getToType(2)->isBooleanType();
5943 
5944   case ICK_Pointer_Conversion:
5945   case ICK_Pointer_Member:
5946     // C++1z: null pointer conversions and null member pointer conversions are
5947     // only permitted if the source type is std::nullptr_t.
5948     return SCS.getFromType()->isNullPtrType();
5949 
5950   case ICK_Floating_Promotion:
5951   case ICK_Complex_Promotion:
5952   case ICK_Floating_Conversion:
5953   case ICK_Complex_Conversion:
5954   case ICK_Floating_Integral:
5955   case ICK_Compatible_Conversion:
5956   case ICK_Derived_To_Base:
5957   case ICK_Vector_Conversion:
5958   case ICK_SVE_Vector_Conversion:
5959   case ICK_RVV_Vector_Conversion:
5960   case ICK_Vector_Splat:
5961   case ICK_Complex_Real:
5962   case ICK_Block_Pointer_Conversion:
5963   case ICK_TransparentUnionConversion:
5964   case ICK_Writeback_Conversion:
5965   case ICK_Zero_Event_Conversion:
5966   case ICK_C_Only_Conversion:
5967   case ICK_Incompatible_Pointer_Conversion:
5968   case ICK_Fixed_Point_Conversion:
5969     return false;
5970 
5971   case ICK_Lvalue_To_Rvalue:
5972   case ICK_Array_To_Pointer:
5973   case ICK_Function_To_Pointer:
5974     llvm_unreachable("found a first conversion kind in Second");
5975 
5976   case ICK_Function_Conversion:
5977   case ICK_Qualification:
5978     llvm_unreachable("found a third conversion kind in Second");
5979 
5980   case ICK_Num_Conversion_Kinds:
5981     break;
5982   }
5983 
5984   llvm_unreachable("unknown conversion kind");
5985 }
5986 
5987 /// BuildConvertedConstantExpression - Check that the expression From is a
5988 /// converted constant expression of type T, perform the conversion but
5989 /// does not evaluate the expression
BuildConvertedConstantExpression(Sema & S,Expr * From,QualType T,Sema::CCEKind CCE,NamedDecl * Dest,APValue & PreNarrowingValue)5990 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
5991                                                    QualType T,
5992                                                    Sema::CCEKind CCE,
5993                                                    NamedDecl *Dest,
5994                                                    APValue &PreNarrowingValue) {
5995   assert(S.getLangOpts().CPlusPlus11 &&
5996          "converted constant expression outside C++11");
5997 
5998   if (checkPlaceholderForOverload(S, From))
5999     return ExprError();
6000 
6001   // C++1z [expr.const]p3:
6002   //  A converted constant expression of type T is an expression,
6003   //  implicitly converted to type T, where the converted
6004   //  expression is a constant expression and the implicit conversion
6005   //  sequence contains only [... list of conversions ...].
6006   ImplicitConversionSequence ICS =
6007       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
6008           ? TryContextuallyConvertToBool(S, From)
6009           : TryCopyInitialization(S, From, T,
6010                                   /*SuppressUserConversions=*/false,
6011                                   /*InOverloadResolution=*/false,
6012                                   /*AllowObjCWritebackConversion=*/false,
6013                                   /*AllowExplicit=*/false);
6014   StandardConversionSequence *SCS = nullptr;
6015   switch (ICS.getKind()) {
6016   case ImplicitConversionSequence::StandardConversion:
6017     SCS = &ICS.Standard;
6018     break;
6019   case ImplicitConversionSequence::UserDefinedConversion:
6020     if (T->isRecordType())
6021       SCS = &ICS.UserDefined.Before;
6022     else
6023       SCS = &ICS.UserDefined.After;
6024     break;
6025   case ImplicitConversionSequence::AmbiguousConversion:
6026   case ImplicitConversionSequence::BadConversion:
6027     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
6028       return S.Diag(From->getBeginLoc(),
6029                     diag::err_typecheck_converted_constant_expression)
6030              << From->getType() << From->getSourceRange() << T;
6031     return ExprError();
6032 
6033   case ImplicitConversionSequence::EllipsisConversion:
6034   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6035     llvm_unreachable("bad conversion in converted constant expression");
6036   }
6037 
6038   // Check that we would only use permitted conversions.
6039   if (!CheckConvertedConstantConversions(S, *SCS)) {
6040     return S.Diag(From->getBeginLoc(),
6041                   diag::err_typecheck_converted_constant_expression_disallowed)
6042            << From->getType() << From->getSourceRange() << T;
6043   }
6044   // [...] and where the reference binding (if any) binds directly.
6045   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6046     return S.Diag(From->getBeginLoc(),
6047                   diag::err_typecheck_converted_constant_expression_indirect)
6048            << From->getType() << From->getSourceRange() << T;
6049   }
6050   // 'TryCopyInitialization' returns incorrect info for attempts to bind
6051   // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6052   // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6053   // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6054   // case explicitly.
6055   if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6056     return S.Diag(From->getBeginLoc(),
6057                   diag::err_reference_bind_to_bitfield_in_cce)
6058            << From->getSourceRange();
6059   }
6060 
6061   // Usually we can simply apply the ImplicitConversionSequence we formed
6062   // earlier, but that's not guaranteed to work when initializing an object of
6063   // class type.
6064   ExprResult Result;
6065   if (T->isRecordType()) {
6066     assert(CCE == Sema::CCEK_TemplateArg &&
6067            "unexpected class type converted constant expr");
6068     Result = S.PerformCopyInitialization(
6069         InitializedEntity::InitializeTemplateParameter(
6070             T, cast<NonTypeTemplateParmDecl>(Dest)),
6071         SourceLocation(), From);
6072   } else {
6073     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
6074   }
6075   if (Result.isInvalid())
6076     return Result;
6077 
6078   // C++2a [intro.execution]p5:
6079   //   A full-expression is [...] a constant-expression [...]
6080   Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6081                                  /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6082                                  CCE == Sema::CCEKind::CCEK_TemplateArg);
6083   if (Result.isInvalid())
6084     return Result;
6085 
6086   // Check for a narrowing implicit conversion.
6087   bool ReturnPreNarrowingValue = false;
6088   QualType PreNarrowingType;
6089   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6090                                 PreNarrowingType)) {
6091   case NK_Dependent_Narrowing:
6092     // Implicit conversion to a narrower type, but the expression is
6093     // value-dependent so we can't tell whether it's actually narrowing.
6094   case NK_Variable_Narrowing:
6095     // Implicit conversion to a narrower type, and the value is not a constant
6096     // expression. We'll diagnose this in a moment.
6097   case NK_Not_Narrowing:
6098     break;
6099 
6100   case NK_Constant_Narrowing:
6101     if (CCE == Sema::CCEK_ArrayBound &&
6102         PreNarrowingType->isIntegralOrEnumerationType() &&
6103         PreNarrowingValue.isInt()) {
6104       // Don't diagnose array bound narrowing here; we produce more precise
6105       // errors by allowing the un-narrowed value through.
6106       ReturnPreNarrowingValue = true;
6107       break;
6108     }
6109     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6110         << CCE << /*Constant*/ 1
6111         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6112     break;
6113 
6114   case NK_Type_Narrowing:
6115     // FIXME: It would be better to diagnose that the expression is not a
6116     // constant expression.
6117     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6118         << CCE << /*Constant*/ 0 << From->getType() << T;
6119     break;
6120   }
6121   if (!ReturnPreNarrowingValue)
6122     PreNarrowingValue = {};
6123 
6124   return Result;
6125 }
6126 
6127 /// CheckConvertedConstantExpression - Check that the expression From is a
6128 /// converted constant expression of type T, perform the conversion and produce
6129 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Sema & S,Expr * From,QualType T,APValue & Value,Sema::CCEKind CCE,bool RequireInt,NamedDecl * Dest)6130 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6131                                                    QualType T, APValue &Value,
6132                                                    Sema::CCEKind CCE,
6133                                                    bool RequireInt,
6134                                                    NamedDecl *Dest) {
6135 
6136   APValue PreNarrowingValue;
6137   ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6138                                                        PreNarrowingValue);
6139   if (Result.isInvalid() || Result.get()->isValueDependent()) {
6140     Value = APValue();
6141     return Result;
6142   }
6143   return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6144                                                RequireInt, PreNarrowingValue);
6145 }
6146 
BuildConvertedConstantExpression(Expr * From,QualType T,CCEKind CCE,NamedDecl * Dest)6147 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6148                                                   CCEKind CCE,
6149                                                   NamedDecl *Dest) {
6150   APValue PreNarrowingValue;
6151   return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6152                                             PreNarrowingValue);
6153 }
6154 
CheckConvertedConstantExpression(Expr * From,QualType T,APValue & Value,CCEKind CCE,NamedDecl * Dest)6155 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6156                                                   APValue &Value, CCEKind CCE,
6157                                                   NamedDecl *Dest) {
6158   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6159                                             Dest);
6160 }
6161 
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)6162 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6163                                                   llvm::APSInt &Value,
6164                                                   CCEKind CCE) {
6165   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6166 
6167   APValue V;
6168   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6169                                               /*Dest=*/nullptr);
6170   if (!R.isInvalid() && !R.get()->isValueDependent())
6171     Value = V.getInt();
6172   return R;
6173 }
6174 
6175 /// EvaluateConvertedConstantExpression - Evaluate an Expression
6176 /// That is a converted constant expression
6177 /// (which was built with BuildConvertedConstantExpression)
6178 ExprResult
EvaluateConvertedConstantExpression(Expr * E,QualType T,APValue & Value,Sema::CCEKind CCE,bool RequireInt,const APValue & PreNarrowingValue)6179 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6180                                           Sema::CCEKind CCE, bool RequireInt,
6181                                           const APValue &PreNarrowingValue) {
6182 
6183   ExprResult Result = E;
6184   // Check the expression is a constant expression.
6185   SmallVector<PartialDiagnosticAt, 8> Notes;
6186   Expr::EvalResult Eval;
6187   Eval.Diag = &Notes;
6188 
6189   ConstantExprKind Kind;
6190   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6191     Kind = ConstantExprKind::ClassTemplateArgument;
6192   else if (CCE == Sema::CCEK_TemplateArg)
6193     Kind = ConstantExprKind::NonClassTemplateArgument;
6194   else
6195     Kind = ConstantExprKind::Normal;
6196 
6197   if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6198       (RequireInt && !Eval.Val.isInt())) {
6199     // The expression can't be folded, so we can't keep it at this position in
6200     // the AST.
6201     Result = ExprError();
6202   } else {
6203     Value = Eval.Val;
6204 
6205     if (Notes.empty()) {
6206       // It's a constant expression.
6207       Expr *E = Result.get();
6208       if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6209         // We expect a ConstantExpr to have a value associated with it
6210         // by this point.
6211         assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6212                "ConstantExpr has no value associated with it");
6213       } else {
6214         E = ConstantExpr::Create(Context, Result.get(), Value);
6215       }
6216       if (!PreNarrowingValue.isAbsent())
6217         Value = std::move(PreNarrowingValue);
6218       return E;
6219     }
6220   }
6221 
6222   // It's not a constant expression. Produce an appropriate diagnostic.
6223   if (Notes.size() == 1 &&
6224       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6225     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6226   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6227                                    diag::note_constexpr_invalid_template_arg) {
6228     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6229     for (unsigned I = 0; I < Notes.size(); ++I)
6230       Diag(Notes[I].first, Notes[I].second);
6231   } else {
6232     Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6233         << CCE << E->getSourceRange();
6234     for (unsigned I = 0; I < Notes.size(); ++I)
6235       Diag(Notes[I].first, Notes[I].second);
6236   }
6237   return ExprError();
6238 }
6239 
6240 /// dropPointerConversions - If the given standard conversion sequence
6241 /// involves any pointer conversions, remove them.  This may change
6242 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)6243 static void dropPointerConversion(StandardConversionSequence &SCS) {
6244   if (SCS.Second == ICK_Pointer_Conversion) {
6245     SCS.Second = ICK_Identity;
6246     SCS.Third = ICK_Identity;
6247     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6248   }
6249 }
6250 
6251 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6252 /// convert the expression From to an Objective-C pointer type.
6253 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)6254 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6255   // Do an implicit conversion to 'id'.
6256   QualType Ty = S.Context.getObjCIdType();
6257   ImplicitConversionSequence ICS
6258     = TryImplicitConversion(S, From, Ty,
6259                             // FIXME: Are these flags correct?
6260                             /*SuppressUserConversions=*/false,
6261                             AllowedExplicit::Conversions,
6262                             /*InOverloadResolution=*/false,
6263                             /*CStyle=*/false,
6264                             /*AllowObjCWritebackConversion=*/false,
6265                             /*AllowObjCConversionOnExplicit=*/true);
6266 
6267   // Strip off any final conversions to 'id'.
6268   switch (ICS.getKind()) {
6269   case ImplicitConversionSequence::BadConversion:
6270   case ImplicitConversionSequence::AmbiguousConversion:
6271   case ImplicitConversionSequence::EllipsisConversion:
6272   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6273     break;
6274 
6275   case ImplicitConversionSequence::UserDefinedConversion:
6276     dropPointerConversion(ICS.UserDefined.After);
6277     break;
6278 
6279   case ImplicitConversionSequence::StandardConversion:
6280     dropPointerConversion(ICS.Standard);
6281     break;
6282   }
6283 
6284   return ICS;
6285 }
6286 
6287 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6288 /// conversion of the expression From to an Objective-C pointer type.
6289 /// Returns a valid but null ExprResult if no conversion sequence exists.
PerformContextuallyConvertToObjCPointer(Expr * From)6290 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6291   if (checkPlaceholderForOverload(*this, From))
6292     return ExprError();
6293 
6294   QualType Ty = Context.getObjCIdType();
6295   ImplicitConversionSequence ICS =
6296     TryContextuallyConvertToObjCPointer(*this, From);
6297   if (!ICS.isBad())
6298     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6299   return ExprResult();
6300 }
6301 
GetExplicitObjectType(Sema & S,const Expr * MemExprE)6302 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6303   const Expr *Base = nullptr;
6304   assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6305          "expected a member expression");
6306 
6307   if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6308       M && !M->isImplicitAccess())
6309     Base = M->getBase();
6310   else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6311            M && !M->isImplicitAccess())
6312     Base = M->getBase();
6313 
6314   QualType T = Base ? Base->getType() : S.getCurrentThisType();
6315 
6316   if (T->isPointerType())
6317     T = T->getPointeeType();
6318 
6319   return T;
6320 }
6321 
GetExplicitObjectExpr(Sema & S,Expr * Obj,const FunctionDecl * Fun)6322 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6323                                    const FunctionDecl *Fun) {
6324   QualType ObjType = Obj->getType();
6325   if (ObjType->isPointerType()) {
6326     ObjType = ObjType->getPointeeType();
6327     Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6328                                 VK_LValue, OK_Ordinary, SourceLocation(),
6329                                 /*CanOverflow=*/false, FPOptionsOverride());
6330   }
6331   if (Obj->Classify(S.getASTContext()).isPRValue()) {
6332     Obj = S.CreateMaterializeTemporaryExpr(
6333         ObjType, Obj,
6334         !Fun->getParamDecl(0)->getType()->isRValueReferenceType());
6335   }
6336   return Obj;
6337 }
6338 
InitializeExplicitObjectArgument(Sema & S,Expr * Obj,FunctionDecl * Fun)6339 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6340                                                   FunctionDecl *Fun) {
6341   Obj = GetExplicitObjectExpr(S, Obj, Fun);
6342   return S.PerformCopyInitialization(
6343       InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)),
6344       Obj->getExprLoc(), Obj);
6345 }
6346 
PrepareExplicitObjectArgument(Sema & S,CXXMethodDecl * Method,Expr * Object,MultiExprArg & Args,SmallVectorImpl<Expr * > & NewArgs)6347 static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6348                                           Expr *Object, MultiExprArg &Args,
6349                                           SmallVectorImpl<Expr *> &NewArgs) {
6350   assert(Method->isExplicitObjectMemberFunction() &&
6351          "Method is not an explicit member function");
6352   assert(NewArgs.empty() && "NewArgs should be empty");
6353   NewArgs.reserve(Args.size() + 1);
6354   Expr *This = GetExplicitObjectExpr(S, Object, Method);
6355   NewArgs.push_back(This);
6356   NewArgs.append(Args.begin(), Args.end());
6357   Args = NewArgs;
6358 }
6359 
6360 /// Determine whether the provided type is an integral type, or an enumeration
6361 /// type of a permitted flavor.
match(QualType T)6362 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6363   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6364                                  : T->isIntegralOrUnscopedEnumerationType();
6365 }
6366 
6367 static ExprResult
diagnoseAmbiguousConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter,QualType T,UnresolvedSetImpl & ViableConversions)6368 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6369                             Sema::ContextualImplicitConverter &Converter,
6370                             QualType T, UnresolvedSetImpl &ViableConversions) {
6371 
6372   if (Converter.Suppress)
6373     return ExprError();
6374 
6375   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6376   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6377     CXXConversionDecl *Conv =
6378         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6379     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6380     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6381   }
6382   return From;
6383 }
6384 
6385 static bool
diagnoseNoViableConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,UnresolvedSetImpl & ExplicitConversions)6386 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6387                            Sema::ContextualImplicitConverter &Converter,
6388                            QualType T, bool HadMultipleCandidates,
6389                            UnresolvedSetImpl &ExplicitConversions) {
6390   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6391     DeclAccessPair Found = ExplicitConversions[0];
6392     CXXConversionDecl *Conversion =
6393         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6394 
6395     // The user probably meant to invoke the given explicit
6396     // conversion; use it.
6397     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6398     std::string TypeStr;
6399     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6400 
6401     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6402         << FixItHint::CreateInsertion(From->getBeginLoc(),
6403                                       "static_cast<" + TypeStr + ">(")
6404         << FixItHint::CreateInsertion(
6405                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6406     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6407 
6408     // If we aren't in a SFINAE context, build a call to the
6409     // explicit conversion function.
6410     if (SemaRef.isSFINAEContext())
6411       return true;
6412 
6413     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6414     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6415                                                        HadMultipleCandidates);
6416     if (Result.isInvalid())
6417       return true;
6418     // Record usage of conversion in an implicit cast.
6419     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6420                                     CK_UserDefinedConversion, Result.get(),
6421                                     nullptr, Result.get()->getValueKind(),
6422                                     SemaRef.CurFPFeatureOverrides());
6423   }
6424   return false;
6425 }
6426 
recordConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,DeclAccessPair & Found)6427 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6428                              Sema::ContextualImplicitConverter &Converter,
6429                              QualType T, bool HadMultipleCandidates,
6430                              DeclAccessPair &Found) {
6431   CXXConversionDecl *Conversion =
6432       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6433   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6434 
6435   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6436   if (!Converter.SuppressConversion) {
6437     if (SemaRef.isSFINAEContext())
6438       return true;
6439 
6440     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6441         << From->getSourceRange();
6442   }
6443 
6444   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6445                                                      HadMultipleCandidates);
6446   if (Result.isInvalid())
6447     return true;
6448   // Record usage of conversion in an implicit cast.
6449   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6450                                   CK_UserDefinedConversion, Result.get(),
6451                                   nullptr, Result.get()->getValueKind(),
6452                                   SemaRef.CurFPFeatureOverrides());
6453   return false;
6454 }
6455 
finishContextualImplicitConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter)6456 static ExprResult finishContextualImplicitConversion(
6457     Sema &SemaRef, SourceLocation Loc, Expr *From,
6458     Sema::ContextualImplicitConverter &Converter) {
6459   if (!Converter.match(From->getType()) && !Converter.Suppress)
6460     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6461         << From->getSourceRange();
6462 
6463   return SemaRef.DefaultLvalueConversion(From);
6464 }
6465 
6466 static void
collectViableConversionCandidates(Sema & SemaRef,Expr * From,QualType ToType,UnresolvedSetImpl & ViableConversions,OverloadCandidateSet & CandidateSet)6467 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6468                                   UnresolvedSetImpl &ViableConversions,
6469                                   OverloadCandidateSet &CandidateSet) {
6470   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6471     DeclAccessPair FoundDecl = ViableConversions[I];
6472     NamedDecl *D = FoundDecl.getDecl();
6473     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6474     if (isa<UsingShadowDecl>(D))
6475       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6476 
6477     CXXConversionDecl *Conv;
6478     FunctionTemplateDecl *ConvTemplate;
6479     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6480       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6481     else
6482       Conv = cast<CXXConversionDecl>(D);
6483 
6484     if (ConvTemplate)
6485       SemaRef.AddTemplateConversionCandidate(
6486           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6487           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6488     else
6489       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6490                                      ToType, CandidateSet,
6491                                      /*AllowObjCConversionOnExplicit=*/false,
6492                                      /*AllowExplicit*/ true);
6493   }
6494 }
6495 
6496 /// Attempt to convert the given expression to a type which is accepted
6497 /// by the given converter.
6498 ///
6499 /// This routine will attempt to convert an expression of class type to a
6500 /// type accepted by the specified converter. In C++11 and before, the class
6501 /// must have a single non-explicit conversion function converting to a matching
6502 /// type. In C++1y, there can be multiple such conversion functions, but only
6503 /// one target type.
6504 ///
6505 /// \param Loc The source location of the construct that requires the
6506 /// conversion.
6507 ///
6508 /// \param From The expression we're converting from.
6509 ///
6510 /// \param Converter Used to control and diagnose the conversion process.
6511 ///
6512 /// \returns The expression, converted to an integral or enumeration type if
6513 /// successful.
PerformContextualImplicitConversion(SourceLocation Loc,Expr * From,ContextualImplicitConverter & Converter)6514 ExprResult Sema::PerformContextualImplicitConversion(
6515     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6516   // We can't perform any more checking for type-dependent expressions.
6517   if (From->isTypeDependent())
6518     return From;
6519 
6520   // Process placeholders immediately.
6521   if (From->hasPlaceholderType()) {
6522     ExprResult result = CheckPlaceholderExpr(From);
6523     if (result.isInvalid())
6524       return result;
6525     From = result.get();
6526   }
6527 
6528   // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6529   ExprResult Converted = DefaultLvalueConversion(From);
6530   QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6531   // If the expression already has a matching type, we're golden.
6532   if (Converter.match(T))
6533     return Converted;
6534 
6535   // FIXME: Check for missing '()' if T is a function type?
6536 
6537   // We can only perform contextual implicit conversions on objects of class
6538   // type.
6539   const RecordType *RecordTy = T->getAs<RecordType>();
6540   if (!RecordTy || !getLangOpts().CPlusPlus) {
6541     if (!Converter.Suppress)
6542       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6543     return From;
6544   }
6545 
6546   // We must have a complete class type.
6547   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6548     ContextualImplicitConverter &Converter;
6549     Expr *From;
6550 
6551     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6552         : Converter(Converter), From(From) {}
6553 
6554     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6555       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6556     }
6557   } IncompleteDiagnoser(Converter, From);
6558 
6559   if (Converter.Suppress ? !isCompleteType(Loc, T)
6560                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6561     return From;
6562 
6563   // Look for a conversion to an integral or enumeration type.
6564   UnresolvedSet<4>
6565       ViableConversions; // These are *potentially* viable in C++1y.
6566   UnresolvedSet<4> ExplicitConversions;
6567   const auto &Conversions =
6568       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6569 
6570   bool HadMultipleCandidates =
6571       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6572 
6573   // To check that there is only one target type, in C++1y:
6574   QualType ToType;
6575   bool HasUniqueTargetType = true;
6576 
6577   // Collect explicit or viable (potentially in C++1y) conversions.
6578   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6579     NamedDecl *D = (*I)->getUnderlyingDecl();
6580     CXXConversionDecl *Conversion;
6581     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6582     if (ConvTemplate) {
6583       if (getLangOpts().CPlusPlus14)
6584         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6585       else
6586         continue; // C++11 does not consider conversion operator templates(?).
6587     } else
6588       Conversion = cast<CXXConversionDecl>(D);
6589 
6590     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6591            "Conversion operator templates are considered potentially "
6592            "viable in C++1y");
6593 
6594     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6595     if (Converter.match(CurToType) || ConvTemplate) {
6596 
6597       if (Conversion->isExplicit()) {
6598         // FIXME: For C++1y, do we need this restriction?
6599         // cf. diagnoseNoViableConversion()
6600         if (!ConvTemplate)
6601           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6602       } else {
6603         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6604           if (ToType.isNull())
6605             ToType = CurToType.getUnqualifiedType();
6606           else if (HasUniqueTargetType &&
6607                    (CurToType.getUnqualifiedType() != ToType))
6608             HasUniqueTargetType = false;
6609         }
6610         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6611       }
6612     }
6613   }
6614 
6615   if (getLangOpts().CPlusPlus14) {
6616     // C++1y [conv]p6:
6617     // ... An expression e of class type E appearing in such a context
6618     // is said to be contextually implicitly converted to a specified
6619     // type T and is well-formed if and only if e can be implicitly
6620     // converted to a type T that is determined as follows: E is searched
6621     // for conversion functions whose return type is cv T or reference to
6622     // cv T such that T is allowed by the context. There shall be
6623     // exactly one such T.
6624 
6625     // If no unique T is found:
6626     if (ToType.isNull()) {
6627       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6628                                      HadMultipleCandidates,
6629                                      ExplicitConversions))
6630         return ExprError();
6631       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6632     }
6633 
6634     // If more than one unique Ts are found:
6635     if (!HasUniqueTargetType)
6636       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6637                                          ViableConversions);
6638 
6639     // If one unique T is found:
6640     // First, build a candidate set from the previously recorded
6641     // potentially viable conversions.
6642     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6643     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6644                                       CandidateSet);
6645 
6646     // Then, perform overload resolution over the candidate set.
6647     OverloadCandidateSet::iterator Best;
6648     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6649     case OR_Success: {
6650       // Apply this conversion.
6651       DeclAccessPair Found =
6652           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6653       if (recordConversion(*this, Loc, From, Converter, T,
6654                            HadMultipleCandidates, Found))
6655         return ExprError();
6656       break;
6657     }
6658     case OR_Ambiguous:
6659       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6660                                          ViableConversions);
6661     case OR_No_Viable_Function:
6662       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6663                                      HadMultipleCandidates,
6664                                      ExplicitConversions))
6665         return ExprError();
6666       [[fallthrough]];
6667     case OR_Deleted:
6668       // We'll complain below about a non-integral condition type.
6669       break;
6670     }
6671   } else {
6672     switch (ViableConversions.size()) {
6673     case 0: {
6674       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6675                                      HadMultipleCandidates,
6676                                      ExplicitConversions))
6677         return ExprError();
6678 
6679       // We'll complain below about a non-integral condition type.
6680       break;
6681     }
6682     case 1: {
6683       // Apply this conversion.
6684       DeclAccessPair Found = ViableConversions[0];
6685       if (recordConversion(*this, Loc, From, Converter, T,
6686                            HadMultipleCandidates, Found))
6687         return ExprError();
6688       break;
6689     }
6690     default:
6691       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6692                                          ViableConversions);
6693     }
6694   }
6695 
6696   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6697 }
6698 
6699 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6700 /// an acceptable non-member overloaded operator for a call whose
6701 /// arguments have types T1 (and, if non-empty, T2). This routine
6702 /// implements the check in C++ [over.match.oper]p3b2 concerning
6703 /// enumeration types.
IsAcceptableNonMemberOperatorCandidate(ASTContext & Context,FunctionDecl * Fn,ArrayRef<Expr * > Args)6704 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6705                                                    FunctionDecl *Fn,
6706                                                    ArrayRef<Expr *> Args) {
6707   QualType T1 = Args[0]->getType();
6708   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6709 
6710   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6711     return true;
6712 
6713   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6714     return true;
6715 
6716   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6717   if (Proto->getNumParams() < 1)
6718     return false;
6719 
6720   if (T1->isEnumeralType()) {
6721     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6722     if (Context.hasSameUnqualifiedType(T1, ArgType))
6723       return true;
6724   }
6725 
6726   if (Proto->getNumParams() < 2)
6727     return false;
6728 
6729   if (!T2.isNull() && T2->isEnumeralType()) {
6730     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6731     if (Context.hasSameUnqualifiedType(T2, ArgType))
6732       return true;
6733   }
6734 
6735   return false;
6736 }
6737 
6738 /// AddOverloadCandidate - Adds the given function to the set of
6739 /// candidate functions, using the given function call arguments.  If
6740 /// @p SuppressUserConversions, then don't allow user-defined
6741 /// conversions via constructors or conversion operators.
6742 ///
6743 /// \param PartialOverloading true if we are performing "partial" overloading
6744 /// based on an incomplete set of function arguments. This feature is used by
6745 /// 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,bool AggregateCandidateDeduction)6746 void Sema::AddOverloadCandidate(
6747     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6748     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6749     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6750     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6751     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6752   const FunctionProtoType *Proto
6753     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6754   assert(Proto && "Functions without a prototype cannot be overloaded");
6755   assert(!Function->getDescribedFunctionTemplate() &&
6756          "Use AddTemplateOverloadCandidate for function templates");
6757 
6758   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6759     if (!isa<CXXConstructorDecl>(Method)) {
6760       // If we get here, it's because we're calling a member function
6761       // that is named without a member access expression (e.g.,
6762       // "this->f") that was either written explicitly or created
6763       // implicitly. This can happen with a qualified call to a member
6764       // function, e.g., X::f(). We use an empty type for the implied
6765       // object argument (C++ [over.call.func]p3), and the acting context
6766       // is irrelevant.
6767       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6768                          Expr::Classification::makeSimpleLValue(), Args,
6769                          CandidateSet, SuppressUserConversions,
6770                          PartialOverloading, EarlyConversions, PO);
6771       return;
6772     }
6773     // We treat a constructor like a non-member function, since its object
6774     // argument doesn't participate in overload resolution.
6775   }
6776 
6777   if (!CandidateSet.isNewCandidate(Function, PO))
6778     return;
6779 
6780   // C++11 [class.copy]p11: [DR1402]
6781   //   A defaulted move constructor that is defined as deleted is ignored by
6782   //   overload resolution.
6783   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6784   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6785       Constructor->isMoveConstructor())
6786     return;
6787 
6788   // Overload resolution is always an unevaluated context.
6789   EnterExpressionEvaluationContext Unevaluated(
6790       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6791 
6792   // C++ [over.match.oper]p3:
6793   //   if no operand has a class type, only those non-member functions in the
6794   //   lookup set that have a first parameter of type T1 or "reference to
6795   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6796   //   is a right operand) a second parameter of type T2 or "reference to
6797   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6798   //   candidate functions.
6799   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6800       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6801     return;
6802 
6803   // Add this candidate
6804   OverloadCandidate &Candidate =
6805       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6806   Candidate.FoundDecl = FoundDecl;
6807   Candidate.Function = Function;
6808   Candidate.Viable = true;
6809   Candidate.RewriteKind =
6810       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6811   Candidate.IsSurrogate = false;
6812   Candidate.IsADLCandidate = IsADLCandidate;
6813   Candidate.IgnoreObjectArgument = false;
6814   Candidate.ExplicitCallArguments = Args.size();
6815 
6816   // Explicit functions are not actually candidates at all if we're not
6817   // allowing them in this context, but keep them around so we can point
6818   // to them in diagnostics.
6819   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6820     Candidate.Viable = false;
6821     Candidate.FailureKind = ovl_fail_explicit;
6822     return;
6823   }
6824 
6825   // Functions with internal linkage are only viable in the same module unit.
6826   if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6827     /// FIXME: Currently, the semantics of linkage in clang is slightly
6828     /// different from the semantics in C++ spec. In C++ spec, only names
6829     /// have linkage. So that all entities of the same should share one
6830     /// linkage. But in clang, different entities of the same could have
6831     /// different linkage.
6832     NamedDecl *ND = Function;
6833     if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6834       ND = SpecInfo->getTemplate();
6835 
6836     if (ND->getFormalLinkage() == Linkage::Internal) {
6837       Candidate.Viable = false;
6838       Candidate.FailureKind = ovl_fail_module_mismatched;
6839       return;
6840     }
6841   }
6842 
6843   if (Function->isMultiVersion() &&
6844       ((Function->hasAttr<TargetAttr>() &&
6845         !Function->getAttr<TargetAttr>()->isDefaultVersion()) ||
6846        (Function->hasAttr<TargetVersionAttr>() &&
6847         !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
6848     Candidate.Viable = false;
6849     Candidate.FailureKind = ovl_non_default_multiversion_function;
6850     return;
6851   }
6852 
6853   if (Constructor) {
6854     // C++ [class.copy]p3:
6855     //   A member function template is never instantiated to perform the copy
6856     //   of a class object to an object of its class type.
6857     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6858     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6859         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6860          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6861                        ClassType))) {
6862       Candidate.Viable = false;
6863       Candidate.FailureKind = ovl_fail_illegal_constructor;
6864       return;
6865     }
6866 
6867     // C++ [over.match.funcs]p8: (proposed DR resolution)
6868     //   A constructor inherited from class type C that has a first parameter
6869     //   of type "reference to P" (including such a constructor instantiated
6870     //   from a template) is excluded from the set of candidate functions when
6871     //   constructing an object of type cv D if the argument list has exactly
6872     //   one argument and D is reference-related to P and P is reference-related
6873     //   to C.
6874     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6875     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6876         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6877       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6878       QualType C = Context.getRecordType(Constructor->getParent());
6879       QualType D = Context.getRecordType(Shadow->getParent());
6880       SourceLocation Loc = Args.front()->getExprLoc();
6881       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6882           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6883         Candidate.Viable = false;
6884         Candidate.FailureKind = ovl_fail_inhctor_slice;
6885         return;
6886       }
6887     }
6888 
6889     // Check that the constructor is capable of constructing an object in the
6890     // destination address space.
6891     if (!Qualifiers::isAddressSpaceSupersetOf(
6892             Constructor->getMethodQualifiers().getAddressSpace(),
6893             CandidateSet.getDestAS())) {
6894       Candidate.Viable = false;
6895       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6896     }
6897   }
6898 
6899   unsigned NumParams = Proto->getNumParams();
6900 
6901   // (C++ 13.3.2p2): A candidate function having fewer than m
6902   // parameters is viable only if it has an ellipsis in its parameter
6903   // list (8.3.5).
6904   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6905       !Proto->isVariadic() &&
6906       shouldEnforceArgLimit(PartialOverloading, Function)) {
6907     Candidate.Viable = false;
6908     Candidate.FailureKind = ovl_fail_too_many_arguments;
6909     return;
6910   }
6911 
6912   // (C++ 13.3.2p2): A candidate function having more than m parameters
6913   // is viable only if the (m+1)st parameter has a default argument
6914   // (8.3.6). For the purposes of overload resolution, the
6915   // parameter list is truncated on the right, so that there are
6916   // exactly m parameters.
6917   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6918   if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
6919       !PartialOverloading) {
6920     // Not enough arguments.
6921     Candidate.Viable = false;
6922     Candidate.FailureKind = ovl_fail_too_few_arguments;
6923     return;
6924   }
6925 
6926   // (CUDA B.1): Check for invalid calls between targets.
6927   if (getLangOpts().CUDA) {
6928     const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
6929     // Skip the check for callers that are implicit members, because in this
6930     // case we may not yet know what the member's target is; the target is
6931     // inferred for the member automatically, based on the bases and fields of
6932     // the class.
6933     if (!(Caller && Caller->isImplicit()) &&
6934         !IsAllowedCUDACall(Caller, Function)) {
6935       Candidate.Viable = false;
6936       Candidate.FailureKind = ovl_fail_bad_target;
6937       return;
6938     }
6939   }
6940 
6941   if (Function->getTrailingRequiresClause()) {
6942     ConstraintSatisfaction Satisfaction;
6943     if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
6944                                  /*ForOverloadResolution*/ true) ||
6945         !Satisfaction.IsSatisfied) {
6946       Candidate.Viable = false;
6947       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6948       return;
6949     }
6950   }
6951 
6952   // Determine the implicit conversion sequences for each of the
6953   // arguments.
6954   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6955     unsigned ConvIdx =
6956         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6957     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6958       // We already formed a conversion sequence for this parameter during
6959       // template argument deduction.
6960     } else if (ArgIdx < NumParams) {
6961       // (C++ 13.3.2p3): for F to be a viable function, there shall
6962       // exist for each argument an implicit conversion sequence
6963       // (13.3.3.1) that converts that argument to the corresponding
6964       // parameter of F.
6965       QualType ParamType = Proto->getParamType(ArgIdx);
6966       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6967           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6968           /*InOverloadResolution=*/true,
6969           /*AllowObjCWritebackConversion=*/
6970           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6971       if (Candidate.Conversions[ConvIdx].isBad()) {
6972         Candidate.Viable = false;
6973         Candidate.FailureKind = ovl_fail_bad_conversion;
6974         return;
6975       }
6976     } else {
6977       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6978       // argument for which there is no corresponding parameter is
6979       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6980       Candidate.Conversions[ConvIdx].setEllipsis();
6981     }
6982   }
6983 
6984   if (EnableIfAttr *FailedAttr =
6985           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6986     Candidate.Viable = false;
6987     Candidate.FailureKind = ovl_fail_enable_if;
6988     Candidate.DeductionFailure.Data = FailedAttr;
6989     return;
6990   }
6991 }
6992 
6993 ObjCMethodDecl *
SelectBestMethod(Selector Sel,MultiExprArg Args,bool IsInstance,SmallVectorImpl<ObjCMethodDecl * > & Methods)6994 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6995                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6996   if (Methods.size() <= 1)
6997     return nullptr;
6998 
6999   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7000     bool Match = true;
7001     ObjCMethodDecl *Method = Methods[b];
7002     unsigned NumNamedArgs = Sel.getNumArgs();
7003     // Method might have more arguments than selector indicates. This is due
7004     // to addition of c-style arguments in method.
7005     if (Method->param_size() > NumNamedArgs)
7006       NumNamedArgs = Method->param_size();
7007     if (Args.size() < NumNamedArgs)
7008       continue;
7009 
7010     for (unsigned i = 0; i < NumNamedArgs; i++) {
7011       // We can't do any type-checking on a type-dependent argument.
7012       if (Args[i]->isTypeDependent()) {
7013         Match = false;
7014         break;
7015       }
7016 
7017       ParmVarDecl *param = Method->parameters()[i];
7018       Expr *argExpr = Args[i];
7019       assert(argExpr && "SelectBestMethod(): missing expression");
7020 
7021       // Strip the unbridged-cast placeholder expression off unless it's
7022       // a consumed argument.
7023       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7024           !param->hasAttr<CFConsumedAttr>())
7025         argExpr = stripARCUnbridgedCast(argExpr);
7026 
7027       // If the parameter is __unknown_anytype, move on to the next method.
7028       if (param->getType() == Context.UnknownAnyTy) {
7029         Match = false;
7030         break;
7031       }
7032 
7033       ImplicitConversionSequence ConversionState
7034         = TryCopyInitialization(*this, argExpr, param->getType(),
7035                                 /*SuppressUserConversions*/false,
7036                                 /*InOverloadResolution=*/true,
7037                                 /*AllowObjCWritebackConversion=*/
7038                                 getLangOpts().ObjCAutoRefCount,
7039                                 /*AllowExplicit*/false);
7040       // This function looks for a reasonably-exact match, so we consider
7041       // incompatible pointer conversions to be a failure here.
7042       if (ConversionState.isBad() ||
7043           (ConversionState.isStandard() &&
7044            ConversionState.Standard.Second ==
7045                ICK_Incompatible_Pointer_Conversion)) {
7046         Match = false;
7047         break;
7048       }
7049     }
7050     // Promote additional arguments to variadic methods.
7051     if (Match && Method->isVariadic()) {
7052       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7053         if (Args[i]->isTypeDependent()) {
7054           Match = false;
7055           break;
7056         }
7057         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7058                                                           nullptr);
7059         if (Arg.isInvalid()) {
7060           Match = false;
7061           break;
7062         }
7063       }
7064     } else {
7065       // Check for extra arguments to non-variadic methods.
7066       if (Args.size() != NumNamedArgs)
7067         Match = false;
7068       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7069         // Special case when selectors have no argument. In this case, select
7070         // one with the most general result type of 'id'.
7071         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7072           QualType ReturnT = Methods[b]->getReturnType();
7073           if (ReturnT->isObjCIdType())
7074             return Methods[b];
7075         }
7076       }
7077     }
7078 
7079     if (Match)
7080       return Method;
7081   }
7082   return nullptr;
7083 }
7084 
convertArgsForAvailabilityChecks(Sema & S,FunctionDecl * Function,Expr * ThisArg,SourceLocation CallLoc,ArrayRef<Expr * > Args,Sema::SFINAETrap & Trap,bool MissingImplicitThis,Expr * & ConvertedThis,SmallVectorImpl<Expr * > & ConvertedArgs)7085 static bool convertArgsForAvailabilityChecks(
7086     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7087     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7088     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7089   if (ThisArg) {
7090     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7091     assert(!isa<CXXConstructorDecl>(Method) &&
7092            "Shouldn't have `this` for ctors!");
7093     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7094     ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7095         ThisArg, /*Qualifier=*/nullptr, Method, Method);
7096     if (R.isInvalid())
7097       return false;
7098     ConvertedThis = R.get();
7099   } else {
7100     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7101       (void)MD;
7102       assert((MissingImplicitThis || MD->isStatic() ||
7103               isa<CXXConstructorDecl>(MD)) &&
7104              "Expected `this` for non-ctor instance methods");
7105     }
7106     ConvertedThis = nullptr;
7107   }
7108 
7109   // Ignore any variadic arguments. Converting them is pointless, since the
7110   // user can't refer to them in the function condition.
7111   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7112 
7113   // Convert the arguments.
7114   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7115     ExprResult R;
7116     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
7117                                         S.Context, Function->getParamDecl(I)),
7118                                     SourceLocation(), Args[I]);
7119 
7120     if (R.isInvalid())
7121       return false;
7122 
7123     ConvertedArgs.push_back(R.get());
7124   }
7125 
7126   if (Trap.hasErrorOccurred())
7127     return false;
7128 
7129   // Push default arguments if needed.
7130   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7131     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7132       ParmVarDecl *P = Function->getParamDecl(i);
7133       if (!P->hasDefaultArg())
7134         return false;
7135       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7136       if (R.isInvalid())
7137         return false;
7138       ConvertedArgs.push_back(R.get());
7139     }
7140 
7141     if (Trap.hasErrorOccurred())
7142       return false;
7143   }
7144   return true;
7145 }
7146 
CheckEnableIf(FunctionDecl * Function,SourceLocation CallLoc,ArrayRef<Expr * > Args,bool MissingImplicitThis)7147 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7148                                   SourceLocation CallLoc,
7149                                   ArrayRef<Expr *> Args,
7150                                   bool MissingImplicitThis) {
7151   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7152   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7153     return nullptr;
7154 
7155   SFINAETrap Trap(*this);
7156   SmallVector<Expr *, 16> ConvertedArgs;
7157   // FIXME: We should look into making enable_if late-parsed.
7158   Expr *DiscardedThis;
7159   if (!convertArgsForAvailabilityChecks(
7160           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7161           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7162     return *EnableIfAttrs.begin();
7163 
7164   for (auto *EIA : EnableIfAttrs) {
7165     APValue Result;
7166     // FIXME: This doesn't consider value-dependent cases, because doing so is
7167     // very difficult. Ideally, we should handle them more gracefully.
7168     if (EIA->getCond()->isValueDependent() ||
7169         !EIA->getCond()->EvaluateWithSubstitution(
7170             Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7171       return EIA;
7172 
7173     if (!Result.isInt() || !Result.getInt().getBoolValue())
7174       return EIA;
7175   }
7176   return nullptr;
7177 }
7178 
7179 template <typename CheckFn>
diagnoseDiagnoseIfAttrsWith(Sema & S,const NamedDecl * ND,bool ArgDependent,SourceLocation Loc,CheckFn && IsSuccessful)7180 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7181                                         bool ArgDependent, SourceLocation Loc,
7182                                         CheckFn &&IsSuccessful) {
7183   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7184   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7185     if (ArgDependent == DIA->getArgDependent())
7186       Attrs.push_back(DIA);
7187   }
7188 
7189   // Common case: No diagnose_if attributes, so we can quit early.
7190   if (Attrs.empty())
7191     return false;
7192 
7193   auto WarningBegin = std::stable_partition(
7194       Attrs.begin(), Attrs.end(),
7195       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7196 
7197   // Note that diagnose_if attributes are late-parsed, so they appear in the
7198   // correct order (unlike enable_if attributes).
7199   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7200                                IsSuccessful);
7201   if (ErrAttr != WarningBegin) {
7202     const DiagnoseIfAttr *DIA = *ErrAttr;
7203     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7204     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7205         << DIA->getParent() << DIA->getCond()->getSourceRange();
7206     return true;
7207   }
7208 
7209   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7210     if (IsSuccessful(DIA)) {
7211       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7212       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7213           << DIA->getParent() << DIA->getCond()->getSourceRange();
7214     }
7215 
7216   return false;
7217 }
7218 
diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl * Function,const Expr * ThisArg,ArrayRef<const Expr * > Args,SourceLocation Loc)7219 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7220                                                const Expr *ThisArg,
7221                                                ArrayRef<const Expr *> Args,
7222                                                SourceLocation Loc) {
7223   return diagnoseDiagnoseIfAttrsWith(
7224       *this, Function, /*ArgDependent=*/true, Loc,
7225       [&](const DiagnoseIfAttr *DIA) {
7226         APValue Result;
7227         // It's sane to use the same Args for any redecl of this function, since
7228         // EvaluateWithSubstitution only cares about the position of each
7229         // argument in the arg list, not the ParmVarDecl* it maps to.
7230         if (!DIA->getCond()->EvaluateWithSubstitution(
7231                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7232           return false;
7233         return Result.isInt() && Result.getInt().getBoolValue();
7234       });
7235 }
7236 
diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl * ND,SourceLocation Loc)7237 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7238                                                  SourceLocation Loc) {
7239   return diagnoseDiagnoseIfAttrsWith(
7240       *this, ND, /*ArgDependent=*/false, Loc,
7241       [&](const DiagnoseIfAttr *DIA) {
7242         bool Result;
7243         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7244                Result;
7245       });
7246 }
7247 
7248 /// Add all of the function declarations in the given function set to
7249 /// the overload candidate set.
AddFunctionCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs,bool SuppressUserConversions,bool PartialOverloading,bool FirstArgumentIsBase)7250 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7251                                  ArrayRef<Expr *> Args,
7252                                  OverloadCandidateSet &CandidateSet,
7253                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7254                                  bool SuppressUserConversions,
7255                                  bool PartialOverloading,
7256                                  bool FirstArgumentIsBase) {
7257   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7258     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7259     ArrayRef<Expr *> FunctionArgs = Args;
7260 
7261     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7262     FunctionDecl *FD =
7263         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7264 
7265     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7266       QualType ObjectType;
7267       Expr::Classification ObjectClassification;
7268       if (Args.size() > 0) {
7269         if (Expr *E = Args[0]) {
7270           // Use the explicit base to restrict the lookup:
7271           ObjectType = E->getType();
7272           // Pointers in the object arguments are implicitly dereferenced, so we
7273           // always classify them as l-values.
7274           if (!ObjectType.isNull() && ObjectType->isPointerType())
7275             ObjectClassification = Expr::Classification::makeSimpleLValue();
7276           else
7277             ObjectClassification = E->Classify(Context);
7278         } // .. else there is an implicit base.
7279         FunctionArgs = Args.slice(1);
7280       }
7281       if (FunTmpl) {
7282         AddMethodTemplateCandidate(
7283             FunTmpl, F.getPair(),
7284             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7285             ExplicitTemplateArgs, ObjectType, ObjectClassification,
7286             FunctionArgs, CandidateSet, SuppressUserConversions,
7287             PartialOverloading);
7288       } else {
7289         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7290                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7291                            ObjectClassification, FunctionArgs, CandidateSet,
7292                            SuppressUserConversions, PartialOverloading);
7293       }
7294     } else {
7295       // This branch handles both standalone functions and static methods.
7296 
7297       // Slice the first argument (which is the base) when we access
7298       // static method as non-static.
7299       if (Args.size() > 0 &&
7300           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7301                         !isa<CXXConstructorDecl>(FD)))) {
7302         assert(cast<CXXMethodDecl>(FD)->isStatic());
7303         FunctionArgs = Args.slice(1);
7304       }
7305       if (FunTmpl) {
7306         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7307                                      ExplicitTemplateArgs, FunctionArgs,
7308                                      CandidateSet, SuppressUserConversions,
7309                                      PartialOverloading);
7310       } else {
7311         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7312                              SuppressUserConversions, PartialOverloading);
7313       }
7314     }
7315   }
7316 }
7317 
7318 /// AddMethodCandidate - Adds a named decl (which is some kind of
7319 /// 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)7320 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7321                               Expr::Classification ObjectClassification,
7322                               ArrayRef<Expr *> Args,
7323                               OverloadCandidateSet &CandidateSet,
7324                               bool SuppressUserConversions,
7325                               OverloadCandidateParamOrder PO) {
7326   NamedDecl *Decl = FoundDecl.getDecl();
7327   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7328 
7329   if (isa<UsingShadowDecl>(Decl))
7330     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7331 
7332   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7333     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7334            "Expected a member function template");
7335     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7336                                /*ExplicitArgs*/ nullptr, ObjectType,
7337                                ObjectClassification, Args, CandidateSet,
7338                                SuppressUserConversions, false, PO);
7339   } else {
7340     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7341                        ObjectType, ObjectClassification, Args, CandidateSet,
7342                        SuppressUserConversions, false, std::nullopt, PO);
7343   }
7344 }
7345 
7346 /// AddMethodCandidate - Adds the given C++ member function to the set
7347 /// of candidate functions, using the given function call arguments
7348 /// and the object argument (@c Object). For example, in a call
7349 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7350 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7351 /// allow user-defined conversions via constructors or conversion
7352 /// operators.
7353 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)7354 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7355                          CXXRecordDecl *ActingContext, QualType ObjectType,
7356                          Expr::Classification ObjectClassification,
7357                          ArrayRef<Expr *> Args,
7358                          OverloadCandidateSet &CandidateSet,
7359                          bool SuppressUserConversions,
7360                          bool PartialOverloading,
7361                          ConversionSequenceList EarlyConversions,
7362                          OverloadCandidateParamOrder PO) {
7363   const FunctionProtoType *Proto
7364     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7365   assert(Proto && "Methods without a prototype cannot be overloaded");
7366   assert(!isa<CXXConstructorDecl>(Method) &&
7367          "Use AddOverloadCandidate for constructors");
7368 
7369   if (!CandidateSet.isNewCandidate(Method, PO))
7370     return;
7371 
7372   // C++11 [class.copy]p23: [DR1402]
7373   //   A defaulted move assignment operator that is defined as deleted is
7374   //   ignored by overload resolution.
7375   if (Method->isDefaulted() && Method->isDeleted() &&
7376       Method->isMoveAssignmentOperator())
7377     return;
7378 
7379   // Overload resolution is always an unevaluated context.
7380   EnterExpressionEvaluationContext Unevaluated(
7381       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7382 
7383   // Add this candidate
7384   OverloadCandidate &Candidate =
7385       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7386   Candidate.FoundDecl = FoundDecl;
7387   Candidate.Function = Method;
7388   Candidate.RewriteKind =
7389       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7390   Candidate.IsSurrogate = false;
7391   Candidate.IgnoreObjectArgument = false;
7392   Candidate.ExplicitCallArguments = Args.size();
7393 
7394   unsigned NumParams = Method->getNumExplicitParams();
7395   unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7396 
7397   // (C++ 13.3.2p2): A candidate function having fewer than m
7398   // parameters is viable only if it has an ellipsis in its parameter
7399   // list (8.3.5).
7400   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7401       !Proto->isVariadic() &&
7402       shouldEnforceArgLimit(PartialOverloading, Method)) {
7403     Candidate.Viable = false;
7404     Candidate.FailureKind = ovl_fail_too_many_arguments;
7405     return;
7406   }
7407 
7408   // (C++ 13.3.2p2): A candidate function having more than m parameters
7409   // is viable only if the (m+1)st parameter has a default argument
7410   // (8.3.6). For the purposes of overload resolution, the
7411   // parameter list is truncated on the right, so that there are
7412   // exactly m parameters.
7413   unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7414   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7415     // Not enough arguments.
7416     Candidate.Viable = false;
7417     Candidate.FailureKind = ovl_fail_too_few_arguments;
7418     return;
7419   }
7420 
7421   Candidate.Viable = true;
7422 
7423   unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7424   if (ObjectType.isNull())
7425     Candidate.IgnoreObjectArgument = true;
7426   else if (Method->isStatic()) {
7427     // [over.best.ics.general]p8
7428     // When the parameter is the implicit object parameter of a static member
7429     // function, the implicit conversion sequence is a standard conversion
7430     // sequence that is neither better nor worse than any other standard
7431     // conversion sequence.
7432     //
7433     // This is a rule that was introduced in C++23 to support static lambdas. We
7434     // apply it retroactively because we want to support static lambdas as an
7435     // extension and it doesn't hurt previous code.
7436     Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7437   } else {
7438     // Determine the implicit conversion sequence for the object
7439     // parameter.
7440     Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7441         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7442         Method, ActingContext, /*InOverloadResolution=*/true);
7443     if (Candidate.Conversions[FirstConvIdx].isBad()) {
7444       Candidate.Viable = false;
7445       Candidate.FailureKind = ovl_fail_bad_conversion;
7446       return;
7447     }
7448   }
7449 
7450   // (CUDA B.1): Check for invalid calls between targets.
7451   if (getLangOpts().CUDA)
7452     if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method)) {
7453       Candidate.Viable = false;
7454       Candidate.FailureKind = ovl_fail_bad_target;
7455       return;
7456     }
7457 
7458   if (Method->getTrailingRequiresClause()) {
7459     ConstraintSatisfaction Satisfaction;
7460     if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7461                                  /*ForOverloadResolution*/ true) ||
7462         !Satisfaction.IsSatisfied) {
7463       Candidate.Viable = false;
7464       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7465       return;
7466     }
7467   }
7468 
7469   // Determine the implicit conversion sequences for each of the
7470   // arguments.
7471   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7472     unsigned ConvIdx =
7473         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7474     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7475       // We already formed a conversion sequence for this parameter during
7476       // template argument deduction.
7477     } else if (ArgIdx < NumParams) {
7478       // (C++ 13.3.2p3): for F to be a viable function, there shall
7479       // exist for each argument an implicit conversion sequence
7480       // (13.3.3.1) that converts that argument to the corresponding
7481       // parameter of F.
7482       QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7483       Candidate.Conversions[ConvIdx]
7484         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7485                                 SuppressUserConversions,
7486                                 /*InOverloadResolution=*/true,
7487                                 /*AllowObjCWritebackConversion=*/
7488                                   getLangOpts().ObjCAutoRefCount);
7489       if (Candidate.Conversions[ConvIdx].isBad()) {
7490         Candidate.Viable = false;
7491         Candidate.FailureKind = ovl_fail_bad_conversion;
7492         return;
7493       }
7494     } else {
7495       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7496       // argument for which there is no corresponding parameter is
7497       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7498       Candidate.Conversions[ConvIdx].setEllipsis();
7499     }
7500   }
7501 
7502   if (EnableIfAttr *FailedAttr =
7503           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7504     Candidate.Viable = false;
7505     Candidate.FailureKind = ovl_fail_enable_if;
7506     Candidate.DeductionFailure.Data = FailedAttr;
7507     return;
7508   }
7509 
7510   if (Method->isMultiVersion() &&
7511       ((Method->hasAttr<TargetAttr>() &&
7512         !Method->getAttr<TargetAttr>()->isDefaultVersion()) ||
7513        (Method->hasAttr<TargetVersionAttr>() &&
7514         !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7515     Candidate.Viable = false;
7516     Candidate.FailureKind = ovl_non_default_multiversion_function;
7517   }
7518 }
7519 
7520 /// Add a C++ member function template as a candidate to the candidate
7521 /// set, using template argument deduction to produce an appropriate member
7522 /// 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)7523 void Sema::AddMethodTemplateCandidate(
7524     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7525     CXXRecordDecl *ActingContext,
7526     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7527     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7528     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7529     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7530   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7531     return;
7532 
7533   // C++ [over.match.funcs]p7:
7534   //   In each case where a candidate is a function template, candidate
7535   //   function template specializations are generated using template argument
7536   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7537   //   candidate functions in the usual way.113) A given name can refer to one
7538   //   or more function templates and also to a set of overloaded non-template
7539   //   functions. In such a case, the candidate functions generated from each
7540   //   function template are combined with the set of non-template candidate
7541   //   functions.
7542   TemplateDeductionInfo Info(CandidateSet.getLocation());
7543   FunctionDecl *Specialization = nullptr;
7544   ConversionSequenceList Conversions;
7545   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7546           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7547           PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7548           ObjectClassification, [&](ArrayRef<QualType> ParamTypes) {
7549             return CheckNonDependentConversions(
7550                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7551                 SuppressUserConversions, ActingContext, ObjectType,
7552                 ObjectClassification, PO);
7553           })) {
7554     OverloadCandidate &Candidate =
7555         CandidateSet.addCandidate(Conversions.size(), Conversions);
7556     Candidate.FoundDecl = FoundDecl;
7557     Candidate.Function = MethodTmpl->getTemplatedDecl();
7558     Candidate.Viable = false;
7559     Candidate.RewriteKind =
7560       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7561     Candidate.IsSurrogate = false;
7562     Candidate.IgnoreObjectArgument =
7563         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7564         ObjectType.isNull();
7565     Candidate.ExplicitCallArguments = Args.size();
7566     if (Result == TDK_NonDependentConversionFailure)
7567       Candidate.FailureKind = ovl_fail_bad_conversion;
7568     else {
7569       Candidate.FailureKind = ovl_fail_bad_deduction;
7570       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7571                                                             Info);
7572     }
7573     return;
7574   }
7575 
7576   // Add the function template specialization produced by template argument
7577   // deduction as a candidate.
7578   assert(Specialization && "Missing member function template specialization?");
7579   assert(isa<CXXMethodDecl>(Specialization) &&
7580          "Specialization is not a member function?");
7581   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7582                      ActingContext, ObjectType, ObjectClassification, Args,
7583                      CandidateSet, SuppressUserConversions, PartialOverloading,
7584                      Conversions, PO);
7585 }
7586 
7587 /// Determine whether a given function template has a simple explicit specifier
7588 /// or a non-value-dependent explicit-specification that evaluates to true.
isNonDependentlyExplicit(FunctionTemplateDecl * FTD)7589 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7590   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7591 }
7592 
7593 /// Add a C++ function template specialization as a candidate
7594 /// in the candidate set, using template argument deduction to produce
7595 /// 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,bool AggregateCandidateDeduction)7596 void Sema::AddTemplateOverloadCandidate(
7597     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7598     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7599     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7600     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7601     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7602   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7603     return;
7604 
7605   // If the function template has a non-dependent explicit specification,
7606   // exclude it now if appropriate; we are not permitted to perform deduction
7607   // and substitution in this case.
7608   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7609     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7610     Candidate.FoundDecl = FoundDecl;
7611     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7612     Candidate.Viable = false;
7613     Candidate.FailureKind = ovl_fail_explicit;
7614     return;
7615   }
7616 
7617   // C++ [over.match.funcs]p7:
7618   //   In each case where a candidate is a function template, candidate
7619   //   function template specializations are generated using template argument
7620   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7621   //   candidate functions in the usual way.113) A given name can refer to one
7622   //   or more function templates and also to a set of overloaded non-template
7623   //   functions. In such a case, the candidate functions generated from each
7624   //   function template are combined with the set of non-template candidate
7625   //   functions.
7626   TemplateDeductionInfo Info(CandidateSet.getLocation());
7627   FunctionDecl *Specialization = nullptr;
7628   ConversionSequenceList Conversions;
7629   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7630           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7631           PartialOverloading, AggregateCandidateDeduction,
7632           /*ObjectType=*/QualType(),
7633           /*ObjectClassification=*/Expr::Classification(),
7634           [&](ArrayRef<QualType> ParamTypes) {
7635             return CheckNonDependentConversions(
7636                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7637                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7638           })) {
7639     OverloadCandidate &Candidate =
7640         CandidateSet.addCandidate(Conversions.size(), Conversions);
7641     Candidate.FoundDecl = FoundDecl;
7642     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7643     Candidate.Viable = false;
7644     Candidate.RewriteKind =
7645       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7646     Candidate.IsSurrogate = false;
7647     Candidate.IsADLCandidate = IsADLCandidate;
7648     // Ignore the object argument if there is one, since we don't have an object
7649     // type.
7650     Candidate.IgnoreObjectArgument =
7651         isa<CXXMethodDecl>(Candidate.Function) &&
7652         !isa<CXXConstructorDecl>(Candidate.Function);
7653     Candidate.ExplicitCallArguments = Args.size();
7654     if (Result == TDK_NonDependentConversionFailure)
7655       Candidate.FailureKind = ovl_fail_bad_conversion;
7656     else {
7657       Candidate.FailureKind = ovl_fail_bad_deduction;
7658       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7659                                                             Info);
7660     }
7661     return;
7662   }
7663 
7664   // Add the function template specialization produced by template argument
7665   // deduction as a candidate.
7666   assert(Specialization && "Missing function template specialization?");
7667   AddOverloadCandidate(
7668       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7669       PartialOverloading, AllowExplicit,
7670       /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7671       Info.AggregateDeductionCandidateHasMismatchedArity);
7672 }
7673 
7674 /// Check that implicit conversion sequences can be formed for each argument
7675 /// whose corresponding parameter has a non-dependent type, per DR1391's
7676 /// [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)7677 bool Sema::CheckNonDependentConversions(
7678     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7679     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7680     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7681     CXXRecordDecl *ActingContext, QualType ObjectType,
7682     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7683   // FIXME: The cases in which we allow explicit conversions for constructor
7684   // arguments never consider calling a constructor template. It's not clear
7685   // that is correct.
7686   const bool AllowExplicit = false;
7687 
7688   auto *FD = FunctionTemplate->getTemplatedDecl();
7689   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7690   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7691   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7692 
7693   Conversions =
7694       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7695 
7696   // Overload resolution is always an unevaluated context.
7697   EnterExpressionEvaluationContext Unevaluated(
7698       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7699 
7700   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7701   // require that, but this check should never result in a hard error, and
7702   // overload resolution is permitted to sidestep instantiations.
7703   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7704       !ObjectType.isNull()) {
7705     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7706     if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7707         !ParamTypes[0]->isDependentType()) {
7708       Conversions[ConvIdx] = TryObjectArgumentInitialization(
7709           *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7710           Method, ActingContext, /*InOverloadResolution=*/true,
7711           FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7712                                                       : QualType());
7713       if (Conversions[ConvIdx].isBad())
7714         return true;
7715     }
7716   }
7717 
7718   unsigned Offset =
7719       Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7720 
7721   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7722        ++I) {
7723     QualType ParamType = ParamTypes[I + Offset];
7724     if (!ParamType->isDependentType()) {
7725       unsigned ConvIdx;
7726       if (PO == OverloadCandidateParamOrder::Reversed) {
7727         ConvIdx = Args.size() - 1 - I;
7728         assert(Args.size() + ThisConversions == 2 &&
7729                "number of args (including 'this') must be exactly 2 for "
7730                "reversed order");
7731         // For members, there would be only one arg 'Args[0]' whose ConvIdx
7732         // would also be 0. 'this' got ConvIdx = 1 previously.
7733         assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7734       } else {
7735         // For members, 'this' got ConvIdx = 0 previously.
7736         ConvIdx = ThisConversions + I;
7737       }
7738       Conversions[ConvIdx]
7739         = TryCopyInitialization(*this, Args[I], ParamType,
7740                                 SuppressUserConversions,
7741                                 /*InOverloadResolution=*/true,
7742                                 /*AllowObjCWritebackConversion=*/
7743                                   getLangOpts().ObjCAutoRefCount,
7744                                 AllowExplicit);
7745       if (Conversions[ConvIdx].isBad())
7746         return true;
7747     }
7748   }
7749 
7750   return false;
7751 }
7752 
7753 /// Determine whether this is an allowable conversion from the result
7754 /// of an explicit conversion operator to the expected type, per C++
7755 /// [over.match.conv]p1 and [over.match.ref]p1.
7756 ///
7757 /// \param ConvType The return type of the conversion function.
7758 ///
7759 /// \param ToType The type we are converting to.
7760 ///
7761 /// \param AllowObjCPointerConversion Allow a conversion from one
7762 /// Objective-C pointer to another.
7763 ///
7764 /// \returns true if the conversion is allowable, false otherwise.
isAllowableExplicitConversion(Sema & S,QualType ConvType,QualType ToType,bool AllowObjCPointerConversion)7765 static bool isAllowableExplicitConversion(Sema &S,
7766                                           QualType ConvType, QualType ToType,
7767                                           bool AllowObjCPointerConversion) {
7768   QualType ToNonRefType = ToType.getNonReferenceType();
7769 
7770   // Easy case: the types are the same.
7771   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7772     return true;
7773 
7774   // Allow qualification conversions.
7775   bool ObjCLifetimeConversion;
7776   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7777                                   ObjCLifetimeConversion))
7778     return true;
7779 
7780   // If we're not allowed to consider Objective-C pointer conversions,
7781   // we're done.
7782   if (!AllowObjCPointerConversion)
7783     return false;
7784 
7785   // Is this an Objective-C pointer conversion?
7786   bool IncompatibleObjC = false;
7787   QualType ConvertedType;
7788   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7789                                    IncompatibleObjC);
7790 }
7791 
7792 /// AddConversionCandidate - Add a C++ conversion function as a
7793 /// candidate in the candidate set (C++ [over.match.conv],
7794 /// C++ [over.match.copy]). From is the expression we're converting from,
7795 /// and ToType is the type that we're eventually trying to convert to
7796 /// (which may or may not be the same type as the type that the
7797 /// conversion function produces).
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion)7798 void Sema::AddConversionCandidate(
7799     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7800     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7801     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7802     bool AllowExplicit, bool AllowResultConversion) {
7803   assert(!Conversion->getDescribedFunctionTemplate() &&
7804          "Conversion function templates use AddTemplateConversionCandidate");
7805   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7806   if (!CandidateSet.isNewCandidate(Conversion))
7807     return;
7808 
7809   // If the conversion function has an undeduced return type, trigger its
7810   // deduction now.
7811   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7812     if (DeduceReturnType(Conversion, From->getExprLoc()))
7813       return;
7814     ConvType = Conversion->getConversionType().getNonReferenceType();
7815   }
7816 
7817   // If we don't allow any conversion of the result type, ignore conversion
7818   // functions that don't convert to exactly (possibly cv-qualified) T.
7819   if (!AllowResultConversion &&
7820       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7821     return;
7822 
7823   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7824   // operator is only a candidate if its return type is the target type or
7825   // can be converted to the target type with a qualification conversion.
7826   //
7827   // FIXME: Include such functions in the candidate list and explain why we
7828   // can't select them.
7829   if (Conversion->isExplicit() &&
7830       !isAllowableExplicitConversion(*this, ConvType, ToType,
7831                                      AllowObjCConversionOnExplicit))
7832     return;
7833 
7834   // Overload resolution is always an unevaluated context.
7835   EnterExpressionEvaluationContext Unevaluated(
7836       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7837 
7838   // Add this candidate
7839   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7840   Candidate.FoundDecl = FoundDecl;
7841   Candidate.Function = Conversion;
7842   Candidate.IsSurrogate = false;
7843   Candidate.IgnoreObjectArgument = false;
7844   Candidate.FinalConversion.setAsIdentityConversion();
7845   Candidate.FinalConversion.setFromType(ConvType);
7846   Candidate.FinalConversion.setAllToTypes(ToType);
7847   Candidate.Viable = true;
7848   Candidate.ExplicitCallArguments = 1;
7849 
7850   // Explicit functions are not actually candidates at all if we're not
7851   // allowing them in this context, but keep them around so we can point
7852   // to them in diagnostics.
7853   if (!AllowExplicit && Conversion->isExplicit()) {
7854     Candidate.Viable = false;
7855     Candidate.FailureKind = ovl_fail_explicit;
7856     return;
7857   }
7858 
7859   // C++ [over.match.funcs]p4:
7860   //   For conversion functions, the function is considered to be a member of
7861   //   the class of the implicit implied object argument for the purpose of
7862   //   defining the type of the implicit object parameter.
7863   //
7864   // Determine the implicit conversion sequence for the implicit
7865   // object parameter.
7866   QualType ObjectType = From->getType();
7867   if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
7868     ObjectType = FromPtrType->getPointeeType();
7869   const auto *ConversionContext =
7870       cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
7871 
7872   // C++23 [over.best.ics.general]
7873   // However, if the target is [...]
7874   // - the object parameter of a user-defined conversion function
7875   // [...] user-defined conversion sequences are not considered.
7876   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7877       *this, CandidateSet.getLocation(), From->getType(),
7878       From->Classify(Context), Conversion, ConversionContext,
7879       /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
7880       /*SuppressUserConversion*/ true);
7881 
7882   if (Candidate.Conversions[0].isBad()) {
7883     Candidate.Viable = false;
7884     Candidate.FailureKind = ovl_fail_bad_conversion;
7885     return;
7886   }
7887 
7888   if (Conversion->getTrailingRequiresClause()) {
7889     ConstraintSatisfaction Satisfaction;
7890     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7891         !Satisfaction.IsSatisfied) {
7892       Candidate.Viable = false;
7893       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7894       return;
7895     }
7896   }
7897 
7898   // We won't go through a user-defined type conversion function to convert a
7899   // derived to base as such conversions are given Conversion Rank. They only
7900   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7901   QualType FromCanon
7902     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7903   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7904   if (FromCanon == ToCanon ||
7905       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7906     Candidate.Viable = false;
7907     Candidate.FailureKind = ovl_fail_trivial_conversion;
7908     return;
7909   }
7910 
7911   // To determine what the conversion from the result of calling the
7912   // conversion function to the type we're eventually trying to
7913   // convert to (ToType), we need to synthesize a call to the
7914   // conversion function and attempt copy initialization from it. This
7915   // makes sure that we get the right semantics with respect to
7916   // lvalues/rvalues and the type. Fortunately, we can allocate this
7917   // call on the stack and we don't need its arguments to be
7918   // well-formed.
7919   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7920                             VK_LValue, From->getBeginLoc());
7921   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7922                                 Context.getPointerType(Conversion->getType()),
7923                                 CK_FunctionToPointerDecay, &ConversionRef,
7924                                 VK_PRValue, FPOptionsOverride());
7925 
7926   QualType ConversionType = Conversion->getConversionType();
7927   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7928     Candidate.Viable = false;
7929     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7930     return;
7931   }
7932 
7933   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7934 
7935   // Note that it is safe to allocate CallExpr on the stack here because
7936   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7937   // allocator).
7938   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7939 
7940   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7941   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7942       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7943 
7944   ImplicitConversionSequence ICS =
7945       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7946                             /*SuppressUserConversions=*/true,
7947                             /*InOverloadResolution=*/false,
7948                             /*AllowObjCWritebackConversion=*/false);
7949 
7950   switch (ICS.getKind()) {
7951   case ImplicitConversionSequence::StandardConversion:
7952     Candidate.FinalConversion = ICS.Standard;
7953 
7954     // C++ [over.ics.user]p3:
7955     //   If the user-defined conversion is specified by a specialization of a
7956     //   conversion function template, the second standard conversion sequence
7957     //   shall have exact match rank.
7958     if (Conversion->getPrimaryTemplate() &&
7959         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7960       Candidate.Viable = false;
7961       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7962       return;
7963     }
7964 
7965     // C++0x [dcl.init.ref]p5:
7966     //    In the second case, if the reference is an rvalue reference and
7967     //    the second standard conversion sequence of the user-defined
7968     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7969     //    program is ill-formed.
7970     if (ToType->isRValueReferenceType() &&
7971         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7972       Candidate.Viable = false;
7973       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7974       return;
7975     }
7976     break;
7977 
7978   case ImplicitConversionSequence::BadConversion:
7979     Candidate.Viable = false;
7980     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7981     return;
7982 
7983   default:
7984     llvm_unreachable(
7985            "Can only end up with a standard conversion sequence or failure");
7986   }
7987 
7988   if (EnableIfAttr *FailedAttr =
7989           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7990     Candidate.Viable = false;
7991     Candidate.FailureKind = ovl_fail_enable_if;
7992     Candidate.DeductionFailure.Data = FailedAttr;
7993     return;
7994   }
7995 
7996   if (Conversion->isMultiVersion() &&
7997       ((Conversion->hasAttr<TargetAttr>() &&
7998         !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) ||
7999        (Conversion->hasAttr<TargetVersionAttr>() &&
8000         !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
8001     Candidate.Viable = false;
8002     Candidate.FailureKind = ovl_non_default_multiversion_function;
8003   }
8004 }
8005 
8006 /// Adds a conversion function template specialization
8007 /// candidate to the overload set, using template argument deduction
8008 /// to deduce the template arguments of the conversion function
8009 /// template from the type that we are converting to (C++
8010 /// [temp.deduct.conv]).
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion)8011 void Sema::AddTemplateConversionCandidate(
8012     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8013     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8014     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8015     bool AllowExplicit, bool AllowResultConversion) {
8016   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8017          "Only conversion function templates permitted here");
8018 
8019   if (!CandidateSet.isNewCandidate(FunctionTemplate))
8020     return;
8021 
8022   // If the function template has a non-dependent explicit specification,
8023   // exclude it now if appropriate; we are not permitted to perform deduction
8024   // and substitution in this case.
8025   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8026     OverloadCandidate &Candidate = CandidateSet.addCandidate();
8027     Candidate.FoundDecl = FoundDecl;
8028     Candidate.Function = FunctionTemplate->getTemplatedDecl();
8029     Candidate.Viable = false;
8030     Candidate.FailureKind = ovl_fail_explicit;
8031     return;
8032   }
8033 
8034   QualType ObjectType = From->getType();
8035   Expr::Classification ObjectClassification = From->Classify(getASTContext());
8036 
8037   TemplateDeductionInfo Info(CandidateSet.getLocation());
8038   CXXConversionDecl *Specialization = nullptr;
8039   if (TemplateDeductionResult Result = DeduceTemplateArguments(
8040           FunctionTemplate, ObjectType, ObjectClassification, ToType,
8041           Specialization, Info)) {
8042     OverloadCandidate &Candidate = CandidateSet.addCandidate();
8043     Candidate.FoundDecl = FoundDecl;
8044     Candidate.Function = FunctionTemplate->getTemplatedDecl();
8045     Candidate.Viable = false;
8046     Candidate.FailureKind = ovl_fail_bad_deduction;
8047     Candidate.IsSurrogate = false;
8048     Candidate.IgnoreObjectArgument = false;
8049     Candidate.ExplicitCallArguments = 1;
8050     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
8051                                                           Info);
8052     return;
8053   }
8054 
8055   // Add the conversion function template specialization produced by
8056   // template argument deduction as a candidate.
8057   assert(Specialization && "Missing function template specialization?");
8058   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8059                          CandidateSet, AllowObjCConversionOnExplicit,
8060                          AllowExplicit, AllowResultConversion);
8061 }
8062 
8063 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8064 /// converts the given @c Object to a function pointer via the
8065 /// conversion function @c Conversion, and then attempts to call it
8066 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
8067 /// 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)8068 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8069                                  DeclAccessPair FoundDecl,
8070                                  CXXRecordDecl *ActingContext,
8071                                  const FunctionProtoType *Proto,
8072                                  Expr *Object,
8073                                  ArrayRef<Expr *> Args,
8074                                  OverloadCandidateSet& CandidateSet) {
8075   if (!CandidateSet.isNewCandidate(Conversion))
8076     return;
8077 
8078   // Overload resolution is always an unevaluated context.
8079   EnterExpressionEvaluationContext Unevaluated(
8080       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8081 
8082   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8083   Candidate.FoundDecl = FoundDecl;
8084   Candidate.Function = nullptr;
8085   Candidate.Surrogate = Conversion;
8086   Candidate.Viable = true;
8087   Candidate.IsSurrogate = true;
8088   Candidate.IgnoreObjectArgument = false;
8089   Candidate.ExplicitCallArguments = Args.size();
8090 
8091   // Determine the implicit conversion sequence for the implicit
8092   // object parameter.
8093   ImplicitConversionSequence ObjectInit;
8094   if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8095     ObjectInit = TryCopyInitialization(*this, Object,
8096                                        Conversion->getParamDecl(0)->getType(),
8097                                        /*SuppressUserConversions=*/false,
8098                                        /*InOverloadResolution=*/true, false);
8099   } else {
8100     ObjectInit = TryObjectArgumentInitialization(
8101         *this, CandidateSet.getLocation(), Object->getType(),
8102         Object->Classify(Context), Conversion, ActingContext);
8103   }
8104 
8105   if (ObjectInit.isBad()) {
8106     Candidate.Viable = false;
8107     Candidate.FailureKind = ovl_fail_bad_conversion;
8108     Candidate.Conversions[0] = ObjectInit;
8109     return;
8110   }
8111 
8112   // The first conversion is actually a user-defined conversion whose
8113   // first conversion is ObjectInit's standard conversion (which is
8114   // effectively a reference binding). Record it as such.
8115   Candidate.Conversions[0].setUserDefined();
8116   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8117   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8118   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8119   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8120   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8121   Candidate.Conversions[0].UserDefined.After
8122     = Candidate.Conversions[0].UserDefined.Before;
8123   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8124 
8125   // Find the
8126   unsigned NumParams = Proto->getNumParams();
8127 
8128   // (C++ 13.3.2p2): A candidate function having fewer than m
8129   // parameters is viable only if it has an ellipsis in its parameter
8130   // list (8.3.5).
8131   if (Args.size() > NumParams && !Proto->isVariadic()) {
8132     Candidate.Viable = false;
8133     Candidate.FailureKind = ovl_fail_too_many_arguments;
8134     return;
8135   }
8136 
8137   // Function types don't have any default arguments, so just check if
8138   // we have enough arguments.
8139   if (Args.size() < NumParams) {
8140     // Not enough arguments.
8141     Candidate.Viable = false;
8142     Candidate.FailureKind = ovl_fail_too_few_arguments;
8143     return;
8144   }
8145 
8146   // Determine the implicit conversion sequences for each of the
8147   // arguments.
8148   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8149     if (ArgIdx < NumParams) {
8150       // (C++ 13.3.2p3): for F to be a viable function, there shall
8151       // exist for each argument an implicit conversion sequence
8152       // (13.3.3.1) that converts that argument to the corresponding
8153       // parameter of F.
8154       QualType ParamType = Proto->getParamType(ArgIdx);
8155       Candidate.Conversions[ArgIdx + 1]
8156         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8157                                 /*SuppressUserConversions=*/false,
8158                                 /*InOverloadResolution=*/false,
8159                                 /*AllowObjCWritebackConversion=*/
8160                                   getLangOpts().ObjCAutoRefCount);
8161       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8162         Candidate.Viable = false;
8163         Candidate.FailureKind = ovl_fail_bad_conversion;
8164         return;
8165       }
8166     } else {
8167       // (C++ 13.3.2p2): For the purposes of overload resolution, any
8168       // argument for which there is no corresponding parameter is
8169       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8170       Candidate.Conversions[ArgIdx + 1].setEllipsis();
8171     }
8172   }
8173 
8174   if (Conversion->getTrailingRequiresClause()) {
8175     ConstraintSatisfaction Satisfaction;
8176     if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8177                                  /*ForOverloadResolution*/ true) ||
8178         !Satisfaction.IsSatisfied) {
8179       Candidate.Viable = false;
8180       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8181       return;
8182     }
8183   }
8184 
8185   if (EnableIfAttr *FailedAttr =
8186           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8187     Candidate.Viable = false;
8188     Candidate.FailureKind = ovl_fail_enable_if;
8189     Candidate.DeductionFailure.Data = FailedAttr;
8190     return;
8191   }
8192 }
8193 
8194 /// Add all of the non-member operator function declarations in the given
8195 /// function set to the overload candidate set.
AddNonMemberOperatorCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs)8196 void Sema::AddNonMemberOperatorCandidates(
8197     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8198     OverloadCandidateSet &CandidateSet,
8199     TemplateArgumentListInfo *ExplicitTemplateArgs) {
8200   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8201     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8202     ArrayRef<Expr *> FunctionArgs = Args;
8203 
8204     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8205     FunctionDecl *FD =
8206         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8207 
8208     // Don't consider rewritten functions if we're not rewriting.
8209     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8210       continue;
8211 
8212     assert(!isa<CXXMethodDecl>(FD) &&
8213            "unqualified operator lookup found a member function");
8214 
8215     if (FunTmpl) {
8216       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8217                                    FunctionArgs, CandidateSet);
8218       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8219         AddTemplateOverloadCandidate(
8220             FunTmpl, F.getPair(), ExplicitTemplateArgs,
8221             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8222             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8223     } else {
8224       if (ExplicitTemplateArgs)
8225         continue;
8226       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8227       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8228         AddOverloadCandidate(
8229             FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8230             false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8231             OverloadCandidateParamOrder::Reversed);
8232     }
8233   }
8234 }
8235 
8236 /// Add overload candidates for overloaded operators that are
8237 /// member functions.
8238 ///
8239 /// Add the overloaded operator candidates that are member functions
8240 /// for the operator Op that was used in an operator expression such
8241 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
8242 /// CandidateSet will store the added overload candidates. (C++
8243 /// [over.match.oper]).
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,OverloadCandidateParamOrder PO)8244 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8245                                        SourceLocation OpLoc,
8246                                        ArrayRef<Expr *> Args,
8247                                        OverloadCandidateSet &CandidateSet,
8248                                        OverloadCandidateParamOrder PO) {
8249   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8250 
8251   // C++ [over.match.oper]p3:
8252   //   For a unary operator @ with an operand of a type whose
8253   //   cv-unqualified version is T1, and for a binary operator @ with
8254   //   a left operand of a type whose cv-unqualified version is T1 and
8255   //   a right operand of a type whose cv-unqualified version is T2,
8256   //   three sets of candidate functions, designated member
8257   //   candidates, non-member candidates and built-in candidates, are
8258   //   constructed as follows:
8259   QualType T1 = Args[0]->getType();
8260 
8261   //     -- If T1 is a complete class type or a class currently being
8262   //        defined, the set of member candidates is the result of the
8263   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8264   //        the set of member candidates is empty.
8265   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8266     // Complete the type if it can be completed.
8267     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8268       return;
8269     // If the type is neither complete nor being defined, bail out now.
8270     if (!T1Rec->getDecl()->getDefinition())
8271       return;
8272 
8273     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8274     LookupQualifiedName(Operators, T1Rec->getDecl());
8275     Operators.suppressAccessDiagnostics();
8276 
8277     for (LookupResult::iterator Oper = Operators.begin(),
8278                                 OperEnd = Operators.end();
8279          Oper != OperEnd; ++Oper) {
8280       if (Oper->getAsFunction() &&
8281           PO == OverloadCandidateParamOrder::Reversed &&
8282           !CandidateSet.getRewriteInfo().shouldAddReversed(
8283               *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8284         continue;
8285       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8286                          Args[0]->Classify(Context), Args.slice(1),
8287                          CandidateSet, /*SuppressUserConversion=*/false, PO);
8288     }
8289   }
8290 }
8291 
8292 /// AddBuiltinCandidate - Add a candidate for a built-in
8293 /// operator. ResultTy and ParamTys are the result and parameter types
8294 /// of the built-in candidate, respectively. Args and NumArgs are the
8295 /// arguments being passed to the candidate. IsAssignmentOperator
8296 /// should be true when this built-in candidate is an assignment
8297 /// operator. NumContextualBoolArguments is the number of arguments
8298 /// (at the beginning of the argument list) that will be contextually
8299 /// converted to bool.
AddBuiltinCandidate(QualType * ParamTys,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)8300 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8301                                OverloadCandidateSet& CandidateSet,
8302                                bool IsAssignmentOperator,
8303                                unsigned NumContextualBoolArguments) {
8304   // Overload resolution is always an unevaluated context.
8305   EnterExpressionEvaluationContext Unevaluated(
8306       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8307 
8308   // Add this candidate
8309   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8310   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8311   Candidate.Function = nullptr;
8312   Candidate.IsSurrogate = false;
8313   Candidate.IgnoreObjectArgument = false;
8314   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8315 
8316   // Determine the implicit conversion sequences for each of the
8317   // arguments.
8318   Candidate.Viable = true;
8319   Candidate.ExplicitCallArguments = Args.size();
8320   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8321     // C++ [over.match.oper]p4:
8322     //   For the built-in assignment operators, conversions of the
8323     //   left operand are restricted as follows:
8324     //     -- no temporaries are introduced to hold the left operand, and
8325     //     -- no user-defined conversions are applied to the left
8326     //        operand to achieve a type match with the left-most
8327     //        parameter of a built-in candidate.
8328     //
8329     // We block these conversions by turning off user-defined
8330     // conversions, since that is the only way that initialization of
8331     // a reference to a non-class type can occur from something that
8332     // is not of the same type.
8333     if (ArgIdx < NumContextualBoolArguments) {
8334       assert(ParamTys[ArgIdx] == Context.BoolTy &&
8335              "Contextual conversion to bool requires bool type");
8336       Candidate.Conversions[ArgIdx]
8337         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8338     } else {
8339       Candidate.Conversions[ArgIdx]
8340         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8341                                 ArgIdx == 0 && IsAssignmentOperator,
8342                                 /*InOverloadResolution=*/false,
8343                                 /*AllowObjCWritebackConversion=*/
8344                                   getLangOpts().ObjCAutoRefCount);
8345     }
8346     if (Candidate.Conversions[ArgIdx].isBad()) {
8347       Candidate.Viable = false;
8348       Candidate.FailureKind = ovl_fail_bad_conversion;
8349       break;
8350     }
8351   }
8352 }
8353 
8354 namespace {
8355 
8356 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8357 /// candidate operator functions for built-in operators (C++
8358 /// [over.built]). The types are separated into pointer types and
8359 /// enumeration types.
8360 class BuiltinCandidateTypeSet  {
8361   /// TypeSet - A set of types.
8362   typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8363 
8364   /// PointerTypes - The set of pointer types that will be used in the
8365   /// built-in candidates.
8366   TypeSet PointerTypes;
8367 
8368   /// MemberPointerTypes - The set of member pointer types that will be
8369   /// used in the built-in candidates.
8370   TypeSet MemberPointerTypes;
8371 
8372   /// EnumerationTypes - The set of enumeration types that will be
8373   /// used in the built-in candidates.
8374   TypeSet EnumerationTypes;
8375 
8376   /// The set of vector types that will be used in the built-in
8377   /// candidates.
8378   TypeSet VectorTypes;
8379 
8380   /// The set of matrix types that will be used in the built-in
8381   /// candidates.
8382   TypeSet MatrixTypes;
8383 
8384   /// A flag indicating non-record types are viable candidates
8385   bool HasNonRecordTypes;
8386 
8387   /// A flag indicating whether either arithmetic or enumeration types
8388   /// were present in the candidate set.
8389   bool HasArithmeticOrEnumeralTypes;
8390 
8391   /// A flag indicating whether the nullptr type was present in the
8392   /// candidate set.
8393   bool HasNullPtrType;
8394 
8395   /// Sema - The semantic analysis instance where we are building the
8396   /// candidate type set.
8397   Sema &SemaRef;
8398 
8399   /// Context - The AST context in which we will build the type sets.
8400   ASTContext &Context;
8401 
8402   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8403                                                const Qualifiers &VisibleQuals);
8404   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8405 
8406 public:
8407   /// iterator - Iterates through the types that are part of the set.
8408   typedef TypeSet::iterator iterator;
8409 
BuiltinCandidateTypeSet(Sema & SemaRef)8410   BuiltinCandidateTypeSet(Sema &SemaRef)
8411     : HasNonRecordTypes(false),
8412       HasArithmeticOrEnumeralTypes(false),
8413       HasNullPtrType(false),
8414       SemaRef(SemaRef),
8415       Context(SemaRef.Context) { }
8416 
8417   void AddTypesConvertedFrom(QualType Ty,
8418                              SourceLocation Loc,
8419                              bool AllowUserConversions,
8420                              bool AllowExplicitConversions,
8421                              const Qualifiers &VisibleTypeConversionsQuals);
8422 
pointer_types()8423   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
member_pointer_types()8424   llvm::iterator_range<iterator> member_pointer_types() {
8425     return MemberPointerTypes;
8426   }
enumeration_types()8427   llvm::iterator_range<iterator> enumeration_types() {
8428     return EnumerationTypes;
8429   }
vector_types()8430   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
matrix_types()8431   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8432 
containsMatrixType(QualType Ty) const8433   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
hasNonRecordTypes()8434   bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()8435   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const8436   bool hasNullPtrType() const { return HasNullPtrType; }
8437 };
8438 
8439 } // end anonymous namespace
8440 
8441 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8442 /// the set of pointer types along with any more-qualified variants of
8443 /// that type. For example, if @p Ty is "int const *", this routine
8444 /// will add "int const *", "int const volatile *", "int const
8445 /// restrict *", and "int const volatile restrict *" to the set of
8446 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8447 /// false otherwise.
8448 ///
8449 /// FIXME: what to do about extended qualifiers?
8450 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)8451 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8452                                              const Qualifiers &VisibleQuals) {
8453 
8454   // Insert this type.
8455   if (!PointerTypes.insert(Ty))
8456     return false;
8457 
8458   QualType PointeeTy;
8459   const PointerType *PointerTy = Ty->getAs<PointerType>();
8460   bool buildObjCPtr = false;
8461   if (!PointerTy) {
8462     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8463     PointeeTy = PTy->getPointeeType();
8464     buildObjCPtr = true;
8465   } else {
8466     PointeeTy = PointerTy->getPointeeType();
8467   }
8468 
8469   // Don't add qualified variants of arrays. For one, they're not allowed
8470   // (the qualifier would sink to the element type), and for another, the
8471   // only overload situation where it matters is subscript or pointer +- int,
8472   // and those shouldn't have qualifier variants anyway.
8473   if (PointeeTy->isArrayType())
8474     return true;
8475 
8476   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8477   bool hasVolatile = VisibleQuals.hasVolatile();
8478   bool hasRestrict = VisibleQuals.hasRestrict();
8479 
8480   // Iterate through all strict supersets of BaseCVR.
8481   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8482     if ((CVR | BaseCVR) != CVR) continue;
8483     // Skip over volatile if no volatile found anywhere in the types.
8484     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8485 
8486     // Skip over restrict if no restrict found anywhere in the types, or if
8487     // the type cannot be restrict-qualified.
8488     if ((CVR & Qualifiers::Restrict) &&
8489         (!hasRestrict ||
8490          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8491       continue;
8492 
8493     // Build qualified pointee type.
8494     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8495 
8496     // Build qualified pointer type.
8497     QualType QPointerTy;
8498     if (!buildObjCPtr)
8499       QPointerTy = Context.getPointerType(QPointeeTy);
8500     else
8501       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8502 
8503     // Insert qualified pointer type.
8504     PointerTypes.insert(QPointerTy);
8505   }
8506 
8507   return true;
8508 }
8509 
8510 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8511 /// to the set of pointer types along with any more-qualified variants of
8512 /// that type. For example, if @p Ty is "int const *", this routine
8513 /// will add "int const *", "int const volatile *", "int const
8514 /// restrict *", and "int const volatile restrict *" to the set of
8515 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8516 /// false otherwise.
8517 ///
8518 /// FIXME: what to do about extended qualifiers?
8519 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)8520 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8521     QualType Ty) {
8522   // Insert this type.
8523   if (!MemberPointerTypes.insert(Ty))
8524     return false;
8525 
8526   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8527   assert(PointerTy && "type was not a member pointer type!");
8528 
8529   QualType PointeeTy = PointerTy->getPointeeType();
8530   // Don't add qualified variants of arrays. For one, they're not allowed
8531   // (the qualifier would sink to the element type), and for another, the
8532   // only overload situation where it matters is subscript or pointer +- int,
8533   // and those shouldn't have qualifier variants anyway.
8534   if (PointeeTy->isArrayType())
8535     return true;
8536   const Type *ClassTy = PointerTy->getClass();
8537 
8538   // Iterate through all strict supersets of the pointee type's CVR
8539   // qualifiers.
8540   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8541   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8542     if ((CVR | BaseCVR) != CVR) continue;
8543 
8544     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8545     MemberPointerTypes.insert(
8546       Context.getMemberPointerType(QPointeeTy, ClassTy));
8547   }
8548 
8549   return true;
8550 }
8551 
8552 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8553 /// Ty can be implicit converted to the given set of @p Types. We're
8554 /// primarily interested in pointer types and enumeration types. We also
8555 /// take member pointer types, for the conditional operator.
8556 /// AllowUserConversions is true if we should look at the conversion
8557 /// functions of a class type, and AllowExplicitConversions if we
8558 /// should also include the explicit conversion functions of a class
8559 /// type.
8560 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)8561 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8562                                                SourceLocation Loc,
8563                                                bool AllowUserConversions,
8564                                                bool AllowExplicitConversions,
8565                                                const Qualifiers &VisibleQuals) {
8566   // Only deal with canonical types.
8567   Ty = Context.getCanonicalType(Ty);
8568 
8569   // Look through reference types; they aren't part of the type of an
8570   // expression for the purposes of conversions.
8571   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8572     Ty = RefTy->getPointeeType();
8573 
8574   // If we're dealing with an array type, decay to the pointer.
8575   if (Ty->isArrayType())
8576     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8577 
8578   // Otherwise, we don't care about qualifiers on the type.
8579   Ty = Ty.getLocalUnqualifiedType();
8580 
8581   // Flag if we ever add a non-record type.
8582   const RecordType *TyRec = Ty->getAs<RecordType>();
8583   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8584 
8585   // Flag if we encounter an arithmetic type.
8586   HasArithmeticOrEnumeralTypes =
8587     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8588 
8589   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8590     PointerTypes.insert(Ty);
8591   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8592     // Insert our type, and its more-qualified variants, into the set
8593     // of types.
8594     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8595       return;
8596   } else if (Ty->isMemberPointerType()) {
8597     // Member pointers are far easier, since the pointee can't be converted.
8598     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8599       return;
8600   } else if (Ty->isEnumeralType()) {
8601     HasArithmeticOrEnumeralTypes = true;
8602     EnumerationTypes.insert(Ty);
8603   } else if (Ty->isVectorType()) {
8604     // We treat vector types as arithmetic types in many contexts as an
8605     // extension.
8606     HasArithmeticOrEnumeralTypes = true;
8607     VectorTypes.insert(Ty);
8608   } else if (Ty->isMatrixType()) {
8609     // Similar to vector types, we treat vector types as arithmetic types in
8610     // many contexts as an extension.
8611     HasArithmeticOrEnumeralTypes = true;
8612     MatrixTypes.insert(Ty);
8613   } else if (Ty->isNullPtrType()) {
8614     HasNullPtrType = true;
8615   } else if (AllowUserConversions && TyRec) {
8616     // No conversion functions in incomplete types.
8617     if (!SemaRef.isCompleteType(Loc, Ty))
8618       return;
8619 
8620     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8621     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8622       if (isa<UsingShadowDecl>(D))
8623         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8624 
8625       // Skip conversion function templates; they don't tell us anything
8626       // about which builtin types we can convert to.
8627       if (isa<FunctionTemplateDecl>(D))
8628         continue;
8629 
8630       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8631       if (AllowExplicitConversions || !Conv->isExplicit()) {
8632         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8633                               VisibleQuals);
8634       }
8635     }
8636   }
8637 }
8638 /// Helper function for adjusting address spaces for the pointer or reference
8639 /// operands of builtin operators depending on the argument.
AdjustAddressSpaceForBuiltinOperandType(Sema & S,QualType T,Expr * Arg)8640 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8641                                                         Expr *Arg) {
8642   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8643 }
8644 
8645 /// Helper function for AddBuiltinOperatorCandidates() that adds
8646 /// the volatile- and non-volatile-qualified assignment operators for the
8647 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)8648 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8649                                                    QualType T,
8650                                                    ArrayRef<Expr *> Args,
8651                                     OverloadCandidateSet &CandidateSet) {
8652   QualType ParamTypes[2];
8653 
8654   // T& operator=(T&, T)
8655   ParamTypes[0] = S.Context.getLValueReferenceType(
8656       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8657   ParamTypes[1] = T;
8658   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8659                         /*IsAssignmentOperator=*/true);
8660 
8661   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8662     // volatile T& operator=(volatile T&, T)
8663     ParamTypes[0] = S.Context.getLValueReferenceType(
8664         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8665                                                 Args[0]));
8666     ParamTypes[1] = T;
8667     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8668                           /*IsAssignmentOperator=*/true);
8669   }
8670 }
8671 
8672 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8673 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)8674 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8675     Qualifiers VRQuals;
8676     const RecordType *TyRec;
8677     if (const MemberPointerType *RHSMPType =
8678         ArgExpr->getType()->getAs<MemberPointerType>())
8679       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8680     else
8681       TyRec = ArgExpr->getType()->getAs<RecordType>();
8682     if (!TyRec) {
8683       // Just to be safe, assume the worst case.
8684       VRQuals.addVolatile();
8685       VRQuals.addRestrict();
8686       return VRQuals;
8687     }
8688 
8689     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8690     if (!ClassDecl->hasDefinition())
8691       return VRQuals;
8692 
8693     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8694       if (isa<UsingShadowDecl>(D))
8695         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8696       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8697         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8698         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8699           CanTy = ResTypeRef->getPointeeType();
8700         // Need to go down the pointer/mempointer chain and add qualifiers
8701         // as see them.
8702         bool done = false;
8703         while (!done) {
8704           if (CanTy.isRestrictQualified())
8705             VRQuals.addRestrict();
8706           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8707             CanTy = ResTypePtr->getPointeeType();
8708           else if (const MemberPointerType *ResTypeMPtr =
8709                 CanTy->getAs<MemberPointerType>())
8710             CanTy = ResTypeMPtr->getPointeeType();
8711           else
8712             done = true;
8713           if (CanTy.isVolatileQualified())
8714             VRQuals.addVolatile();
8715           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8716             return VRQuals;
8717         }
8718       }
8719     }
8720     return VRQuals;
8721 }
8722 
8723 // Note: We're currently only handling qualifiers that are meaningful for the
8724 // LHS of compound assignment overloading.
forAllQualifierCombinationsImpl(QualifiersAndAtomic Available,QualifiersAndAtomic Applied,llvm::function_ref<void (QualifiersAndAtomic)> Callback)8725 static void forAllQualifierCombinationsImpl(
8726     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8727     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8728   // _Atomic
8729   if (Available.hasAtomic()) {
8730     Available.removeAtomic();
8731     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8732     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8733     return;
8734   }
8735 
8736   // volatile
8737   if (Available.hasVolatile()) {
8738     Available.removeVolatile();
8739     assert(!Applied.hasVolatile());
8740     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8741                                     Callback);
8742     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8743     return;
8744   }
8745 
8746   Callback(Applied);
8747 }
8748 
forAllQualifierCombinations(QualifiersAndAtomic Quals,llvm::function_ref<void (QualifiersAndAtomic)> Callback)8749 static void forAllQualifierCombinations(
8750     QualifiersAndAtomic Quals,
8751     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8752   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8753                                          Callback);
8754 }
8755 
makeQualifiedLValueReferenceType(QualType Base,QualifiersAndAtomic Quals,Sema & S)8756 static QualType makeQualifiedLValueReferenceType(QualType Base,
8757                                                  QualifiersAndAtomic Quals,
8758                                                  Sema &S) {
8759   if (Quals.hasAtomic())
8760     Base = S.Context.getAtomicType(Base);
8761   if (Quals.hasVolatile())
8762     Base = S.Context.getVolatileType(Base);
8763   return S.Context.getLValueReferenceType(Base);
8764 }
8765 
8766 namespace {
8767 
8768 /// Helper class to manage the addition of builtin operator overload
8769 /// candidates. It provides shared state and utility methods used throughout
8770 /// the process, as well as a helper method to add each group of builtin
8771 /// operator overloads from the standard to a candidate set.
8772 class BuiltinOperatorOverloadBuilder {
8773   // Common instance state available to all overload candidate addition methods.
8774   Sema &S;
8775   ArrayRef<Expr *> Args;
8776   QualifiersAndAtomic VisibleTypeConversionsQuals;
8777   bool HasArithmeticOrEnumeralCandidateType;
8778   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8779   OverloadCandidateSet &CandidateSet;
8780 
8781   static constexpr int ArithmeticTypesCap = 24;
8782   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8783 
8784   // Define some indices used to iterate over the arithmetic types in
8785   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8786   // types are that preserved by promotion (C++ [over.built]p2).
8787   unsigned FirstIntegralType,
8788            LastIntegralType;
8789   unsigned FirstPromotedIntegralType,
8790            LastPromotedIntegralType;
8791   unsigned FirstPromotedArithmeticType,
8792            LastPromotedArithmeticType;
8793   unsigned NumArithmeticTypes;
8794 
InitArithmeticTypes()8795   void InitArithmeticTypes() {
8796     // Start of promoted types.
8797     FirstPromotedArithmeticType = 0;
8798     ArithmeticTypes.push_back(S.Context.FloatTy);
8799     ArithmeticTypes.push_back(S.Context.DoubleTy);
8800     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8801     if (S.Context.getTargetInfo().hasFloat128Type())
8802       ArithmeticTypes.push_back(S.Context.Float128Ty);
8803     if (S.Context.getTargetInfo().hasIbm128Type())
8804       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8805 
8806     // Start of integral types.
8807     FirstIntegralType = ArithmeticTypes.size();
8808     FirstPromotedIntegralType = ArithmeticTypes.size();
8809     ArithmeticTypes.push_back(S.Context.IntTy);
8810     ArithmeticTypes.push_back(S.Context.LongTy);
8811     ArithmeticTypes.push_back(S.Context.LongLongTy);
8812     if (S.Context.getTargetInfo().hasInt128Type() ||
8813         (S.Context.getAuxTargetInfo() &&
8814          S.Context.getAuxTargetInfo()->hasInt128Type()))
8815       ArithmeticTypes.push_back(S.Context.Int128Ty);
8816     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8817     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8818     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8819     if (S.Context.getTargetInfo().hasInt128Type() ||
8820         (S.Context.getAuxTargetInfo() &&
8821          S.Context.getAuxTargetInfo()->hasInt128Type()))
8822       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8823     LastPromotedIntegralType = ArithmeticTypes.size();
8824     LastPromotedArithmeticType = ArithmeticTypes.size();
8825     // End of promoted types.
8826 
8827     ArithmeticTypes.push_back(S.Context.BoolTy);
8828     ArithmeticTypes.push_back(S.Context.CharTy);
8829     ArithmeticTypes.push_back(S.Context.WCharTy);
8830     if (S.Context.getLangOpts().Char8)
8831       ArithmeticTypes.push_back(S.Context.Char8Ty);
8832     ArithmeticTypes.push_back(S.Context.Char16Ty);
8833     ArithmeticTypes.push_back(S.Context.Char32Ty);
8834     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8835     ArithmeticTypes.push_back(S.Context.ShortTy);
8836     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8837     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8838     LastIntegralType = ArithmeticTypes.size();
8839     NumArithmeticTypes = ArithmeticTypes.size();
8840     // End of integral types.
8841     // FIXME: What about complex? What about half?
8842 
8843     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8844            "Enough inline storage for all arithmetic types.");
8845   }
8846 
8847   /// Helper method to factor out the common pattern of adding overloads
8848   /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile,bool HasRestrict)8849   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8850                                            bool HasVolatile,
8851                                            bool HasRestrict) {
8852     QualType ParamTypes[2] = {
8853       S.Context.getLValueReferenceType(CandidateTy),
8854       S.Context.IntTy
8855     };
8856 
8857     // Non-volatile version.
8858     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8859 
8860     // Use a heuristic to reduce number of builtin candidates in the set:
8861     // add volatile version only if there are conversions to a volatile type.
8862     if (HasVolatile) {
8863       ParamTypes[0] =
8864         S.Context.getLValueReferenceType(
8865           S.Context.getVolatileType(CandidateTy));
8866       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8867     }
8868 
8869     // Add restrict version only if there are conversions to a restrict type
8870     // and our candidate type is a non-restrict-qualified pointer.
8871     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8872         !CandidateTy.isRestrictQualified()) {
8873       ParamTypes[0]
8874         = S.Context.getLValueReferenceType(
8875             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8876       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8877 
8878       if (HasVolatile) {
8879         ParamTypes[0]
8880           = S.Context.getLValueReferenceType(
8881               S.Context.getCVRQualifiedType(CandidateTy,
8882                                             (Qualifiers::Volatile |
8883                                              Qualifiers::Restrict)));
8884         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8885       }
8886     }
8887 
8888   }
8889 
8890   /// Helper to add an overload candidate for a binary builtin with types \p L
8891   /// and \p R.
AddCandidate(QualType L,QualType R)8892   void AddCandidate(QualType L, QualType R) {
8893     QualType LandR[2] = {L, R};
8894     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8895   }
8896 
8897 public:
BuiltinOperatorOverloadBuilder(Sema & S,ArrayRef<Expr * > Args,QualifiersAndAtomic VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)8898   BuiltinOperatorOverloadBuilder(
8899     Sema &S, ArrayRef<Expr *> Args,
8900     QualifiersAndAtomic VisibleTypeConversionsQuals,
8901     bool HasArithmeticOrEnumeralCandidateType,
8902     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8903     OverloadCandidateSet &CandidateSet)
8904     : S(S), Args(Args),
8905       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8906       HasArithmeticOrEnumeralCandidateType(
8907         HasArithmeticOrEnumeralCandidateType),
8908       CandidateTypes(CandidateTypes),
8909       CandidateSet(CandidateSet) {
8910 
8911     InitArithmeticTypes();
8912   }
8913 
8914   // Increment is deprecated for bool since C++17.
8915   //
8916   // C++ [over.built]p3:
8917   //
8918   //   For every pair (T, VQ), where T is an arithmetic type other
8919   //   than bool, and VQ is either volatile or empty, there exist
8920   //   candidate operator functions of the form
8921   //
8922   //       VQ T&      operator++(VQ T&);
8923   //       T          operator++(VQ T&, int);
8924   //
8925   // C++ [over.built]p4:
8926   //
8927   //   For every pair (T, VQ), where T is an arithmetic type other
8928   //   than bool, and VQ is either volatile or empty, there exist
8929   //   candidate operator functions of the form
8930   //
8931   //       VQ T&      operator--(VQ T&);
8932   //       T          operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)8933   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8934     if (!HasArithmeticOrEnumeralCandidateType)
8935       return;
8936 
8937     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8938       const auto TypeOfT = ArithmeticTypes[Arith];
8939       if (TypeOfT == S.Context.BoolTy) {
8940         if (Op == OO_MinusMinus)
8941           continue;
8942         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8943           continue;
8944       }
8945       addPlusPlusMinusMinusStyleOverloads(
8946         TypeOfT,
8947         VisibleTypeConversionsQuals.hasVolatile(),
8948         VisibleTypeConversionsQuals.hasRestrict());
8949     }
8950   }
8951 
8952   // C++ [over.built]p5:
8953   //
8954   //   For every pair (T, VQ), where T is a cv-qualified or
8955   //   cv-unqualified object type, and VQ is either volatile or
8956   //   empty, there exist candidate operator functions of the form
8957   //
8958   //       T*VQ&      operator++(T*VQ&);
8959   //       T*VQ&      operator--(T*VQ&);
8960   //       T*         operator++(T*VQ&, int);
8961   //       T*         operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()8962   void addPlusPlusMinusMinusPointerOverloads() {
8963     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8964       // Skip pointer types that aren't pointers to object types.
8965       if (!PtrTy->getPointeeType()->isObjectType())
8966         continue;
8967 
8968       addPlusPlusMinusMinusStyleOverloads(
8969           PtrTy,
8970           (!PtrTy.isVolatileQualified() &&
8971            VisibleTypeConversionsQuals.hasVolatile()),
8972           (!PtrTy.isRestrictQualified() &&
8973            VisibleTypeConversionsQuals.hasRestrict()));
8974     }
8975   }
8976 
8977   // C++ [over.built]p6:
8978   //   For every cv-qualified or cv-unqualified object type T, there
8979   //   exist candidate operator functions of the form
8980   //
8981   //       T&         operator*(T*);
8982   //
8983   // C++ [over.built]p7:
8984   //   For every function type T that does not have cv-qualifiers or a
8985   //   ref-qualifier, there exist candidate operator functions of the form
8986   //       T&         operator*(T*);
addUnaryStarPointerOverloads()8987   void addUnaryStarPointerOverloads() {
8988     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8989       QualType PointeeTy = ParamTy->getPointeeType();
8990       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8991         continue;
8992 
8993       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8994         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8995           continue;
8996 
8997       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8998     }
8999   }
9000 
9001   // C++ [over.built]p9:
9002   //  For every promoted arithmetic type T, there exist candidate
9003   //  operator functions of the form
9004   //
9005   //       T         operator+(T);
9006   //       T         operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()9007   void addUnaryPlusOrMinusArithmeticOverloads() {
9008     if (!HasArithmeticOrEnumeralCandidateType)
9009       return;
9010 
9011     for (unsigned Arith = FirstPromotedArithmeticType;
9012          Arith < LastPromotedArithmeticType; ++Arith) {
9013       QualType ArithTy = ArithmeticTypes[Arith];
9014       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9015     }
9016 
9017     // Extension: We also add these operators for vector types.
9018     for (QualType VecTy : CandidateTypes[0].vector_types())
9019       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9020   }
9021 
9022   // C++ [over.built]p8:
9023   //   For every type T, there exist candidate operator functions of
9024   //   the form
9025   //
9026   //       T*         operator+(T*);
addUnaryPlusPointerOverloads()9027   void addUnaryPlusPointerOverloads() {
9028     for (QualType ParamTy : CandidateTypes[0].pointer_types())
9029       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9030   }
9031 
9032   // C++ [over.built]p10:
9033   //   For every promoted integral type T, there exist candidate
9034   //   operator functions of the form
9035   //
9036   //        T         operator~(T);
addUnaryTildePromotedIntegralOverloads()9037   void addUnaryTildePromotedIntegralOverloads() {
9038     if (!HasArithmeticOrEnumeralCandidateType)
9039       return;
9040 
9041     for (unsigned Int = FirstPromotedIntegralType;
9042          Int < LastPromotedIntegralType; ++Int) {
9043       QualType IntTy = ArithmeticTypes[Int];
9044       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9045     }
9046 
9047     // Extension: We also add this operator for vector types.
9048     for (QualType VecTy : CandidateTypes[0].vector_types())
9049       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9050   }
9051 
9052   // C++ [over.match.oper]p16:
9053   //   For every pointer to member type T or type std::nullptr_t, there
9054   //   exist candidate operator functions of the form
9055   //
9056   //        bool operator==(T,T);
9057   //        bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads()9058   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9059     /// Set of (canonical) types that we've already handled.
9060     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9061 
9062     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9063       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9064         // Don't add the same builtin candidate twice.
9065         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9066           continue;
9067 
9068         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9069         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9070       }
9071 
9072       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9073         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
9074         if (AddedTypes.insert(NullPtrTy).second) {
9075           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9076           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9077         }
9078       }
9079     }
9080   }
9081 
9082   // C++ [over.built]p15:
9083   //
9084   //   For every T, where T is an enumeration type or a pointer type,
9085   //   there exist candidate operator functions of the form
9086   //
9087   //        bool       operator<(T, T);
9088   //        bool       operator>(T, T);
9089   //        bool       operator<=(T, T);
9090   //        bool       operator>=(T, T);
9091   //        bool       operator==(T, T);
9092   //        bool       operator!=(T, T);
9093   //           R       operator<=>(T, T)
addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship)9094   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9095     // C++ [over.match.oper]p3:
9096     //   [...]the built-in candidates include all of the candidate operator
9097     //   functions defined in 13.6 that, compared to the given operator, [...]
9098     //   do not have the same parameter-type-list as any non-template non-member
9099     //   candidate.
9100     //
9101     // Note that in practice, this only affects enumeration types because there
9102     // aren't any built-in candidates of record type, and a user-defined operator
9103     // must have an operand of record or enumeration type. Also, the only other
9104     // overloaded operator with enumeration arguments, operator=,
9105     // cannot be overloaded for enumeration types, so this is the only place
9106     // where we must suppress candidates like this.
9107     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9108       UserDefinedBinaryOperators;
9109 
9110     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9111       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9112         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9113                                          CEnd = CandidateSet.end();
9114              C != CEnd; ++C) {
9115           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9116             continue;
9117 
9118           if (C->Function->isFunctionTemplateSpecialization())
9119             continue;
9120 
9121           // We interpret "same parameter-type-list" as applying to the
9122           // "synthesized candidate, with the order of the two parameters
9123           // reversed", not to the original function.
9124           bool Reversed = C->isReversed();
9125           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9126                                         ->getType()
9127                                         .getUnqualifiedType();
9128           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9129                                          ->getType()
9130                                          .getUnqualifiedType();
9131 
9132           // Skip if either parameter isn't of enumeral type.
9133           if (!FirstParamType->isEnumeralType() ||
9134               !SecondParamType->isEnumeralType())
9135             continue;
9136 
9137           // Add this operator to the set of known user-defined operators.
9138           UserDefinedBinaryOperators.insert(
9139             std::make_pair(S.Context.getCanonicalType(FirstParamType),
9140                            S.Context.getCanonicalType(SecondParamType)));
9141         }
9142       }
9143     }
9144 
9145     /// Set of (canonical) types that we've already handled.
9146     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9147 
9148     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9149       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9150         // Don't add the same builtin candidate twice.
9151         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9152           continue;
9153         if (IsSpaceship && PtrTy->isFunctionPointerType())
9154           continue;
9155 
9156         QualType ParamTypes[2] = {PtrTy, PtrTy};
9157         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9158       }
9159       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9160         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9161 
9162         // Don't add the same builtin candidate twice, or if a user defined
9163         // candidate exists.
9164         if (!AddedTypes.insert(CanonType).second ||
9165             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9166                                                             CanonType)))
9167           continue;
9168         QualType ParamTypes[2] = {EnumTy, EnumTy};
9169         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9170       }
9171     }
9172   }
9173 
9174   // C++ [over.built]p13:
9175   //
9176   //   For every cv-qualified or cv-unqualified object type T
9177   //   there exist candidate operator functions of the form
9178   //
9179   //      T*         operator+(T*, ptrdiff_t);
9180   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
9181   //      T*         operator-(T*, ptrdiff_t);
9182   //      T*         operator+(ptrdiff_t, T*);
9183   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
9184   //
9185   // C++ [over.built]p14:
9186   //
9187   //   For every T, where T is a pointer to object type, there
9188   //   exist candidate operator functions of the form
9189   //
9190   //      ptrdiff_t  operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)9191   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9192     /// Set of (canonical) types that we've already handled.
9193     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9194 
9195     for (int Arg = 0; Arg < 2; ++Arg) {
9196       QualType AsymmetricParamTypes[2] = {
9197         S.Context.getPointerDiffType(),
9198         S.Context.getPointerDiffType(),
9199       };
9200       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9201         QualType PointeeTy = PtrTy->getPointeeType();
9202         if (!PointeeTy->isObjectType())
9203           continue;
9204 
9205         AsymmetricParamTypes[Arg] = PtrTy;
9206         if (Arg == 0 || Op == OO_Plus) {
9207           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9208           // T* operator+(ptrdiff_t, T*);
9209           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9210         }
9211         if (Op == OO_Minus) {
9212           // ptrdiff_t operator-(T, T);
9213           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9214             continue;
9215 
9216           QualType ParamTypes[2] = {PtrTy, PtrTy};
9217           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9218         }
9219       }
9220     }
9221   }
9222 
9223   // C++ [over.built]p12:
9224   //
9225   //   For every pair of promoted arithmetic types L and R, there
9226   //   exist candidate operator functions of the form
9227   //
9228   //        LR         operator*(L, R);
9229   //        LR         operator/(L, R);
9230   //        LR         operator+(L, R);
9231   //        LR         operator-(L, R);
9232   //        bool       operator<(L, R);
9233   //        bool       operator>(L, R);
9234   //        bool       operator<=(L, R);
9235   //        bool       operator>=(L, R);
9236   //        bool       operator==(L, R);
9237   //        bool       operator!=(L, R);
9238   //
9239   //   where LR is the result of the usual arithmetic conversions
9240   //   between types L and R.
9241   //
9242   // C++ [over.built]p24:
9243   //
9244   //   For every pair of promoted arithmetic types L and R, there exist
9245   //   candidate operator functions of the form
9246   //
9247   //        LR       operator?(bool, L, R);
9248   //
9249   //   where LR is the result of the usual arithmetic conversions
9250   //   between types L and R.
9251   // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads()9252   void addGenericBinaryArithmeticOverloads() {
9253     if (!HasArithmeticOrEnumeralCandidateType)
9254       return;
9255 
9256     for (unsigned Left = FirstPromotedArithmeticType;
9257          Left < LastPromotedArithmeticType; ++Left) {
9258       for (unsigned Right = FirstPromotedArithmeticType;
9259            Right < LastPromotedArithmeticType; ++Right) {
9260         QualType LandR[2] = { ArithmeticTypes[Left],
9261                               ArithmeticTypes[Right] };
9262         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9263       }
9264     }
9265 
9266     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9267     // conditional operator for vector types.
9268     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9269       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9270         QualType LandR[2] = {Vec1Ty, Vec2Ty};
9271         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9272       }
9273   }
9274 
9275   /// Add binary operator overloads for each candidate matrix type M1, M2:
9276   ///  * (M1, M1) -> M1
9277   ///  * (M1, M1.getElementType()) -> M1
9278   ///  * (M2.getElementType(), M2) -> M2
9279   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
addMatrixBinaryArithmeticOverloads()9280   void addMatrixBinaryArithmeticOverloads() {
9281     if (!HasArithmeticOrEnumeralCandidateType)
9282       return;
9283 
9284     for (QualType M1 : CandidateTypes[0].matrix_types()) {
9285       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9286       AddCandidate(M1, M1);
9287     }
9288 
9289     for (QualType M2 : CandidateTypes[1].matrix_types()) {
9290       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9291       if (!CandidateTypes[0].containsMatrixType(M2))
9292         AddCandidate(M2, M2);
9293     }
9294   }
9295 
9296   // C++2a [over.built]p14:
9297   //
9298   //   For every integral type T there exists a candidate operator function
9299   //   of the form
9300   //
9301   //        std::strong_ordering operator<=>(T, T)
9302   //
9303   // C++2a [over.built]p15:
9304   //
9305   //   For every pair of floating-point types L and R, there exists a candidate
9306   //   operator function of the form
9307   //
9308   //       std::partial_ordering operator<=>(L, R);
9309   //
9310   // FIXME: The current specification for integral types doesn't play nice with
9311   // the direction of p0946r0, which allows mixed integral and unscoped-enum
9312   // comparisons. Under the current spec this can lead to ambiguity during
9313   // overload resolution. For example:
9314   //
9315   //   enum A : int {a};
9316   //   auto x = (a <=> (long)42);
9317   //
9318   //   error: call is ambiguous for arguments 'A' and 'long'.
9319   //   note: candidate operator<=>(int, int)
9320   //   note: candidate operator<=>(long, long)
9321   //
9322   // To avoid this error, this function deviates from the specification and adds
9323   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9324   // arithmetic types (the same as the generic relational overloads).
9325   //
9326   // For now this function acts as a placeholder.
addThreeWayArithmeticOverloads()9327   void addThreeWayArithmeticOverloads() {
9328     addGenericBinaryArithmeticOverloads();
9329   }
9330 
9331   // C++ [over.built]p17:
9332   //
9333   //   For every pair of promoted integral types L and R, there
9334   //   exist candidate operator functions of the form
9335   //
9336   //      LR         operator%(L, R);
9337   //      LR         operator&(L, R);
9338   //      LR         operator^(L, R);
9339   //      LR         operator|(L, R);
9340   //      L          operator<<(L, R);
9341   //      L          operator>>(L, R);
9342   //
9343   //   where LR is the result of the usual arithmetic conversions
9344   //   between types L and R.
addBinaryBitwiseArithmeticOverloads()9345   void addBinaryBitwiseArithmeticOverloads() {
9346     if (!HasArithmeticOrEnumeralCandidateType)
9347       return;
9348 
9349     for (unsigned Left = FirstPromotedIntegralType;
9350          Left < LastPromotedIntegralType; ++Left) {
9351       for (unsigned Right = FirstPromotedIntegralType;
9352            Right < LastPromotedIntegralType; ++Right) {
9353         QualType LandR[2] = { ArithmeticTypes[Left],
9354                               ArithmeticTypes[Right] };
9355         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9356       }
9357     }
9358   }
9359 
9360   // C++ [over.built]p20:
9361   //
9362   //   For every pair (T, VQ), where T is an enumeration or
9363   //   pointer to member type and VQ is either volatile or
9364   //   empty, there exist candidate operator functions of the form
9365   //
9366   //        VQ T&      operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()9367   void addAssignmentMemberPointerOrEnumeralOverloads() {
9368     /// Set of (canonical) types that we've already handled.
9369     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9370 
9371     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9372       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9373         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9374           continue;
9375 
9376         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9377       }
9378 
9379       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9380         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9381           continue;
9382 
9383         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9384       }
9385     }
9386   }
9387 
9388   // C++ [over.built]p19:
9389   //
9390   //   For every pair (T, VQ), where T is any type and VQ is either
9391   //   volatile or empty, there exist candidate operator functions
9392   //   of the form
9393   //
9394   //        T*VQ&      operator=(T*VQ&, T*);
9395   //
9396   // C++ [over.built]p21:
9397   //
9398   //   For every pair (T, VQ), where T is a cv-qualified or
9399   //   cv-unqualified object type and VQ is either volatile or
9400   //   empty, there exist candidate operator functions of the form
9401   //
9402   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
9403   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)9404   void addAssignmentPointerOverloads(bool isEqualOp) {
9405     /// Set of (canonical) types that we've already handled.
9406     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9407 
9408     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9409       // If this is operator=, keep track of the builtin candidates we added.
9410       if (isEqualOp)
9411         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9412       else if (!PtrTy->getPointeeType()->isObjectType())
9413         continue;
9414 
9415       // non-volatile version
9416       QualType ParamTypes[2] = {
9417           S.Context.getLValueReferenceType(PtrTy),
9418           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9419       };
9420       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9421                             /*IsAssignmentOperator=*/ isEqualOp);
9422 
9423       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9424                           VisibleTypeConversionsQuals.hasVolatile();
9425       if (NeedVolatile) {
9426         // volatile version
9427         ParamTypes[0] =
9428             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
9429         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9430                               /*IsAssignmentOperator=*/isEqualOp);
9431       }
9432 
9433       if (!PtrTy.isRestrictQualified() &&
9434           VisibleTypeConversionsQuals.hasRestrict()) {
9435         // restrict version
9436         ParamTypes[0] =
9437             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
9438         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9439                               /*IsAssignmentOperator=*/isEqualOp);
9440 
9441         if (NeedVolatile) {
9442           // volatile restrict version
9443           ParamTypes[0] =
9444               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9445                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9446           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9447                                 /*IsAssignmentOperator=*/isEqualOp);
9448         }
9449       }
9450     }
9451 
9452     if (isEqualOp) {
9453       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9454         // Make sure we don't add the same candidate twice.
9455         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9456           continue;
9457 
9458         QualType ParamTypes[2] = {
9459             S.Context.getLValueReferenceType(PtrTy),
9460             PtrTy,
9461         };
9462 
9463         // non-volatile version
9464         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9465                               /*IsAssignmentOperator=*/true);
9466 
9467         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9468                             VisibleTypeConversionsQuals.hasVolatile();
9469         if (NeedVolatile) {
9470           // volatile version
9471           ParamTypes[0] = S.Context.getLValueReferenceType(
9472               S.Context.getVolatileType(PtrTy));
9473           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9474                                 /*IsAssignmentOperator=*/true);
9475         }
9476 
9477         if (!PtrTy.isRestrictQualified() &&
9478             VisibleTypeConversionsQuals.hasRestrict()) {
9479           // restrict version
9480           ParamTypes[0] = S.Context.getLValueReferenceType(
9481               S.Context.getRestrictType(PtrTy));
9482           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9483                                 /*IsAssignmentOperator=*/true);
9484 
9485           if (NeedVolatile) {
9486             // volatile restrict version
9487             ParamTypes[0] =
9488                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9489                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9490             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9491                                   /*IsAssignmentOperator=*/true);
9492           }
9493         }
9494       }
9495     }
9496   }
9497 
9498   // C++ [over.built]p18:
9499   //
9500   //   For every triple (L, VQ, R), where L is an arithmetic type,
9501   //   VQ is either volatile or empty, and R is a promoted
9502   //   arithmetic type, there exist candidate operator functions of
9503   //   the form
9504   //
9505   //        VQ L&      operator=(VQ L&, R);
9506   //        VQ L&      operator*=(VQ L&, R);
9507   //        VQ L&      operator/=(VQ L&, R);
9508   //        VQ L&      operator+=(VQ L&, R);
9509   //        VQ L&      operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)9510   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9511     if (!HasArithmeticOrEnumeralCandidateType)
9512       return;
9513 
9514     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9515       for (unsigned Right = FirstPromotedArithmeticType;
9516            Right < LastPromotedArithmeticType; ++Right) {
9517         QualType ParamTypes[2];
9518         ParamTypes[1] = ArithmeticTypes[Right];
9519         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9520             S, ArithmeticTypes[Left], Args[0]);
9521 
9522         forAllQualifierCombinations(
9523             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9524               ParamTypes[0] =
9525                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9526               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9527                                     /*IsAssignmentOperator=*/isEqualOp);
9528             });
9529       }
9530     }
9531 
9532     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9533     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9534       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9535         QualType ParamTypes[2];
9536         ParamTypes[1] = Vec2Ty;
9537         // Add this built-in operator as a candidate (VQ is empty).
9538         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9539         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9540                               /*IsAssignmentOperator=*/isEqualOp);
9541 
9542         // Add this built-in operator as a candidate (VQ is 'volatile').
9543         if (VisibleTypeConversionsQuals.hasVolatile()) {
9544           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9545           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9546           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9547                                 /*IsAssignmentOperator=*/isEqualOp);
9548         }
9549       }
9550   }
9551 
9552   // C++ [over.built]p22:
9553   //
9554   //   For every triple (L, VQ, R), where L is an integral type, VQ
9555   //   is either volatile or empty, and R is a promoted integral
9556   //   type, there exist candidate operator functions of the form
9557   //
9558   //        VQ L&       operator%=(VQ L&, R);
9559   //        VQ L&       operator<<=(VQ L&, R);
9560   //        VQ L&       operator>>=(VQ L&, R);
9561   //        VQ L&       operator&=(VQ L&, R);
9562   //        VQ L&       operator^=(VQ L&, R);
9563   //        VQ L&       operator|=(VQ L&, R);
addAssignmentIntegralOverloads()9564   void addAssignmentIntegralOverloads() {
9565     if (!HasArithmeticOrEnumeralCandidateType)
9566       return;
9567 
9568     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9569       for (unsigned Right = FirstPromotedIntegralType;
9570            Right < LastPromotedIntegralType; ++Right) {
9571         QualType ParamTypes[2];
9572         ParamTypes[1] = ArithmeticTypes[Right];
9573         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9574             S, ArithmeticTypes[Left], Args[0]);
9575 
9576         forAllQualifierCombinations(
9577             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9578               ParamTypes[0] =
9579                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9580               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9581             });
9582       }
9583     }
9584   }
9585 
9586   // C++ [over.operator]p23:
9587   //
9588   //   There also exist candidate operator functions of the form
9589   //
9590   //        bool        operator!(bool);
9591   //        bool        operator&&(bool, bool);
9592   //        bool        operator||(bool, bool);
addExclaimOverload()9593   void addExclaimOverload() {
9594     QualType ParamTy = S.Context.BoolTy;
9595     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9596                           /*IsAssignmentOperator=*/false,
9597                           /*NumContextualBoolArguments=*/1);
9598   }
addAmpAmpOrPipePipeOverload()9599   void addAmpAmpOrPipePipeOverload() {
9600     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9601     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9602                           /*IsAssignmentOperator=*/false,
9603                           /*NumContextualBoolArguments=*/2);
9604   }
9605 
9606   // C++ [over.built]p13:
9607   //
9608   //   For every cv-qualified or cv-unqualified object type T there
9609   //   exist candidate operator functions of the form
9610   //
9611   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9612   //        T&         operator[](T*, ptrdiff_t);
9613   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9614   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9615   //        T&         operator[](ptrdiff_t, T*);
addSubscriptOverloads()9616   void addSubscriptOverloads() {
9617     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9618       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9619       QualType PointeeType = PtrTy->getPointeeType();
9620       if (!PointeeType->isObjectType())
9621         continue;
9622 
9623       // T& operator[](T*, ptrdiff_t)
9624       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9625     }
9626 
9627     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9628       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9629       QualType PointeeType = PtrTy->getPointeeType();
9630       if (!PointeeType->isObjectType())
9631         continue;
9632 
9633       // T& operator[](ptrdiff_t, T*)
9634       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9635     }
9636   }
9637 
9638   // C++ [over.built]p11:
9639   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9640   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9641   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9642   //    there exist candidate operator functions of the form
9643   //
9644   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9645   //
9646   //    where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()9647   void addArrowStarOverloads() {
9648     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9649       QualType C1Ty = PtrTy;
9650       QualType C1;
9651       QualifierCollector Q1;
9652       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9653       if (!isa<RecordType>(C1))
9654         continue;
9655       // heuristic to reduce number of builtin candidates in the set.
9656       // Add volatile/restrict version only if there are conversions to a
9657       // volatile/restrict type.
9658       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9659         continue;
9660       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9661         continue;
9662       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9663         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9664         QualType C2 = QualType(mptr->getClass(), 0);
9665         C2 = C2.getUnqualifiedType();
9666         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9667           break;
9668         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9669         // build CV12 T&
9670         QualType T = mptr->getPointeeType();
9671         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9672             T.isVolatileQualified())
9673           continue;
9674         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9675             T.isRestrictQualified())
9676           continue;
9677         T = Q1.apply(S.Context, T);
9678         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9679       }
9680     }
9681   }
9682 
9683   // Note that we don't consider the first argument, since it has been
9684   // contextually converted to bool long ago. The candidates below are
9685   // therefore added as binary.
9686   //
9687   // C++ [over.built]p25:
9688   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9689   //   enumeration type, there exist candidate operator functions of the form
9690   //
9691   //        T        operator?(bool, T, T);
9692   //
addConditionalOperatorOverloads()9693   void addConditionalOperatorOverloads() {
9694     /// Set of (canonical) types that we've already handled.
9695     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9696 
9697     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9698       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9699         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9700           continue;
9701 
9702         QualType ParamTypes[2] = {PtrTy, PtrTy};
9703         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9704       }
9705 
9706       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9707         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9708           continue;
9709 
9710         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9711         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9712       }
9713 
9714       if (S.getLangOpts().CPlusPlus11) {
9715         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9716           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9717             continue;
9718 
9719           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9720             continue;
9721 
9722           QualType ParamTypes[2] = {EnumTy, EnumTy};
9723           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9724         }
9725       }
9726     }
9727   }
9728 };
9729 
9730 } // end anonymous namespace
9731 
9732 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9733 /// operator overloads to the candidate set (C++ [over.built]), based
9734 /// on the operator @p Op and the arguments given. For example, if the
9735 /// operator is a binary '+', this routine might add "int
9736 /// operator+(int, int)" to cover integer addition.
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)9737 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9738                                         SourceLocation OpLoc,
9739                                         ArrayRef<Expr *> Args,
9740                                         OverloadCandidateSet &CandidateSet) {
9741   // Find all of the types that the arguments can convert to, but only
9742   // if the operator we're looking at has built-in operator candidates
9743   // that make use of these types. Also record whether we encounter non-record
9744   // candidate types or either arithmetic or enumeral candidate types.
9745   QualifiersAndAtomic VisibleTypeConversionsQuals;
9746   VisibleTypeConversionsQuals.addConst();
9747   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9748     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9749     if (Args[ArgIdx]->getType()->isAtomicType())
9750       VisibleTypeConversionsQuals.addAtomic();
9751   }
9752 
9753   bool HasNonRecordCandidateType = false;
9754   bool HasArithmeticOrEnumeralCandidateType = false;
9755   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9756   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9757     CandidateTypes.emplace_back(*this);
9758     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9759                                                  OpLoc,
9760                                                  true,
9761                                                  (Op == OO_Exclaim ||
9762                                                   Op == OO_AmpAmp ||
9763                                                   Op == OO_PipePipe),
9764                                                  VisibleTypeConversionsQuals);
9765     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9766         CandidateTypes[ArgIdx].hasNonRecordTypes();
9767     HasArithmeticOrEnumeralCandidateType =
9768         HasArithmeticOrEnumeralCandidateType ||
9769         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9770   }
9771 
9772   // Exit early when no non-record types have been added to the candidate set
9773   // for any of the arguments to the operator.
9774   //
9775   // We can't exit early for !, ||, or &&, since there we have always have
9776   // 'bool' overloads.
9777   if (!HasNonRecordCandidateType &&
9778       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9779     return;
9780 
9781   // Setup an object to manage the common state for building overloads.
9782   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9783                                            VisibleTypeConversionsQuals,
9784                                            HasArithmeticOrEnumeralCandidateType,
9785                                            CandidateTypes, CandidateSet);
9786 
9787   // Dispatch over the operation to add in only those overloads which apply.
9788   switch (Op) {
9789   case OO_None:
9790   case NUM_OVERLOADED_OPERATORS:
9791     llvm_unreachable("Expected an overloaded operator");
9792 
9793   case OO_New:
9794   case OO_Delete:
9795   case OO_Array_New:
9796   case OO_Array_Delete:
9797   case OO_Call:
9798     llvm_unreachable(
9799                     "Special operators don't use AddBuiltinOperatorCandidates");
9800 
9801   case OO_Comma:
9802   case OO_Arrow:
9803   case OO_Coawait:
9804     // C++ [over.match.oper]p3:
9805     //   -- For the operator ',', the unary operator '&', the
9806     //      operator '->', or the operator 'co_await', the
9807     //      built-in candidates set is empty.
9808     break;
9809 
9810   case OO_Plus: // '+' is either unary or binary
9811     if (Args.size() == 1)
9812       OpBuilder.addUnaryPlusPointerOverloads();
9813     [[fallthrough]];
9814 
9815   case OO_Minus: // '-' is either unary or binary
9816     if (Args.size() == 1) {
9817       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9818     } else {
9819       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9820       OpBuilder.addGenericBinaryArithmeticOverloads();
9821       OpBuilder.addMatrixBinaryArithmeticOverloads();
9822     }
9823     break;
9824 
9825   case OO_Star: // '*' is either unary or binary
9826     if (Args.size() == 1)
9827       OpBuilder.addUnaryStarPointerOverloads();
9828     else {
9829       OpBuilder.addGenericBinaryArithmeticOverloads();
9830       OpBuilder.addMatrixBinaryArithmeticOverloads();
9831     }
9832     break;
9833 
9834   case OO_Slash:
9835     OpBuilder.addGenericBinaryArithmeticOverloads();
9836     break;
9837 
9838   case OO_PlusPlus:
9839   case OO_MinusMinus:
9840     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9841     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9842     break;
9843 
9844   case OO_EqualEqual:
9845   case OO_ExclaimEqual:
9846     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9847     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9848     OpBuilder.addGenericBinaryArithmeticOverloads();
9849     break;
9850 
9851   case OO_Less:
9852   case OO_Greater:
9853   case OO_LessEqual:
9854   case OO_GreaterEqual:
9855     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9856     OpBuilder.addGenericBinaryArithmeticOverloads();
9857     break;
9858 
9859   case OO_Spaceship:
9860     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9861     OpBuilder.addThreeWayArithmeticOverloads();
9862     break;
9863 
9864   case OO_Percent:
9865   case OO_Caret:
9866   case OO_Pipe:
9867   case OO_LessLess:
9868   case OO_GreaterGreater:
9869     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9870     break;
9871 
9872   case OO_Amp: // '&' is either unary or binary
9873     if (Args.size() == 1)
9874       // C++ [over.match.oper]p3:
9875       //   -- For the operator ',', the unary operator '&', or the
9876       //      operator '->', the built-in candidates set is empty.
9877       break;
9878 
9879     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9880     break;
9881 
9882   case OO_Tilde:
9883     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9884     break;
9885 
9886   case OO_Equal:
9887     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9888     [[fallthrough]];
9889 
9890   case OO_PlusEqual:
9891   case OO_MinusEqual:
9892     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9893     [[fallthrough]];
9894 
9895   case OO_StarEqual:
9896   case OO_SlashEqual:
9897     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9898     break;
9899 
9900   case OO_PercentEqual:
9901   case OO_LessLessEqual:
9902   case OO_GreaterGreaterEqual:
9903   case OO_AmpEqual:
9904   case OO_CaretEqual:
9905   case OO_PipeEqual:
9906     OpBuilder.addAssignmentIntegralOverloads();
9907     break;
9908 
9909   case OO_Exclaim:
9910     OpBuilder.addExclaimOverload();
9911     break;
9912 
9913   case OO_AmpAmp:
9914   case OO_PipePipe:
9915     OpBuilder.addAmpAmpOrPipePipeOverload();
9916     break;
9917 
9918   case OO_Subscript:
9919     if (Args.size() == 2)
9920       OpBuilder.addSubscriptOverloads();
9921     break;
9922 
9923   case OO_ArrowStar:
9924     OpBuilder.addArrowStarOverloads();
9925     break;
9926 
9927   case OO_Conditional:
9928     OpBuilder.addConditionalOperatorOverloads();
9929     OpBuilder.addGenericBinaryArithmeticOverloads();
9930     break;
9931   }
9932 }
9933 
9934 /// Add function candidates found via argument-dependent lookup
9935 /// to the set of overloading candidates.
9936 ///
9937 /// This routine performs argument-dependent name lookup based on the
9938 /// given function name (which may also be an operator name) and adds
9939 /// all of the overload candidates found by ADL to the overload
9940 /// candidate set (C++ [basic.lookup.argdep]).
9941 void
AddArgumentDependentLookupCandidates(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading)9942 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9943                                            SourceLocation Loc,
9944                                            ArrayRef<Expr *> Args,
9945                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9946                                            OverloadCandidateSet& CandidateSet,
9947                                            bool PartialOverloading) {
9948   ADLResult Fns;
9949 
9950   // FIXME: This approach for uniquing ADL results (and removing
9951   // redundant candidates from the set) relies on pointer-equality,
9952   // which means we need to key off the canonical decl.  However,
9953   // always going back to the canonical decl might not get us the
9954   // right set of default arguments.  What default arguments are
9955   // we supposed to consider on ADL candidates, anyway?
9956 
9957   // FIXME: Pass in the explicit template arguments?
9958   ArgumentDependentLookup(Name, Loc, Args, Fns);
9959 
9960   // Erase all of the candidates we already knew about.
9961   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9962                                    CandEnd = CandidateSet.end();
9963        Cand != CandEnd; ++Cand)
9964     if (Cand->Function) {
9965       Fns.erase(Cand->Function);
9966       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9967         Fns.erase(FunTmpl);
9968     }
9969 
9970   // For each of the ADL candidates we found, add it to the overload
9971   // set.
9972   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9973     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9974 
9975     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9976       if (ExplicitTemplateArgs)
9977         continue;
9978 
9979       AddOverloadCandidate(
9980           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9981           PartialOverloading, /*AllowExplicit=*/true,
9982           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9983       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9984         AddOverloadCandidate(
9985             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9986             /*SuppressUserConversions=*/false, PartialOverloading,
9987             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9988             ADLCallKind::UsesADL, std::nullopt,
9989             OverloadCandidateParamOrder::Reversed);
9990       }
9991     } else {
9992       auto *FTD = cast<FunctionTemplateDecl>(*I);
9993       AddTemplateOverloadCandidate(
9994           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9995           /*SuppressUserConversions=*/false, PartialOverloading,
9996           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9997       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9998               *this, Args, FTD->getTemplatedDecl())) {
9999         AddTemplateOverloadCandidate(
10000             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10001             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10002             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10003             OverloadCandidateParamOrder::Reversed);
10004       }
10005     }
10006   }
10007 }
10008 
10009 namespace {
10010 enum class Comparison { Equal, Better, Worse };
10011 }
10012 
10013 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10014 /// overload resolution.
10015 ///
10016 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10017 /// Cand1's first N enable_if attributes have precisely the same conditions as
10018 /// Cand2's first N enable_if attributes (where N = the number of enable_if
10019 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10020 ///
10021 /// Note that you can have a pair of candidates such that Cand1's enable_if
10022 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10023 /// worse than Cand1's.
compareEnableIfAttrs(const Sema & S,const FunctionDecl * Cand1,const FunctionDecl * Cand2)10024 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10025                                        const FunctionDecl *Cand2) {
10026   // Common case: One (or both) decls don't have enable_if attrs.
10027   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10028   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10029   if (!Cand1Attr || !Cand2Attr) {
10030     if (Cand1Attr == Cand2Attr)
10031       return Comparison::Equal;
10032     return Cand1Attr ? Comparison::Better : Comparison::Worse;
10033   }
10034 
10035   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10036   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10037 
10038   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10039   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10040     std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10041     std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10042 
10043     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10044     // has fewer enable_if attributes than Cand2, and vice versa.
10045     if (!Cand1A)
10046       return Comparison::Worse;
10047     if (!Cand2A)
10048       return Comparison::Better;
10049 
10050     Cand1ID.clear();
10051     Cand2ID.clear();
10052 
10053     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10054     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10055     if (Cand1ID != Cand2ID)
10056       return Comparison::Worse;
10057   }
10058 
10059   return Comparison::Equal;
10060 }
10061 
10062 static Comparison
isBetterMultiversionCandidate(const OverloadCandidate & Cand1,const OverloadCandidate & Cand2)10063 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10064                               const OverloadCandidate &Cand2) {
10065   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10066       !Cand2.Function->isMultiVersion())
10067     return Comparison::Equal;
10068 
10069   // If both are invalid, they are equal. If one of them is invalid, the other
10070   // is better.
10071   if (Cand1.Function->isInvalidDecl()) {
10072     if (Cand2.Function->isInvalidDecl())
10073       return Comparison::Equal;
10074     return Comparison::Worse;
10075   }
10076   if (Cand2.Function->isInvalidDecl())
10077     return Comparison::Better;
10078 
10079   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10080   // cpu_dispatch, else arbitrarily based on the identifiers.
10081   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10082   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10083   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10084   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10085 
10086   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10087     return Comparison::Equal;
10088 
10089   if (Cand1CPUDisp && !Cand2CPUDisp)
10090     return Comparison::Better;
10091   if (Cand2CPUDisp && !Cand1CPUDisp)
10092     return Comparison::Worse;
10093 
10094   if (Cand1CPUSpec && Cand2CPUSpec) {
10095     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10096       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10097                  ? Comparison::Better
10098                  : Comparison::Worse;
10099 
10100     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10101         FirstDiff = std::mismatch(
10102             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10103             Cand2CPUSpec->cpus_begin(),
10104             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10105               return LHS->getName() == RHS->getName();
10106             });
10107 
10108     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10109            "Two different cpu-specific versions should not have the same "
10110            "identifier list, otherwise they'd be the same decl!");
10111     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10112                ? Comparison::Better
10113                : Comparison::Worse;
10114   }
10115   llvm_unreachable("No way to get here unless both had cpu_dispatch");
10116 }
10117 
10118 /// Compute the type of the implicit object parameter for the given function,
10119 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10120 /// null QualType if there is a 'matches anything' implicit object parameter.
10121 static std::optional<QualType>
getImplicitObjectParamType(ASTContext & Context,const FunctionDecl * F)10122 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10123   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10124     return std::nullopt;
10125 
10126   auto *M = cast<CXXMethodDecl>(F);
10127   // Static member functions' object parameters match all types.
10128   if (M->isStatic())
10129     return QualType();
10130   return M->getFunctionObjectParameterReferenceType();
10131 }
10132 
10133 // As a Clang extension, allow ambiguity among F1 and F2 if they represent
10134 // represent the same entity.
allowAmbiguity(ASTContext & Context,const FunctionDecl * F1,const FunctionDecl * F2)10135 static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10136                            const FunctionDecl *F2) {
10137   if (declaresSameEntity(F1, F2))
10138     return true;
10139   auto PT1 = F1->getPrimaryTemplate();
10140   auto PT2 = F2->getPrimaryTemplate();
10141   if (PT1 && PT2) {
10142     if (declaresSameEntity(PT1, PT2) ||
10143         declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10144                            PT2->getInstantiatedFromMemberTemplate()))
10145       return true;
10146   }
10147   // TODO: It is not clear whether comparing parameters is necessary (i.e.
10148   // different functions with same params). Consider removing this (as no test
10149   // fail w/o it).
10150   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10151     if (First) {
10152       if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10153         return *T;
10154     }
10155     assert(I < F->getNumParams());
10156     return F->getParamDecl(I++)->getType();
10157   };
10158 
10159   unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10160   unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10161 
10162   if (F1NumParams != F2NumParams)
10163     return false;
10164 
10165   unsigned I1 = 0, I2 = 0;
10166   for (unsigned I = 0; I != F1NumParams; ++I) {
10167     QualType T1 = NextParam(F1, I1, I == 0);
10168     QualType T2 = NextParam(F2, I2, I == 0);
10169     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10170     if (!Context.hasSameUnqualifiedType(T1, T2))
10171       return false;
10172   }
10173   return true;
10174 }
10175 
10176 /// We're allowed to use constraints partial ordering only if the candidates
10177 /// have the same parameter types:
10178 /// [over.match.best.general]p2.6
10179 /// F1 and F2 are non-template functions with the same
10180 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
sameFunctionParameterTypeLists(Sema & S,const OverloadCandidate & Cand1,const OverloadCandidate & Cand2)10181 static bool sameFunctionParameterTypeLists(Sema &S,
10182                                            const OverloadCandidate &Cand1,
10183                                            const OverloadCandidate &Cand2) {
10184   if (!Cand1.Function || !Cand2.Function)
10185     return false;
10186 
10187   FunctionDecl *Fn1 = Cand1.Function;
10188   FunctionDecl *Fn2 = Cand2.Function;
10189 
10190   if (Fn1->isVariadic() != Fn1->isVariadic())
10191     return false;
10192 
10193   if (!S.FunctionNonObjectParamTypesAreEqual(
10194           Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10195     return false;
10196 
10197   auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10198   auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10199   if (Mem1 && Mem2) {
10200     // if they are member functions, both are direct members of the same class,
10201     // and
10202     if (Mem1->getParent() != Mem2->getParent())
10203       return false;
10204     // if both are non-static member functions, they have the same types for
10205     // their object parameters
10206     if (Mem1->isInstance() && Mem2->isInstance() &&
10207         !S.getASTContext().hasSameType(
10208             Mem1->getFunctionObjectParameterReferenceType(),
10209             Mem1->getFunctionObjectParameterReferenceType()))
10210       return false;
10211   }
10212   return true;
10213 }
10214 
10215 /// isBetterOverloadCandidate - Determines whether the first overload
10216 /// 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)10217 bool clang::isBetterOverloadCandidate(
10218     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10219     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
10220   // Define viable functions to be better candidates than non-viable
10221   // functions.
10222   if (!Cand2.Viable)
10223     return Cand1.Viable;
10224   else if (!Cand1.Viable)
10225     return false;
10226 
10227   // [CUDA] A function with 'never' preference is marked not viable, therefore
10228   // is never shown up here. The worst preference shown up here is 'wrong side',
10229   // e.g. an H function called by a HD function in device compilation. This is
10230   // valid AST as long as the HD function is not emitted, e.g. it is an inline
10231   // function which is called only by an H function. A deferred diagnostic will
10232   // be triggered if it is emitted. However a wrong-sided function is still
10233   // a viable candidate here.
10234   //
10235   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10236   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10237   // can be emitted, Cand1 is not better than Cand2. This rule should have
10238   // precedence over other rules.
10239   //
10240   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10241   // other rules should be used to determine which is better. This is because
10242   // host/device based overloading resolution is mostly for determining
10243   // viability of a function. If two functions are both viable, other factors
10244   // should take precedence in preference, e.g. the standard-defined preferences
10245   // like argument conversion ranks or enable_if partial-ordering. The
10246   // preference for pass-object-size parameters is probably most similar to a
10247   // type-based-overloading decision and so should take priority.
10248   //
10249   // If other rules cannot determine which is better, CUDA preference will be
10250   // used again to determine which is better.
10251   //
10252   // TODO: Currently IdentifyCUDAPreference does not return correct values
10253   // for functions called in global variable initializers due to missing
10254   // correct context about device/host. Therefore we can only enforce this
10255   // rule when there is a caller. We should enforce this rule for functions
10256   // in global variable initializers once proper context is added.
10257   //
10258   // TODO: We can only enable the hostness based overloading resolution when
10259   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10260   // overloading resolution diagnostics.
10261   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10262       S.getLangOpts().GPUExcludeWrongSideOverloads) {
10263     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10264       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
10265       bool IsCand1ImplicitHD =
10266           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
10267       bool IsCand2ImplicitHD =
10268           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
10269       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
10270       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
10271       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
10272       // The implicit HD function may be a function in a system header which
10273       // is forced by pragma. In device compilation, if we prefer HD candidates
10274       // over wrong-sided candidates, overloading resolution may change, which
10275       // may result in non-deferrable diagnostics. As a workaround, we let
10276       // implicit HD candidates take equal preference as wrong-sided candidates.
10277       // This will preserve the overloading resolution.
10278       // TODO: We still need special handling of implicit HD functions since
10279       // they may incur other diagnostics to be deferred. We should make all
10280       // host/device related diagnostics deferrable and remove special handling
10281       // of implicit HD functions.
10282       auto EmitThreshold =
10283           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10284            (IsCand1ImplicitHD || IsCand2ImplicitHD))
10285               ? Sema::CFP_Never
10286               : Sema::CFP_WrongSide;
10287       auto Cand1Emittable = P1 > EmitThreshold;
10288       auto Cand2Emittable = P2 > EmitThreshold;
10289       if (Cand1Emittable && !Cand2Emittable)
10290         return true;
10291       if (!Cand1Emittable && Cand2Emittable)
10292         return false;
10293     }
10294   }
10295 
10296   // C++ [over.match.best]p1: (Changed in C++23)
10297   //
10298   //   -- if F is a static member function, ICS1(F) is defined such
10299   //      that ICS1(F) is neither better nor worse than ICS1(G) for
10300   //      any function G, and, symmetrically, ICS1(G) is neither
10301   //      better nor worse than ICS1(F).
10302   unsigned StartArg = 0;
10303   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10304     StartArg = 1;
10305 
10306   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10307     // We don't allow incompatible pointer conversions in C++.
10308     if (!S.getLangOpts().CPlusPlus)
10309       return ICS.isStandard() &&
10310              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10311 
10312     // The only ill-formed conversion we allow in C++ is the string literal to
10313     // char* conversion, which is only considered ill-formed after C++11.
10314     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10315            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10316   };
10317 
10318   // Define functions that don't require ill-formed conversions for a given
10319   // argument to be better candidates than functions that do.
10320   unsigned NumArgs = Cand1.Conversions.size();
10321   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10322   bool HasBetterConversion = false;
10323   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10324     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10325     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10326     if (Cand1Bad != Cand2Bad) {
10327       if (Cand1Bad)
10328         return false;
10329       HasBetterConversion = true;
10330     }
10331   }
10332 
10333   if (HasBetterConversion)
10334     return true;
10335 
10336   // C++ [over.match.best]p1:
10337   //   A viable function F1 is defined to be a better function than another
10338   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
10339   //   conversion sequence than ICSi(F2), and then...
10340   bool HasWorseConversion = false;
10341   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10342     switch (CompareImplicitConversionSequences(S, Loc,
10343                                                Cand1.Conversions[ArgIdx],
10344                                                Cand2.Conversions[ArgIdx])) {
10345     case ImplicitConversionSequence::Better:
10346       // Cand1 has a better conversion sequence.
10347       HasBetterConversion = true;
10348       break;
10349 
10350     case ImplicitConversionSequence::Worse:
10351       if (Cand1.Function && Cand2.Function &&
10352           Cand1.isReversed() != Cand2.isReversed() &&
10353           allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10354         // Work around large-scale breakage caused by considering reversed
10355         // forms of operator== in C++20:
10356         //
10357         // When comparing a function against a reversed function, if we have a
10358         // better conversion for one argument and a worse conversion for the
10359         // other, the implicit conversion sequences are treated as being equally
10360         // good.
10361         //
10362         // This prevents a comparison function from being considered ambiguous
10363         // with a reversed form that is written in the same way.
10364         //
10365         // We diagnose this as an extension from CreateOverloadedBinOp.
10366         HasWorseConversion = true;
10367         break;
10368       }
10369 
10370       // Cand1 can't be better than Cand2.
10371       return false;
10372 
10373     case ImplicitConversionSequence::Indistinguishable:
10374       // Do nothing.
10375       break;
10376     }
10377   }
10378 
10379   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
10380   //       ICSj(F2), or, if not that,
10381   if (HasBetterConversion && !HasWorseConversion)
10382     return true;
10383 
10384   //   -- the context is an initialization by user-defined conversion
10385   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
10386   //      from the return type of F1 to the destination type (i.e.,
10387   //      the type of the entity being initialized) is a better
10388   //      conversion sequence than the standard conversion sequence
10389   //      from the return type of F2 to the destination type.
10390   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10391       Cand1.Function && Cand2.Function &&
10392       isa<CXXConversionDecl>(Cand1.Function) &&
10393       isa<CXXConversionDecl>(Cand2.Function)) {
10394     // First check whether we prefer one of the conversion functions over the
10395     // other. This only distinguishes the results in non-standard, extension
10396     // cases such as the conversion from a lambda closure type to a function
10397     // pointer or block.
10398     ImplicitConversionSequence::CompareKind Result =
10399         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10400     if (Result == ImplicitConversionSequence::Indistinguishable)
10401       Result = CompareStandardConversionSequences(S, Loc,
10402                                                   Cand1.FinalConversion,
10403                                                   Cand2.FinalConversion);
10404 
10405     if (Result != ImplicitConversionSequence::Indistinguishable)
10406       return Result == ImplicitConversionSequence::Better;
10407 
10408     // FIXME: Compare kind of reference binding if conversion functions
10409     // convert to a reference type used in direct reference binding, per
10410     // C++14 [over.match.best]p1 section 2 bullet 3.
10411   }
10412 
10413   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10414   // as combined with the resolution to CWG issue 243.
10415   //
10416   // When the context is initialization by constructor ([over.match.ctor] or
10417   // either phase of [over.match.list]), a constructor is preferred over
10418   // a conversion function.
10419   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10420       Cand1.Function && Cand2.Function &&
10421       isa<CXXConstructorDecl>(Cand1.Function) !=
10422           isa<CXXConstructorDecl>(Cand2.Function))
10423     return isa<CXXConstructorDecl>(Cand1.Function);
10424 
10425   //    -- F1 is a non-template function and F2 is a function template
10426   //       specialization, or, if not that,
10427   bool Cand1IsSpecialization = Cand1.Function &&
10428                                Cand1.Function->getPrimaryTemplate();
10429   bool Cand2IsSpecialization = Cand2.Function &&
10430                                Cand2.Function->getPrimaryTemplate();
10431   if (Cand1IsSpecialization != Cand2IsSpecialization)
10432     return Cand2IsSpecialization;
10433 
10434   //   -- F1 and F2 are function template specializations, and the function
10435   //      template for F1 is more specialized than the template for F2
10436   //      according to the partial ordering rules described in 14.5.5.2, or,
10437   //      if not that,
10438   if (Cand1IsSpecialization && Cand2IsSpecialization) {
10439     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10440             Cand1.Function->getPrimaryTemplate(),
10441             Cand2.Function->getPrimaryTemplate(), Loc,
10442             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10443                                                    : TPOC_Call,
10444             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
10445             Cand1.isReversed() ^ Cand2.isReversed()))
10446       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10447   }
10448 
10449   //   -— F1 and F2 are non-template functions with the same
10450   //      parameter-type-lists, and F1 is more constrained than F2 [...],
10451   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10452       sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10453     FunctionDecl *Function1 = Cand1.Function;
10454     FunctionDecl *Function2 = Cand2.Function;
10455     if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10456       Function1 = MF;
10457     if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10458       Function2 = MF;
10459 
10460     const Expr *RC1 = Function1->getTrailingRequiresClause();
10461     const Expr *RC2 = Function2->getTrailingRequiresClause();
10462     if (RC1 && RC2) {
10463       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10464       if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10465                                    AtLeastAsConstrained1) ||
10466           S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10467                                    AtLeastAsConstrained2))
10468         return false;
10469       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10470         return AtLeastAsConstrained1;
10471     } else if (RC1 || RC2) {
10472       return RC1 != nullptr;
10473     }
10474   }
10475 
10476   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
10477   //      class B of D, and for all arguments the corresponding parameters of
10478   //      F1 and F2 have the same type.
10479   // FIXME: Implement the "all parameters have the same type" check.
10480   bool Cand1IsInherited =
10481       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10482   bool Cand2IsInherited =
10483       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10484   if (Cand1IsInherited != Cand2IsInherited)
10485     return Cand2IsInherited;
10486   else if (Cand1IsInherited) {
10487     assert(Cand2IsInherited);
10488     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10489     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10490     if (Cand1Class->isDerivedFrom(Cand2Class))
10491       return true;
10492     if (Cand2Class->isDerivedFrom(Cand1Class))
10493       return false;
10494     // Inherited from sibling base classes: still ambiguous.
10495   }
10496 
10497   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10498   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10499   //      with reversed order of parameters and F1 is not
10500   //
10501   // We rank reversed + different operator as worse than just reversed, but
10502   // that comparison can never happen, because we only consider reversing for
10503   // the maximally-rewritten operator (== or <=>).
10504   if (Cand1.RewriteKind != Cand2.RewriteKind)
10505     return Cand1.RewriteKind < Cand2.RewriteKind;
10506 
10507   // Check C++17 tie-breakers for deduction guides.
10508   {
10509     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10510     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10511     if (Guide1 && Guide2) {
10512       //  -- F1 is generated from a deduction-guide and F2 is not
10513       if (Guide1->isImplicit() != Guide2->isImplicit())
10514         return Guide2->isImplicit();
10515 
10516       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10517       if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10518         return true;
10519       if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10520         return false;
10521 
10522       //  --F1 is generated from a non-template constructor and F2 is generated
10523       //  from a constructor template
10524       const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10525       const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10526       if (Constructor1 && Constructor2) {
10527         bool isC1Templated = Constructor1->getTemplatedKind() !=
10528                              FunctionDecl::TemplatedKind::TK_NonTemplate;
10529         bool isC2Templated = Constructor2->getTemplatedKind() !=
10530                              FunctionDecl::TemplatedKind::TK_NonTemplate;
10531         if (isC1Templated != isC2Templated)
10532           return isC2Templated;
10533       }
10534     }
10535   }
10536 
10537   // Check for enable_if value-based overload resolution.
10538   if (Cand1.Function && Cand2.Function) {
10539     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10540     if (Cmp != Comparison::Equal)
10541       return Cmp == Comparison::Better;
10542   }
10543 
10544   bool HasPS1 = Cand1.Function != nullptr &&
10545                 functionHasPassObjectSizeParams(Cand1.Function);
10546   bool HasPS2 = Cand2.Function != nullptr &&
10547                 functionHasPassObjectSizeParams(Cand2.Function);
10548   if (HasPS1 != HasPS2 && HasPS1)
10549     return true;
10550 
10551   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10552   if (MV == Comparison::Better)
10553     return true;
10554   if (MV == Comparison::Worse)
10555     return false;
10556 
10557   // If other rules cannot determine which is better, CUDA preference is used
10558   // to determine which is better.
10559   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10560     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10561     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10562            S.IdentifyCUDAPreference(Caller, Cand2.Function);
10563   }
10564 
10565   // General member function overloading is handled above, so this only handles
10566   // constructors with address spaces.
10567   // This only handles address spaces since C++ has no other
10568   // qualifier that can be used with constructors.
10569   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10570   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10571   if (CD1 && CD2) {
10572     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10573     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10574     if (AS1 != AS2) {
10575       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10576         return true;
10577       if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
10578         return false;
10579     }
10580   }
10581 
10582   return false;
10583 }
10584 
10585 /// Determine whether two declarations are "equivalent" for the purposes of
10586 /// name lookup and overload resolution. This applies when the same internal/no
10587 /// linkage entity is defined by two modules (probably by textually including
10588 /// the same header). In such a case, we don't consider the declarations to
10589 /// declare the same entity, but we also don't want lookups with both
10590 /// declarations visible to be ambiguous in some cases (this happens when using
10591 /// a modularized libstdc++).
isEquivalentInternalLinkageDeclaration(const NamedDecl * A,const NamedDecl * B)10592 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10593                                                   const NamedDecl *B) {
10594   auto *VA = dyn_cast_or_null<ValueDecl>(A);
10595   auto *VB = dyn_cast_or_null<ValueDecl>(B);
10596   if (!VA || !VB)
10597     return false;
10598 
10599   // The declarations must be declaring the same name as an internal linkage
10600   // entity in different modules.
10601   if (!VA->getDeclContext()->getRedeclContext()->Equals(
10602           VB->getDeclContext()->getRedeclContext()) ||
10603       getOwningModule(VA) == getOwningModule(VB) ||
10604       VA->isExternallyVisible() || VB->isExternallyVisible())
10605     return false;
10606 
10607   // Check that the declarations appear to be equivalent.
10608   //
10609   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10610   // For constants and functions, we should check the initializer or body is
10611   // the same. For non-constant variables, we shouldn't allow it at all.
10612   if (Context.hasSameType(VA->getType(), VB->getType()))
10613     return true;
10614 
10615   // Enum constants within unnamed enumerations will have different types, but
10616   // may still be similar enough to be interchangeable for our purposes.
10617   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10618     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10619       // Only handle anonymous enums. If the enumerations were named and
10620       // equivalent, they would have been merged to the same type.
10621       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10622       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10623       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10624           !Context.hasSameType(EnumA->getIntegerType(),
10625                                EnumB->getIntegerType()))
10626         return false;
10627       // Allow this only if the value is the same for both enumerators.
10628       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10629     }
10630   }
10631 
10632   // Nothing else is sufficiently similar.
10633   return false;
10634 }
10635 
diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc,const NamedDecl * D,ArrayRef<const NamedDecl * > Equiv)10636 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10637     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10638   assert(D && "Unknown declaration");
10639   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10640 
10641   Module *M = getOwningModule(D);
10642   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10643       << !M << (M ? M->getFullModuleName() : "");
10644 
10645   for (auto *E : Equiv) {
10646     Module *M = getOwningModule(E);
10647     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10648         << !M << (M ? M->getFullModuleName() : "");
10649   }
10650 }
10651 
NotValidBecauseConstraintExprHasError() const10652 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10653   return FailureKind == ovl_fail_bad_deduction &&
10654          DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied &&
10655          static_cast<CNSInfo *>(DeductionFailure.Data)
10656              ->Satisfaction.ContainsErrors;
10657 }
10658 
10659 /// Computes the best viable function (C++ 13.3.3)
10660 /// within an overload candidate set.
10661 ///
10662 /// \param Loc The location of the function name (or operator symbol) for
10663 /// which overload resolution occurs.
10664 ///
10665 /// \param Best If overload resolution was successful or found a deleted
10666 /// function, \p Best points to the candidate function found.
10667 ///
10668 /// \returns The result of overload resolution.
10669 OverloadingResult
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best)10670 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10671                                          iterator &Best) {
10672   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10673   std::transform(begin(), end(), std::back_inserter(Candidates),
10674                  [](OverloadCandidate &Cand) { return &Cand; });
10675 
10676   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10677   // are accepted by both clang and NVCC. However, during a particular
10678   // compilation mode only one call variant is viable. We need to
10679   // exclude non-viable overload candidates from consideration based
10680   // only on their host/device attributes. Specifically, if one
10681   // candidate call is WrongSide and the other is SameSide, we ignore
10682   // the WrongSide candidate.
10683   // We only need to remove wrong-sided candidates here if
10684   // -fgpu-exclude-wrong-side-overloads is off. When
10685   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10686   // uniformly in isBetterOverloadCandidate.
10687   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10688     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10689     bool ContainsSameSideCandidate =
10690         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10691           // Check viable function only.
10692           return Cand->Viable && Cand->Function &&
10693                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10694                      Sema::CFP_SameSide;
10695         });
10696     if (ContainsSameSideCandidate) {
10697       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10698         // Check viable function only to avoid unnecessary data copying/moving.
10699         return Cand->Viable && Cand->Function &&
10700                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10701                    Sema::CFP_WrongSide;
10702       };
10703       llvm::erase_if(Candidates, IsWrongSideCandidate);
10704     }
10705   }
10706 
10707   // Find the best viable function.
10708   Best = end();
10709   for (auto *Cand : Candidates) {
10710     Cand->Best = false;
10711     if (Cand->Viable) {
10712       if (Best == end() ||
10713           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10714         Best = Cand;
10715     } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10716       // This candidate has constraint that we were unable to evaluate because
10717       // it referenced an expression that contained an error. Rather than fall
10718       // back onto a potentially unintended candidate (made worse by
10719       // subsuming constraints), treat this as 'no viable candidate'.
10720       Best = end();
10721       return OR_No_Viable_Function;
10722     }
10723   }
10724 
10725   // If we didn't find any viable functions, abort.
10726   if (Best == end())
10727     return OR_No_Viable_Function;
10728 
10729   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10730 
10731   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10732   PendingBest.push_back(&*Best);
10733   Best->Best = true;
10734 
10735   // Make sure that this function is better than every other viable
10736   // function. If not, we have an ambiguity.
10737   while (!PendingBest.empty()) {
10738     auto *Curr = PendingBest.pop_back_val();
10739     for (auto *Cand : Candidates) {
10740       if (Cand->Viable && !Cand->Best &&
10741           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10742         PendingBest.push_back(Cand);
10743         Cand->Best = true;
10744 
10745         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10746                                                      Curr->Function))
10747           EquivalentCands.push_back(Cand->Function);
10748         else
10749           Best = end();
10750       }
10751     }
10752   }
10753 
10754   // If we found more than one best candidate, this is ambiguous.
10755   if (Best == end())
10756     return OR_Ambiguous;
10757 
10758   // Best is the best viable function.
10759   if (Best->Function && Best->Function->isDeleted())
10760     return OR_Deleted;
10761 
10762   if (!EquivalentCands.empty())
10763     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10764                                                     EquivalentCands);
10765 
10766   return OR_Success;
10767 }
10768 
10769 namespace {
10770 
10771 enum OverloadCandidateKind {
10772   oc_function,
10773   oc_method,
10774   oc_reversed_binary_operator,
10775   oc_constructor,
10776   oc_implicit_default_constructor,
10777   oc_implicit_copy_constructor,
10778   oc_implicit_move_constructor,
10779   oc_implicit_copy_assignment,
10780   oc_implicit_move_assignment,
10781   oc_implicit_equality_comparison,
10782   oc_inherited_constructor
10783 };
10784 
10785 enum OverloadCandidateSelect {
10786   ocs_non_template,
10787   ocs_template,
10788   ocs_described_template,
10789 };
10790 
10791 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
ClassifyOverloadCandidate(Sema & S,const NamedDecl * Found,const FunctionDecl * Fn,OverloadCandidateRewriteKind CRK,std::string & Description)10792 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10793                           const FunctionDecl *Fn,
10794                           OverloadCandidateRewriteKind CRK,
10795                           std::string &Description) {
10796 
10797   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10798   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10799     isTemplate = true;
10800     Description = S.getTemplateArgumentBindingsText(
10801         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10802   }
10803 
10804   OverloadCandidateSelect Select = [&]() {
10805     if (!Description.empty())
10806       return ocs_described_template;
10807     return isTemplate ? ocs_template : ocs_non_template;
10808   }();
10809 
10810   OverloadCandidateKind Kind = [&]() {
10811     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10812       return oc_implicit_equality_comparison;
10813 
10814     if (CRK & CRK_Reversed)
10815       return oc_reversed_binary_operator;
10816 
10817     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10818       if (!Ctor->isImplicit()) {
10819         if (isa<ConstructorUsingShadowDecl>(Found))
10820           return oc_inherited_constructor;
10821         else
10822           return oc_constructor;
10823       }
10824 
10825       if (Ctor->isDefaultConstructor())
10826         return oc_implicit_default_constructor;
10827 
10828       if (Ctor->isMoveConstructor())
10829         return oc_implicit_move_constructor;
10830 
10831       assert(Ctor->isCopyConstructor() &&
10832              "unexpected sort of implicit constructor");
10833       return oc_implicit_copy_constructor;
10834     }
10835 
10836     if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10837       // This actually gets spelled 'candidate function' for now, but
10838       // it doesn't hurt to split it out.
10839       if (!Meth->isImplicit())
10840         return oc_method;
10841 
10842       if (Meth->isMoveAssignmentOperator())
10843         return oc_implicit_move_assignment;
10844 
10845       if (Meth->isCopyAssignmentOperator())
10846         return oc_implicit_copy_assignment;
10847 
10848       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10849       return oc_method;
10850     }
10851 
10852     return oc_function;
10853   }();
10854 
10855   return std::make_pair(Kind, Select);
10856 }
10857 
MaybeEmitInheritedConstructorNote(Sema & S,const Decl * FoundDecl)10858 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10859   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10860   // set.
10861   if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10862     S.Diag(FoundDecl->getLocation(),
10863            diag::note_ovl_candidate_inherited_constructor)
10864       << Shadow->getNominatedBaseClass();
10865 }
10866 
10867 } // end anonymous namespace
10868 
isFunctionAlwaysEnabled(const ASTContext & Ctx,const FunctionDecl * FD)10869 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10870                                     const FunctionDecl *FD) {
10871   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10872     bool AlwaysTrue;
10873     if (EnableIf->getCond()->isValueDependent() ||
10874         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10875       return false;
10876     if (!AlwaysTrue)
10877       return false;
10878   }
10879   return true;
10880 }
10881 
10882 /// Returns true if we can take the address of the function.
10883 ///
10884 /// \param Complain - If true, we'll emit a diagnostic
10885 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10886 ///   we in overload resolution?
10887 /// \param Loc - The location of the statement we're complaining about. Ignored
10888 ///   if we're not complaining, or if we're in overload resolution.
checkAddressOfFunctionIsAvailable(Sema & S,const FunctionDecl * FD,bool Complain,bool InOverloadResolution,SourceLocation Loc)10889 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10890                                               bool Complain,
10891                                               bool InOverloadResolution,
10892                                               SourceLocation Loc) {
10893   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10894     if (Complain) {
10895       if (InOverloadResolution)
10896         S.Diag(FD->getBeginLoc(),
10897                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10898       else
10899         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10900     }
10901     return false;
10902   }
10903 
10904   if (FD->getTrailingRequiresClause()) {
10905     ConstraintSatisfaction Satisfaction;
10906     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10907       return false;
10908     if (!Satisfaction.IsSatisfied) {
10909       if (Complain) {
10910         if (InOverloadResolution) {
10911           SmallString<128> TemplateArgString;
10912           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10913             TemplateArgString += " ";
10914             TemplateArgString += S.getTemplateArgumentBindingsText(
10915                 FunTmpl->getTemplateParameters(),
10916                 *FD->getTemplateSpecializationArgs());
10917           }
10918 
10919           S.Diag(FD->getBeginLoc(),
10920                  diag::note_ovl_candidate_unsatisfied_constraints)
10921               << TemplateArgString;
10922         } else
10923           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10924               << FD;
10925         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10926       }
10927       return false;
10928     }
10929   }
10930 
10931   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10932     return P->hasAttr<PassObjectSizeAttr>();
10933   });
10934   if (I == FD->param_end())
10935     return true;
10936 
10937   if (Complain) {
10938     // Add one to ParamNo because it's user-facing
10939     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10940     if (InOverloadResolution)
10941       S.Diag(FD->getLocation(),
10942              diag::note_ovl_candidate_has_pass_object_size_params)
10943           << ParamNo;
10944     else
10945       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10946           << FD << ParamNo;
10947   }
10948   return false;
10949 }
10950 
checkAddressOfCandidateIsAvailable(Sema & S,const FunctionDecl * FD)10951 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10952                                                const FunctionDecl *FD) {
10953   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10954                                            /*InOverloadResolution=*/true,
10955                                            /*Loc=*/SourceLocation());
10956 }
10957 
checkAddressOfFunctionIsAvailable(const FunctionDecl * Function,bool Complain,SourceLocation Loc)10958 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10959                                              bool Complain,
10960                                              SourceLocation Loc) {
10961   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10962                                              /*InOverloadResolution=*/false,
10963                                              Loc);
10964 }
10965 
10966 // Don't print candidates other than the one that matches the calling
10967 // convention of the call operator, since that is guaranteed to exist.
shouldSkipNotingLambdaConversionDecl(const FunctionDecl * Fn)10968 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
10969   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10970 
10971   if (!ConvD)
10972     return false;
10973   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10974   if (!RD->isLambda())
10975     return false;
10976 
10977   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10978   CallingConv CallOpCC =
10979       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10980   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10981   CallingConv ConvToCC =
10982       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10983 
10984   return ConvToCC != CallOpCC;
10985 }
10986 
10987 // Notes the location of an overload candidate.
NoteOverloadCandidate(const NamedDecl * Found,const FunctionDecl * Fn,OverloadCandidateRewriteKind RewriteKind,QualType DestType,bool TakingAddress)10988 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
10989                                  OverloadCandidateRewriteKind RewriteKind,
10990                                  QualType DestType, bool TakingAddress) {
10991   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10992     return;
10993   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10994       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10995     return;
10996   if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
10997       !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
10998     return;
10999   if (shouldSkipNotingLambdaConversionDecl(Fn))
11000     return;
11001 
11002   std::string FnDesc;
11003   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11004       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11005   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11006                          << (unsigned)KSPair.first << (unsigned)KSPair.second
11007                          << Fn << FnDesc;
11008 
11009   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11010   Diag(Fn->getLocation(), PD);
11011   MaybeEmitInheritedConstructorNote(*this, Found);
11012 }
11013 
11014 static void
MaybeDiagnoseAmbiguousConstraints(Sema & S,ArrayRef<OverloadCandidate> Cands)11015 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11016   // Perhaps the ambiguity was caused by two atomic constraints that are
11017   // 'identical' but not equivalent:
11018   //
11019   // void foo() requires (sizeof(T) > 4) { } // #1
11020   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11021   //
11022   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11023   // #2 to subsume #1, but these constraint are not considered equivalent
11024   // according to the subsumption rules because they are not the same
11025   // source-level construct. This behavior is quite confusing and we should try
11026   // to help the user figure out what happened.
11027 
11028   SmallVector<const Expr *, 3> FirstAC, SecondAC;
11029   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11030   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11031     if (!I->Function)
11032       continue;
11033     SmallVector<const Expr *, 3> AC;
11034     if (auto *Template = I->Function->getPrimaryTemplate())
11035       Template->getAssociatedConstraints(AC);
11036     else
11037       I->Function->getAssociatedConstraints(AC);
11038     if (AC.empty())
11039       continue;
11040     if (FirstCand == nullptr) {
11041       FirstCand = I->Function;
11042       FirstAC = AC;
11043     } else if (SecondCand == nullptr) {
11044       SecondCand = I->Function;
11045       SecondAC = AC;
11046     } else {
11047       // We have more than one pair of constrained functions - this check is
11048       // expensive and we'd rather not try to diagnose it.
11049       return;
11050     }
11051   }
11052   if (!SecondCand)
11053     return;
11054   // The diagnostic can only happen if there are associated constraints on
11055   // both sides (there needs to be some identical atomic constraint).
11056   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11057                                                       SecondCand, SecondAC))
11058     // Just show the user one diagnostic, they'll probably figure it out
11059     // from here.
11060     return;
11061 }
11062 
11063 // Notes the location of all overload candidates designated through
11064 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType,bool TakingAddress)11065 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11066                                      bool TakingAddress) {
11067   assert(OverloadedExpr->getType() == Context.OverloadTy);
11068 
11069   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11070   OverloadExpr *OvlExpr = Ovl.Expression;
11071 
11072   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11073                             IEnd = OvlExpr->decls_end();
11074        I != IEnd; ++I) {
11075     if (FunctionTemplateDecl *FunTmpl =
11076                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11077       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11078                             TakingAddress);
11079     } else if (FunctionDecl *Fun
11080                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11081       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11082     }
11083   }
11084 }
11085 
11086 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
11087 /// "lead" diagnostic; it will be given two arguments, the source and
11088 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const11089 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11090                                  Sema &S,
11091                                  SourceLocation CaretLoc,
11092                                  const PartialDiagnostic &PDiag) const {
11093   S.Diag(CaretLoc, PDiag)
11094     << Ambiguous.getFromType() << Ambiguous.getToType();
11095   unsigned CandsShown = 0;
11096   AmbiguousConversionSequence::const_iterator I, E;
11097   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11098     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11099       break;
11100     ++CandsShown;
11101     S.NoteOverloadCandidate(I->first, I->second);
11102   }
11103   S.Diags.overloadCandidatesShown(CandsShown);
11104   if (I != E)
11105     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11106 }
11107 
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I,bool TakingCandidateAddress)11108 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11109                                   unsigned I, bool TakingCandidateAddress) {
11110   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11111   assert(Conv.isBad());
11112   assert(Cand->Function && "for now, candidate must be a function");
11113   FunctionDecl *Fn = Cand->Function;
11114 
11115   // There's a conversion slot for the object argument if this is a
11116   // non-constructor method.  Note that 'I' corresponds the
11117   // conversion-slot index.
11118   bool isObjectArgument = false;
11119   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11120     if (I == 0)
11121       isObjectArgument = true;
11122     else
11123       I--;
11124   }
11125 
11126   std::string FnDesc;
11127   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11128       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11129                                 FnDesc);
11130 
11131   Expr *FromExpr = Conv.Bad.FromExpr;
11132   QualType FromTy = Conv.Bad.getFromType();
11133   QualType ToTy = Conv.Bad.getToType();
11134   SourceRange ToParamRange =
11135       !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
11136 
11137   if (FromTy == S.Context.OverloadTy) {
11138     assert(FromExpr && "overload set argument came from implicit argument?");
11139     Expr *E = FromExpr->IgnoreParens();
11140     if (isa<UnaryOperator>(E))
11141       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11142     DeclarationName Name = cast<OverloadExpr>(E)->getName();
11143 
11144     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11145         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11146         << ToParamRange << ToTy << Name << I + 1;
11147     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11148     return;
11149   }
11150 
11151   // Do some hand-waving analysis to see if the non-viability is due
11152   // to a qualifier mismatch.
11153   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11154   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11155   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11156     CToTy = RT->getPointeeType();
11157   else {
11158     // TODO: detect and diagnose the full richness of const mismatches.
11159     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11160       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11161         CFromTy = FromPT->getPointeeType();
11162         CToTy = ToPT->getPointeeType();
11163       }
11164   }
11165 
11166   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11167       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11168     Qualifiers FromQs = CFromTy.getQualifiers();
11169     Qualifiers ToQs = CToTy.getQualifiers();
11170 
11171     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11172       if (isObjectArgument)
11173         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11174             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11175             << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11176       else
11177         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11178             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11179             << FnDesc << ToParamRange << FromQs.getAddressSpace()
11180             << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11181       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11182       return;
11183     }
11184 
11185     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11186       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11187           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11188           << ToParamRange << FromTy << FromQs.getObjCLifetime()
11189           << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11190       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11191       return;
11192     }
11193 
11194     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11195       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11196           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11197           << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11198           << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11199       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11200       return;
11201     }
11202 
11203     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11204     assert(CVR && "expected qualifiers mismatch");
11205 
11206     if (isObjectArgument) {
11207       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11208           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11209           << FromTy << (CVR - 1);
11210     } else {
11211       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11212           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11213           << ToParamRange << FromTy << (CVR - 1) << I + 1;
11214     }
11215     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11216     return;
11217   }
11218 
11219   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11220       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11221     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11222         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11223         << (unsigned)isObjectArgument << I + 1
11224         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11225         << ToParamRange;
11226     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11227     return;
11228   }
11229 
11230   // Special diagnostic for failure to convert an initializer list, since
11231   // telling the user that it has type void is not useful.
11232   if (FromExpr && isa<InitListExpr>(FromExpr)) {
11233     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11234         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11235         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11236         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11237             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11238                 ? 2
11239                 : 0);
11240     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11241     return;
11242   }
11243 
11244   // Diagnose references or pointers to incomplete types differently,
11245   // since it's far from impossible that the incompleteness triggered
11246   // the failure.
11247   QualType TempFromTy = FromTy.getNonReferenceType();
11248   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11249     TempFromTy = PTy->getPointeeType();
11250   if (TempFromTy->isIncompleteType()) {
11251     // Emit the generic diagnostic and, optionally, add the hints to it.
11252     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11253         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11254         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11255         << (unsigned)(Cand->Fix.Kind);
11256 
11257     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11258     return;
11259   }
11260 
11261   // Diagnose base -> derived pointer conversions.
11262   unsigned BaseToDerivedConversion = 0;
11263   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11264     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11265       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11266                                                FromPtrTy->getPointeeType()) &&
11267           !FromPtrTy->getPointeeType()->isIncompleteType() &&
11268           !ToPtrTy->getPointeeType()->isIncompleteType() &&
11269           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11270                           FromPtrTy->getPointeeType()))
11271         BaseToDerivedConversion = 1;
11272     }
11273   } else if (const ObjCObjectPointerType *FromPtrTy
11274                                     = FromTy->getAs<ObjCObjectPointerType>()) {
11275     if (const ObjCObjectPointerType *ToPtrTy
11276                                         = ToTy->getAs<ObjCObjectPointerType>())
11277       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11278         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11279           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11280                                                 FromPtrTy->getPointeeType()) &&
11281               FromIface->isSuperClassOf(ToIface))
11282             BaseToDerivedConversion = 2;
11283   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11284     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11285         !FromTy->isIncompleteType() &&
11286         !ToRefTy->getPointeeType()->isIncompleteType() &&
11287         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11288       BaseToDerivedConversion = 3;
11289     }
11290   }
11291 
11292   if (BaseToDerivedConversion) {
11293     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11294         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11295         << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11296         << I + 1;
11297     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11298     return;
11299   }
11300 
11301   if (isa<ObjCObjectPointerType>(CFromTy) &&
11302       isa<PointerType>(CToTy)) {
11303     Qualifiers FromQs = CFromTy.getQualifiers();
11304     Qualifiers ToQs = CToTy.getQualifiers();
11305     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11306       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11307           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11308           << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11309           << I + 1;
11310       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11311       return;
11312     }
11313   }
11314 
11315   if (TakingCandidateAddress &&
11316       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
11317     return;
11318 
11319   // Emit the generic diagnostic and, optionally, add the hints to it.
11320   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11321   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11322         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11323         << (unsigned)(Cand->Fix.Kind);
11324 
11325   // Check that location of Fn is not in system header.
11326   if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11327     // If we can fix the conversion, suggest the FixIts.
11328     for (const FixItHint &HI : Cand->Fix.Hints)
11329         FDiag << HI;
11330   }
11331 
11332   S.Diag(Fn->getLocation(), FDiag);
11333 
11334   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11335 }
11336 
11337 /// Additional arity mismatch diagnosis specific to a function overload
11338 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11339 /// over a candidate in any candidate set.
CheckArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)11340 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
11341                                unsigned NumArgs) {
11342   FunctionDecl *Fn = Cand->Function;
11343   unsigned MinParams = Fn->getMinRequiredArguments();
11344 
11345   // With invalid overloaded operators, it's possible that we think we
11346   // have an arity mismatch when in fact it looks like we have the
11347   // right number of arguments, because only overloaded operators have
11348   // the weird behavior of overloading member and non-member functions.
11349   // Just don't report anything.
11350   if (Fn->isInvalidDecl() &&
11351       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11352     return true;
11353 
11354   if (NumArgs < MinParams) {
11355     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11356            (Cand->FailureKind == ovl_fail_bad_deduction &&
11357             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
11358   } else {
11359     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11360            (Cand->FailureKind == ovl_fail_bad_deduction &&
11361             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
11362   }
11363 
11364   return false;
11365 }
11366 
11367 /// General arity mismatch diagnosis over a candidate in a candidate set.
DiagnoseArityMismatch(Sema & S,NamedDecl * Found,Decl * D,unsigned NumFormalArgs)11368 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11369                                   unsigned NumFormalArgs) {
11370   assert(isa<FunctionDecl>(D) &&
11371       "The templated declaration should at least be a function"
11372       " when diagnosing bad template argument deduction due to too many"
11373       " or too few arguments");
11374 
11375   FunctionDecl *Fn = cast<FunctionDecl>(D);
11376 
11377   // TODO: treat calls to a missing default constructor as a special case
11378   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11379   unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11380 
11381   // at least / at most / exactly
11382   bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11383   unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11384   unsigned mode, modeCount;
11385   if (NumFormalArgs < MinParams) {
11386     if (MinParams != ParamCount || FnTy->isVariadic() ||
11387         FnTy->isTemplateVariadic())
11388       mode = 0; // "at least"
11389     else
11390       mode = 2; // "exactly"
11391     modeCount = MinParams;
11392   } else {
11393     if (MinParams != ParamCount)
11394       mode = 1; // "at most"
11395     else
11396       mode = 2; // "exactly"
11397     modeCount = ParamCount;
11398   }
11399 
11400   std::string Description;
11401   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11402       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11403 
11404   if (modeCount == 1 &&
11405       Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11406     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11407         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11408         << Description << mode
11409         << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11410         << HasExplicitObjectParam << Fn->getParametersSourceRange();
11411   else
11412     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11413         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11414         << Description << mode << modeCount << NumFormalArgs
11415         << HasExplicitObjectParam << Fn->getParametersSourceRange();
11416 
11417   MaybeEmitInheritedConstructorNote(S, Found);
11418 }
11419 
11420 /// Arity mismatch diagnosis specific to a function overload candidate.
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)11421 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11422                                   unsigned NumFormalArgs) {
11423   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11424     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11425 }
11426 
getDescribedTemplate(Decl * Templated)11427 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11428   if (TemplateDecl *TD = Templated->getDescribedTemplate())
11429     return TD;
11430   llvm_unreachable("Unsupported: Getting the described template declaration"
11431                    " for bad deduction diagnosis");
11432 }
11433 
11434 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,NamedDecl * Found,Decl * Templated,DeductionFailureInfo & DeductionFailure,unsigned NumArgs,bool TakingCandidateAddress)11435 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11436                                  DeductionFailureInfo &DeductionFailure,
11437                                  unsigned NumArgs,
11438                                  bool TakingCandidateAddress) {
11439   TemplateParameter Param = DeductionFailure.getTemplateParameter();
11440   NamedDecl *ParamD;
11441   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11442   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11443   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11444   switch (DeductionFailure.Result) {
11445   case Sema::TDK_Success:
11446     llvm_unreachable("TDK_success while diagnosing bad deduction");
11447 
11448   case Sema::TDK_Incomplete: {
11449     assert(ParamD && "no parameter found for incomplete deduction result");
11450     S.Diag(Templated->getLocation(),
11451            diag::note_ovl_candidate_incomplete_deduction)
11452         << ParamD->getDeclName();
11453     MaybeEmitInheritedConstructorNote(S, Found);
11454     return;
11455   }
11456 
11457   case Sema::TDK_IncompletePack: {
11458     assert(ParamD && "no parameter found for incomplete deduction result");
11459     S.Diag(Templated->getLocation(),
11460            diag::note_ovl_candidate_incomplete_deduction_pack)
11461         << ParamD->getDeclName()
11462         << (DeductionFailure.getFirstArg()->pack_size() + 1)
11463         << *DeductionFailure.getFirstArg();
11464     MaybeEmitInheritedConstructorNote(S, Found);
11465     return;
11466   }
11467 
11468   case Sema::TDK_Underqualified: {
11469     assert(ParamD && "no parameter found for bad qualifiers deduction result");
11470     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11471 
11472     QualType Param = DeductionFailure.getFirstArg()->getAsType();
11473 
11474     // Param will have been canonicalized, but it should just be a
11475     // qualified version of ParamD, so move the qualifiers to that.
11476     QualifierCollector Qs;
11477     Qs.strip(Param);
11478     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11479     assert(S.Context.hasSameType(Param, NonCanonParam));
11480 
11481     // Arg has also been canonicalized, but there's nothing we can do
11482     // about that.  It also doesn't matter as much, because it won't
11483     // have any template parameters in it (because deduction isn't
11484     // done on dependent types).
11485     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11486 
11487     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11488         << ParamD->getDeclName() << Arg << NonCanonParam;
11489     MaybeEmitInheritedConstructorNote(S, Found);
11490     return;
11491   }
11492 
11493   case Sema::TDK_Inconsistent: {
11494     assert(ParamD && "no parameter found for inconsistent deduction result");
11495     int which = 0;
11496     if (isa<TemplateTypeParmDecl>(ParamD))
11497       which = 0;
11498     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11499       // Deduction might have failed because we deduced arguments of two
11500       // different types for a non-type template parameter.
11501       // FIXME: Use a different TDK value for this.
11502       QualType T1 =
11503           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11504       QualType T2 =
11505           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11506       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11507         S.Diag(Templated->getLocation(),
11508                diag::note_ovl_candidate_inconsistent_deduction_types)
11509           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11510           << *DeductionFailure.getSecondArg() << T2;
11511         MaybeEmitInheritedConstructorNote(S, Found);
11512         return;
11513       }
11514 
11515       which = 1;
11516     } else {
11517       which = 2;
11518     }
11519 
11520     // Tweak the diagnostic if the problem is that we deduced packs of
11521     // different arities. We'll print the actual packs anyway in case that
11522     // includes additional useful information.
11523     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11524         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11525         DeductionFailure.getFirstArg()->pack_size() !=
11526             DeductionFailure.getSecondArg()->pack_size()) {
11527       which = 3;
11528     }
11529 
11530     S.Diag(Templated->getLocation(),
11531            diag::note_ovl_candidate_inconsistent_deduction)
11532         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11533         << *DeductionFailure.getSecondArg();
11534     MaybeEmitInheritedConstructorNote(S, Found);
11535     return;
11536   }
11537 
11538   case Sema::TDK_InvalidExplicitArguments:
11539     assert(ParamD && "no parameter found for invalid explicit arguments");
11540     if (ParamD->getDeclName())
11541       S.Diag(Templated->getLocation(),
11542              diag::note_ovl_candidate_explicit_arg_mismatch_named)
11543           << ParamD->getDeclName();
11544     else {
11545       int index = 0;
11546       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11547         index = TTP->getIndex();
11548       else if (NonTypeTemplateParmDecl *NTTP
11549                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11550         index = NTTP->getIndex();
11551       else
11552         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11553       S.Diag(Templated->getLocation(),
11554              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11555           << (index + 1);
11556     }
11557     MaybeEmitInheritedConstructorNote(S, Found);
11558     return;
11559 
11560   case Sema::TDK_ConstraintsNotSatisfied: {
11561     // Format the template argument list into the argument string.
11562     SmallString<128> TemplateArgString;
11563     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11564     TemplateArgString = " ";
11565     TemplateArgString += S.getTemplateArgumentBindingsText(
11566         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11567     if (TemplateArgString.size() == 1)
11568       TemplateArgString.clear();
11569     S.Diag(Templated->getLocation(),
11570            diag::note_ovl_candidate_unsatisfied_constraints)
11571         << TemplateArgString;
11572 
11573     S.DiagnoseUnsatisfiedConstraint(
11574         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11575     return;
11576   }
11577   case Sema::TDK_TooManyArguments:
11578   case Sema::TDK_TooFewArguments:
11579     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11580     return;
11581 
11582   case Sema::TDK_InstantiationDepth:
11583     S.Diag(Templated->getLocation(),
11584            diag::note_ovl_candidate_instantiation_depth);
11585     MaybeEmitInheritedConstructorNote(S, Found);
11586     return;
11587 
11588   case Sema::TDK_SubstitutionFailure: {
11589     // Format the template argument list into the argument string.
11590     SmallString<128> TemplateArgString;
11591     if (TemplateArgumentList *Args =
11592             DeductionFailure.getTemplateArgumentList()) {
11593       TemplateArgString = " ";
11594       TemplateArgString += S.getTemplateArgumentBindingsText(
11595           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11596       if (TemplateArgString.size() == 1)
11597         TemplateArgString.clear();
11598     }
11599 
11600     // If this candidate was disabled by enable_if, say so.
11601     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11602     if (PDiag && PDiag->second.getDiagID() ==
11603           diag::err_typename_nested_not_found_enable_if) {
11604       // FIXME: Use the source range of the condition, and the fully-qualified
11605       //        name of the enable_if template. These are both present in PDiag.
11606       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11607         << "'enable_if'" << TemplateArgString;
11608       return;
11609     }
11610 
11611     // We found a specific requirement that disabled the enable_if.
11612     if (PDiag && PDiag->second.getDiagID() ==
11613         diag::err_typename_nested_not_found_requirement) {
11614       S.Diag(Templated->getLocation(),
11615              diag::note_ovl_candidate_disabled_by_requirement)
11616         << PDiag->second.getStringArg(0) << TemplateArgString;
11617       return;
11618     }
11619 
11620     // Format the SFINAE diagnostic into the argument string.
11621     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11622     //        formatted message in another diagnostic.
11623     SmallString<128> SFINAEArgString;
11624     SourceRange R;
11625     if (PDiag) {
11626       SFINAEArgString = ": ";
11627       R = SourceRange(PDiag->first, PDiag->first);
11628       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11629     }
11630 
11631     S.Diag(Templated->getLocation(),
11632            diag::note_ovl_candidate_substitution_failure)
11633         << TemplateArgString << SFINAEArgString << R;
11634     MaybeEmitInheritedConstructorNote(S, Found);
11635     return;
11636   }
11637 
11638   case Sema::TDK_DeducedMismatch:
11639   case Sema::TDK_DeducedMismatchNested: {
11640     // Format the template argument list into the argument string.
11641     SmallString<128> TemplateArgString;
11642     if (TemplateArgumentList *Args =
11643             DeductionFailure.getTemplateArgumentList()) {
11644       TemplateArgString = " ";
11645       TemplateArgString += S.getTemplateArgumentBindingsText(
11646           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11647       if (TemplateArgString.size() == 1)
11648         TemplateArgString.clear();
11649     }
11650 
11651     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11652         << (*DeductionFailure.getCallArgIndex() + 1)
11653         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11654         << TemplateArgString
11655         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11656     break;
11657   }
11658 
11659   case Sema::TDK_NonDeducedMismatch: {
11660     // FIXME: Provide a source location to indicate what we couldn't match.
11661     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11662     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11663     if (FirstTA.getKind() == TemplateArgument::Template &&
11664         SecondTA.getKind() == TemplateArgument::Template) {
11665       TemplateName FirstTN = FirstTA.getAsTemplate();
11666       TemplateName SecondTN = SecondTA.getAsTemplate();
11667       if (FirstTN.getKind() == TemplateName::Template &&
11668           SecondTN.getKind() == TemplateName::Template) {
11669         if (FirstTN.getAsTemplateDecl()->getName() ==
11670             SecondTN.getAsTemplateDecl()->getName()) {
11671           // FIXME: This fixes a bad diagnostic where both templates are named
11672           // the same.  This particular case is a bit difficult since:
11673           // 1) It is passed as a string to the diagnostic printer.
11674           // 2) The diagnostic printer only attempts to find a better
11675           //    name for types, not decls.
11676           // Ideally, this should folded into the diagnostic printer.
11677           S.Diag(Templated->getLocation(),
11678                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11679               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11680           return;
11681         }
11682       }
11683     }
11684 
11685     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11686         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11687       return;
11688 
11689     // FIXME: For generic lambda parameters, check if the function is a lambda
11690     // call operator, and if so, emit a prettier and more informative
11691     // diagnostic that mentions 'auto' and lambda in addition to
11692     // (or instead of?) the canonical template type parameters.
11693     S.Diag(Templated->getLocation(),
11694            diag::note_ovl_candidate_non_deduced_mismatch)
11695         << FirstTA << SecondTA;
11696     return;
11697   }
11698   // TODO: diagnose these individually, then kill off
11699   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11700   case Sema::TDK_MiscellaneousDeductionFailure:
11701     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11702     MaybeEmitInheritedConstructorNote(S, Found);
11703     return;
11704   case Sema::TDK_CUDATargetMismatch:
11705     S.Diag(Templated->getLocation(),
11706            diag::note_cuda_ovl_candidate_target_mismatch);
11707     return;
11708   }
11709 }
11710 
11711 /// Diagnose a failed template-argument deduction, for function calls.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress)11712 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11713                                  unsigned NumArgs,
11714                                  bool TakingCandidateAddress) {
11715   unsigned TDK = Cand->DeductionFailure.Result;
11716   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11717     if (CheckArityMismatch(S, Cand, NumArgs))
11718       return;
11719   }
11720   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11721                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11722 }
11723 
11724 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)11725 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11726   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11727   FunctionDecl *Callee = Cand->Function;
11728 
11729   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11730                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11731 
11732   std::string FnDesc;
11733   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11734       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11735                                 Cand->getRewriteKind(), FnDesc);
11736 
11737   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11738       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11739       << FnDesc /* Ignored */
11740       << CalleeTarget << CallerTarget;
11741 
11742   // This could be an implicit constructor for which we could not infer the
11743   // target due to a collsion. Diagnose that case.
11744   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11745   if (Meth != nullptr && Meth->isImplicit()) {
11746     CXXRecordDecl *ParentClass = Meth->getParent();
11747     Sema::CXXSpecialMember CSM;
11748 
11749     switch (FnKindPair.first) {
11750     default:
11751       return;
11752     case oc_implicit_default_constructor:
11753       CSM = Sema::CXXDefaultConstructor;
11754       break;
11755     case oc_implicit_copy_constructor:
11756       CSM = Sema::CXXCopyConstructor;
11757       break;
11758     case oc_implicit_move_constructor:
11759       CSM = Sema::CXXMoveConstructor;
11760       break;
11761     case oc_implicit_copy_assignment:
11762       CSM = Sema::CXXCopyAssignment;
11763       break;
11764     case oc_implicit_move_assignment:
11765       CSM = Sema::CXXMoveAssignment;
11766       break;
11767     };
11768 
11769     bool ConstRHS = false;
11770     if (Meth->getNumParams()) {
11771       if (const ReferenceType *RT =
11772               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11773         ConstRHS = RT->getPointeeType().isConstQualified();
11774       }
11775     }
11776 
11777     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11778                                               /* ConstRHS */ ConstRHS,
11779                                               /* Diagnose */ true);
11780   }
11781 }
11782 
DiagnoseFailedEnableIfAttr(Sema & S,OverloadCandidate * Cand)11783 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11784   FunctionDecl *Callee = Cand->Function;
11785   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11786 
11787   S.Diag(Callee->getLocation(),
11788          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11789       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11790 }
11791 
DiagnoseFailedExplicitSpec(Sema & S,OverloadCandidate * Cand)11792 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11793   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11794   assert(ES.isExplicit() && "not an explicit candidate");
11795 
11796   unsigned Kind;
11797   switch (Cand->Function->getDeclKind()) {
11798   case Decl::Kind::CXXConstructor:
11799     Kind = 0;
11800     break;
11801   case Decl::Kind::CXXConversion:
11802     Kind = 1;
11803     break;
11804   case Decl::Kind::CXXDeductionGuide:
11805     Kind = Cand->Function->isImplicit() ? 0 : 2;
11806     break;
11807   default:
11808     llvm_unreachable("invalid Decl");
11809   }
11810 
11811   // Note the location of the first (in-class) declaration; a redeclaration
11812   // (particularly an out-of-class definition) will typically lack the
11813   // 'explicit' specifier.
11814   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11815   FunctionDecl *First = Cand->Function->getFirstDecl();
11816   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11817     First = Pattern->getFirstDecl();
11818 
11819   S.Diag(First->getLocation(),
11820          diag::note_ovl_candidate_explicit)
11821       << Kind << (ES.getExpr() ? 1 : 0)
11822       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11823 }
11824 
11825 /// Generates a 'note' diagnostic for an overload candidate.  We've
11826 /// already generated a primary error at the call site.
11827 ///
11828 /// It really does need to be a single diagnostic with its caret
11829 /// pointed at the candidate declaration.  Yes, this creates some
11830 /// major challenges of technical writing.  Yes, this makes pointing
11831 /// out problems with specific arguments quite awkward.  It's still
11832 /// better than generating twenty screens of text for every failed
11833 /// overload.
11834 ///
11835 /// It would be great to be able to express per-candidate problems
11836 /// more richly for those diagnostic clients that cared, but we'd
11837 /// still have to be just as careful with the default diagnostics.
11838 /// \param CtorDestAS Addr space of object being constructed (for ctor
11839 /// candidates only).
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress,LangAS CtorDestAS=LangAS::Default)11840 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11841                                   unsigned NumArgs,
11842                                   bool TakingCandidateAddress,
11843                                   LangAS CtorDestAS = LangAS::Default) {
11844   FunctionDecl *Fn = Cand->Function;
11845   if (shouldSkipNotingLambdaConversionDecl(Fn))
11846     return;
11847 
11848   // There is no physical candidate declaration to point to for OpenCL builtins.
11849   // Except for failed conversions, the notes are identical for each candidate,
11850   // so do not generate such notes.
11851   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11852       Cand->FailureKind != ovl_fail_bad_conversion)
11853     return;
11854 
11855   // Note deleted candidates, but only if they're viable.
11856   if (Cand->Viable) {
11857     if (Fn->isDeleted()) {
11858       std::string FnDesc;
11859       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11860           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11861                                     Cand->getRewriteKind(), FnDesc);
11862 
11863       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11864           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11865           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11866       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11867       return;
11868     }
11869 
11870     // We don't really have anything else to say about viable candidates.
11871     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11872     return;
11873   }
11874 
11875   switch (Cand->FailureKind) {
11876   case ovl_fail_too_many_arguments:
11877   case ovl_fail_too_few_arguments:
11878     return DiagnoseArityMismatch(S, Cand, NumArgs);
11879 
11880   case ovl_fail_bad_deduction:
11881     return DiagnoseBadDeduction(S, Cand, NumArgs,
11882                                 TakingCandidateAddress);
11883 
11884   case ovl_fail_illegal_constructor: {
11885     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11886       << (Fn->getPrimaryTemplate() ? 1 : 0);
11887     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11888     return;
11889   }
11890 
11891   case ovl_fail_object_addrspace_mismatch: {
11892     Qualifiers QualsForPrinting;
11893     QualsForPrinting.setAddressSpace(CtorDestAS);
11894     S.Diag(Fn->getLocation(),
11895            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11896         << QualsForPrinting;
11897     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11898     return;
11899   }
11900 
11901   case ovl_fail_trivial_conversion:
11902   case ovl_fail_bad_final_conversion:
11903   case ovl_fail_final_conversion_not_exact:
11904     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11905 
11906   case ovl_fail_bad_conversion: {
11907     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11908     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11909       if (Cand->Conversions[I].isBad())
11910         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11911 
11912     // FIXME: this currently happens when we're called from SemaInit
11913     // when user-conversion overload fails.  Figure out how to handle
11914     // those conditions and diagnose them well.
11915     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11916   }
11917 
11918   case ovl_fail_bad_target:
11919     return DiagnoseBadTarget(S, Cand);
11920 
11921   case ovl_fail_enable_if:
11922     return DiagnoseFailedEnableIfAttr(S, Cand);
11923 
11924   case ovl_fail_explicit:
11925     return DiagnoseFailedExplicitSpec(S, Cand);
11926 
11927   case ovl_fail_inhctor_slice:
11928     // It's generally not interesting to note copy/move constructors here.
11929     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11930       return;
11931     S.Diag(Fn->getLocation(),
11932            diag::note_ovl_candidate_inherited_constructor_slice)
11933       << (Fn->getPrimaryTemplate() ? 1 : 0)
11934       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11935     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11936     return;
11937 
11938   case ovl_fail_addr_not_available: {
11939     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11940     (void)Available;
11941     assert(!Available);
11942     break;
11943   }
11944   case ovl_non_default_multiversion_function:
11945     // Do nothing, these should simply be ignored.
11946     break;
11947 
11948   case ovl_fail_constraints_not_satisfied: {
11949     std::string FnDesc;
11950     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11951         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11952                                   Cand->getRewriteKind(), FnDesc);
11953 
11954     S.Diag(Fn->getLocation(),
11955            diag::note_ovl_candidate_constraints_not_satisfied)
11956         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11957         << FnDesc /* Ignored */;
11958     ConstraintSatisfaction Satisfaction;
11959     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11960       break;
11961     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11962   }
11963   }
11964 }
11965 
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)11966 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11967   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11968     return;
11969 
11970   // Desugar the type of the surrogate down to a function type,
11971   // retaining as many typedefs as possible while still showing
11972   // the function type (and, therefore, its parameter types).
11973   QualType FnType = Cand->Surrogate->getConversionType();
11974   bool isLValueReference = false;
11975   bool isRValueReference = false;
11976   bool isPointer = false;
11977   if (const LValueReferenceType *FnTypeRef =
11978         FnType->getAs<LValueReferenceType>()) {
11979     FnType = FnTypeRef->getPointeeType();
11980     isLValueReference = true;
11981   } else if (const RValueReferenceType *FnTypeRef =
11982                FnType->getAs<RValueReferenceType>()) {
11983     FnType = FnTypeRef->getPointeeType();
11984     isRValueReference = true;
11985   }
11986   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11987     FnType = FnTypePtr->getPointeeType();
11988     isPointer = true;
11989   }
11990   // Desugar down to a function type.
11991   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11992   // Reconstruct the pointer/reference as appropriate.
11993   if (isPointer) FnType = S.Context.getPointerType(FnType);
11994   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11995   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11996 
11997   if (!Cand->Viable &&
11998       Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
11999     S.Diag(Cand->Surrogate->getLocation(),
12000            diag::note_ovl_surrogate_constraints_not_satisfied)
12001         << Cand->Surrogate;
12002     ConstraintSatisfaction Satisfaction;
12003     if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12004       S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12005   } else {
12006     S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12007         << FnType;
12008   }
12009 }
12010 
NoteBuiltinOperatorCandidate(Sema & S,StringRef Opc,SourceLocation OpLoc,OverloadCandidate * Cand)12011 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12012                                          SourceLocation OpLoc,
12013                                          OverloadCandidate *Cand) {
12014   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12015   std::string TypeStr("operator");
12016   TypeStr += Opc;
12017   TypeStr += "(";
12018   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12019   if (Cand->Conversions.size() == 1) {
12020     TypeStr += ")";
12021     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12022   } else {
12023     TypeStr += ", ";
12024     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12025     TypeStr += ")";
12026     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12027   }
12028 }
12029 
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)12030 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12031                                          OverloadCandidate *Cand) {
12032   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12033     if (ICS.isBad()) break; // all meaningless after first invalid
12034     if (!ICS.isAmbiguous()) continue;
12035 
12036     ICS.DiagnoseAmbiguousConversion(
12037         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12038   }
12039 }
12040 
GetLocationForCandidate(const OverloadCandidate * Cand)12041 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12042   if (Cand->Function)
12043     return Cand->Function->getLocation();
12044   if (Cand->IsSurrogate)
12045     return Cand->Surrogate->getLocation();
12046   return SourceLocation();
12047 }
12048 
RankDeductionFailure(const DeductionFailureInfo & DFI)12049 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12050   switch ((Sema::TemplateDeductionResult)DFI.Result) {
12051   case Sema::TDK_Success:
12052   case Sema::TDK_NonDependentConversionFailure:
12053   case Sema::TDK_AlreadyDiagnosed:
12054     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12055 
12056   case Sema::TDK_Invalid:
12057   case Sema::TDK_Incomplete:
12058   case Sema::TDK_IncompletePack:
12059     return 1;
12060 
12061   case Sema::TDK_Underqualified:
12062   case Sema::TDK_Inconsistent:
12063     return 2;
12064 
12065   case Sema::TDK_SubstitutionFailure:
12066   case Sema::TDK_DeducedMismatch:
12067   case Sema::TDK_ConstraintsNotSatisfied:
12068   case Sema::TDK_DeducedMismatchNested:
12069   case Sema::TDK_NonDeducedMismatch:
12070   case Sema::TDK_MiscellaneousDeductionFailure:
12071   case Sema::TDK_CUDATargetMismatch:
12072     return 3;
12073 
12074   case Sema::TDK_InstantiationDepth:
12075     return 4;
12076 
12077   case Sema::TDK_InvalidExplicitArguments:
12078     return 5;
12079 
12080   case Sema::TDK_TooManyArguments:
12081   case Sema::TDK_TooFewArguments:
12082     return 6;
12083   }
12084   llvm_unreachable("Unhandled deduction result");
12085 }
12086 
12087 namespace {
12088 
12089 struct CompareOverloadCandidatesForDisplay {
12090   Sema &S;
12091   SourceLocation Loc;
12092   size_t NumArgs;
12093   OverloadCandidateSet::CandidateSetKind CSK;
12094 
CompareOverloadCandidatesForDisplay__anon68a0e3592011::CompareOverloadCandidatesForDisplay12095   CompareOverloadCandidatesForDisplay(
12096       Sema &S, SourceLocation Loc, size_t NArgs,
12097       OverloadCandidateSet::CandidateSetKind CSK)
12098       : S(S), NumArgs(NArgs), CSK(CSK) {}
12099 
EffectiveFailureKind__anon68a0e3592011::CompareOverloadCandidatesForDisplay12100   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12101     // If there are too many or too few arguments, that's the high-order bit we
12102     // want to sort by, even if the immediate failure kind was something else.
12103     if (C->FailureKind == ovl_fail_too_many_arguments ||
12104         C->FailureKind == ovl_fail_too_few_arguments)
12105       return static_cast<OverloadFailureKind>(C->FailureKind);
12106 
12107     if (C->Function) {
12108       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12109         return ovl_fail_too_many_arguments;
12110       if (NumArgs < C->Function->getMinRequiredArguments())
12111         return ovl_fail_too_few_arguments;
12112     }
12113 
12114     return static_cast<OverloadFailureKind>(C->FailureKind);
12115   }
12116 
operator ()__anon68a0e3592011::CompareOverloadCandidatesForDisplay12117   bool operator()(const OverloadCandidate *L,
12118                   const OverloadCandidate *R) {
12119     // Fast-path this check.
12120     if (L == R) return false;
12121 
12122     // Order first by viability.
12123     if (L->Viable) {
12124       if (!R->Viable) return true;
12125 
12126       if (int Ord = CompareConversions(*L, *R))
12127         return Ord < 0;
12128       // Use other tie breakers.
12129     } else if (R->Viable)
12130       return false;
12131 
12132     assert(L->Viable == R->Viable);
12133 
12134     // Criteria by which we can sort non-viable candidates:
12135     if (!L->Viable) {
12136       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12137       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12138 
12139       // 1. Arity mismatches come after other candidates.
12140       if (LFailureKind == ovl_fail_too_many_arguments ||
12141           LFailureKind == ovl_fail_too_few_arguments) {
12142         if (RFailureKind == ovl_fail_too_many_arguments ||
12143             RFailureKind == ovl_fail_too_few_arguments) {
12144           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12145           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12146           if (LDist == RDist) {
12147             if (LFailureKind == RFailureKind)
12148               // Sort non-surrogates before surrogates.
12149               return !L->IsSurrogate && R->IsSurrogate;
12150             // Sort candidates requiring fewer parameters than there were
12151             // arguments given after candidates requiring more parameters
12152             // than there were arguments given.
12153             return LFailureKind == ovl_fail_too_many_arguments;
12154           }
12155           return LDist < RDist;
12156         }
12157         return false;
12158       }
12159       if (RFailureKind == ovl_fail_too_many_arguments ||
12160           RFailureKind == ovl_fail_too_few_arguments)
12161         return true;
12162 
12163       // 2. Bad conversions come first and are ordered by the number
12164       // of bad conversions and quality of good conversions.
12165       if (LFailureKind == ovl_fail_bad_conversion) {
12166         if (RFailureKind != ovl_fail_bad_conversion)
12167           return true;
12168 
12169         // The conversion that can be fixed with a smaller number of changes,
12170         // comes first.
12171         unsigned numLFixes = L->Fix.NumConversionsFixed;
12172         unsigned numRFixes = R->Fix.NumConversionsFixed;
12173         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12174         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12175         if (numLFixes != numRFixes) {
12176           return numLFixes < numRFixes;
12177         }
12178 
12179         // If there's any ordering between the defined conversions...
12180         if (int Ord = CompareConversions(*L, *R))
12181           return Ord < 0;
12182       } else if (RFailureKind == ovl_fail_bad_conversion)
12183         return false;
12184 
12185       if (LFailureKind == ovl_fail_bad_deduction) {
12186         if (RFailureKind != ovl_fail_bad_deduction)
12187           return true;
12188 
12189         if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
12190           unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12191           unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12192           if (LRank != RRank)
12193             return LRank < RRank;
12194         }
12195       } else if (RFailureKind == ovl_fail_bad_deduction)
12196         return false;
12197 
12198       // TODO: others?
12199     }
12200 
12201     // Sort everything else by location.
12202     SourceLocation LLoc = GetLocationForCandidate(L);
12203     SourceLocation RLoc = GetLocationForCandidate(R);
12204 
12205     // Put candidates without locations (e.g. builtins) at the end.
12206     if (LLoc.isValid() && RLoc.isValid())
12207       return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12208     if (LLoc.isValid() && !RLoc.isValid())
12209       return true;
12210     if (RLoc.isValid() && !LLoc.isValid())
12211       return false;
12212     assert(!LLoc.isValid() && !RLoc.isValid());
12213     // For builtins and other functions without locations, fallback to the order
12214     // in which they were added into the candidate set.
12215     return L < R;
12216   }
12217 
12218 private:
12219   struct ConversionSignals {
12220     unsigned KindRank = 0;
12221     ImplicitConversionRank Rank = ICR_Exact_Match;
12222 
ForSequence__anon68a0e3592011::CompareOverloadCandidatesForDisplay::ConversionSignals12223     static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12224       ConversionSignals Sig;
12225       Sig.KindRank = Seq.getKindRank();
12226       if (Seq.isStandard())
12227         Sig.Rank = Seq.Standard.getRank();
12228       else if (Seq.isUserDefined())
12229         Sig.Rank = Seq.UserDefined.After.getRank();
12230       // We intend StaticObjectArgumentConversion to compare the same as
12231       // StandardConversion with ICR_ExactMatch rank.
12232       return Sig;
12233     }
12234 
ForObjectArgument__anon68a0e3592011::CompareOverloadCandidatesForDisplay::ConversionSignals12235     static ConversionSignals ForObjectArgument() {
12236       // We intend StaticObjectArgumentConversion to compare the same as
12237       // StandardConversion with ICR_ExactMatch rank. Default give us that.
12238       return {};
12239     }
12240   };
12241 
12242   // Returns -1 if conversions in L are considered better.
12243   //          0 if they are considered indistinguishable.
12244   //          1 if conversions in R are better.
CompareConversions__anon68a0e3592011::CompareOverloadCandidatesForDisplay12245   int CompareConversions(const OverloadCandidate &L,
12246                          const OverloadCandidate &R) {
12247     // We cannot use `isBetterOverloadCandidate` because it is defined
12248     // according to the C++ standard and provides a partial order, but we need
12249     // a total order as this function is used in sort.
12250     assert(L.Conversions.size() == R.Conversions.size());
12251     for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12252       auto LS = L.IgnoreObjectArgument && I == 0
12253                     ? ConversionSignals::ForObjectArgument()
12254                     : ConversionSignals::ForSequence(L.Conversions[I]);
12255       auto RS = R.IgnoreObjectArgument
12256                     ? ConversionSignals::ForObjectArgument()
12257                     : ConversionSignals::ForSequence(R.Conversions[I]);
12258       if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12259         return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12260                    ? -1
12261                    : 1;
12262     }
12263     // FIXME: find a way to compare templates for being more or less
12264     // specialized that provides a strict weak ordering.
12265     return 0;
12266   }
12267 };
12268 }
12269 
12270 /// CompleteNonViableCandidate - Normally, overload resolution only
12271 /// computes up to the first bad conversion. Produces the FixIt set if
12272 /// possible.
12273 static void
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,ArrayRef<Expr * > Args,OverloadCandidateSet::CandidateSetKind CSK)12274 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
12275                            ArrayRef<Expr *> Args,
12276                            OverloadCandidateSet::CandidateSetKind CSK) {
12277   assert(!Cand->Viable);
12278 
12279   // Don't do anything on failures other than bad conversion.
12280   if (Cand->FailureKind != ovl_fail_bad_conversion)
12281     return;
12282 
12283   // We only want the FixIts if all the arguments can be corrected.
12284   bool Unfixable = false;
12285   // Use a implicit copy initialization to check conversion fixes.
12286   Cand->Fix.setConversionChecker(TryCopyInitialization);
12287 
12288   // Attempt to fix the bad conversion.
12289   unsigned ConvCount = Cand->Conversions.size();
12290   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12291        ++ConvIdx) {
12292     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12293     if (Cand->Conversions[ConvIdx].isInitialized() &&
12294         Cand->Conversions[ConvIdx].isBad()) {
12295       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12296       break;
12297     }
12298   }
12299 
12300   // FIXME: this should probably be preserved from the overload
12301   // operation somehow.
12302   bool SuppressUserConversions = false;
12303 
12304   unsigned ConvIdx = 0;
12305   unsigned ArgIdx = 0;
12306   ArrayRef<QualType> ParamTypes;
12307   bool Reversed = Cand->isReversed();
12308 
12309   if (Cand->IsSurrogate) {
12310     QualType ConvType
12311       = Cand->Surrogate->getConversionType().getNonReferenceType();
12312     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12313       ConvType = ConvPtrType->getPointeeType();
12314     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12315     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12316     ConvIdx = 1;
12317   } else if (Cand->Function) {
12318     ParamTypes =
12319         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12320     if (isa<CXXMethodDecl>(Cand->Function) &&
12321         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12322       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12323       ConvIdx = 1;
12324       if (CSK == OverloadCandidateSet::CSK_Operator &&
12325           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12326           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
12327               OO_Subscript)
12328         // Argument 0 is 'this', which doesn't have a corresponding parameter.
12329         ArgIdx = 1;
12330     }
12331   } else {
12332     // Builtin operator.
12333     assert(ConvCount <= 3);
12334     ParamTypes = Cand->BuiltinParamTypes;
12335   }
12336 
12337   // Fill in the rest of the conversions.
12338   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12339        ConvIdx != ConvCount;
12340        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12341     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12342     if (Cand->Conversions[ConvIdx].isInitialized()) {
12343       // We've already checked this conversion.
12344     } else if (ParamIdx < ParamTypes.size()) {
12345       if (ParamTypes[ParamIdx]->isDependentType())
12346         Cand->Conversions[ConvIdx].setAsIdentityConversion(
12347             Args[ArgIdx]->getType());
12348       else {
12349         Cand->Conversions[ConvIdx] =
12350             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12351                                   SuppressUserConversions,
12352                                   /*InOverloadResolution=*/true,
12353                                   /*AllowObjCWritebackConversion=*/
12354                                   S.getLangOpts().ObjCAutoRefCount);
12355         // Store the FixIt in the candidate if it exists.
12356         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12357           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12358       }
12359     } else
12360       Cand->Conversions[ConvIdx].setEllipsis();
12361   }
12362 }
12363 
CompleteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,SourceLocation OpLoc,llvm::function_ref<bool (OverloadCandidate &)> Filter)12364 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
12365     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
12366     SourceLocation OpLoc,
12367     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12368   // Sort the candidates by viability and position.  Sorting directly would
12369   // be prohibitive, so we make a set of pointers and sort those.
12370   SmallVector<OverloadCandidate*, 32> Cands;
12371   if (OCD == OCD_AllCandidates) Cands.reserve(size());
12372   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12373     if (!Filter(*Cand))
12374       continue;
12375     switch (OCD) {
12376     case OCD_AllCandidates:
12377       if (!Cand->Viable) {
12378         if (!Cand->Function && !Cand->IsSurrogate) {
12379           // This a non-viable builtin candidate.  We do not, in general,
12380           // want to list every possible builtin candidate.
12381           continue;
12382         }
12383         CompleteNonViableCandidate(S, Cand, Args, Kind);
12384       }
12385       break;
12386 
12387     case OCD_ViableCandidates:
12388       if (!Cand->Viable)
12389         continue;
12390       break;
12391 
12392     case OCD_AmbiguousCandidates:
12393       if (!Cand->Best)
12394         continue;
12395       break;
12396     }
12397 
12398     Cands.push_back(Cand);
12399   }
12400 
12401   llvm::stable_sort(
12402       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12403 
12404   return Cands;
12405 }
12406 
shouldDeferDiags(Sema & S,ArrayRef<Expr * > Args,SourceLocation OpLoc)12407 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
12408                                             SourceLocation OpLoc) {
12409   bool DeferHint = false;
12410   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12411     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12412     // host device candidates.
12413     auto WrongSidedCands =
12414         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12415           return (Cand.Viable == false &&
12416                   Cand.FailureKind == ovl_fail_bad_target) ||
12417                  (Cand.Function &&
12418                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
12419                   Cand.Function->template hasAttr<CUDADeviceAttr>());
12420         });
12421     DeferHint = !WrongSidedCands.empty();
12422   }
12423   return DeferHint;
12424 }
12425 
12426 /// When overload resolution fails, prints diagnostic messages containing the
12427 /// 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)12428 void OverloadCandidateSet::NoteCandidates(
12429     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
12430     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12431     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12432 
12433   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12434 
12435   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12436 
12437   // In WebAssembly we don't want to emit further diagnostics if a table is
12438   // passed as an argument to a function.
12439   bool NoteCands = true;
12440   for (const Expr *Arg : Args) {
12441     if (Arg->getType()->isWebAssemblyTableType())
12442       NoteCands = false;
12443   }
12444 
12445   if (NoteCands)
12446     NoteCandidates(S, Args, Cands, Opc, OpLoc);
12447 
12448   if (OCD == OCD_AmbiguousCandidates)
12449     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
12450 }
12451 
NoteCandidates(Sema & S,ArrayRef<Expr * > Args,ArrayRef<OverloadCandidate * > Cands,StringRef Opc,SourceLocation OpLoc)12452 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
12453                                           ArrayRef<OverloadCandidate *> Cands,
12454                                           StringRef Opc, SourceLocation OpLoc) {
12455   bool ReportedAmbiguousConversions = false;
12456 
12457   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12458   unsigned CandsShown = 0;
12459   auto I = Cands.begin(), E = Cands.end();
12460   for (; I != E; ++I) {
12461     OverloadCandidate *Cand = *I;
12462 
12463     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12464         ShowOverloads == Ovl_Best) {
12465       break;
12466     }
12467     ++CandsShown;
12468 
12469     if (Cand->Function)
12470       NoteFunctionCandidate(S, Cand, Args.size(),
12471                             /*TakingCandidateAddress=*/false, DestAS);
12472     else if (Cand->IsSurrogate)
12473       NoteSurrogateCandidate(S, Cand);
12474     else {
12475       assert(Cand->Viable &&
12476              "Non-viable built-in candidates are not added to Cands.");
12477       // Generally we only see ambiguities including viable builtin
12478       // operators if overload resolution got screwed up by an
12479       // ambiguous user-defined conversion.
12480       //
12481       // FIXME: It's quite possible for different conversions to see
12482       // different ambiguities, though.
12483       if (!ReportedAmbiguousConversions) {
12484         NoteAmbiguousUserConversions(S, OpLoc, Cand);
12485         ReportedAmbiguousConversions = true;
12486       }
12487 
12488       // If this is a viable builtin, print it.
12489       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12490     }
12491   }
12492 
12493   // Inform S.Diags that we've shown an overload set with N elements.  This may
12494   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12495   S.Diags.overloadCandidatesShown(CandsShown);
12496 
12497   if (I != E)
12498     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12499            shouldDeferDiags(S, Args, OpLoc))
12500         << int(E - I);
12501 }
12502 
12503 static SourceLocation
GetLocationForCandidate(const TemplateSpecCandidate * Cand)12504 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12505   return Cand->Specialization ? Cand->Specialization->getLocation()
12506                               : SourceLocation();
12507 }
12508 
12509 namespace {
12510 struct CompareTemplateSpecCandidatesForDisplay {
12511   Sema &S;
CompareTemplateSpecCandidatesForDisplay__anon68a0e3592211::CompareTemplateSpecCandidatesForDisplay12512   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12513 
operator ()__anon68a0e3592211::CompareTemplateSpecCandidatesForDisplay12514   bool operator()(const TemplateSpecCandidate *L,
12515                   const TemplateSpecCandidate *R) {
12516     // Fast-path this check.
12517     if (L == R)
12518       return false;
12519 
12520     // Assuming that both candidates are not matches...
12521 
12522     // Sort by the ranking of deduction failures.
12523     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12524       return RankDeductionFailure(L->DeductionFailure) <
12525              RankDeductionFailure(R->DeductionFailure);
12526 
12527     // Sort everything else by location.
12528     SourceLocation LLoc = GetLocationForCandidate(L);
12529     SourceLocation RLoc = GetLocationForCandidate(R);
12530 
12531     // Put candidates without locations (e.g. builtins) at the end.
12532     if (LLoc.isInvalid())
12533       return false;
12534     if (RLoc.isInvalid())
12535       return true;
12536 
12537     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12538   }
12539 };
12540 }
12541 
12542 /// Diagnose a template argument deduction failure.
12543 /// We are treating these failures as overload failures due to bad
12544 /// deductions.
NoteDeductionFailure(Sema & S,bool ForTakingAddress)12545 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12546                                                  bool ForTakingAddress) {
12547   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12548                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12549 }
12550 
destroyCandidates()12551 void TemplateSpecCandidateSet::destroyCandidates() {
12552   for (iterator i = begin(), e = end(); i != e; ++i) {
12553     i->DeductionFailure.Destroy();
12554   }
12555 }
12556 
clear()12557 void TemplateSpecCandidateSet::clear() {
12558   destroyCandidates();
12559   Candidates.clear();
12560 }
12561 
12562 /// NoteCandidates - When no template specialization match is found, prints
12563 /// diagnostic messages containing the non-matching specializations that form
12564 /// the candidate set.
12565 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12566 /// OCD == OCD_AllCandidates and Cand->Viable == false.
NoteCandidates(Sema & S,SourceLocation Loc)12567 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12568   // Sort the candidates by position (assuming no candidate is a match).
12569   // Sorting directly would be prohibitive, so we make a set of pointers
12570   // and sort those.
12571   SmallVector<TemplateSpecCandidate *, 32> Cands;
12572   Cands.reserve(size());
12573   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12574     if (Cand->Specialization)
12575       Cands.push_back(Cand);
12576     // Otherwise, this is a non-matching builtin candidate.  We do not,
12577     // in general, want to list every possible builtin candidate.
12578   }
12579 
12580   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12581 
12582   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12583   // for generalization purposes (?).
12584   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12585 
12586   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12587   unsigned CandsShown = 0;
12588   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12589     TemplateSpecCandidate *Cand = *I;
12590 
12591     // Set an arbitrary limit on the number of candidates we'll spam
12592     // the user with.  FIXME: This limit should depend on details of the
12593     // candidate list.
12594     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12595       break;
12596     ++CandsShown;
12597 
12598     assert(Cand->Specialization &&
12599            "Non-matching built-in candidates are not added to Cands.");
12600     Cand->NoteDeductionFailure(S, ForTakingAddress);
12601   }
12602 
12603   if (I != E)
12604     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12605 }
12606 
12607 // [PossiblyAFunctionType]  -->   [Return]
12608 // NonFunctionType --> NonFunctionType
12609 // R (A) --> R(A)
12610 // R (*)(A) --> R (A)
12611 // R (&)(A) --> R (A)
12612 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)12613 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12614   QualType Ret = PossiblyAFunctionType;
12615   if (const PointerType *ToTypePtr =
12616     PossiblyAFunctionType->getAs<PointerType>())
12617     Ret = ToTypePtr->getPointeeType();
12618   else if (const ReferenceType *ToTypeRef =
12619     PossiblyAFunctionType->getAs<ReferenceType>())
12620     Ret = ToTypeRef->getPointeeType();
12621   else if (const MemberPointerType *MemTypePtr =
12622     PossiblyAFunctionType->getAs<MemberPointerType>())
12623     Ret = MemTypePtr->getPointeeType();
12624   Ret =
12625     Context.getCanonicalType(Ret).getUnqualifiedType();
12626   return Ret;
12627 }
12628 
completeFunctionType(Sema & S,FunctionDecl * FD,SourceLocation Loc,bool Complain=true)12629 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12630                                  bool Complain = true) {
12631   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12632       S.DeduceReturnType(FD, Loc, Complain))
12633     return true;
12634 
12635   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12636   if (S.getLangOpts().CPlusPlus17 &&
12637       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12638       !S.ResolveExceptionSpec(Loc, FPT))
12639     return true;
12640 
12641   return false;
12642 }
12643 
12644 namespace {
12645 // A helper class to help with address of function resolution
12646 // - allows us to avoid passing around all those ugly parameters
12647 class AddressOfFunctionResolver {
12648   Sema& S;
12649   Expr* SourceExpr;
12650   const QualType& TargetType;
12651   QualType TargetFunctionType; // Extracted function type from target type
12652 
12653   bool Complain;
12654   //DeclAccessPair& ResultFunctionAccessPair;
12655   ASTContext& Context;
12656 
12657   bool TargetTypeIsNonStaticMemberFunction;
12658   bool FoundNonTemplateFunction;
12659   bool StaticMemberFunctionFromBoundPointer;
12660   bool HasComplained;
12661 
12662   OverloadExpr::FindResult OvlExprInfo;
12663   OverloadExpr *OvlExpr;
12664   TemplateArgumentListInfo OvlExplicitTemplateArgs;
12665   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12666   TemplateSpecCandidateSet FailedCandidates;
12667 
12668 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)12669   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12670                             const QualType &TargetType, bool Complain)
12671       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12672         Complain(Complain), Context(S.getASTContext()),
12673         TargetTypeIsNonStaticMemberFunction(
12674             !!TargetType->getAs<MemberPointerType>()),
12675         FoundNonTemplateFunction(false),
12676         StaticMemberFunctionFromBoundPointer(false),
12677         HasComplained(false),
12678         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12679         OvlExpr(OvlExprInfo.Expression),
12680         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12681     ExtractUnqualifiedFunctionTypeFromTargetType();
12682 
12683     if (TargetFunctionType->isFunctionType()) {
12684       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12685         if (!UME->isImplicitAccess() &&
12686             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12687           StaticMemberFunctionFromBoundPointer = true;
12688     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12689       DeclAccessPair dap;
12690       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12691               OvlExpr, false, &dap)) {
12692         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12693           if (!Method->isStatic()) {
12694             // If the target type is a non-function type and the function found
12695             // is a non-static member function, pretend as if that was the
12696             // target, it's the only possible type to end up with.
12697             TargetTypeIsNonStaticMemberFunction = true;
12698 
12699             // And skip adding the function if its not in the proper form.
12700             // We'll diagnose this due to an empty set of functions.
12701             if (!OvlExprInfo.HasFormOfMemberPointer)
12702               return;
12703           }
12704 
12705         Matches.push_back(std::make_pair(dap, Fn));
12706       }
12707       return;
12708     }
12709 
12710     if (OvlExpr->hasExplicitTemplateArgs())
12711       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12712 
12713     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12714       // C++ [over.over]p4:
12715       //   If more than one function is selected, [...]
12716       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12717         if (FoundNonTemplateFunction)
12718           EliminateAllTemplateMatches();
12719         else
12720           EliminateAllExceptMostSpecializedTemplate();
12721       }
12722     }
12723 
12724     if (S.getLangOpts().CUDA && Matches.size() > 1)
12725       EliminateSuboptimalCudaMatches();
12726   }
12727 
hasComplained() const12728   bool hasComplained() const { return HasComplained; }
12729 
12730 private:
candidateHasExactlyCorrectType(const FunctionDecl * FD)12731   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12732     QualType Discard;
12733     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12734            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12735   }
12736 
12737   /// \return true if A is considered a better overload candidate for the
12738   /// desired type than B.
isBetterCandidate(const FunctionDecl * A,const FunctionDecl * B)12739   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12740     // If A doesn't have exactly the correct type, we don't want to classify it
12741     // as "better" than anything else. This way, the user is required to
12742     // disambiguate for us if there are multiple candidates and no exact match.
12743     return candidateHasExactlyCorrectType(A) &&
12744            (!candidateHasExactlyCorrectType(B) ||
12745             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12746   }
12747 
12748   /// \return true if we were able to eliminate all but one overload candidate,
12749   /// false otherwise.
eliminiateSuboptimalOverloadCandidates()12750   bool eliminiateSuboptimalOverloadCandidates() {
12751     // Same algorithm as overload resolution -- one pass to pick the "best",
12752     // another pass to be sure that nothing is better than the best.
12753     auto Best = Matches.begin();
12754     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12755       if (isBetterCandidate(I->second, Best->second))
12756         Best = I;
12757 
12758     const FunctionDecl *BestFn = Best->second;
12759     auto IsBestOrInferiorToBest = [this, BestFn](
12760         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12761       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12762     };
12763 
12764     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12765     // option, so we can potentially give the user a better error
12766     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12767       return false;
12768     Matches[0] = *Best;
12769     Matches.resize(1);
12770     return true;
12771   }
12772 
isTargetTypeAFunction() const12773   bool isTargetTypeAFunction() const {
12774     return TargetFunctionType->isFunctionType();
12775   }
12776 
12777   // [ToType]     [Return]
12778 
12779   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12780   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12781   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()12782   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12783     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12784   }
12785 
12786   // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)12787   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12788                                    const DeclAccessPair& CurAccessFunPair) {
12789     if (CXXMethodDecl *Method
12790               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12791       // Skip non-static function templates when converting to pointer, and
12792       // static when converting to member pointer.
12793       bool CanConvertToFunctionPointer =
12794           Method->isStatic() || Method->isExplicitObjectMemberFunction();
12795       if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12796         return false;
12797     }
12798     else if (TargetTypeIsNonStaticMemberFunction)
12799       return false;
12800 
12801     // C++ [over.over]p2:
12802     //   If the name is a function template, template argument deduction is
12803     //   done (14.8.2.2), and if the argument deduction succeeds, the
12804     //   resulting template argument list is used to generate a single
12805     //   function template specialization, which is added to the set of
12806     //   overloaded functions considered.
12807     FunctionDecl *Specialization = nullptr;
12808     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12809     if (Sema::TemplateDeductionResult Result
12810           = S.DeduceTemplateArguments(FunctionTemplate,
12811                                       &OvlExplicitTemplateArgs,
12812                                       TargetFunctionType, Specialization,
12813                                       Info, /*IsAddressOfFunction*/true)) {
12814       // Make a note of the failed deduction for diagnostics.
12815       FailedCandidates.addCandidate()
12816           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12817                MakeDeductionFailureInfo(Context, Result, Info));
12818       return false;
12819     }
12820 
12821     // Template argument deduction ensures that we have an exact match or
12822     // compatible pointer-to-function arguments that would be adjusted by ICS.
12823     // This function template specicalization works.
12824     assert(S.isSameOrCompatibleFunctionType(
12825               Context.getCanonicalType(Specialization->getType()),
12826               Context.getCanonicalType(TargetFunctionType)));
12827 
12828     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12829       return false;
12830 
12831     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12832     return true;
12833   }
12834 
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)12835   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12836                                       const DeclAccessPair& CurAccessFunPair) {
12837     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12838       // Skip non-static functions when converting to pointer, and static
12839       // when converting to member pointer.
12840       bool CanConvertToFunctionPointer =
12841           Method->isStatic() || Method->isExplicitObjectMemberFunction();
12842       if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12843         return false;
12844     }
12845     else if (TargetTypeIsNonStaticMemberFunction)
12846       return false;
12847 
12848     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12849       if (S.getLangOpts().CUDA) {
12850         FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12851         if (!(Caller && Caller->isImplicit()) &&
12852             !S.IsAllowedCUDACall(Caller, FunDecl))
12853           return false;
12854       }
12855       if (FunDecl->isMultiVersion()) {
12856         const auto *TA = FunDecl->getAttr<TargetAttr>();
12857         if (TA && !TA->isDefaultVersion())
12858           return false;
12859         const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
12860         if (TVA && !TVA->isDefaultVersion())
12861           return false;
12862       }
12863 
12864       // If any candidate has a placeholder return type, trigger its deduction
12865       // now.
12866       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12867                                Complain)) {
12868         HasComplained |= Complain;
12869         return false;
12870       }
12871 
12872       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12873         return false;
12874 
12875       // If we're in C, we need to support types that aren't exactly identical.
12876       if (!S.getLangOpts().CPlusPlus ||
12877           candidateHasExactlyCorrectType(FunDecl)) {
12878         Matches.push_back(std::make_pair(
12879             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12880         FoundNonTemplateFunction = true;
12881         return true;
12882       }
12883     }
12884 
12885     return false;
12886   }
12887 
FindAllFunctionsThatMatchTargetTypeExactly()12888   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12889     bool Ret = false;
12890 
12891     // If the overload expression doesn't have the form of a pointer to
12892     // member, don't try to convert it to a pointer-to-member type.
12893     if (IsInvalidFormOfPointerToMemberFunction())
12894       return false;
12895 
12896     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12897                                E = OvlExpr->decls_end();
12898          I != E; ++I) {
12899       // Look through any using declarations to find the underlying function.
12900       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12901 
12902       // C++ [over.over]p3:
12903       //   Non-member functions and static member functions match
12904       //   targets of type "pointer-to-function" or "reference-to-function."
12905       //   Nonstatic member functions match targets of
12906       //   type "pointer-to-member-function."
12907       // Note that according to DR 247, the containing class does not matter.
12908       if (FunctionTemplateDecl *FunctionTemplate
12909                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12910         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12911           Ret = true;
12912       }
12913       // If we have explicit template arguments supplied, skip non-templates.
12914       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12915                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12916         Ret = true;
12917     }
12918     assert(Ret || Matches.empty());
12919     return Ret;
12920   }
12921 
EliminateAllExceptMostSpecializedTemplate()12922   void EliminateAllExceptMostSpecializedTemplate() {
12923     //   [...] and any given function template specialization F1 is
12924     //   eliminated if the set contains a second function template
12925     //   specialization whose function template is more specialized
12926     //   than the function template of F1 according to the partial
12927     //   ordering rules of 14.5.5.2.
12928 
12929     // The algorithm specified above is quadratic. We instead use a
12930     // two-pass algorithm (similar to the one used to identify the
12931     // best viable function in an overload set) that identifies the
12932     // best function template (if it exists).
12933 
12934     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12935     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12936       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12937 
12938     // TODO: It looks like FailedCandidates does not serve much purpose
12939     // here, since the no_viable diagnostic has index 0.
12940     UnresolvedSetIterator Result = S.getMostSpecialized(
12941         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12942         SourceExpr->getBeginLoc(), S.PDiag(),
12943         S.PDiag(diag::err_addr_ovl_ambiguous)
12944             << Matches[0].second->getDeclName(),
12945         S.PDiag(diag::note_ovl_candidate)
12946             << (unsigned)oc_function << (unsigned)ocs_described_template,
12947         Complain, TargetFunctionType);
12948 
12949     if (Result != MatchesCopy.end()) {
12950       // Make it the first and only element
12951       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12952       Matches[0].second = cast<FunctionDecl>(*Result);
12953       Matches.resize(1);
12954     } else
12955       HasComplained |= Complain;
12956   }
12957 
EliminateAllTemplateMatches()12958   void EliminateAllTemplateMatches() {
12959     //   [...] any function template specializations in the set are
12960     //   eliminated if the set also contains a non-template function, [...]
12961     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12962       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12963         ++I;
12964       else {
12965         Matches[I] = Matches[--N];
12966         Matches.resize(N);
12967       }
12968     }
12969   }
12970 
EliminateSuboptimalCudaMatches()12971   void EliminateSuboptimalCudaMatches() {
12972     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12973                                Matches);
12974   }
12975 
12976 public:
ComplainNoMatchesFound() const12977   void ComplainNoMatchesFound() const {
12978     assert(Matches.empty());
12979     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12980         << OvlExpr->getName() << TargetFunctionType
12981         << OvlExpr->getSourceRange();
12982     if (FailedCandidates.empty())
12983       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12984                                   /*TakingAddress=*/true);
12985     else {
12986       // We have some deduction failure messages. Use them to diagnose
12987       // the function templates, and diagnose the non-template candidates
12988       // normally.
12989       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12990                                  IEnd = OvlExpr->decls_end();
12991            I != IEnd; ++I)
12992         if (FunctionDecl *Fun =
12993                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12994           if (!functionHasPassObjectSizeParams(Fun))
12995             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12996                                     /*TakingAddress=*/true);
12997       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12998     }
12999   }
13000 
IsInvalidFormOfPointerToMemberFunction() const13001   bool IsInvalidFormOfPointerToMemberFunction() const {
13002     return TargetTypeIsNonStaticMemberFunction &&
13003       !OvlExprInfo.HasFormOfMemberPointer;
13004   }
13005 
ComplainIsInvalidFormOfPointerToMemberFunction() const13006   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13007       // TODO: Should we condition this on whether any functions might
13008       // have matched, or is it more appropriate to do that in callers?
13009       // TODO: a fixit wouldn't hurt.
13010       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13011         << TargetType << OvlExpr->getSourceRange();
13012   }
13013 
IsStaticMemberFunctionFromBoundPointer() const13014   bool IsStaticMemberFunctionFromBoundPointer() const {
13015     return StaticMemberFunctionFromBoundPointer;
13016   }
13017 
ComplainIsStaticMemberFunctionFromBoundPointer() const13018   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13019     S.Diag(OvlExpr->getBeginLoc(),
13020            diag::err_invalid_form_pointer_member_function)
13021         << OvlExpr->getSourceRange();
13022   }
13023 
ComplainOfInvalidConversion() const13024   void ComplainOfInvalidConversion() const {
13025     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13026         << OvlExpr->getName() << TargetType;
13027   }
13028 
ComplainMultipleMatchesFound() const13029   void ComplainMultipleMatchesFound() const {
13030     assert(Matches.size() > 1);
13031     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13032         << OvlExpr->getName() << OvlExpr->getSourceRange();
13033     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13034                                 /*TakingAddress=*/true);
13035   }
13036 
hadMultipleCandidates() const13037   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13038 
getNumMatches() const13039   int getNumMatches() const { return Matches.size(); }
13040 
getMatchingFunctionDecl() const13041   FunctionDecl* getMatchingFunctionDecl() const {
13042     if (Matches.size() != 1) return nullptr;
13043     return Matches[0].second;
13044   }
13045 
getMatchingFunctionAccessPair() const13046   const DeclAccessPair* getMatchingFunctionAccessPair() const {
13047     if (Matches.size() != 1) return nullptr;
13048     return &Matches[0].first;
13049   }
13050 };
13051 }
13052 
13053 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13054 /// an overloaded function (C++ [over.over]), where @p From is an
13055 /// expression with overloaded function type and @p ToType is the type
13056 /// we're trying to resolve to. For example:
13057 ///
13058 /// @code
13059 /// int f(double);
13060 /// int f(int);
13061 ///
13062 /// int (*pfd)(double) = f; // selects f(double)
13063 /// @endcode
13064 ///
13065 /// This routine returns the resulting FunctionDecl if it could be
13066 /// resolved, and NULL otherwise. When @p Complain is true, this
13067 /// routine will emit diagnostics if there is an error.
13068 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)13069 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13070                                          QualType TargetType,
13071                                          bool Complain,
13072                                          DeclAccessPair &FoundResult,
13073                                          bool *pHadMultipleCandidates) {
13074   assert(AddressOfExpr->getType() == Context.OverloadTy);
13075 
13076   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13077                                      Complain);
13078   int NumMatches = Resolver.getNumMatches();
13079   FunctionDecl *Fn = nullptr;
13080   bool ShouldComplain = Complain && !Resolver.hasComplained();
13081   if (NumMatches == 0 && ShouldComplain) {
13082     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13083       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13084     else
13085       Resolver.ComplainNoMatchesFound();
13086   }
13087   else if (NumMatches > 1 && ShouldComplain)
13088     Resolver.ComplainMultipleMatchesFound();
13089   else if (NumMatches == 1) {
13090     Fn = Resolver.getMatchingFunctionDecl();
13091     assert(Fn);
13092     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13093       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13094     FoundResult = *Resolver.getMatchingFunctionAccessPair();
13095     if (Complain) {
13096       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13097         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13098       else
13099         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13100     }
13101   }
13102 
13103   if (pHadMultipleCandidates)
13104     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13105   return Fn;
13106 }
13107 
13108 /// Given an expression that refers to an overloaded function, try to
13109 /// resolve that function to a single function that can have its address taken.
13110 /// This will modify `Pair` iff it returns non-null.
13111 ///
13112 /// This routine can only succeed if from all of the candidates in the overload
13113 /// set for SrcExpr that can have their addresses taken, there is one candidate
13114 /// that is more constrained than the rest.
13115 FunctionDecl *
resolveAddressOfSingleOverloadCandidate(Expr * E,DeclAccessPair & Pair)13116 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13117   OverloadExpr::FindResult R = OverloadExpr::find(E);
13118   OverloadExpr *Ovl = R.Expression;
13119   bool IsResultAmbiguous = false;
13120   FunctionDecl *Result = nullptr;
13121   DeclAccessPair DAP;
13122   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13123 
13124   // Return positive for better, negative for worse, 0 for equal preference.
13125   auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13126     FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13127     return static_cast<int>(IdentifyCUDAPreference(Caller, FD1)) -
13128            static_cast<int>(IdentifyCUDAPreference(Caller, FD2));
13129   };
13130 
13131   auto CheckMoreConstrained = [&](FunctionDecl *FD1,
13132                                   FunctionDecl *FD2) -> std::optional<bool> {
13133     if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
13134       FD1 = MF;
13135     if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
13136       FD2 = MF;
13137     SmallVector<const Expr *, 1> AC1, AC2;
13138     FD1->getAssociatedConstraints(AC1);
13139     FD2->getAssociatedConstraints(AC2);
13140     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
13141     if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
13142       return std::nullopt;
13143     if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
13144       return std::nullopt;
13145     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
13146       return std::nullopt;
13147     return AtLeastAsConstrained1;
13148   };
13149 
13150   // Don't use the AddressOfResolver because we're specifically looking for
13151   // cases where we have one overload candidate that lacks
13152   // enable_if/pass_object_size/...
13153   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13154     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13155     if (!FD)
13156       return nullptr;
13157 
13158     if (!checkAddressOfFunctionIsAvailable(FD))
13159       continue;
13160 
13161     // If we found a better result, update Result.
13162     auto FoundBetter = [&]() {
13163       IsResultAmbiguous = false;
13164       DAP = I.getPair();
13165       Result = FD;
13166     };
13167 
13168     // We have more than one result - see if it is more constrained than the
13169     // previous one.
13170     if (Result) {
13171       // Check CUDA preference first. If the candidates have differennt CUDA
13172       // preference, choose the one with higher CUDA preference. Otherwise,
13173       // choose the one with more constraints.
13174       if (getLangOpts().CUDA) {
13175         int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13176         // FD has different preference than Result.
13177         if (PreferenceByCUDA != 0) {
13178           // FD is more preferable than Result.
13179           if (PreferenceByCUDA > 0)
13180             FoundBetter();
13181           continue;
13182         }
13183       }
13184       // FD has the same CUDA prefernece than Result. Continue check
13185       // constraints.
13186       std::optional<bool> MoreConstrainedThanPrevious =
13187           CheckMoreConstrained(FD, Result);
13188       if (!MoreConstrainedThanPrevious) {
13189         IsResultAmbiguous = true;
13190         AmbiguousDecls.push_back(FD);
13191         continue;
13192       }
13193       if (!*MoreConstrainedThanPrevious)
13194         continue;
13195       // FD is more constrained - replace Result with it.
13196     }
13197     FoundBetter();
13198   }
13199 
13200   if (IsResultAmbiguous)
13201     return nullptr;
13202 
13203   if (Result) {
13204     SmallVector<const Expr *, 1> ResultAC;
13205     // We skipped over some ambiguous declarations which might be ambiguous with
13206     // the selected result.
13207     for (FunctionDecl *Skipped : AmbiguousDecls) {
13208       // If skipped candidate has different CUDA preference than the result,
13209       // there is no ambiguity. Otherwise check whether they have different
13210       // constraints.
13211       if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13212         continue;
13213       if (!CheckMoreConstrained(Skipped, Result))
13214         return nullptr;
13215     }
13216     Pair = DAP;
13217   }
13218   return Result;
13219 }
13220 
13221 /// Given an overloaded function, tries to turn it into a non-overloaded
13222 /// function reference using resolveAddressOfSingleOverloadCandidate. This
13223 /// will perform access checks, diagnose the use of the resultant decl, and, if
13224 /// requested, potentially perform a function-to-pointer decay.
13225 ///
13226 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13227 /// Otherwise, returns true. This may emit diagnostics and return true.
resolveAndFixAddressOfSingleOverloadCandidate(ExprResult & SrcExpr,bool DoFunctionPointerConversion)13228 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
13229     ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13230   Expr *E = SrcExpr.get();
13231   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13232 
13233   DeclAccessPair DAP;
13234   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13235   if (!Found || Found->isCPUDispatchMultiVersion() ||
13236       Found->isCPUSpecificMultiVersion())
13237     return false;
13238 
13239   // Emitting multiple diagnostics for a function that is both inaccessible and
13240   // unavailable is consistent with our behavior elsewhere. So, always check
13241   // for both.
13242   DiagnoseUseOfDecl(Found, E->getExprLoc());
13243   CheckAddressOfMemberAccess(E, DAP);
13244   ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13245   if (Res.isInvalid())
13246     return false;
13247   Expr *Fixed = Res.get();
13248   if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13249     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13250   else
13251     SrcExpr = Fixed;
13252   return true;
13253 }
13254 
13255 /// Given an expression that refers to an overloaded function, try to
13256 /// resolve that overloaded function expression down to a single function.
13257 ///
13258 /// This routine can only resolve template-ids that refer to a single function
13259 /// template, where that template-id refers to a single template whose template
13260 /// arguments are either provided by the template-id or have defaults,
13261 /// as described in C++0x [temp.arg.explicit]p3.
13262 ///
13263 /// If no template-ids are found, no diagnostics are emitted and NULL is
13264 /// returned.
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult,TemplateSpecCandidateSet * FailedTSC)13265 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
13266     OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13267     TemplateSpecCandidateSet *FailedTSC) {
13268   // C++ [over.over]p1:
13269   //   [...] [Note: any redundant set of parentheses surrounding the
13270   //   overloaded function name is ignored (5.1). ]
13271   // C++ [over.over]p1:
13272   //   [...] The overloaded function name can be preceded by the &
13273   //   operator.
13274 
13275   // If we didn't actually find any template-ids, we're done.
13276   if (!ovl->hasExplicitTemplateArgs())
13277     return nullptr;
13278 
13279   TemplateArgumentListInfo ExplicitTemplateArgs;
13280   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13281 
13282   // Look through all of the overloaded functions, searching for one
13283   // whose type matches exactly.
13284   FunctionDecl *Matched = nullptr;
13285   for (UnresolvedSetIterator I = ovl->decls_begin(),
13286          E = ovl->decls_end(); I != E; ++I) {
13287     // C++0x [temp.arg.explicit]p3:
13288     //   [...] In contexts where deduction is done and fails, or in contexts
13289     //   where deduction is not done, if a template argument list is
13290     //   specified and it, along with any default template arguments,
13291     //   identifies a single function template specialization, then the
13292     //   template-id is an lvalue for the function template specialization.
13293     FunctionTemplateDecl *FunctionTemplate
13294       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13295 
13296     // C++ [over.over]p2:
13297     //   If the name is a function template, template argument deduction is
13298     //   done (14.8.2.2), and if the argument deduction succeeds, the
13299     //   resulting template argument list is used to generate a single
13300     //   function template specialization, which is added to the set of
13301     //   overloaded functions considered.
13302     FunctionDecl *Specialization = nullptr;
13303     TemplateDeductionInfo Info(ovl->getNameLoc());
13304     if (TemplateDeductionResult Result
13305           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
13306                                     Specialization, Info,
13307                                     /*IsAddressOfFunction*/true)) {
13308       // Make a note of the failed deduction for diagnostics.
13309       if (FailedTSC)
13310         FailedTSC->addCandidate().set(
13311             I.getPair(), FunctionTemplate->getTemplatedDecl(),
13312             MakeDeductionFailureInfo(Context, Result, Info));
13313       continue;
13314     }
13315 
13316     assert(Specialization && "no specialization and no error?");
13317 
13318     // Multiple matches; we can't resolve to a single declaration.
13319     if (Matched) {
13320       if (Complain) {
13321         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13322           << ovl->getName();
13323         NoteAllOverloadCandidates(ovl);
13324       }
13325       return nullptr;
13326     }
13327 
13328     Matched = Specialization;
13329     if (FoundResult) *FoundResult = I.getPair();
13330   }
13331 
13332   if (Matched &&
13333       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13334     return nullptr;
13335 
13336   return Matched;
13337 }
13338 
13339 // Resolve and fix an overloaded expression that can be resolved
13340 // because it identifies a single function template specialization.
13341 //
13342 // Last three arguments should only be supplied if Complain = true
13343 //
13344 // Return true if it was logically possible to so resolve the
13345 // expression, regardless of whether or not it succeeded.  Always
13346 // returns true if 'complain' is set.
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConversion,bool complain,SourceRange OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)13347 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
13348     ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13349     SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13350     unsigned DiagIDForComplaining) {
13351   assert(SrcExpr.get()->getType() == Context.OverloadTy);
13352 
13353   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
13354 
13355   DeclAccessPair found;
13356   ExprResult SingleFunctionExpression;
13357   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13358                            ovl.Expression, /*complain*/ false, &found)) {
13359     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13360       SrcExpr = ExprError();
13361       return true;
13362     }
13363 
13364     // It is only correct to resolve to an instance method if we're
13365     // resolving a form that's permitted to be a pointer to member.
13366     // Otherwise we'll end up making a bound member expression, which
13367     // is illegal in all the contexts we resolve like this.
13368     if (!ovl.HasFormOfMemberPointer &&
13369         isa<CXXMethodDecl>(fn) &&
13370         cast<CXXMethodDecl>(fn)->isInstance()) {
13371       if (!complain) return false;
13372 
13373       Diag(ovl.Expression->getExprLoc(),
13374            diag::err_bound_member_function)
13375         << 0 << ovl.Expression->getSourceRange();
13376 
13377       // TODO: I believe we only end up here if there's a mix of
13378       // static and non-static candidates (otherwise the expression
13379       // would have 'bound member' type, not 'overload' type).
13380       // Ideally we would note which candidate was chosen and why
13381       // the static candidates were rejected.
13382       SrcExpr = ExprError();
13383       return true;
13384     }
13385 
13386     // Fix the expression to refer to 'fn'.
13387     SingleFunctionExpression =
13388         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13389 
13390     // If desired, do function-to-pointer decay.
13391     if (doFunctionPointerConversion) {
13392       SingleFunctionExpression =
13393         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13394       if (SingleFunctionExpression.isInvalid()) {
13395         SrcExpr = ExprError();
13396         return true;
13397       }
13398     }
13399   }
13400 
13401   if (!SingleFunctionExpression.isUsable()) {
13402     if (complain) {
13403       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13404         << ovl.Expression->getName()
13405         << DestTypeForComplaining
13406         << OpRangeForComplaining
13407         << ovl.Expression->getQualifierLoc().getSourceRange();
13408       NoteAllOverloadCandidates(SrcExpr.get());
13409 
13410       SrcExpr = ExprError();
13411       return true;
13412     }
13413 
13414     return false;
13415   }
13416 
13417   SrcExpr = SingleFunctionExpression;
13418   return true;
13419 }
13420 
13421 /// Add a single candidate to the overload set.
AddOverloadedCallCandidate(Sema & S,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool KnownValid)13422 static void AddOverloadedCallCandidate(Sema &S,
13423                                        DeclAccessPair FoundDecl,
13424                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
13425                                        ArrayRef<Expr *> Args,
13426                                        OverloadCandidateSet &CandidateSet,
13427                                        bool PartialOverloading,
13428                                        bool KnownValid) {
13429   NamedDecl *Callee = FoundDecl.getDecl();
13430   if (isa<UsingShadowDecl>(Callee))
13431     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13432 
13433   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13434     if (ExplicitTemplateArgs) {
13435       assert(!KnownValid && "Explicit template arguments?");
13436       return;
13437     }
13438     // Prevent ill-formed function decls to be added as overload candidates.
13439     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13440       return;
13441 
13442     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13443                            /*SuppressUserConversions=*/false,
13444                            PartialOverloading);
13445     return;
13446   }
13447 
13448   if (FunctionTemplateDecl *FuncTemplate
13449       = dyn_cast<FunctionTemplateDecl>(Callee)) {
13450     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13451                                    ExplicitTemplateArgs, Args, CandidateSet,
13452                                    /*SuppressUserConversions=*/false,
13453                                    PartialOverloading);
13454     return;
13455   }
13456 
13457   assert(!KnownValid && "unhandled case in overloaded call candidate");
13458 }
13459 
13460 /// Add the overload candidates named by callee and/or found by argument
13461 /// dependent lookup to the given overload set.
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)13462 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
13463                                        ArrayRef<Expr *> Args,
13464                                        OverloadCandidateSet &CandidateSet,
13465                                        bool PartialOverloading) {
13466 
13467 #ifndef NDEBUG
13468   // Verify that ArgumentDependentLookup is consistent with the rules
13469   // in C++0x [basic.lookup.argdep]p3:
13470   //
13471   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
13472   //   and let Y be the lookup set produced by argument dependent
13473   //   lookup (defined as follows). If X contains
13474   //
13475   //     -- a declaration of a class member, or
13476   //
13477   //     -- a block-scope function declaration that is not a
13478   //        using-declaration, or
13479   //
13480   //     -- a declaration that is neither a function or a function
13481   //        template
13482   //
13483   //   then Y is empty.
13484 
13485   if (ULE->requiresADL()) {
13486     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13487            E = ULE->decls_end(); I != E; ++I) {
13488       assert(!(*I)->getDeclContext()->isRecord());
13489       assert(isa<UsingShadowDecl>(*I) ||
13490              !(*I)->getDeclContext()->isFunctionOrMethod());
13491       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13492     }
13493   }
13494 #endif
13495 
13496   // It would be nice to avoid this copy.
13497   TemplateArgumentListInfo TABuffer;
13498   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13499   if (ULE->hasExplicitTemplateArgs()) {
13500     ULE->copyTemplateArgumentsInto(TABuffer);
13501     ExplicitTemplateArgs = &TABuffer;
13502   }
13503 
13504   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13505          E = ULE->decls_end(); I != E; ++I)
13506     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13507                                CandidateSet, PartialOverloading,
13508                                /*KnownValid*/ true);
13509 
13510   if (ULE->requiresADL())
13511     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13512                                          Args, ExplicitTemplateArgs,
13513                                          CandidateSet, PartialOverloading);
13514 }
13515 
13516 /// Add the call candidates from the given set of lookup results to the given
13517 /// overload set. Non-function lookup results are ignored.
AddOverloadedCallCandidates(LookupResult & R,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)13518 void Sema::AddOverloadedCallCandidates(
13519     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13520     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13521   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13522     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13523                                CandidateSet, false, /*KnownValid*/ false);
13524 }
13525 
13526 /// Determine whether a declaration with the specified name could be moved into
13527 /// a different namespace.
canBeDeclaredInNamespace(const DeclarationName & Name)13528 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13529   switch (Name.getCXXOverloadedOperator()) {
13530   case OO_New: case OO_Array_New:
13531   case OO_Delete: case OO_Array_Delete:
13532     return false;
13533 
13534   default:
13535     return true;
13536   }
13537 }
13538 
13539 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13540 /// template, where the non-dependent name was declared after the template
13541 /// was defined. This is common in code written for a compilers which do not
13542 /// correctly implement two-stage name lookup.
13543 ///
13544 /// Returns true if a viable candidate was found and a diagnostic was issued.
DiagnoseTwoPhaseLookup(Sema & SemaRef,SourceLocation FnLoc,const CXXScopeSpec & SS,LookupResult & R,OverloadCandidateSet::CandidateSetKind CSK,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,CXXRecordDecl ** FoundInClass=nullptr)13545 static bool DiagnoseTwoPhaseLookup(
13546     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13547     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13548     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13549     CXXRecordDecl **FoundInClass = nullptr) {
13550   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13551     return false;
13552 
13553   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13554     if (DC->isTransparentContext())
13555       continue;
13556 
13557     SemaRef.LookupQualifiedName(R, DC);
13558 
13559     if (!R.empty()) {
13560       R.suppressDiagnostics();
13561 
13562       OverloadCandidateSet Candidates(FnLoc, CSK);
13563       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13564                                           Candidates);
13565 
13566       OverloadCandidateSet::iterator Best;
13567       OverloadingResult OR =
13568           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13569 
13570       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13571         // We either found non-function declarations or a best viable function
13572         // at class scope. A class-scope lookup result disables ADL. Don't
13573         // look past this, but let the caller know that we found something that
13574         // either is, or might be, usable in this class.
13575         if (FoundInClass) {
13576           *FoundInClass = RD;
13577           if (OR == OR_Success) {
13578             R.clear();
13579             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13580             R.resolveKind();
13581           }
13582         }
13583         return false;
13584       }
13585 
13586       if (OR != OR_Success) {
13587         // There wasn't a unique best function or function template.
13588         return false;
13589       }
13590 
13591       // Find the namespaces where ADL would have looked, and suggest
13592       // declaring the function there instead.
13593       Sema::AssociatedNamespaceSet AssociatedNamespaces;
13594       Sema::AssociatedClassSet AssociatedClasses;
13595       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13596                                                  AssociatedNamespaces,
13597                                                  AssociatedClasses);
13598       Sema::AssociatedNamespaceSet SuggestedNamespaces;
13599       if (canBeDeclaredInNamespace(R.getLookupName())) {
13600         DeclContext *Std = SemaRef.getStdNamespace();
13601         for (Sema::AssociatedNamespaceSet::iterator
13602                it = AssociatedNamespaces.begin(),
13603                end = AssociatedNamespaces.end(); it != end; ++it) {
13604           // Never suggest declaring a function within namespace 'std'.
13605           if (Std && Std->Encloses(*it))
13606             continue;
13607 
13608           // Never suggest declaring a function within a namespace with a
13609           // reserved name, like __gnu_cxx.
13610           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13611           if (NS &&
13612               NS->getQualifiedNameAsString().find("__") != std::string::npos)
13613             continue;
13614 
13615           SuggestedNamespaces.insert(*it);
13616         }
13617       }
13618 
13619       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13620         << R.getLookupName();
13621       if (SuggestedNamespaces.empty()) {
13622         SemaRef.Diag(Best->Function->getLocation(),
13623                      diag::note_not_found_by_two_phase_lookup)
13624           << R.getLookupName() << 0;
13625       } else if (SuggestedNamespaces.size() == 1) {
13626         SemaRef.Diag(Best->Function->getLocation(),
13627                      diag::note_not_found_by_two_phase_lookup)
13628           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13629       } else {
13630         // FIXME: It would be useful to list the associated namespaces here,
13631         // but the diagnostics infrastructure doesn't provide a way to produce
13632         // a localized representation of a list of items.
13633         SemaRef.Diag(Best->Function->getLocation(),
13634                      diag::note_not_found_by_two_phase_lookup)
13635           << R.getLookupName() << 2;
13636       }
13637 
13638       // Try to recover by calling this function.
13639       return true;
13640     }
13641 
13642     R.clear();
13643   }
13644 
13645   return false;
13646 }
13647 
13648 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13649 /// template, where the non-dependent operator was declared after the template
13650 /// was defined.
13651 ///
13652 /// Returns true if a viable candidate was found and a diagnostic was issued.
13653 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args)13654 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13655                                SourceLocation OpLoc,
13656                                ArrayRef<Expr *> Args) {
13657   DeclarationName OpName =
13658     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13659   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13660   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13661                                 OverloadCandidateSet::CSK_Operator,
13662                                 /*ExplicitTemplateArgs=*/nullptr, Args);
13663 }
13664 
13665 namespace {
13666 class BuildRecoveryCallExprRAII {
13667   Sema &SemaRef;
13668   Sema::SatisfactionStackResetRAII SatStack;
13669 
13670 public:
BuildRecoveryCallExprRAII(Sema & S)13671   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13672     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13673     SemaRef.IsBuildingRecoveryCallExpr = true;
13674   }
13675 
~BuildRecoveryCallExprRAII()13676   ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13677 };
13678 }
13679 
13680 /// Attempts to recover from a call where no functions were found.
13681 ///
13682 /// This function will do one of three things:
13683 ///  * Diagnose, recover, and return a recovery expression.
13684 ///  * Diagnose, fail to recover, and return ExprError().
13685 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
13686 ///    expected to diagnose as appropriate.
13687 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)13688 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13689                       UnresolvedLookupExpr *ULE,
13690                       SourceLocation LParenLoc,
13691                       MutableArrayRef<Expr *> Args,
13692                       SourceLocation RParenLoc,
13693                       bool EmptyLookup, bool AllowTypoCorrection) {
13694   // Do not try to recover if it is already building a recovery call.
13695   // This stops infinite loops for template instantiations like
13696   //
13697   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13698   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13699   if (SemaRef.IsBuildingRecoveryCallExpr)
13700     return ExprResult();
13701   BuildRecoveryCallExprRAII RCE(SemaRef);
13702 
13703   CXXScopeSpec SS;
13704   SS.Adopt(ULE->getQualifierLoc());
13705   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13706 
13707   TemplateArgumentListInfo TABuffer;
13708   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13709   if (ULE->hasExplicitTemplateArgs()) {
13710     ULE->copyTemplateArgumentsInto(TABuffer);
13711     ExplicitTemplateArgs = &TABuffer;
13712   }
13713 
13714   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13715                  Sema::LookupOrdinaryName);
13716   CXXRecordDecl *FoundInClass = nullptr;
13717   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13718                              OverloadCandidateSet::CSK_Normal,
13719                              ExplicitTemplateArgs, Args, &FoundInClass)) {
13720     // OK, diagnosed a two-phase lookup issue.
13721   } else if (EmptyLookup) {
13722     // Try to recover from an empty lookup with typo correction.
13723     R.clear();
13724     NoTypoCorrectionCCC NoTypoValidator{};
13725     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13726                                                 ExplicitTemplateArgs != nullptr,
13727                                                 dyn_cast<MemberExpr>(Fn));
13728     CorrectionCandidateCallback &Validator =
13729         AllowTypoCorrection
13730             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13731             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13732     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13733                                     Args))
13734       return ExprError();
13735   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13736     // We found a usable declaration of the name in a dependent base of some
13737     // enclosing class.
13738     // FIXME: We should also explain why the candidates found by name lookup
13739     // were not viable.
13740     if (SemaRef.DiagnoseDependentMemberLookup(R))
13741       return ExprError();
13742   } else {
13743     // We had viable candidates and couldn't recover; let the caller diagnose
13744     // this.
13745     return ExprResult();
13746   }
13747 
13748   // If we get here, we should have issued a diagnostic and formed a recovery
13749   // lookup result.
13750   assert(!R.empty() && "lookup results empty despite recovery");
13751 
13752   // If recovery created an ambiguity, just bail out.
13753   if (R.isAmbiguous()) {
13754     R.suppressDiagnostics();
13755     return ExprError();
13756   }
13757 
13758   // Build an implicit member call if appropriate.  Just drop the
13759   // casts and such from the call, we don't really care.
13760   ExprResult NewFn = ExprError();
13761   if ((*R.begin())->isCXXClassMember())
13762     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13763                                                     ExplicitTemplateArgs, S);
13764   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13765     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13766                                         ExplicitTemplateArgs);
13767   else
13768     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13769 
13770   if (NewFn.isInvalid())
13771     return ExprError();
13772 
13773   // This shouldn't cause an infinite loop because we're giving it
13774   // an expression with viable lookup results, which should never
13775   // end up here.
13776   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13777                                MultiExprArg(Args.data(), Args.size()),
13778                                RParenLoc);
13779 }
13780 
13781 /// Constructs and populates an OverloadedCandidateSet from
13782 /// the given function.
13783 /// \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)13784 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13785                                   UnresolvedLookupExpr *ULE,
13786                                   MultiExprArg Args,
13787                                   SourceLocation RParenLoc,
13788                                   OverloadCandidateSet *CandidateSet,
13789                                   ExprResult *Result) {
13790 #ifndef NDEBUG
13791   if (ULE->requiresADL()) {
13792     // To do ADL, we must have found an unqualified name.
13793     assert(!ULE->getQualifier() && "qualified name with ADL");
13794 
13795     // We don't perform ADL for implicit declarations of builtins.
13796     // Verify that this was correctly set up.
13797     FunctionDecl *F;
13798     if (ULE->decls_begin() != ULE->decls_end() &&
13799         ULE->decls_begin() + 1 == ULE->decls_end() &&
13800         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13801         F->getBuiltinID() && F->isImplicit())
13802       llvm_unreachable("performing ADL for builtin");
13803 
13804     // We don't perform ADL in C.
13805     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13806   }
13807 #endif
13808 
13809   UnbridgedCastsSet UnbridgedCasts;
13810   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13811     *Result = ExprError();
13812     return true;
13813   }
13814 
13815   // Add the functions denoted by the callee to the set of candidate
13816   // functions, including those from argument-dependent lookup.
13817   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13818 
13819   if (getLangOpts().MSVCCompat &&
13820       CurContext->isDependentContext() && !isSFINAEContext() &&
13821       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13822 
13823     OverloadCandidateSet::iterator Best;
13824     if (CandidateSet->empty() ||
13825         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13826             OR_No_Viable_Function) {
13827       // In Microsoft mode, if we are inside a template class member function
13828       // then create a type dependent CallExpr. The goal is to postpone name
13829       // lookup to instantiation time to be able to search into type dependent
13830       // base classes.
13831       CallExpr *CE =
13832           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13833                            RParenLoc, CurFPFeatureOverrides());
13834       CE->markDependentForPostponedNameLookup();
13835       *Result = CE;
13836       return true;
13837     }
13838   }
13839 
13840   if (CandidateSet->empty())
13841     return false;
13842 
13843   UnbridgedCasts.restore();
13844   return false;
13845 }
13846 
13847 // Guess at what the return type for an unresolvable overload should be.
chooseRecoveryType(OverloadCandidateSet & CS,OverloadCandidateSet::iterator * Best)13848 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13849                                    OverloadCandidateSet::iterator *Best) {
13850   std::optional<QualType> Result;
13851   // Adjust Type after seeing a candidate.
13852   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13853     if (!Candidate.Function)
13854       return;
13855     if (Candidate.Function->isInvalidDecl())
13856       return;
13857     QualType T = Candidate.Function->getReturnType();
13858     if (T.isNull())
13859       return;
13860     if (!Result)
13861       Result = T;
13862     else if (Result != T)
13863       Result = QualType();
13864   };
13865 
13866   // Look for an unambiguous type from a progressively larger subset.
13867   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13868   //
13869   // First, consider only the best candidate.
13870   if (Best && *Best != CS.end())
13871     ConsiderCandidate(**Best);
13872   // Next, consider only viable candidates.
13873   if (!Result)
13874     for (const auto &C : CS)
13875       if (C.Viable)
13876         ConsiderCandidate(C);
13877   // Finally, consider all candidates.
13878   if (!Result)
13879     for (const auto &C : CS)
13880       ConsiderCandidate(C);
13881 
13882   if (!Result)
13883     return QualType();
13884   auto Value = *Result;
13885   if (Value.isNull() || Value->isUndeducedType())
13886     return QualType();
13887   return Value;
13888 }
13889 
13890 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13891 /// the completed call expression. If overload resolution fails, emits
13892 /// 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)13893 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13894                                            UnresolvedLookupExpr *ULE,
13895                                            SourceLocation LParenLoc,
13896                                            MultiExprArg Args,
13897                                            SourceLocation RParenLoc,
13898                                            Expr *ExecConfig,
13899                                            OverloadCandidateSet *CandidateSet,
13900                                            OverloadCandidateSet::iterator *Best,
13901                                            OverloadingResult OverloadResult,
13902                                            bool AllowTypoCorrection) {
13903   switch (OverloadResult) {
13904   case OR_Success: {
13905     FunctionDecl *FDecl = (*Best)->Function;
13906     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13907     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13908       return ExprError();
13909     ExprResult Res =
13910         SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13911     if (Res.isInvalid())
13912       return ExprError();
13913     return SemaRef.BuildResolvedCallExpr(
13914         Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
13915         /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
13916   }
13917 
13918   case OR_No_Viable_Function: {
13919     // Try to recover by looking for viable functions which the user might
13920     // have meant to call.
13921     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13922                                                 Args, RParenLoc,
13923                                                 CandidateSet->empty(),
13924                                                 AllowTypoCorrection);
13925     if (Recovery.isInvalid() || Recovery.isUsable())
13926       return Recovery;
13927 
13928     // If the user passes in a function that we can't take the address of, we
13929     // generally end up emitting really bad error messages. Here, we attempt to
13930     // emit better ones.
13931     for (const Expr *Arg : Args) {
13932       if (!Arg->getType()->isFunctionType())
13933         continue;
13934       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13935         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13936         if (FD &&
13937             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13938                                                        Arg->getExprLoc()))
13939           return ExprError();
13940       }
13941     }
13942 
13943     CandidateSet->NoteCandidates(
13944         PartialDiagnosticAt(
13945             Fn->getBeginLoc(),
13946             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13947                 << ULE->getName() << Fn->getSourceRange()),
13948         SemaRef, OCD_AllCandidates, Args);
13949     break;
13950   }
13951 
13952   case OR_Ambiguous:
13953     CandidateSet->NoteCandidates(
13954         PartialDiagnosticAt(Fn->getBeginLoc(),
13955                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13956                                 << ULE->getName() << Fn->getSourceRange()),
13957         SemaRef, OCD_AmbiguousCandidates, Args);
13958     break;
13959 
13960   case OR_Deleted: {
13961     CandidateSet->NoteCandidates(
13962         PartialDiagnosticAt(Fn->getBeginLoc(),
13963                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13964                                 << ULE->getName() << Fn->getSourceRange()),
13965         SemaRef, OCD_AllCandidates, Args);
13966 
13967     // We emitted an error for the unavailable/deleted function call but keep
13968     // the call in the AST.
13969     FunctionDecl *FDecl = (*Best)->Function;
13970     ExprResult Res =
13971         SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13972     if (Res.isInvalid())
13973       return ExprError();
13974     return SemaRef.BuildResolvedCallExpr(
13975         Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
13976         /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
13977   }
13978   }
13979 
13980   // Overload resolution failed, try to recover.
13981   SmallVector<Expr *, 8> SubExprs = {Fn};
13982   SubExprs.append(Args.begin(), Args.end());
13983   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13984                                     chooseRecoveryType(*CandidateSet, Best));
13985 }
13986 
markUnaddressableCandidatesUnviable(Sema & S,OverloadCandidateSet & CS)13987 static void markUnaddressableCandidatesUnviable(Sema &S,
13988                                                 OverloadCandidateSet &CS) {
13989   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13990     if (I->Viable &&
13991         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13992       I->Viable = false;
13993       I->FailureKind = ovl_fail_addr_not_available;
13994     }
13995   }
13996 }
13997 
13998 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13999 /// (which eventually refers to the declaration Func) and the call
14000 /// arguments Args/NumArgs, attempt to resolve the function call down
14001 /// to a specific function. If overload resolution succeeds, returns
14002 /// the call expression produced by overload resolution.
14003 /// 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)14004 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14005                                          UnresolvedLookupExpr *ULE,
14006                                          SourceLocation LParenLoc,
14007                                          MultiExprArg Args,
14008                                          SourceLocation RParenLoc,
14009                                          Expr *ExecConfig,
14010                                          bool AllowTypoCorrection,
14011                                          bool CalleesAddressIsTaken) {
14012   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
14013                                     OverloadCandidateSet::CSK_Normal);
14014   ExprResult result;
14015 
14016   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14017                              &result))
14018     return result;
14019 
14020   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14021   // functions that aren't addressible are considered unviable.
14022   if (CalleesAddressIsTaken)
14023     markUnaddressableCandidatesUnviable(*this, CandidateSet);
14024 
14025   OverloadCandidateSet::iterator Best;
14026   OverloadingResult OverloadResult =
14027       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14028 
14029   // Model the case with a call to a templated function whose definition
14030   // encloses the call and whose return type contains a placeholder type as if
14031   // the UnresolvedLookupExpr was type-dependent.
14032   if (OverloadResult == OR_Success) {
14033     const FunctionDecl *FDecl = Best->Function;
14034     if (FDecl && FDecl->isTemplateInstantiation() &&
14035         FDecl->getReturnType()->isUndeducedType()) {
14036       if (const auto *TP =
14037               FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14038           TP && TP->willHaveBody()) {
14039         return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14040                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14041       }
14042     }
14043   }
14044 
14045   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14046                                   ExecConfig, &CandidateSet, &Best,
14047                                   OverloadResult, AllowTypoCorrection);
14048 }
14049 
IsOverloaded(const UnresolvedSetImpl & Functions)14050 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
14051   return Functions.size() > 1 ||
14052          (Functions.size() == 1 &&
14053           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
14054 }
14055 
CreateUnresolvedLookupExpr(CXXRecordDecl * NamingClass,NestedNameSpecifierLoc NNSLoc,DeclarationNameInfo DNI,const UnresolvedSetImpl & Fns,bool PerformADL)14056 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14057                                             NestedNameSpecifierLoc NNSLoc,
14058                                             DeclarationNameInfo DNI,
14059                                             const UnresolvedSetImpl &Fns,
14060                                             bool PerformADL) {
14061   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14062                                       PerformADL, IsOverloaded(Fns),
14063                                       Fns.begin(), Fns.end());
14064 }
14065 
BuildCXXMemberCallExpr(Expr * E,NamedDecl * FoundDecl,CXXConversionDecl * Method,bool HadMultipleCandidates)14066 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14067                                         CXXConversionDecl *Method,
14068                                         bool HadMultipleCandidates) {
14069   // Convert the expression to match the conversion function's implicit object
14070   // parameter.
14071   ExprResult Exp;
14072   if (Method->isExplicitObjectMemberFunction())
14073     Exp = InitializeExplicitObjectArgument(*this, E, Method);
14074   else
14075     Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14076                                                       FoundDecl, Method);
14077   if (Exp.isInvalid())
14078     return true;
14079 
14080   if (Method->getParent()->isLambda() &&
14081       Method->getConversionType()->isBlockPointerType()) {
14082     // This is a lambda conversion to block pointer; check if the argument
14083     // was a LambdaExpr.
14084     Expr *SubE = E;
14085     auto *CE = dyn_cast<CastExpr>(SubE);
14086     if (CE && CE->getCastKind() == CK_NoOp)
14087       SubE = CE->getSubExpr();
14088     SubE = SubE->IgnoreParens();
14089     if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14090       SubE = BE->getSubExpr();
14091     if (isa<LambdaExpr>(SubE)) {
14092       // For the conversion to block pointer on a lambda expression, we
14093       // construct a special BlockLiteral instead; this doesn't really make
14094       // a difference in ARC, but outside of ARC the resulting block literal
14095       // follows the normal lifetime rules for block literals instead of being
14096       // autoreleased.
14097       PushExpressionEvaluationContext(
14098           ExpressionEvaluationContext::PotentiallyEvaluated);
14099       ExprResult BlockExp = BuildBlockForLambdaConversion(
14100           Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14101       PopExpressionEvaluationContext();
14102 
14103       // FIXME: This note should be produced by a CodeSynthesisContext.
14104       if (BlockExp.isInvalid())
14105         Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14106       return BlockExp;
14107     }
14108   }
14109   CallExpr *CE;
14110   QualType ResultType = Method->getReturnType();
14111   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14112   ResultType = ResultType.getNonLValueExprType(Context);
14113   if (Method->isExplicitObjectMemberFunction()) {
14114     ExprResult FnExpr =
14115         CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14116                               HadMultipleCandidates, E->getBeginLoc());
14117     if (FnExpr.isInvalid())
14118       return ExprError();
14119     Expr *ObjectParam = Exp.get();
14120     CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14121                           ResultType, VK, Exp.get()->getEndLoc(),
14122                           CurFPFeatureOverrides());
14123   } else {
14124     MemberExpr *ME =
14125         BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14126                         NestedNameSpecifierLoc(), SourceLocation(), Method,
14127                         DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14128                         HadMultipleCandidates, DeclarationNameInfo(),
14129                         Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14130 
14131     CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14132                                    Exp.get()->getEndLoc(),
14133                                    CurFPFeatureOverrides());
14134   }
14135 
14136   if (CheckFunctionCall(Method, CE,
14137                         Method->getType()->castAs<FunctionProtoType>()))
14138     return ExprError();
14139 
14140   return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14141 }
14142 
14143 /// Create a unary operation that may resolve to an overloaded
14144 /// operator.
14145 ///
14146 /// \param OpLoc The location of the operator itself (e.g., '*').
14147 ///
14148 /// \param Opc The UnaryOperatorKind that describes this operator.
14149 ///
14150 /// \param Fns The set of non-member functions that will be
14151 /// considered by overload resolution. The caller needs to build this
14152 /// set based on the context using, e.g.,
14153 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14154 /// set should not contain any member functions; those will be added
14155 /// by CreateOverloadedUnaryOp().
14156 ///
14157 /// \param Input The input argument.
14158 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * Input,bool PerformADL)14159 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14160                               const UnresolvedSetImpl &Fns,
14161                               Expr *Input, bool PerformADL) {
14162   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14163   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14164   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14165   // TODO: provide better source location info.
14166   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14167 
14168   if (checkPlaceholderForOverload(*this, Input))
14169     return ExprError();
14170 
14171   Expr *Args[2] = { Input, nullptr };
14172   unsigned NumArgs = 1;
14173 
14174   // For post-increment and post-decrement, add the implicit '0' as
14175   // the second argument, so that we know this is a post-increment or
14176   // post-decrement.
14177   if (Opc == UO_PostInc || Opc == UO_PostDec) {
14178     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14179     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14180                                      SourceLocation());
14181     NumArgs = 2;
14182   }
14183 
14184   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14185 
14186   if (Input->isTypeDependent()) {
14187     if (Fns.empty())
14188       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
14189                                    VK_PRValue, OK_Ordinary, OpLoc, false,
14190                                    CurFPFeatureOverrides());
14191 
14192     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14193     ExprResult Fn = CreateUnresolvedLookupExpr(
14194         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14195     if (Fn.isInvalid())
14196       return ExprError();
14197     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14198                                        Context.DependentTy, VK_PRValue, OpLoc,
14199                                        CurFPFeatureOverrides());
14200   }
14201 
14202   // Build an empty overload set.
14203   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
14204 
14205   // Add the candidates from the given function set.
14206   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14207 
14208   // Add operator candidates that are member functions.
14209   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14210 
14211   // Add candidates from ADL.
14212   if (PerformADL) {
14213     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14214                                          /*ExplicitTemplateArgs*/nullptr,
14215                                          CandidateSet);
14216   }
14217 
14218   // Add builtin operator candidates.
14219   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14220 
14221   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14222 
14223   // Perform overload resolution.
14224   OverloadCandidateSet::iterator Best;
14225   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14226   case OR_Success: {
14227     // We found a built-in operator or an overloaded operator.
14228     FunctionDecl *FnDecl = Best->Function;
14229 
14230     if (FnDecl) {
14231       Expr *Base = nullptr;
14232       // We matched an overloaded operator. Build a call to that
14233       // operator.
14234 
14235       // Convert the arguments.
14236       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14237         CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14238 
14239         ExprResult InputInit;
14240         if (Method->isExplicitObjectMemberFunction())
14241           InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14242         else
14243           InputInit = PerformImplicitObjectArgumentInitialization(
14244               Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14245         if (InputInit.isInvalid())
14246           return ExprError();
14247         Base = Input = InputInit.get();
14248       } else {
14249         // Convert the arguments.
14250         ExprResult InputInit
14251           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14252                                                       Context,
14253                                                       FnDecl->getParamDecl(0)),
14254                                       SourceLocation(),
14255                                       Input);
14256         if (InputInit.isInvalid())
14257           return ExprError();
14258         Input = InputInit.get();
14259       }
14260 
14261       // Build the actual expression node.
14262       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14263                                                 Base, HadMultipleCandidates,
14264                                                 OpLoc);
14265       if (FnExpr.isInvalid())
14266         return ExprError();
14267 
14268       // Determine the result type.
14269       QualType ResultTy = FnDecl->getReturnType();
14270       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14271       ResultTy = ResultTy.getNonLValueExprType(Context);
14272 
14273       Args[0] = Input;
14274       CallExpr *TheCall = CXXOperatorCallExpr::Create(
14275           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14276           CurFPFeatureOverrides(), Best->IsADLCandidate);
14277 
14278       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14279         return ExprError();
14280 
14281       if (CheckFunctionCall(FnDecl, TheCall,
14282                             FnDecl->getType()->castAs<FunctionProtoType>()))
14283         return ExprError();
14284       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14285     } else {
14286       // We matched a built-in operator. Convert the arguments, then
14287       // break out so that we will build the appropriate built-in
14288       // operator node.
14289       ExprResult InputRes = PerformImplicitConversion(
14290           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14291           CCK_ForBuiltinOverloadedOp);
14292       if (InputRes.isInvalid())
14293         return ExprError();
14294       Input = InputRes.get();
14295       break;
14296     }
14297   }
14298 
14299   case OR_No_Viable_Function:
14300     // This is an erroneous use of an operator which can be overloaded by
14301     // a non-member function. Check for non-member operators which were
14302     // defined too late to be candidates.
14303     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14304       // FIXME: Recover by calling the found function.
14305       return ExprError();
14306 
14307     // No viable function; fall through to handling this as a
14308     // built-in operator, which will produce an error message for us.
14309     break;
14310 
14311   case OR_Ambiguous:
14312     CandidateSet.NoteCandidates(
14313         PartialDiagnosticAt(OpLoc,
14314                             PDiag(diag::err_ovl_ambiguous_oper_unary)
14315                                 << UnaryOperator::getOpcodeStr(Opc)
14316                                 << Input->getType() << Input->getSourceRange()),
14317         *this, OCD_AmbiguousCandidates, ArgsArray,
14318         UnaryOperator::getOpcodeStr(Opc), OpLoc);
14319     return ExprError();
14320 
14321   case OR_Deleted:
14322     // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14323     // object whose method was called. Later in NoteCandidates size of ArgsArray
14324     // is passed further and it eventually ends up compared to number of
14325     // function candidate parameters which never includes the object parameter,
14326     // so slice ArgsArray to make sure apples are compared to apples.
14327     CandidateSet.NoteCandidates(
14328         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14329                                        << UnaryOperator::getOpcodeStr(Opc)
14330                                        << Input->getSourceRange()),
14331         *this, OCD_AllCandidates, ArgsArray.drop_front(),
14332         UnaryOperator::getOpcodeStr(Opc), OpLoc);
14333     return ExprError();
14334   }
14335 
14336   // Either we found no viable overloaded operator or we matched a
14337   // built-in operator. In either case, fall through to trying to
14338   // build a built-in operation.
14339   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14340 }
14341 
14342 /// Perform lookup for an overloaded binary operator.
LookupOverloadedBinOp(OverloadCandidateSet & CandidateSet,OverloadedOperatorKind Op,const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,bool PerformADL)14343 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
14344                                  OverloadedOperatorKind Op,
14345                                  const UnresolvedSetImpl &Fns,
14346                                  ArrayRef<Expr *> Args, bool PerformADL) {
14347   SourceLocation OpLoc = CandidateSet.getLocation();
14348 
14349   OverloadedOperatorKind ExtraOp =
14350       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
14351           ? getRewrittenOverloadedOperator(Op)
14352           : OO_None;
14353 
14354   // Add the candidates from the given function set. This also adds the
14355   // rewritten candidates using these functions if necessary.
14356   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14357 
14358   // Add operator candidates that are member functions.
14359   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14360   if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14361     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14362                                 OverloadCandidateParamOrder::Reversed);
14363 
14364   // In C++20, also add any rewritten member candidates.
14365   if (ExtraOp) {
14366     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14367     if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14368       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14369                                   CandidateSet,
14370                                   OverloadCandidateParamOrder::Reversed);
14371   }
14372 
14373   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14374   // performed for an assignment operator (nor for operator[] nor operator->,
14375   // which don't get here).
14376   if (Op != OO_Equal && PerformADL) {
14377     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14378     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14379                                          /*ExplicitTemplateArgs*/ nullptr,
14380                                          CandidateSet);
14381     if (ExtraOp) {
14382       DeclarationName ExtraOpName =
14383           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14384       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14385                                            /*ExplicitTemplateArgs*/ nullptr,
14386                                            CandidateSet);
14387     }
14388   }
14389 
14390   // Add builtin operator candidates.
14391   //
14392   // FIXME: We don't add any rewritten candidates here. This is strictly
14393   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14394   // resulting in our selecting a rewritten builtin candidate. For example:
14395   //
14396   //   enum class E { e };
14397   //   bool operator!=(E, E) requires false;
14398   //   bool k = E::e != E::e;
14399   //
14400   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14401   // it seems unreasonable to consider rewritten builtin candidates. A core
14402   // issue has been filed proposing to removed this requirement.
14403   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14404 }
14405 
14406 /// Create a binary operation that may resolve to an overloaded
14407 /// operator.
14408 ///
14409 /// \param OpLoc The location of the operator itself (e.g., '+').
14410 ///
14411 /// \param Opc The BinaryOperatorKind that describes this operator.
14412 ///
14413 /// \param Fns The set of non-member functions that will be
14414 /// considered by overload resolution. The caller needs to build this
14415 /// set based on the context using, e.g.,
14416 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14417 /// set should not contain any member functions; those will be added
14418 /// by CreateOverloadedBinOp().
14419 ///
14420 /// \param LHS Left-hand argument.
14421 /// \param RHS Right-hand argument.
14422 /// \param PerformADL Whether to consider operator candidates found by ADL.
14423 /// \param AllowRewrittenCandidates Whether to consider candidates found by
14424 ///        C++20 operator rewrites.
14425 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
14426 ///        the function in question. Such a function is never a candidate in
14427 ///        our overload resolution. This also enables synthesizing a three-way
14428 ///        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)14429 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
14430                                        BinaryOperatorKind Opc,
14431                                        const UnresolvedSetImpl &Fns, Expr *LHS,
14432                                        Expr *RHS, bool PerformADL,
14433                                        bool AllowRewrittenCandidates,
14434                                        FunctionDecl *DefaultedFn) {
14435   Expr *Args[2] = { LHS, RHS };
14436   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14437 
14438   if (!getLangOpts().CPlusPlus20)
14439     AllowRewrittenCandidates = false;
14440 
14441   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
14442 
14443   // If either side is type-dependent, create an appropriate dependent
14444   // expression.
14445   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14446     if (Fns.empty()) {
14447       // If there are no functions to store, just build a dependent
14448       // BinaryOperator or CompoundAssignment.
14449       if (BinaryOperator::isCompoundAssignmentOp(Opc))
14450         return CompoundAssignOperator::Create(
14451             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14452             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14453             Context.DependentTy);
14454       return BinaryOperator::Create(
14455           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14456           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14457     }
14458 
14459     // FIXME: save results of ADL from here?
14460     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14461     // TODO: provide better source location info in DNLoc component.
14462     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14463     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14464     ExprResult Fn = CreateUnresolvedLookupExpr(
14465         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14466     if (Fn.isInvalid())
14467       return ExprError();
14468     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14469                                        Context.DependentTy, VK_PRValue, OpLoc,
14470                                        CurFPFeatureOverrides());
14471   }
14472 
14473   // If this is the .* operator, which is not overloadable, just
14474   // create a built-in binary operator.
14475   if (Opc == BO_PtrMemD) {
14476     auto CheckPlaceholder = [&](Expr *&Arg) {
14477       ExprResult Res = CheckPlaceholderExpr(Arg);
14478       if (Res.isUsable())
14479         Arg = Res.get();
14480       return !Res.isUsable();
14481     };
14482 
14483     // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14484     // expression that contains placeholders (in either the LHS or RHS).
14485     if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14486       return ExprError();
14487     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14488   }
14489 
14490   // Always do placeholder-like conversions on the RHS.
14491   if (checkPlaceholderForOverload(*this, Args[1]))
14492     return ExprError();
14493 
14494   // Do placeholder-like conversion on the LHS; note that we should
14495   // not get here with a PseudoObject LHS.
14496   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14497   if (checkPlaceholderForOverload(*this, Args[0]))
14498     return ExprError();
14499 
14500   // If this is the assignment operator, we only perform overload resolution
14501   // if the left-hand side is a class or enumeration type. This is actually
14502   // a hack. The standard requires that we do overload resolution between the
14503   // various built-in candidates, but as DR507 points out, this can lead to
14504   // problems. So we do it this way, which pretty much follows what GCC does.
14505   // Note that we go the traditional code path for compound assignment forms.
14506   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14507     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14508 
14509   // Build the overload set.
14510   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
14511                                     OverloadCandidateSet::OperatorRewriteInfo(
14512                                         Op, OpLoc, AllowRewrittenCandidates));
14513   if (DefaultedFn)
14514     CandidateSet.exclude(DefaultedFn);
14515   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14516 
14517   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14518 
14519   // Perform overload resolution.
14520   OverloadCandidateSet::iterator Best;
14521   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14522     case OR_Success: {
14523       // We found a built-in operator or an overloaded operator.
14524       FunctionDecl *FnDecl = Best->Function;
14525 
14526       bool IsReversed = Best->isReversed();
14527       if (IsReversed)
14528         std::swap(Args[0], Args[1]);
14529 
14530       if (FnDecl) {
14531 
14532         if (FnDecl->isInvalidDecl())
14533           return ExprError();
14534 
14535         Expr *Base = nullptr;
14536         // We matched an overloaded operator. Build a call to that
14537         // operator.
14538 
14539         OverloadedOperatorKind ChosenOp =
14540             FnDecl->getDeclName().getCXXOverloadedOperator();
14541 
14542         // C++2a [over.match.oper]p9:
14543         //   If a rewritten operator== candidate is selected by overload
14544         //   resolution for an operator@, its return type shall be cv bool
14545         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14546             !FnDecl->getReturnType()->isBooleanType()) {
14547           bool IsExtension =
14548               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
14549           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14550                                   : diag::err_ovl_rewrite_equalequal_not_bool)
14551               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14552               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14553           Diag(FnDecl->getLocation(), diag::note_declared_at);
14554           if (!IsExtension)
14555             return ExprError();
14556         }
14557 
14558         if (AllowRewrittenCandidates && !IsReversed &&
14559             CandidateSet.getRewriteInfo().isReversible()) {
14560           // We could have reversed this operator, but didn't. Check if some
14561           // reversed form was a viable candidate, and if so, if it had a
14562           // better conversion for either parameter. If so, this call is
14563           // formally ambiguous, and allowing it is an extension.
14564           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
14565           for (OverloadCandidate &Cand : CandidateSet) {
14566             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14567                 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14568               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14569                 if (CompareImplicitConversionSequences(
14570                         *this, OpLoc, Cand.Conversions[ArgIdx],
14571                         Best->Conversions[ArgIdx]) ==
14572                     ImplicitConversionSequence::Better) {
14573                   AmbiguousWith.push_back(Cand.Function);
14574                   break;
14575                 }
14576               }
14577             }
14578           }
14579 
14580           if (!AmbiguousWith.empty()) {
14581             bool AmbiguousWithSelf =
14582                 AmbiguousWith.size() == 1 &&
14583                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14584             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14585                 << BinaryOperator::getOpcodeStr(Opc)
14586                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14587                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14588             if (AmbiguousWithSelf) {
14589               Diag(FnDecl->getLocation(),
14590                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
14591               // Mark member== const or provide matching != to disallow reversed
14592               // args. Eg.
14593               // struct S { bool operator==(const S&); };
14594               // S()==S();
14595               if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14596                 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14597                     !MD->isConst() &&
14598                     !MD->hasCXXExplicitFunctionObjectParameter() &&
14599                     Context.hasSameUnqualifiedType(
14600                         MD->getFunctionObjectParameterType(),
14601                         MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14602                     Context.hasSameUnqualifiedType(
14603                         MD->getFunctionObjectParameterType(),
14604                         Args[0]->getType()) &&
14605                     Context.hasSameUnqualifiedType(
14606                         MD->getFunctionObjectParameterType(),
14607                         Args[1]->getType()))
14608                   Diag(FnDecl->getLocation(),
14609                        diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14610             } else {
14611               Diag(FnDecl->getLocation(),
14612                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14613               for (auto *F : AmbiguousWith)
14614                 Diag(F->getLocation(),
14615                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14616             }
14617           }
14618         }
14619 
14620         // Convert the arguments.
14621         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14622           // Best->Access is only meaningful for class members.
14623           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14624 
14625           ExprResult Arg0, Arg1;
14626           unsigned ParamIdx = 0;
14627           if (Method->isExplicitObjectMemberFunction()) {
14628             Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14629             ParamIdx = 1;
14630           } else {
14631             Arg0 = PerformImplicitObjectArgumentInitialization(
14632                 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14633           }
14634           Arg1 = PerformCopyInitialization(
14635               InitializedEntity::InitializeParameter(
14636                   Context, FnDecl->getParamDecl(ParamIdx)),
14637               SourceLocation(), Args[1]);
14638           if (Arg0.isInvalid() || Arg1.isInvalid())
14639             return ExprError();
14640 
14641           Base = Args[0] = Arg0.getAs<Expr>();
14642           Args[1] = RHS = Arg1.getAs<Expr>();
14643         } else {
14644           // Convert the arguments.
14645           ExprResult Arg0 = PerformCopyInitialization(
14646             InitializedEntity::InitializeParameter(Context,
14647                                                    FnDecl->getParamDecl(0)),
14648             SourceLocation(), Args[0]);
14649           if (Arg0.isInvalid())
14650             return ExprError();
14651 
14652           ExprResult Arg1 =
14653             PerformCopyInitialization(
14654               InitializedEntity::InitializeParameter(Context,
14655                                                      FnDecl->getParamDecl(1)),
14656               SourceLocation(), Args[1]);
14657           if (Arg1.isInvalid())
14658             return ExprError();
14659           Args[0] = LHS = Arg0.getAs<Expr>();
14660           Args[1] = RHS = Arg1.getAs<Expr>();
14661         }
14662 
14663         // Build the actual expression node.
14664         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14665                                                   Best->FoundDecl, Base,
14666                                                   HadMultipleCandidates, OpLoc);
14667         if (FnExpr.isInvalid())
14668           return ExprError();
14669 
14670         // Determine the result type.
14671         QualType ResultTy = FnDecl->getReturnType();
14672         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14673         ResultTy = ResultTy.getNonLValueExprType(Context);
14674 
14675         CallExpr *TheCall;
14676         ArrayRef<const Expr *> ArgsArray(Args, 2);
14677         const Expr *ImplicitThis = nullptr;
14678 
14679         // We always create a CXXOperatorCallExpr, even for explicit object
14680         // members; CodeGen should take care not to emit the this pointer.
14681         TheCall = CXXOperatorCallExpr::Create(
14682             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14683             CurFPFeatureOverrides(), Best->IsADLCandidate);
14684 
14685         if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14686             Method && Method->isImplicitObjectMemberFunction()) {
14687           // Cut off the implicit 'this'.
14688           ImplicitThis = ArgsArray[0];
14689           ArgsArray = ArgsArray.slice(1);
14690         }
14691 
14692         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14693                                 FnDecl))
14694           return ExprError();
14695 
14696         // Check for a self move.
14697         if (Op == OO_Equal)
14698           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14699 
14700         if (ImplicitThis) {
14701           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14702           QualType ThisTypeFromDecl = Context.getPointerType(
14703               cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14704 
14705           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14706                             ThisTypeFromDecl);
14707         }
14708 
14709         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14710                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14711                   VariadicDoesNotApply);
14712 
14713         ExprResult R = MaybeBindToTemporary(TheCall);
14714         if (R.isInvalid())
14715           return ExprError();
14716 
14717         R = CheckForImmediateInvocation(R, FnDecl);
14718         if (R.isInvalid())
14719           return ExprError();
14720 
14721         // For a rewritten candidate, we've already reversed the arguments
14722         // if needed. Perform the rest of the rewrite now.
14723         if ((Best->RewriteKind & CRK_DifferentOperator) ||
14724             (Op == OO_Spaceship && IsReversed)) {
14725           if (Op == OO_ExclaimEqual) {
14726             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14727             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14728           } else {
14729             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14730             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14731             Expr *ZeroLiteral =
14732                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14733 
14734             Sema::CodeSynthesisContext Ctx;
14735             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14736             Ctx.Entity = FnDecl;
14737             pushCodeSynthesisContext(Ctx);
14738 
14739             R = CreateOverloadedBinOp(
14740                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14741                 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14742                 /*AllowRewrittenCandidates=*/false);
14743 
14744             popCodeSynthesisContext();
14745           }
14746           if (R.isInvalid())
14747             return ExprError();
14748         } else {
14749           assert(ChosenOp == Op && "unexpected operator name");
14750         }
14751 
14752         // Make a note in the AST if we did any rewriting.
14753         if (Best->RewriteKind != CRK_None)
14754           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14755 
14756         return R;
14757       } else {
14758         // We matched a built-in operator. Convert the arguments, then
14759         // break out so that we will build the appropriate built-in
14760         // operator node.
14761         ExprResult ArgsRes0 = PerformImplicitConversion(
14762             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14763             AA_Passing, CCK_ForBuiltinOverloadedOp);
14764         if (ArgsRes0.isInvalid())
14765           return ExprError();
14766         Args[0] = ArgsRes0.get();
14767 
14768         ExprResult ArgsRes1 = PerformImplicitConversion(
14769             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14770             AA_Passing, CCK_ForBuiltinOverloadedOp);
14771         if (ArgsRes1.isInvalid())
14772           return ExprError();
14773         Args[1] = ArgsRes1.get();
14774         break;
14775       }
14776     }
14777 
14778     case OR_No_Viable_Function: {
14779       // C++ [over.match.oper]p9:
14780       //   If the operator is the operator , [...] and there are no
14781       //   viable functions, then the operator is assumed to be the
14782       //   built-in operator and interpreted according to clause 5.
14783       if (Opc == BO_Comma)
14784         break;
14785 
14786       // When defaulting an 'operator<=>', we can try to synthesize a three-way
14787       // compare result using '==' and '<'.
14788       if (DefaultedFn && Opc == BO_Cmp) {
14789         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14790                                                           Args[1], DefaultedFn);
14791         if (E.isInvalid() || E.isUsable())
14792           return E;
14793       }
14794 
14795       // For class as left operand for assignment or compound assignment
14796       // operator do not fall through to handling in built-in, but report that
14797       // no overloaded assignment operator found
14798       ExprResult Result = ExprError();
14799       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14800       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14801                                                    Args, OpLoc);
14802       DeferDiagsRAII DDR(*this,
14803                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14804       if (Args[0]->getType()->isRecordType() &&
14805           Opc >= BO_Assign && Opc <= BO_OrAssign) {
14806         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
14807              << BinaryOperator::getOpcodeStr(Opc)
14808              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14809         if (Args[0]->getType()->isIncompleteType()) {
14810           Diag(OpLoc, diag::note_assign_lhs_incomplete)
14811             << Args[0]->getType()
14812             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14813         }
14814       } else {
14815         // This is an erroneous use of an operator which can be overloaded by
14816         // a non-member function. Check for non-member operators which were
14817         // defined too late to be candidates.
14818         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14819           // FIXME: Recover by calling the found function.
14820           return ExprError();
14821 
14822         // No viable function; try to create a built-in operation, which will
14823         // produce an error. Then, show the non-viable candidates.
14824         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14825       }
14826       assert(Result.isInvalid() &&
14827              "C++ binary operator overloading is missing candidates!");
14828       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14829       return Result;
14830     }
14831 
14832     case OR_Ambiguous:
14833       CandidateSet.NoteCandidates(
14834           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14835                                          << BinaryOperator::getOpcodeStr(Opc)
14836                                          << Args[0]->getType()
14837                                          << Args[1]->getType()
14838                                          << Args[0]->getSourceRange()
14839                                          << Args[1]->getSourceRange()),
14840           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14841           OpLoc);
14842       return ExprError();
14843 
14844     case OR_Deleted:
14845       if (isImplicitlyDeleted(Best->Function)) {
14846         FunctionDecl *DeletedFD = Best->Function;
14847         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14848         if (DFK.isSpecialMember()) {
14849           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14850             << Args[0]->getType() << DFK.asSpecialMember();
14851         } else {
14852           assert(DFK.isComparison());
14853           Diag(OpLoc, diag::err_ovl_deleted_comparison)
14854             << Args[0]->getType() << DeletedFD;
14855         }
14856 
14857         // The user probably meant to call this special member. Just
14858         // explain why it's deleted.
14859         NoteDeletedFunction(DeletedFD);
14860         return ExprError();
14861       }
14862       CandidateSet.NoteCandidates(
14863           PartialDiagnosticAt(
14864               OpLoc, PDiag(diag::err_ovl_deleted_oper)
14865                          << getOperatorSpelling(Best->Function->getDeclName()
14866                                                     .getCXXOverloadedOperator())
14867                          << Args[0]->getSourceRange()
14868                          << Args[1]->getSourceRange()),
14869           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14870           OpLoc);
14871       return ExprError();
14872   }
14873 
14874   // We matched a built-in operator; build it.
14875   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14876 }
14877 
BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS,FunctionDecl * DefaultedFn)14878 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14879     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14880     FunctionDecl *DefaultedFn) {
14881   const ComparisonCategoryInfo *Info =
14882       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14883   // If we're not producing a known comparison category type, we can't
14884   // synthesize a three-way comparison. Let the caller diagnose this.
14885   if (!Info)
14886     return ExprResult((Expr*)nullptr);
14887 
14888   // If we ever want to perform this synthesis more generally, we will need to
14889   // apply the temporary materialization conversion to the operands.
14890   assert(LHS->isGLValue() && RHS->isGLValue() &&
14891          "cannot use prvalue expressions more than once");
14892   Expr *OrigLHS = LHS;
14893   Expr *OrigRHS = RHS;
14894 
14895   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14896   // each of them multiple times below.
14897   LHS = new (Context)
14898       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14899                       LHS->getObjectKind(), LHS);
14900   RHS = new (Context)
14901       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14902                       RHS->getObjectKind(), RHS);
14903 
14904   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14905                                         DefaultedFn);
14906   if (Eq.isInvalid())
14907     return ExprError();
14908 
14909   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14910                                           true, DefaultedFn);
14911   if (Less.isInvalid())
14912     return ExprError();
14913 
14914   ExprResult Greater;
14915   if (Info->isPartial()) {
14916     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14917                                     DefaultedFn);
14918     if (Greater.isInvalid())
14919       return ExprError();
14920   }
14921 
14922   // Form the list of comparisons we're going to perform.
14923   struct Comparison {
14924     ExprResult Cmp;
14925     ComparisonCategoryResult Result;
14926   } Comparisons[4] =
14927   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14928                           : ComparisonCategoryResult::Equivalent},
14929     {Less, ComparisonCategoryResult::Less},
14930     {Greater, ComparisonCategoryResult::Greater},
14931     {ExprResult(), ComparisonCategoryResult::Unordered},
14932   };
14933 
14934   int I = Info->isPartial() ? 3 : 2;
14935 
14936   // Combine the comparisons with suitable conditional expressions.
14937   ExprResult Result;
14938   for (; I >= 0; --I) {
14939     // Build a reference to the comparison category constant.
14940     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14941     // FIXME: Missing a constant for a comparison category. Diagnose this?
14942     if (!VI)
14943       return ExprResult((Expr*)nullptr);
14944     ExprResult ThisResult =
14945         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14946     if (ThisResult.isInvalid())
14947       return ExprError();
14948 
14949     // Build a conditional unless this is the final case.
14950     if (Result.get()) {
14951       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14952                                   ThisResult.get(), Result.get());
14953       if (Result.isInvalid())
14954         return ExprError();
14955     } else {
14956       Result = ThisResult;
14957     }
14958   }
14959 
14960   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14961   // bind the OpaqueValueExprs before they're (repeatedly) used.
14962   Expr *SyntacticForm = BinaryOperator::Create(
14963       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14964       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14965       CurFPFeatureOverrides());
14966   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14967   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14968 }
14969 
PrepareArgumentsForCallToObjectOfClassType(Sema & S,SmallVectorImpl<Expr * > & MethodArgs,CXXMethodDecl * Method,MultiExprArg Args,SourceLocation LParenLoc)14970 static bool PrepareArgumentsForCallToObjectOfClassType(
14971     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14972     MultiExprArg Args, SourceLocation LParenLoc) {
14973 
14974   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14975   unsigned NumParams = Proto->getNumParams();
14976   unsigned NumArgsSlots =
14977       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14978   // Build the full argument list for the method call (the implicit object
14979   // parameter is placed at the beginning of the list).
14980   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14981   bool IsError = false;
14982   // Initialize the implicit object parameter.
14983   // Check the argument types.
14984   for (unsigned i = 0; i != NumParams; i++) {
14985     Expr *Arg;
14986     if (i < Args.size()) {
14987       Arg = Args[i];
14988       ExprResult InputInit =
14989           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14990                                           S.Context, Method->getParamDecl(i)),
14991                                       SourceLocation(), Arg);
14992       IsError |= InputInit.isInvalid();
14993       Arg = InputInit.getAs<Expr>();
14994     } else {
14995       ExprResult DefArg =
14996           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14997       if (DefArg.isInvalid()) {
14998         IsError = true;
14999         break;
15000       }
15001       Arg = DefArg.getAs<Expr>();
15002     }
15003 
15004     MethodArgs.push_back(Arg);
15005   }
15006   return IsError;
15007 }
15008 
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,MultiExprArg ArgExpr)15009 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15010                                                     SourceLocation RLoc,
15011                                                     Expr *Base,
15012                                                     MultiExprArg ArgExpr) {
15013   SmallVector<Expr *, 2> Args;
15014   Args.push_back(Base);
15015   for (auto *e : ArgExpr) {
15016     Args.push_back(e);
15017   }
15018   DeclarationName OpName =
15019       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15020 
15021   SourceRange Range = ArgExpr.empty()
15022                           ? SourceRange{}
15023                           : SourceRange(ArgExpr.front()->getBeginLoc(),
15024                                         ArgExpr.back()->getEndLoc());
15025 
15026   // If either side is type-dependent, create an appropriate dependent
15027   // expression.
15028   if (Expr::hasAnyTypeDependentArguments(Args)) {
15029 
15030     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15031     // CHECKME: no 'operator' keyword?
15032     DeclarationNameInfo OpNameInfo(OpName, LLoc);
15033     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15034     ExprResult Fn = CreateUnresolvedLookupExpr(
15035         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15036     if (Fn.isInvalid())
15037       return ExprError();
15038     // Can't add any actual overloads yet
15039 
15040     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15041                                        Context.DependentTy, VK_PRValue, RLoc,
15042                                        CurFPFeatureOverrides());
15043   }
15044 
15045   // Handle placeholders
15046   UnbridgedCastsSet UnbridgedCasts;
15047   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15048     return ExprError();
15049   }
15050   // Build an empty overload set.
15051   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15052 
15053   // Subscript can only be overloaded as a member function.
15054 
15055   // Add operator candidates that are member functions.
15056   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15057 
15058   // Add builtin operator candidates.
15059   if (Args.size() == 2)
15060     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15061 
15062   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15063 
15064   // Perform overload resolution.
15065   OverloadCandidateSet::iterator Best;
15066   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15067     case OR_Success: {
15068       // We found a built-in operator or an overloaded operator.
15069       FunctionDecl *FnDecl = Best->Function;
15070 
15071       if (FnDecl) {
15072         // We matched an overloaded operator. Build a call to that
15073         // operator.
15074 
15075         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15076 
15077         // Convert the arguments.
15078         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15079         SmallVector<Expr *, 2> MethodArgs;
15080 
15081         // Initialize the object parameter.
15082         if (Method->isExplicitObjectMemberFunction()) {
15083           ExprResult Res =
15084               InitializeExplicitObjectArgument(*this, Args[0], Method);
15085           if (Res.isInvalid())
15086             return ExprError();
15087           Args[0] = Res.get();
15088           ArgExpr = Args;
15089         } else {
15090           ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15091               Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15092           if (Arg0.isInvalid())
15093             return ExprError();
15094 
15095           MethodArgs.push_back(Arg0.get());
15096         }
15097 
15098         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15099             *this, MethodArgs, Method, ArgExpr, LLoc);
15100         if (IsError)
15101           return ExprError();
15102 
15103         // Build the actual expression node.
15104         DeclarationNameInfo OpLocInfo(OpName, LLoc);
15105         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15106         ExprResult FnExpr = CreateFunctionRefExpr(
15107             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15108             OpLocInfo.getLoc(), OpLocInfo.getInfo());
15109         if (FnExpr.isInvalid())
15110           return ExprError();
15111 
15112         // Determine the result type
15113         QualType ResultTy = FnDecl->getReturnType();
15114         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15115         ResultTy = ResultTy.getNonLValueExprType(Context);
15116 
15117         CallExpr *TheCall = CXXOperatorCallExpr::Create(
15118             Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15119             CurFPFeatureOverrides());
15120 
15121         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15122           return ExprError();
15123 
15124         if (CheckFunctionCall(Method, TheCall,
15125                               Method->getType()->castAs<FunctionProtoType>()))
15126           return ExprError();
15127 
15128         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15129                                            FnDecl);
15130       } else {
15131         // We matched a built-in operator. Convert the arguments, then
15132         // break out so that we will build the appropriate built-in
15133         // operator node.
15134         ExprResult ArgsRes0 = PerformImplicitConversion(
15135             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15136             AA_Passing, CCK_ForBuiltinOverloadedOp);
15137         if (ArgsRes0.isInvalid())
15138           return ExprError();
15139         Args[0] = ArgsRes0.get();
15140 
15141         ExprResult ArgsRes1 = PerformImplicitConversion(
15142             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15143             AA_Passing, CCK_ForBuiltinOverloadedOp);
15144         if (ArgsRes1.isInvalid())
15145           return ExprError();
15146         Args[1] = ArgsRes1.get();
15147 
15148         break;
15149       }
15150     }
15151 
15152     case OR_No_Viable_Function: {
15153       PartialDiagnostic PD =
15154           CandidateSet.empty()
15155               ? (PDiag(diag::err_ovl_no_oper)
15156                  << Args[0]->getType() << /*subscript*/ 0
15157                  << Args[0]->getSourceRange() << Range)
15158               : (PDiag(diag::err_ovl_no_viable_subscript)
15159                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15160       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15161                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
15162       return ExprError();
15163     }
15164 
15165     case OR_Ambiguous:
15166       if (Args.size() == 2) {
15167         CandidateSet.NoteCandidates(
15168             PartialDiagnosticAt(
15169                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15170                           << "[]" << Args[0]->getType() << Args[1]->getType()
15171                           << Args[0]->getSourceRange() << Range),
15172             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15173       } else {
15174         CandidateSet.NoteCandidates(
15175             PartialDiagnosticAt(LLoc,
15176                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
15177                                     << Args[0]->getType()
15178                                     << Args[0]->getSourceRange() << Range),
15179             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15180       }
15181       return ExprError();
15182 
15183     case OR_Deleted:
15184       CandidateSet.NoteCandidates(
15185           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
15186                                         << "[]" << Args[0]->getSourceRange()
15187                                         << Range),
15188           *this, OCD_AllCandidates, Args, "[]", LLoc);
15189       return ExprError();
15190     }
15191 
15192   // We matched a built-in operator; build it.
15193   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15194 }
15195 
15196 /// BuildCallToMemberFunction - Build a call to a member
15197 /// function. MemExpr is the expression that refers to the member
15198 /// function (and includes the object parameter), Args/NumArgs are the
15199 /// arguments to the function call (not including the object
15200 /// parameter). The caller needs to validate that the member
15201 /// expression refers to a non-static member function or an overloaded
15202 /// member function.
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig,bool AllowRecovery)15203 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
15204                                            SourceLocation LParenLoc,
15205                                            MultiExprArg Args,
15206                                            SourceLocation RParenLoc,
15207                                            Expr *ExecConfig, bool IsExecConfig,
15208                                            bool AllowRecovery) {
15209   assert(MemExprE->getType() == Context.BoundMemberTy ||
15210          MemExprE->getType() == Context.OverloadTy);
15211 
15212   // Dig out the member expression. This holds both the object
15213   // argument and the member function we're referring to.
15214   Expr *NakedMemExpr = MemExprE->IgnoreParens();
15215 
15216   // Determine whether this is a call to a pointer-to-member function.
15217   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15218     assert(op->getType() == Context.BoundMemberTy);
15219     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15220 
15221     QualType fnType =
15222       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15223 
15224     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15225     QualType resultType = proto->getCallResultType(Context);
15226     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
15227 
15228     // Check that the object type isn't more qualified than the
15229     // member function we're calling.
15230     Qualifiers funcQuals = proto->getMethodQuals();
15231 
15232     QualType objectType = op->getLHS()->getType();
15233     if (op->getOpcode() == BO_PtrMemI)
15234       objectType = objectType->castAs<PointerType>()->getPointeeType();
15235     Qualifiers objectQuals = objectType.getQualifiers();
15236 
15237     Qualifiers difference = objectQuals - funcQuals;
15238     difference.removeObjCGCAttr();
15239     difference.removeAddressSpace();
15240     if (difference) {
15241       std::string qualsString = difference.getAsString();
15242       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15243         << fnType.getUnqualifiedType()
15244         << qualsString
15245         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15246     }
15247 
15248     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
15249         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15250         CurFPFeatureOverrides(), proto->getNumParams());
15251 
15252     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15253                             call, nullptr))
15254       return ExprError();
15255 
15256     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15257       return ExprError();
15258 
15259     if (CheckOtherCall(call, proto))
15260       return ExprError();
15261 
15262     return MaybeBindToTemporary(call);
15263   }
15264 
15265   // We only try to build a recovery expr at this level if we can preserve
15266   // the return type, otherwise we return ExprError() and let the caller
15267   // recover.
15268   auto BuildRecoveryExpr = [&](QualType Type) {
15269     if (!AllowRecovery)
15270       return ExprError();
15271     std::vector<Expr *> SubExprs = {MemExprE};
15272     llvm::append_range(SubExprs, Args);
15273     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15274                               Type);
15275   };
15276   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15277     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15278                             RParenLoc, CurFPFeatureOverrides());
15279 
15280   UnbridgedCastsSet UnbridgedCasts;
15281   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15282     return ExprError();
15283 
15284   MemberExpr *MemExpr;
15285   CXXMethodDecl *Method = nullptr;
15286   bool HadMultipleCandidates = false;
15287   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15288   NestedNameSpecifier *Qualifier = nullptr;
15289   if (isa<MemberExpr>(NakedMemExpr)) {
15290     MemExpr = cast<MemberExpr>(NakedMemExpr);
15291     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15292     FoundDecl = MemExpr->getFoundDecl();
15293     Qualifier = MemExpr->getQualifier();
15294     UnbridgedCasts.restore();
15295   } else {
15296     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15297     Qualifier = UnresExpr->getQualifier();
15298 
15299     QualType ObjectType = UnresExpr->getBaseType();
15300     Expr::Classification ObjectClassification
15301       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
15302                             : UnresExpr->getBase()->Classify(Context);
15303 
15304     // Add overload candidates
15305     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15306                                       OverloadCandidateSet::CSK_Normal);
15307 
15308     // FIXME: avoid copy.
15309     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15310     if (UnresExpr->hasExplicitTemplateArgs()) {
15311       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15312       TemplateArgs = &TemplateArgsBuffer;
15313     }
15314 
15315     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
15316            E = UnresExpr->decls_end(); I != E; ++I) {
15317 
15318       QualType ExplicitObjectType = ObjectType;
15319 
15320       NamedDecl *Func = *I;
15321       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15322       if (isa<UsingShadowDecl>(Func))
15323         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15324 
15325       bool HasExplicitParameter = false;
15326       if (const auto *M = dyn_cast<FunctionDecl>(Func);
15327           M && M->hasCXXExplicitFunctionObjectParameter())
15328         HasExplicitParameter = true;
15329       else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15330                M &&
15331                M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15332         HasExplicitParameter = true;
15333 
15334       if (HasExplicitParameter)
15335         ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15336 
15337       // Microsoft supports direct constructor calls.
15338       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15339         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15340                              CandidateSet,
15341                              /*SuppressUserConversions*/ false);
15342       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15343         // If explicit template arguments were provided, we can't call a
15344         // non-template member function.
15345         if (TemplateArgs)
15346           continue;
15347 
15348         AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15349                            ObjectClassification, Args, CandidateSet,
15350                            /*SuppressUserConversions=*/false);
15351       } else {
15352         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15353                                    I.getPair(), ActingDC, TemplateArgs,
15354                                    ExplicitObjectType, ObjectClassification,
15355                                    Args, CandidateSet,
15356                                    /*SuppressUserConversions=*/false);
15357       }
15358     }
15359 
15360     HadMultipleCandidates = (CandidateSet.size() > 1);
15361 
15362     DeclarationName DeclName = UnresExpr->getMemberName();
15363 
15364     UnbridgedCasts.restore();
15365 
15366     OverloadCandidateSet::iterator Best;
15367     bool Succeeded = false;
15368     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15369                                             Best)) {
15370     case OR_Success:
15371       Method = cast<CXXMethodDecl>(Best->Function);
15372       FoundDecl = Best->FoundDecl;
15373       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15374       if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15375         break;
15376       // If FoundDecl is different from Method (such as if one is a template
15377       // and the other a specialization), make sure DiagnoseUseOfDecl is
15378       // called on both.
15379       // FIXME: This would be more comprehensively addressed by modifying
15380       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15381       // being used.
15382       if (Method != FoundDecl.getDecl() &&
15383           DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15384         break;
15385       Succeeded = true;
15386       break;
15387 
15388     case OR_No_Viable_Function:
15389       CandidateSet.NoteCandidates(
15390           PartialDiagnosticAt(
15391               UnresExpr->getMemberLoc(),
15392               PDiag(diag::err_ovl_no_viable_member_function_in_call)
15393                   << DeclName << MemExprE->getSourceRange()),
15394           *this, OCD_AllCandidates, Args);
15395       break;
15396     case OR_Ambiguous:
15397       CandidateSet.NoteCandidates(
15398           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15399                               PDiag(diag::err_ovl_ambiguous_member_call)
15400                                   << DeclName << MemExprE->getSourceRange()),
15401           *this, OCD_AmbiguousCandidates, Args);
15402       break;
15403     case OR_Deleted:
15404       CandidateSet.NoteCandidates(
15405           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15406                               PDiag(diag::err_ovl_deleted_member_call)
15407                                   << DeclName << MemExprE->getSourceRange()),
15408           *this, OCD_AllCandidates, Args);
15409       break;
15410     }
15411     // Overload resolution fails, try to recover.
15412     if (!Succeeded)
15413       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15414 
15415     ExprResult Res =
15416         FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15417     if (Res.isInvalid())
15418       return ExprError();
15419     MemExprE = Res.get();
15420 
15421     // If overload resolution picked a static member
15422     // build a non-member call based on that function.
15423     if (Method->isStatic()) {
15424       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15425                                    ExecConfig, IsExecConfig);
15426     }
15427 
15428     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15429   }
15430 
15431   QualType ResultType = Method->getReturnType();
15432   ExprValueKind VK = Expr::getValueKindForType(ResultType);
15433   ResultType = ResultType.getNonLValueExprType(Context);
15434 
15435   assert(Method && "Member call to something that isn't a method?");
15436   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15437 
15438   CallExpr *TheCall = nullptr;
15439   llvm::SmallVector<Expr *, 8> NewArgs;
15440   if (Method->isExplicitObjectMemberFunction()) {
15441     PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15442                                   NewArgs);
15443     // Build the actual expression node.
15444     ExprResult FnExpr =
15445         CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15446                               HadMultipleCandidates, MemExpr->getExprLoc());
15447     if (FnExpr.isInvalid())
15448       return ExprError();
15449 
15450     TheCall =
15451         CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15452                          CurFPFeatureOverrides(), Proto->getNumParams());
15453   } else {
15454     // Convert the object argument (for a non-static member function call).
15455     // We only need to do this if there was actually an overload; otherwise
15456     // it was done at lookup.
15457     ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15458         MemExpr->getBase(), Qualifier, FoundDecl, Method);
15459     if (ObjectArg.isInvalid())
15460       return ExprError();
15461     MemExpr->setBase(ObjectArg.get());
15462     TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15463                                         RParenLoc, CurFPFeatureOverrides(),
15464                                         Proto->getNumParams());
15465   }
15466 
15467   // Check for a valid return type.
15468   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15469                           TheCall, Method))
15470     return BuildRecoveryExpr(ResultType);
15471 
15472   // Convert the rest of the arguments
15473   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15474                               RParenLoc))
15475     return BuildRecoveryExpr(ResultType);
15476 
15477   DiagnoseSentinelCalls(Method, LParenLoc, Args);
15478 
15479   if (CheckFunctionCall(Method, TheCall, Proto))
15480     return ExprError();
15481 
15482   // In the case the method to call was not selected by the overloading
15483   // resolution process, we still need to handle the enable_if attribute. Do
15484   // that here, so it will not hide previous -- and more relevant -- errors.
15485   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15486     if (const EnableIfAttr *Attr =
15487             CheckEnableIf(Method, LParenLoc, Args, true)) {
15488       Diag(MemE->getMemberLoc(),
15489            diag::err_ovl_no_viable_member_function_in_call)
15490           << Method << Method->getSourceRange();
15491       Diag(Method->getLocation(),
15492            diag::note_ovl_candidate_disabled_by_function_cond_attr)
15493           << Attr->getCond()->getSourceRange() << Attr->getMessage();
15494       return ExprError();
15495     }
15496   }
15497 
15498   if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15499       TheCall->getDirectCallee()->isPureVirtual()) {
15500     const FunctionDecl *MD = TheCall->getDirectCallee();
15501 
15502     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15503         MemExpr->performsVirtualDispatch(getLangOpts())) {
15504       Diag(MemExpr->getBeginLoc(),
15505            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15506           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15507           << MD->getParent();
15508 
15509       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15510       if (getLangOpts().AppleKext)
15511         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15512             << MD->getParent() << MD->getDeclName();
15513     }
15514   }
15515 
15516   if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15517     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15518     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15519     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15520                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15521                          MemExpr->getMemberLoc());
15522   }
15523 
15524   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15525                                      TheCall->getDirectCallee());
15526 }
15527 
15528 /// BuildCallToObjectOfClassType - Build a call to an object of class
15529 /// type (C++ [over.call.object]), which can end up invoking an
15530 /// overloaded function call operator (@c operator()) or performing a
15531 /// user-defined conversion on the object argument.
15532 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)15533 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
15534                                    SourceLocation LParenLoc,
15535                                    MultiExprArg Args,
15536                                    SourceLocation RParenLoc) {
15537   if (checkPlaceholderForOverload(*this, Obj))
15538     return ExprError();
15539   ExprResult Object = Obj;
15540 
15541   UnbridgedCastsSet UnbridgedCasts;
15542   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15543     return ExprError();
15544 
15545   assert(Object.get()->getType()->isRecordType() &&
15546          "Requires object type argument");
15547 
15548   // C++ [over.call.object]p1:
15549   //  If the primary-expression E in the function call syntax
15550   //  evaluates to a class object of type "cv T", then the set of
15551   //  candidate functions includes at least the function call
15552   //  operators of T. The function call operators of T are obtained by
15553   //  ordinary lookup of the name operator() in the context of
15554   //  (E).operator().
15555   OverloadCandidateSet CandidateSet(LParenLoc,
15556                                     OverloadCandidateSet::CSK_Operator);
15557   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15558 
15559   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15560                           diag::err_incomplete_object_call, Object.get()))
15561     return true;
15562 
15563   const auto *Record = Object.get()->getType()->castAs<RecordType>();
15564   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15565   LookupQualifiedName(R, Record->getDecl());
15566   R.suppressAccessDiagnostics();
15567 
15568   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15569        Oper != OperEnd; ++Oper) {
15570     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15571                        Object.get()->Classify(Context), Args, CandidateSet,
15572                        /*SuppressUserConversion=*/false);
15573   }
15574 
15575   // When calling a lambda, both the call operator, and
15576   // the conversion operator to function pointer
15577   // are considered. But when constraint checking
15578   // on the call operator fails, it will also fail on the
15579   // conversion operator as the constraints are always the same.
15580   // As the user probably does not intend to perform a surrogate call,
15581   // we filter them out to produce better error diagnostics, ie to avoid
15582   // showing 2 failed overloads instead of one.
15583   bool IgnoreSurrogateFunctions = false;
15584   if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15585     const OverloadCandidate &Candidate = *CandidateSet.begin();
15586     if (!Candidate.Viable &&
15587         Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
15588       IgnoreSurrogateFunctions = true;
15589   }
15590 
15591   // C++ [over.call.object]p2:
15592   //   In addition, for each (non-explicit in C++0x) conversion function
15593   //   declared in T of the form
15594   //
15595   //        operator conversion-type-id () cv-qualifier;
15596   //
15597   //   where cv-qualifier is the same cv-qualification as, or a
15598   //   greater cv-qualification than, cv, and where conversion-type-id
15599   //   denotes the type "pointer to function of (P1,...,Pn) returning
15600   //   R", or the type "reference to pointer to function of
15601   //   (P1,...,Pn) returning R", or the type "reference to function
15602   //   of (P1,...,Pn) returning R", a surrogate call function [...]
15603   //   is also considered as a candidate function. Similarly,
15604   //   surrogate call functions are added to the set of candidate
15605   //   functions for each conversion function declared in an
15606   //   accessible base class provided the function is not hidden
15607   //   within T by another intervening declaration.
15608   const auto &Conversions =
15609       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15610   for (auto I = Conversions.begin(), E = Conversions.end();
15611        !IgnoreSurrogateFunctions && I != E; ++I) {
15612     NamedDecl *D = *I;
15613     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15614     if (isa<UsingShadowDecl>(D))
15615       D = cast<UsingShadowDecl>(D)->getTargetDecl();
15616 
15617     // Skip over templated conversion functions; they aren't
15618     // surrogates.
15619     if (isa<FunctionTemplateDecl>(D))
15620       continue;
15621 
15622     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15623     if (!Conv->isExplicit()) {
15624       // Strip the reference type (if any) and then the pointer type (if
15625       // any) to get down to what might be a function type.
15626       QualType ConvType = Conv->getConversionType().getNonReferenceType();
15627       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15628         ConvType = ConvPtrType->getPointeeType();
15629 
15630       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15631       {
15632         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15633                               Object.get(), Args, CandidateSet);
15634       }
15635     }
15636   }
15637 
15638   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15639 
15640   // Perform overload resolution.
15641   OverloadCandidateSet::iterator Best;
15642   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15643                                           Best)) {
15644   case OR_Success:
15645     // Overload resolution succeeded; we'll build the appropriate call
15646     // below.
15647     break;
15648 
15649   case OR_No_Viable_Function: {
15650     PartialDiagnostic PD =
15651         CandidateSet.empty()
15652             ? (PDiag(diag::err_ovl_no_oper)
15653                << Object.get()->getType() << /*call*/ 1
15654                << Object.get()->getSourceRange())
15655             : (PDiag(diag::err_ovl_no_viable_object_call)
15656                << Object.get()->getType() << Object.get()->getSourceRange());
15657     CandidateSet.NoteCandidates(
15658         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15659         OCD_AllCandidates, Args);
15660     break;
15661   }
15662   case OR_Ambiguous:
15663     if (!R.isAmbiguous())
15664       CandidateSet.NoteCandidates(
15665           PartialDiagnosticAt(Object.get()->getBeginLoc(),
15666                               PDiag(diag::err_ovl_ambiguous_object_call)
15667                                   << Object.get()->getType()
15668                                   << Object.get()->getSourceRange()),
15669           *this, OCD_AmbiguousCandidates, Args);
15670     break;
15671 
15672   case OR_Deleted:
15673     CandidateSet.NoteCandidates(
15674         PartialDiagnosticAt(Object.get()->getBeginLoc(),
15675                             PDiag(diag::err_ovl_deleted_object_call)
15676                                 << Object.get()->getType()
15677                                 << Object.get()->getSourceRange()),
15678         *this, OCD_AllCandidates, Args);
15679     break;
15680   }
15681 
15682   if (Best == CandidateSet.end())
15683     return true;
15684 
15685   UnbridgedCasts.restore();
15686 
15687   if (Best->Function == nullptr) {
15688     // Since there is no function declaration, this is one of the
15689     // surrogate candidates. Dig out the conversion function.
15690     CXXConversionDecl *Conv
15691       = cast<CXXConversionDecl>(
15692                          Best->Conversions[0].UserDefined.ConversionFunction);
15693 
15694     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15695                               Best->FoundDecl);
15696     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15697       return ExprError();
15698     assert(Conv == Best->FoundDecl.getDecl() &&
15699              "Found Decl & conversion-to-functionptr should be same, right?!");
15700     // We selected one of the surrogate functions that converts the
15701     // object parameter to a function pointer. Perform the conversion
15702     // on the object argument, then let BuildCallExpr finish the job.
15703 
15704     // Create an implicit member expr to refer to the conversion operator.
15705     // and then call it.
15706     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15707                                              Conv, HadMultipleCandidates);
15708     if (Call.isInvalid())
15709       return ExprError();
15710     // Record usage of conversion in an implicit cast.
15711     Call = ImplicitCastExpr::Create(
15712         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15713         nullptr, VK_PRValue, CurFPFeatureOverrides());
15714 
15715     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15716   }
15717 
15718   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15719 
15720   // We found an overloaded operator(). Build a CXXOperatorCallExpr
15721   // that calls this method, using Object for the implicit object
15722   // parameter and passing along the remaining arguments.
15723   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15724 
15725   // An error diagnostic has already been printed when parsing the declaration.
15726   if (Method->isInvalidDecl())
15727     return ExprError();
15728 
15729   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15730   unsigned NumParams = Proto->getNumParams();
15731 
15732   DeclarationNameInfo OpLocInfo(
15733                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15734   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15735   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15736                                            Obj, HadMultipleCandidates,
15737                                            OpLocInfo.getLoc(),
15738                                            OpLocInfo.getInfo());
15739   if (NewFn.isInvalid())
15740     return true;
15741 
15742   SmallVector<Expr *, 8> MethodArgs;
15743   MethodArgs.reserve(NumParams + 1);
15744 
15745   bool IsError = false;
15746 
15747   // Initialize the object parameter.
15748   llvm::SmallVector<Expr *, 8> NewArgs;
15749   if (Method->isExplicitObjectMemberFunction()) {
15750     // FIXME: we should do that during the definition of the lambda when we can.
15751     DiagnoseInvalidExplicitObjectParameterInLambda(Method);
15752     PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15753   } else {
15754     ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15755         Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15756     if (ObjRes.isInvalid())
15757       IsError = true;
15758     else
15759       Object = ObjRes;
15760     MethodArgs.push_back(Object.get());
15761   }
15762 
15763   IsError |= PrepareArgumentsForCallToObjectOfClassType(
15764       *this, MethodArgs, Method, Args, LParenLoc);
15765 
15766   // If this is a variadic call, handle args passed through "...".
15767   if (Proto->isVariadic()) {
15768     // Promote the arguments (C99 6.5.2.2p7).
15769     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15770       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15771                                                         nullptr);
15772       IsError |= Arg.isInvalid();
15773       MethodArgs.push_back(Arg.get());
15774     }
15775   }
15776 
15777   if (IsError)
15778     return true;
15779 
15780   DiagnoseSentinelCalls(Method, LParenLoc, Args);
15781 
15782   // Once we've built TheCall, all of the expressions are properly owned.
15783   QualType ResultTy = Method->getReturnType();
15784   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15785   ResultTy = ResultTy.getNonLValueExprType(Context);
15786 
15787   CallExpr *TheCall = CXXOperatorCallExpr::Create(
15788       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15789       CurFPFeatureOverrides());
15790 
15791   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15792     return true;
15793 
15794   if (CheckFunctionCall(Method, TheCall, Proto))
15795     return true;
15796 
15797   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15798 }
15799 
15800 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15801 ///  (if one exists), where @c Base is an expression of class type and
15802 /// @c Member is the name of the member we're trying to find.
15803 ExprResult
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc,bool * NoArrowOperatorFound)15804 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
15805                                bool *NoArrowOperatorFound) {
15806   assert(Base->getType()->isRecordType() &&
15807          "left-hand side must have class type");
15808 
15809   if (checkPlaceholderForOverload(*this, Base))
15810     return ExprError();
15811 
15812   SourceLocation Loc = Base->getExprLoc();
15813 
15814   // C++ [over.ref]p1:
15815   //
15816   //   [...] An expression x->m is interpreted as (x.operator->())->m
15817   //   for a class object x of type T if T::operator->() exists and if
15818   //   the operator is selected as the best match function by the
15819   //   overload resolution mechanism (13.3).
15820   DeclarationName OpName =
15821     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15822   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
15823 
15824   if (RequireCompleteType(Loc, Base->getType(),
15825                           diag::err_typecheck_incomplete_tag, Base))
15826     return ExprError();
15827 
15828   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15829   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15830   R.suppressAccessDiagnostics();
15831 
15832   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15833        Oper != OperEnd; ++Oper) {
15834     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15835                        std::nullopt, CandidateSet,
15836                        /*SuppressUserConversion=*/false);
15837   }
15838 
15839   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15840 
15841   // Perform overload resolution.
15842   OverloadCandidateSet::iterator Best;
15843   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15844   case OR_Success:
15845     // Overload resolution succeeded; we'll build the call below.
15846     break;
15847 
15848   case OR_No_Viable_Function: {
15849     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15850     if (CandidateSet.empty()) {
15851       QualType BaseType = Base->getType();
15852       if (NoArrowOperatorFound) {
15853         // Report this specific error to the caller instead of emitting a
15854         // diagnostic, as requested.
15855         *NoArrowOperatorFound = true;
15856         return ExprError();
15857       }
15858       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15859         << BaseType << Base->getSourceRange();
15860       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15861         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15862           << FixItHint::CreateReplacement(OpLoc, ".");
15863       }
15864     } else
15865       Diag(OpLoc, diag::err_ovl_no_viable_oper)
15866         << "operator->" << Base->getSourceRange();
15867     CandidateSet.NoteCandidates(*this, Base, Cands);
15868     return ExprError();
15869   }
15870   case OR_Ambiguous:
15871     if (!R.isAmbiguous())
15872       CandidateSet.NoteCandidates(
15873           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15874                                          << "->" << Base->getType()
15875                                          << Base->getSourceRange()),
15876           *this, OCD_AmbiguousCandidates, Base);
15877     return ExprError();
15878 
15879   case OR_Deleted:
15880     CandidateSet.NoteCandidates(
15881         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15882                                        << "->" << Base->getSourceRange()),
15883         *this, OCD_AllCandidates, Base);
15884     return ExprError();
15885   }
15886 
15887   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15888 
15889   // Convert the object parameter.
15890   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15891 
15892   if (Method->isExplicitObjectMemberFunction()) {
15893     ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
15894     if (R.isInvalid())
15895       return ExprError();
15896     Base = R.get();
15897   } else {
15898     ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
15899         Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15900     if (BaseResult.isInvalid())
15901       return ExprError();
15902     Base = BaseResult.get();
15903   }
15904 
15905   // Build the operator call.
15906   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15907                                             Base, HadMultipleCandidates, OpLoc);
15908   if (FnExpr.isInvalid())
15909     return ExprError();
15910 
15911   QualType ResultTy = Method->getReturnType();
15912   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15913   ResultTy = ResultTy.getNonLValueExprType(Context);
15914 
15915   CallExpr *TheCall =
15916       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15917                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15918 
15919   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15920     return ExprError();
15921 
15922   if (CheckFunctionCall(Method, TheCall,
15923                         Method->getType()->castAs<FunctionProtoType>()))
15924     return ExprError();
15925 
15926   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15927 }
15928 
15929 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15930 /// a literal operator described by the provided lookup results.
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)15931 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15932                                           DeclarationNameInfo &SuffixInfo,
15933                                           ArrayRef<Expr*> Args,
15934                                           SourceLocation LitEndLoc,
15935                                        TemplateArgumentListInfo *TemplateArgs) {
15936   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15937 
15938   OverloadCandidateSet CandidateSet(UDSuffixLoc,
15939                                     OverloadCandidateSet::CSK_Normal);
15940   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15941                                  TemplateArgs);
15942 
15943   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15944 
15945   // Perform overload resolution. This will usually be trivial, but might need
15946   // to perform substitutions for a literal operator template.
15947   OverloadCandidateSet::iterator Best;
15948   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15949   case OR_Success:
15950   case OR_Deleted:
15951     break;
15952 
15953   case OR_No_Viable_Function:
15954     CandidateSet.NoteCandidates(
15955         PartialDiagnosticAt(UDSuffixLoc,
15956                             PDiag(diag::err_ovl_no_viable_function_in_call)
15957                                 << R.getLookupName()),
15958         *this, OCD_AllCandidates, Args);
15959     return ExprError();
15960 
15961   case OR_Ambiguous:
15962     CandidateSet.NoteCandidates(
15963         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15964                                                 << R.getLookupName()),
15965         *this, OCD_AmbiguousCandidates, Args);
15966     return ExprError();
15967   }
15968 
15969   FunctionDecl *FD = Best->Function;
15970   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15971                                         nullptr, HadMultipleCandidates,
15972                                         SuffixInfo.getLoc(),
15973                                         SuffixInfo.getInfo());
15974   if (Fn.isInvalid())
15975     return true;
15976 
15977   // Check the argument types. This should almost always be a no-op, except
15978   // that array-to-pointer decay is applied to string literals.
15979   Expr *ConvArgs[2];
15980   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15981     ExprResult InputInit = PerformCopyInitialization(
15982       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15983       SourceLocation(), Args[ArgIdx]);
15984     if (InputInit.isInvalid())
15985       return true;
15986     ConvArgs[ArgIdx] = InputInit.get();
15987   }
15988 
15989   QualType ResultTy = FD->getReturnType();
15990   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15991   ResultTy = ResultTy.getNonLValueExprType(Context);
15992 
15993   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15994       Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
15995       LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15996 
15997   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15998     return ExprError();
15999 
16000   if (CheckFunctionCall(FD, UDL, nullptr))
16001     return ExprError();
16002 
16003   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16004 }
16005 
16006 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
16007 /// given LookupResult is non-empty, it is assumed to describe a member which
16008 /// will be invoked. Otherwise, the function will be found via argument
16009 /// dependent lookup.
16010 /// CallExpr is set to a valid expression and FRS_Success returned on success,
16011 /// otherwise CallExpr is set to ExprError() and some non-success value
16012 /// is returned.
16013 Sema::ForRangeStatus
BuildForRangeBeginEndCall(SourceLocation Loc,SourceLocation RangeLoc,const DeclarationNameInfo & NameInfo,LookupResult & MemberLookup,OverloadCandidateSet * CandidateSet,Expr * Range,ExprResult * CallExpr)16014 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16015                                 SourceLocation RangeLoc,
16016                                 const DeclarationNameInfo &NameInfo,
16017                                 LookupResult &MemberLookup,
16018                                 OverloadCandidateSet *CandidateSet,
16019                                 Expr *Range, ExprResult *CallExpr) {
16020   Scope *S = nullptr;
16021 
16022   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
16023   if (!MemberLookup.empty()) {
16024     ExprResult MemberRef =
16025         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16026                                  /*IsPtr=*/false, CXXScopeSpec(),
16027                                  /*TemplateKWLoc=*/SourceLocation(),
16028                                  /*FirstQualifierInScope=*/nullptr,
16029                                  MemberLookup,
16030                                  /*TemplateArgs=*/nullptr, S);
16031     if (MemberRef.isInvalid()) {
16032       *CallExpr = ExprError();
16033       return FRS_DiagnosticIssued;
16034     }
16035     *CallExpr =
16036         BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16037     if (CallExpr->isInvalid()) {
16038       *CallExpr = ExprError();
16039       return FRS_DiagnosticIssued;
16040     }
16041   } else {
16042     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16043                                                 NestedNameSpecifierLoc(),
16044                                                 NameInfo, UnresolvedSet<0>());
16045     if (FnR.isInvalid())
16046       return FRS_DiagnosticIssued;
16047     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16048 
16049     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16050                                                     CandidateSet, CallExpr);
16051     if (CandidateSet->empty() || CandidateSetError) {
16052       *CallExpr = ExprError();
16053       return FRS_NoViableFunction;
16054     }
16055     OverloadCandidateSet::iterator Best;
16056     OverloadingResult OverloadResult =
16057         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16058 
16059     if (OverloadResult == OR_No_Viable_Function) {
16060       *CallExpr = ExprError();
16061       return FRS_NoViableFunction;
16062     }
16063     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16064                                          Loc, nullptr, CandidateSet, &Best,
16065                                          OverloadResult,
16066                                          /*AllowTypoCorrection=*/false);
16067     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16068       *CallExpr = ExprError();
16069       return FRS_DiagnosticIssued;
16070     }
16071   }
16072   return FRS_Success;
16073 }
16074 
16075 
16076 /// FixOverloadedFunctionReference - E is an expression that refers to
16077 /// a C++ overloaded function (possibly with some parentheses and
16078 /// perhaps a '&' around it). We have resolved the overloaded function
16079 /// to the function declaration Fn, so patch up the expression E to
16080 /// refer (possibly indirectly) to Fn. Returns the new expr.
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)16081 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16082                                                 FunctionDecl *Fn) {
16083   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16084     ExprResult SubExpr =
16085         FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16086     if (SubExpr.isInvalid())
16087       return ExprError();
16088     if (SubExpr.get() == PE->getSubExpr())
16089       return PE;
16090 
16091     return new (Context)
16092         ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16093   }
16094 
16095   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16096     ExprResult SubExpr =
16097         FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16098     if (SubExpr.isInvalid())
16099       return ExprError();
16100     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16101                                SubExpr.get()->getType()) &&
16102            "Implicit cast type cannot be determined from overload");
16103     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16104     if (SubExpr.get() == ICE->getSubExpr())
16105       return ICE;
16106 
16107     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16108                                     SubExpr.get(), nullptr, ICE->getValueKind(),
16109                                     CurFPFeatureOverrides());
16110   }
16111 
16112   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16113     if (!GSE->isResultDependent()) {
16114       ExprResult SubExpr =
16115           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16116       if (SubExpr.isInvalid())
16117         return ExprError();
16118       if (SubExpr.get() == GSE->getResultExpr())
16119         return GSE;
16120 
16121       // Replace the resulting type information before rebuilding the generic
16122       // selection expression.
16123       ArrayRef<Expr *> A = GSE->getAssocExprs();
16124       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16125       unsigned ResultIdx = GSE->getResultIndex();
16126       AssocExprs[ResultIdx] = SubExpr.get();
16127 
16128       if (GSE->isExprPredicate())
16129         return GenericSelectionExpr::Create(
16130             Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16131             GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16132             GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16133             ResultIdx);
16134       return GenericSelectionExpr::Create(
16135           Context, GSE->getGenericLoc(), GSE->getControllingType(),
16136           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16137           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16138           ResultIdx);
16139     }
16140     // Rather than fall through to the unreachable, return the original generic
16141     // selection expression.
16142     return GSE;
16143   }
16144 
16145   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16146     assert(UnOp->getOpcode() == UO_AddrOf &&
16147            "Can only take the address of an overloaded function");
16148     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16149       if (Method->isStatic()) {
16150         // Do nothing: static member functions aren't any different
16151         // from non-member functions.
16152       } else {
16153         // Fix the subexpression, which really has to be an
16154         // UnresolvedLookupExpr holding an overloaded member function
16155         // or template.
16156         ExprResult SubExpr =
16157             FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16158         if (SubExpr.isInvalid())
16159           return ExprError();
16160         if (SubExpr.get() == UnOp->getSubExpr())
16161           return UnOp;
16162 
16163         if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16164                                                   SubExpr.get(), Method))
16165           return ExprError();
16166 
16167         assert(isa<DeclRefExpr>(SubExpr.get()) &&
16168                "fixed to something other than a decl ref");
16169         assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16170                "fixed to a member ref with no nested name qualifier");
16171 
16172         // We have taken the address of a pointer to member
16173         // function. Perform the computation here so that we get the
16174         // appropriate pointer to member type.
16175         QualType ClassType
16176           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16177         QualType MemPtrType
16178           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16179         // Under the MS ABI, lock down the inheritance model now.
16180         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16181           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16182 
16183         return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16184                                      MemPtrType, VK_PRValue, OK_Ordinary,
16185                                      UnOp->getOperatorLoc(), false,
16186                                      CurFPFeatureOverrides());
16187       }
16188     }
16189     ExprResult SubExpr =
16190         FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16191     if (SubExpr.isInvalid())
16192       return ExprError();
16193     if (SubExpr.get() == UnOp->getSubExpr())
16194       return UnOp;
16195 
16196     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16197                                 SubExpr.get());
16198   }
16199 
16200   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16201     // FIXME: avoid copy.
16202     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16203     if (ULE->hasExplicitTemplateArgs()) {
16204       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16205       TemplateArgs = &TemplateArgsBuffer;
16206     }
16207 
16208     QualType Type = Fn->getType();
16209     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16210 
16211     // FIXME: Duplicated from BuildDeclarationNameExpr.
16212     if (unsigned BID = Fn->getBuiltinID()) {
16213       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16214         Type = Context.BuiltinFnTy;
16215         ValueKind = VK_PRValue;
16216       }
16217     }
16218 
16219     DeclRefExpr *DRE = BuildDeclRefExpr(
16220         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16221         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16222     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16223     return DRE;
16224   }
16225 
16226   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16227     // FIXME: avoid copy.
16228     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16229     if (MemExpr->hasExplicitTemplateArgs()) {
16230       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16231       TemplateArgs = &TemplateArgsBuffer;
16232     }
16233 
16234     Expr *Base;
16235 
16236     // If we're filling in a static method where we used to have an
16237     // implicit member access, rewrite to a simple decl ref.
16238     if (MemExpr->isImplicitAccess()) {
16239       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16240         DeclRefExpr *DRE = BuildDeclRefExpr(
16241             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16242             MemExpr->getQualifierLoc(), Found.getDecl(),
16243             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16244         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16245         return DRE;
16246       } else {
16247         SourceLocation Loc = MemExpr->getMemberLoc();
16248         if (MemExpr->getQualifier())
16249           Loc = MemExpr->getQualifierLoc().getBeginLoc();
16250         Base =
16251             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16252       }
16253     } else
16254       Base = MemExpr->getBase();
16255 
16256     ExprValueKind valueKind;
16257     QualType type;
16258     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16259       valueKind = VK_LValue;
16260       type = Fn->getType();
16261     } else {
16262       valueKind = VK_PRValue;
16263       type = Context.BoundMemberTy;
16264     }
16265 
16266     return BuildMemberExpr(
16267         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16268         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16269         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16270         type, valueKind, OK_Ordinary, TemplateArgs);
16271   }
16272 
16273   llvm_unreachable("Invalid reference to overloaded function");
16274 }
16275 
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)16276 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
16277                                                 DeclAccessPair Found,
16278                                                 FunctionDecl *Fn) {
16279   return FixOverloadedFunctionReference(E.get(), Found, Fn);
16280 }
16281 
shouldEnforceArgLimit(bool PartialOverloading,FunctionDecl * Function)16282 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16283                                   FunctionDecl *Function) {
16284   if (!PartialOverloading || !Function)
16285     return true;
16286   if (Function->isVariadic())
16287     return false;
16288   if (const auto *Proto =
16289           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16290     if (Proto->isTemplateVariadic())
16291       return false;
16292   if (auto *Pattern = Function->getTemplateInstantiationPattern())
16293     if (const auto *Proto =
16294             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16295       if (Proto->isTemplateVariadic())
16296         return false;
16297   return true;
16298 }
16299