xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaOverload.cpp (revision 1dfe63e4f75fa2a8c94aaf4aefaf48d164bc90db)
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 "CheckExprLifetime.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.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/Basic/Diagnostic.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/EnterExpressionEvaluationContext.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Overload.h"
33 #include "clang/Sema/SemaARM.h"
34 #include "clang/Sema/SemaCUDA.h"
35 #include "clang/Sema/SemaObjC.h"
36 #include "clang/Sema/Template.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "llvm/ADT/DenseSet.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/STLForwardCompat.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include <algorithm>
45 #include <cassert>
46 #include <cstddef>
47 #include <cstdlib>
48 #include <optional>
49 
50 using namespace clang;
51 using namespace sema;
52 
53 using AllowedExplicit = Sema::AllowedExplicit;
54 
functionHasPassObjectSizeParams(const FunctionDecl * FD)55 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
56   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57     return P->hasAttr<PassObjectSizeAttr>();
58   });
59 }
60 
61 /// 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 ())62 static ExprResult CreateFunctionRefExpr(
63     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67     return ExprError();
68   // If FoundDecl is different from Fn (such as if one is a template
69   // and the other a specialization), make sure DiagnoseUseOfDecl is
70   // called on both.
71   // FIXME: This would be more comprehensively addressed by modifying
72   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73   // being used.
74   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75     return ExprError();
76   DeclRefExpr *DRE = new (S.Context)
77       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78   if (HadMultipleCandidates)
79     DRE->setHadMultipleCandidates(true);
80 
81   S.MarkDeclRefReferenced(DRE, Base);
82   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84       S.ResolveExceptionSpec(Loc, FPT);
85       DRE->setType(Fn->getType());
86     }
87   }
88   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89                              CK_FunctionToPointerDecay);
90 }
91 
92 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93                                  bool InOverloadResolution,
94                                  StandardConversionSequence &SCS,
95                                  bool CStyle,
96                                  bool AllowObjCWritebackConversion);
97 
98 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
99                                                  QualType &ToType,
100                                                  bool InOverloadResolution,
101                                                  StandardConversionSequence &SCS,
102                                                  bool CStyle);
103 static OverloadingResult
104 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105                         UserDefinedConversionSequence& User,
106                         OverloadCandidateSet& Conversions,
107                         AllowedExplicit AllowExplicit,
108                         bool AllowObjCConversionOnExplicit);
109 
110 static ImplicitConversionSequence::CompareKind
111 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
112                                    const StandardConversionSequence& SCS1,
113                                    const StandardConversionSequence& SCS2);
114 
115 static ImplicitConversionSequence::CompareKind
116 CompareQualificationConversions(Sema &S,
117                                 const StandardConversionSequence& SCS1,
118                                 const StandardConversionSequence& SCS2);
119 
120 static ImplicitConversionSequence::CompareKind
121 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
122                                 const StandardConversionSequence& SCS1,
123                                 const StandardConversionSequence& SCS2);
124 
125 /// GetConversionRank - Retrieve the implicit conversion rank
126 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)127 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
128   static const ImplicitConversionRank Rank[] = {
129       ICR_Exact_Match,
130       ICR_Exact_Match,
131       ICR_Exact_Match,
132       ICR_Exact_Match,
133       ICR_Exact_Match,
134       ICR_Exact_Match,
135       ICR_Promotion,
136       ICR_Promotion,
137       ICR_Promotion,
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_Conversion,
150       ICR_OCL_Scalar_Widening,
151       ICR_Complex_Real_Conversion,
152       ICR_Conversion,
153       ICR_Conversion,
154       ICR_Writeback_Conversion,
155       ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156                        // it was omitted by the patch that added
157                        // ICK_Zero_Event_Conversion
158       ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159                        // it was omitted by the patch that added
160                        // ICK_Zero_Queue_Conversion
161       ICR_C_Conversion,
162       ICR_C_Conversion_Extension,
163       ICR_Conversion,
164       ICR_HLSL_Dimension_Reduction,
165       ICR_Conversion,
166       ICR_HLSL_Scalar_Widening,
167   };
168   static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
169   return Rank[(int)Kind];
170 }
171 
172 ImplicitConversionRank
GetDimensionConversionRank(ImplicitConversionRank Base,ImplicitConversionKind Dimension)173 clang::GetDimensionConversionRank(ImplicitConversionRank Base,
174                                   ImplicitConversionKind Dimension) {
175   ImplicitConversionRank Rank = GetConversionRank(Dimension);
176   if (Rank == ICR_HLSL_Scalar_Widening) {
177     if (Base == ICR_Promotion)
178       return ICR_HLSL_Scalar_Widening_Promotion;
179     if (Base == ICR_Conversion)
180       return ICR_HLSL_Scalar_Widening_Conversion;
181   }
182   if (Rank == ICR_HLSL_Dimension_Reduction) {
183     if (Base == ICR_Promotion)
184       return ICR_HLSL_Dimension_Reduction_Promotion;
185     if (Base == ICR_Conversion)
186       return ICR_HLSL_Dimension_Reduction_Conversion;
187   }
188   return Rank;
189 }
190 
191 /// GetImplicitConversionName - Return the name of this kind of
192 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)193 static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
194   static const char *const Name[] = {
195       "No conversion",
196       "Lvalue-to-rvalue",
197       "Array-to-pointer",
198       "Function-to-pointer",
199       "Function pointer conversion",
200       "Qualification",
201       "Integral promotion",
202       "Floating point promotion",
203       "Complex promotion",
204       "Integral conversion",
205       "Floating conversion",
206       "Complex conversion",
207       "Floating-integral conversion",
208       "Pointer conversion",
209       "Pointer-to-member conversion",
210       "Boolean conversion",
211       "Compatible-types conversion",
212       "Derived-to-base conversion",
213       "Vector conversion",
214       "SVE Vector conversion",
215       "RVV Vector conversion",
216       "Vector splat",
217       "Complex-real conversion",
218       "Block Pointer conversion",
219       "Transparent Union Conversion",
220       "Writeback conversion",
221       "OpenCL Zero Event Conversion",
222       "OpenCL Zero Queue Conversion",
223       "C specific type conversion",
224       "Incompatible pointer conversion",
225       "Fixed point conversion",
226       "HLSL vector truncation",
227       "Non-decaying array conversion",
228       "HLSL vector splat",
229   };
230   static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
231   return Name[Kind];
232 }
233 
234 /// StandardConversionSequence - Set the standard conversion
235 /// sequence to the identity conversion.
setAsIdentityConversion()236 void StandardConversionSequence::setAsIdentityConversion() {
237   First = ICK_Identity;
238   Second = ICK_Identity;
239   Dimension = ICK_Identity;
240   Third = ICK_Identity;
241   DeprecatedStringLiteralToCharPtr = false;
242   QualificationIncludesObjCLifetime = false;
243   ReferenceBinding = false;
244   DirectBinding = false;
245   IsLvalueReference = true;
246   BindsToFunctionLvalue = false;
247   BindsToRvalue = false;
248   BindsImplicitObjectArgumentWithoutRefQualifier = false;
249   ObjCLifetimeConversionBinding = false;
250   FromBracedInitList = false;
251   CopyConstructor = nullptr;
252 }
253 
254 /// getRank - Retrieve the rank of this standard conversion sequence
255 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
256 /// implicit conversions.
getRank() const257 ImplicitConversionRank StandardConversionSequence::getRank() const {
258   ImplicitConversionRank Rank = ICR_Exact_Match;
259   if (GetConversionRank(First) > Rank)
260     Rank = GetConversionRank(First);
261   if (GetConversionRank(Second) > Rank)
262     Rank = GetConversionRank(Second);
263   if (GetDimensionConversionRank(Rank, Dimension) > Rank)
264     Rank = GetDimensionConversionRank(Rank, Dimension);
265   if (GetConversionRank(Third) > Rank)
266     Rank = GetConversionRank(Third);
267   return Rank;
268 }
269 
270 /// isPointerConversionToBool - Determines whether this conversion is
271 /// a conversion of a pointer or pointer-to-member to bool. This is
272 /// used as part of the ranking of standard conversion sequences
273 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const274 bool StandardConversionSequence::isPointerConversionToBool() const {
275   // Note that FromType has not necessarily been transformed by the
276   // array-to-pointer or function-to-pointer implicit conversions, so
277   // check for their presence as well as checking whether FromType is
278   // a pointer.
279   if (getToType(1)->isBooleanType() &&
280       (getFromType()->isPointerType() ||
281        getFromType()->isMemberPointerType() ||
282        getFromType()->isObjCObjectPointerType() ||
283        getFromType()->isBlockPointerType() ||
284        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
285     return true;
286 
287   return false;
288 }
289 
290 /// isPointerConversionToVoidPointer - Determines whether this
291 /// conversion is a conversion of a pointer to a void pointer. This is
292 /// used as part of the ranking of standard conversion sequences (C++
293 /// 13.3.3.2p4).
294 bool
295 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const296 isPointerConversionToVoidPointer(ASTContext& Context) const {
297   QualType FromType = getFromType();
298   QualType ToType = getToType(1);
299 
300   // Note that FromType has not necessarily been transformed by the
301   // array-to-pointer implicit conversion, so check for its presence
302   // and redo the conversion to get a pointer.
303   if (First == ICK_Array_To_Pointer)
304     FromType = Context.getArrayDecayedType(FromType);
305 
306   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
307     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
308       return ToPtrType->getPointeeType()->isVoidType();
309 
310   return false;
311 }
312 
313 /// Skip any implicit casts which could be either part of a narrowing conversion
314 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(ASTContext & Ctx,const Expr * Converted)315 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
316                                              const Expr *Converted) {
317   // We can have cleanups wrapping the converted expression; these need to be
318   // preserved so that destructors run if necessary.
319   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
320     Expr *Inner =
321         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
322     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
323                                     EWC->getObjects());
324   }
325 
326   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
327     switch (ICE->getCastKind()) {
328     case CK_NoOp:
329     case CK_IntegralCast:
330     case CK_IntegralToBoolean:
331     case CK_IntegralToFloating:
332     case CK_BooleanToSignedIntegral:
333     case CK_FloatingToIntegral:
334     case CK_FloatingToBoolean:
335     case CK_FloatingCast:
336       Converted = ICE->getSubExpr();
337       continue;
338 
339     default:
340       return Converted;
341     }
342   }
343 
344   return Converted;
345 }
346 
347 /// Check if this standard conversion sequence represents a narrowing
348 /// conversion, according to C++11 [dcl.init.list]p7.
349 ///
350 /// \param Ctx  The AST context.
351 /// \param Converted  The result of applying this standard conversion sequence.
352 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
353 ///        value of the expression prior to the narrowing conversion.
354 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
355 ///        type of the expression prior to the narrowing conversion.
356 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
357 ///        from floating point types to integral types should be ignored.
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType,bool IgnoreFloatToIntegralConversion) const358 NarrowingKind StandardConversionSequence::getNarrowingKind(
359     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
360     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
361   assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
362          "narrowing check outside C++");
363 
364   // C++11 [dcl.init.list]p7:
365   //   A narrowing conversion is an implicit conversion ...
366   QualType FromType = getToType(0);
367   QualType ToType = getToType(1);
368 
369   // A conversion to an enumeration type is narrowing if the conversion to
370   // the underlying type is narrowing. This only arises for expressions of
371   // the form 'Enum{init}'.
372   if (auto *ET = ToType->getAs<EnumType>())
373     ToType = ET->getDecl()->getIntegerType();
374 
375   switch (Second) {
376   // 'bool' is an integral type; dispatch to the right place to handle it.
377   case ICK_Boolean_Conversion:
378     if (FromType->isRealFloatingType())
379       goto FloatingIntegralConversion;
380     if (FromType->isIntegralOrUnscopedEnumerationType())
381       goto IntegralConversion;
382     // -- from a pointer type or pointer-to-member type to bool, or
383     return NK_Type_Narrowing;
384 
385   // -- from a floating-point type to an integer type, or
386   //
387   // -- from an integer type or unscoped enumeration type to a floating-point
388   //    type, except where the source is a constant expression and the actual
389   //    value after conversion will fit into the target type and will produce
390   //    the original value when converted back to the original type, or
391   case ICK_Floating_Integral:
392   FloatingIntegralConversion:
393     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
394       return NK_Type_Narrowing;
395     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
396                ToType->isRealFloatingType()) {
397       if (IgnoreFloatToIntegralConversion)
398         return NK_Not_Narrowing;
399       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
400       assert(Initializer && "Unknown conversion expression");
401 
402       // If it's value-dependent, we can't tell whether it's narrowing.
403       if (Initializer->isValueDependent())
404         return NK_Dependent_Narrowing;
405 
406       if (std::optional<llvm::APSInt> IntConstantValue =
407               Initializer->getIntegerConstantExpr(Ctx)) {
408         // Convert the integer to the floating type.
409         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
410         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
411                                 llvm::APFloat::rmNearestTiesToEven);
412         // And back.
413         llvm::APSInt ConvertedValue = *IntConstantValue;
414         bool ignored;
415         Result.convertToInteger(ConvertedValue,
416                                 llvm::APFloat::rmTowardZero, &ignored);
417         // If the resulting value is different, this was a narrowing conversion.
418         if (*IntConstantValue != ConvertedValue) {
419           ConstantValue = APValue(*IntConstantValue);
420           ConstantType = Initializer->getType();
421           return NK_Constant_Narrowing;
422         }
423       } else {
424         // Variables are always narrowings.
425         return NK_Variable_Narrowing;
426       }
427     }
428     return NK_Not_Narrowing;
429 
430   // -- from long double to double or float, or from double to float, except
431   //    where the source is a constant expression and the actual value after
432   //    conversion is within the range of values that can be represented (even
433   //    if it cannot be represented exactly), or
434   case ICK_Floating_Conversion:
435     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
436         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
437       // FromType is larger than ToType.
438       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439 
440       // If it's value-dependent, we can't tell whether it's narrowing.
441       if (Initializer->isValueDependent())
442         return NK_Dependent_Narrowing;
443 
444       Expr::EvalResult R;
445       if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
446           Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
447         // Constant!
448         if (Ctx.getLangOpts().C23)
449           ConstantValue = R.Val;
450         assert(ConstantValue.isFloat());
451         llvm::APFloat FloatVal = ConstantValue.getFloat();
452         // Convert the source value into the target type.
453         bool ignored;
454         llvm::APFloat Converted = FloatVal;
455         llvm::APFloat::opStatus ConvertStatus =
456             Converted.convert(Ctx.getFloatTypeSemantics(ToType),
457                               llvm::APFloat::rmNearestTiesToEven, &ignored);
458         Converted.convert(Ctx.getFloatTypeSemantics(FromType),
459                           llvm::APFloat::rmNearestTiesToEven, &ignored);
460         if (Ctx.getLangOpts().C23) {
461           if (FloatVal.isNaN() && Converted.isNaN() &&
462               !FloatVal.isSignaling() && !Converted.isSignaling()) {
463             // Quiet NaNs are considered the same value, regardless of
464             // payloads.
465             return NK_Not_Narrowing;
466           }
467           // For normal values, check exact equality.
468           if (!Converted.bitwiseIsEqual(FloatVal)) {
469             ConstantType = Initializer->getType();
470             return NK_Constant_Narrowing;
471           }
472         } else {
473           // If there was no overflow, the source value is within the range of
474           // values that can be represented.
475           if (ConvertStatus & llvm::APFloat::opOverflow) {
476             ConstantType = Initializer->getType();
477             return NK_Constant_Narrowing;
478           }
479         }
480       } else {
481         return NK_Variable_Narrowing;
482       }
483     }
484     return NK_Not_Narrowing;
485 
486   // -- from an integer type or unscoped enumeration type to an integer type
487   //    that cannot represent all the values of the original type, except where
488   //    (CWG2627) -- the source is a bit-field whose width w is less than that
489   //    of its type (or, for an enumeration type, its underlying type) and the
490   //    target type can represent all the values of a hypothetical extended
491   //    integer type with width w and with the same signedness as the original
492   //    type or
493   //    -- the source is a constant expression and the actual value after
494   //    conversion will fit into the target type and will produce the original
495   //    value when converted back to the original type.
496   case ICK_Integral_Conversion:
497   IntegralConversion: {
498     assert(FromType->isIntegralOrUnscopedEnumerationType());
499     assert(ToType->isIntegralOrUnscopedEnumerationType());
500     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
501     unsigned FromWidth = Ctx.getIntWidth(FromType);
502     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
503     const unsigned ToWidth = Ctx.getIntWidth(ToType);
504 
505     constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
506                                         bool ToSigned, unsigned ToWidth) {
507       return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
508              !(FromSigned && !ToSigned);
509     };
510 
511     if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
512       return NK_Not_Narrowing;
513 
514     // Not all values of FromType can be represented in ToType.
515     const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
516 
517     bool DependentBitField = false;
518     if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
519       if (BitField->getBitWidth()->isValueDependent())
520         DependentBitField = true;
521       else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
522                BitFieldWidth < FromWidth) {
523         if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
524           return NK_Not_Narrowing;
525 
526         // The initializer will be truncated to the bit-field width
527         FromWidth = BitFieldWidth;
528       }
529     }
530 
531     // If it's value-dependent, we can't tell whether it's narrowing.
532     if (Initializer->isValueDependent())
533       return NK_Dependent_Narrowing;
534 
535     std::optional<llvm::APSInt> OptInitializerValue =
536         Initializer->getIntegerConstantExpr(Ctx);
537     if (!OptInitializerValue) {
538       // If the bit-field width was dependent, it might end up being small
539       // enough to fit in the target type (unless the target type is unsigned
540       // and the source type is signed, in which case it will never fit)
541       if (DependentBitField && !(FromSigned && !ToSigned))
542         return NK_Dependent_Narrowing;
543 
544       // Otherwise, such a conversion is always narrowing
545       return NK_Variable_Narrowing;
546     }
547     llvm::APSInt &InitializerValue = *OptInitializerValue;
548     bool Narrowing = false;
549     if (FromWidth < ToWidth) {
550       // Negative -> unsigned is narrowing. Otherwise, more bits is never
551       // narrowing.
552       if (InitializerValue.isSigned() && InitializerValue.isNegative())
553         Narrowing = true;
554     } else {
555       // Add a bit to the InitializerValue so we don't have to worry about
556       // signed vs. unsigned comparisons.
557       InitializerValue =
558           InitializerValue.extend(InitializerValue.getBitWidth() + 1);
559       // Convert the initializer to and from the target width and signed-ness.
560       llvm::APSInt ConvertedValue = InitializerValue;
561       ConvertedValue = ConvertedValue.trunc(ToWidth);
562       ConvertedValue.setIsSigned(ToSigned);
563       ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
564       ConvertedValue.setIsSigned(InitializerValue.isSigned());
565       // If the result is different, this was a narrowing conversion.
566       if (ConvertedValue != InitializerValue)
567         Narrowing = true;
568     }
569     if (Narrowing) {
570       ConstantType = Initializer->getType();
571       ConstantValue = APValue(InitializerValue);
572       return NK_Constant_Narrowing;
573     }
574 
575     return NK_Not_Narrowing;
576   }
577   case ICK_Complex_Real:
578     if (FromType->isComplexType() && !ToType->isComplexType())
579       return NK_Type_Narrowing;
580     return NK_Not_Narrowing;
581 
582   case ICK_Floating_Promotion:
583     if (Ctx.getLangOpts().C23) {
584       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
585       Expr::EvalResult R;
586       if (Initializer->EvaluateAsRValue(R, Ctx)) {
587         ConstantValue = R.Val;
588         assert(ConstantValue.isFloat());
589         llvm::APFloat FloatVal = ConstantValue.getFloat();
590         // C23 6.7.3p6 If the initializer has real type and a signaling NaN
591         // value, the unqualified versions of the type of the initializer and
592         // the corresponding real type of the object declared shall be
593         // compatible.
594         if (FloatVal.isNaN() && FloatVal.isSignaling()) {
595           ConstantType = Initializer->getType();
596           return NK_Constant_Narrowing;
597         }
598       }
599     }
600     return NK_Not_Narrowing;
601   default:
602     // Other kinds of conversions are not narrowings.
603     return NK_Not_Narrowing;
604   }
605 }
606 
607 /// dump - Print this standard conversion sequence to standard
608 /// error. Useful for debugging overloading issues.
dump() const609 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
610   raw_ostream &OS = llvm::errs();
611   bool PrintedSomething = false;
612   if (First != ICK_Identity) {
613     OS << GetImplicitConversionName(First);
614     PrintedSomething = true;
615   }
616 
617   if (Second != ICK_Identity) {
618     if (PrintedSomething) {
619       OS << " -> ";
620     }
621     OS << GetImplicitConversionName(Second);
622 
623     if (CopyConstructor) {
624       OS << " (by copy constructor)";
625     } else if (DirectBinding) {
626       OS << " (direct reference binding)";
627     } else if (ReferenceBinding) {
628       OS << " (reference binding)";
629     }
630     PrintedSomething = true;
631   }
632 
633   if (Third != ICK_Identity) {
634     if (PrintedSomething) {
635       OS << " -> ";
636     }
637     OS << GetImplicitConversionName(Third);
638     PrintedSomething = true;
639   }
640 
641   if (!PrintedSomething) {
642     OS << "No conversions required";
643   }
644 }
645 
646 /// dump - Print this user-defined conversion sequence to standard
647 /// error. Useful for debugging overloading issues.
dump() const648 void UserDefinedConversionSequence::dump() const {
649   raw_ostream &OS = llvm::errs();
650   if (Before.First || Before.Second || Before.Third) {
651     Before.dump();
652     OS << " -> ";
653   }
654   if (ConversionFunction)
655     OS << '\'' << *ConversionFunction << '\'';
656   else
657     OS << "aggregate initialization";
658   if (After.First || After.Second || After.Third) {
659     OS << " -> ";
660     After.dump();
661   }
662 }
663 
664 /// dump - Print this implicit conversion sequence to standard
665 /// error. Useful for debugging overloading issues.
dump() const666 void ImplicitConversionSequence::dump() const {
667   raw_ostream &OS = llvm::errs();
668   if (hasInitializerListContainerType())
669     OS << "Worst list element conversion: ";
670   switch (ConversionKind) {
671   case StandardConversion:
672     OS << "Standard conversion: ";
673     Standard.dump();
674     break;
675   case UserDefinedConversion:
676     OS << "User-defined conversion: ";
677     UserDefined.dump();
678     break;
679   case EllipsisConversion:
680     OS << "Ellipsis conversion";
681     break;
682   case AmbiguousConversion:
683     OS << "Ambiguous conversion";
684     break;
685   case BadConversion:
686     OS << "Bad conversion";
687     break;
688   }
689 
690   OS << "\n";
691 }
692 
construct()693 void AmbiguousConversionSequence::construct() {
694   new (&conversions()) ConversionSet();
695 }
696 
destruct()697 void AmbiguousConversionSequence::destruct() {
698   conversions().~ConversionSet();
699 }
700 
701 void
copyFrom(const AmbiguousConversionSequence & O)702 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
703   FromTypePtr = O.FromTypePtr;
704   ToTypePtr = O.ToTypePtr;
705   new (&conversions()) ConversionSet(O.conversions());
706 }
707 
708 namespace {
709   // Structure used by DeductionFailureInfo to store
710   // template argument information.
711   struct DFIArguments {
712     TemplateArgument FirstArg;
713     TemplateArgument SecondArg;
714   };
715   // Structure used by DeductionFailureInfo to store
716   // template parameter and template argument information.
717   struct DFIParamWithArguments : DFIArguments {
718     TemplateParameter Param;
719   };
720   // Structure used by DeductionFailureInfo to store template argument
721   // information and the index of the problematic call argument.
722   struct DFIDeducedMismatchArgs : DFIArguments {
723     TemplateArgumentList *TemplateArgs;
724     unsigned CallArgIndex;
725   };
726   // Structure used by DeductionFailureInfo to store information about
727   // unsatisfied constraints.
728   struct CNSInfo {
729     TemplateArgumentList *TemplateArgs;
730     ConstraintSatisfaction Satisfaction;
731   };
732 }
733 
734 /// Convert from Sema's representation of template deduction information
735 /// to the form used in overload-candidate information.
736 DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext & Context,TemplateDeductionResult TDK,TemplateDeductionInfo & Info)737 clang::MakeDeductionFailureInfo(ASTContext &Context,
738                                 TemplateDeductionResult TDK,
739                                 TemplateDeductionInfo &Info) {
740   DeductionFailureInfo Result;
741   Result.Result = static_cast<unsigned>(TDK);
742   Result.HasDiagnostic = false;
743   switch (TDK) {
744   case TemplateDeductionResult::Invalid:
745   case TemplateDeductionResult::InstantiationDepth:
746   case TemplateDeductionResult::TooManyArguments:
747   case TemplateDeductionResult::TooFewArguments:
748   case TemplateDeductionResult::MiscellaneousDeductionFailure:
749   case TemplateDeductionResult::CUDATargetMismatch:
750     Result.Data = nullptr;
751     break;
752 
753   case TemplateDeductionResult::Incomplete:
754   case TemplateDeductionResult::InvalidExplicitArguments:
755     Result.Data = Info.Param.getOpaqueValue();
756     break;
757 
758   case TemplateDeductionResult::DeducedMismatch:
759   case TemplateDeductionResult::DeducedMismatchNested: {
760     // FIXME: Should allocate from normal heap so that we can free this later.
761     auto *Saved = new (Context) DFIDeducedMismatchArgs;
762     Saved->FirstArg = Info.FirstArg;
763     Saved->SecondArg = Info.SecondArg;
764     Saved->TemplateArgs = Info.takeSugared();
765     Saved->CallArgIndex = Info.CallArgIndex;
766     Result.Data = Saved;
767     break;
768   }
769 
770   case TemplateDeductionResult::NonDeducedMismatch: {
771     // FIXME: Should allocate from normal heap so that we can free this later.
772     DFIArguments *Saved = new (Context) DFIArguments;
773     Saved->FirstArg = Info.FirstArg;
774     Saved->SecondArg = Info.SecondArg;
775     Result.Data = Saved;
776     break;
777   }
778 
779   case TemplateDeductionResult::IncompletePack:
780     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
781   case TemplateDeductionResult::Inconsistent:
782   case TemplateDeductionResult::Underqualified: {
783     // FIXME: Should allocate from normal heap so that we can free this later.
784     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
785     Saved->Param = Info.Param;
786     Saved->FirstArg = Info.FirstArg;
787     Saved->SecondArg = Info.SecondArg;
788     Result.Data = Saved;
789     break;
790   }
791 
792   case TemplateDeductionResult::SubstitutionFailure:
793     Result.Data = Info.takeSugared();
794     if (Info.hasSFINAEDiagnostic()) {
795       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
796           SourceLocation(), PartialDiagnostic::NullDiagnostic());
797       Info.takeSFINAEDiagnostic(*Diag);
798       Result.HasDiagnostic = true;
799     }
800     break;
801 
802   case TemplateDeductionResult::ConstraintsNotSatisfied: {
803     CNSInfo *Saved = new (Context) CNSInfo;
804     Saved->TemplateArgs = Info.takeSugared();
805     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
806     Result.Data = Saved;
807     break;
808   }
809 
810   case TemplateDeductionResult::Success:
811   case TemplateDeductionResult::NonDependentConversionFailure:
812   case TemplateDeductionResult::AlreadyDiagnosed:
813     llvm_unreachable("not a deduction failure");
814   }
815 
816   return Result;
817 }
818 
Destroy()819 void DeductionFailureInfo::Destroy() {
820   switch (static_cast<TemplateDeductionResult>(Result)) {
821   case TemplateDeductionResult::Success:
822   case TemplateDeductionResult::Invalid:
823   case TemplateDeductionResult::InstantiationDepth:
824   case TemplateDeductionResult::Incomplete:
825   case TemplateDeductionResult::TooManyArguments:
826   case TemplateDeductionResult::TooFewArguments:
827   case TemplateDeductionResult::InvalidExplicitArguments:
828   case TemplateDeductionResult::CUDATargetMismatch:
829   case TemplateDeductionResult::NonDependentConversionFailure:
830     break;
831 
832   case TemplateDeductionResult::IncompletePack:
833   case TemplateDeductionResult::Inconsistent:
834   case TemplateDeductionResult::Underqualified:
835   case TemplateDeductionResult::DeducedMismatch:
836   case TemplateDeductionResult::DeducedMismatchNested:
837   case TemplateDeductionResult::NonDeducedMismatch:
838     // FIXME: Destroy the data?
839     Data = nullptr;
840     break;
841 
842   case TemplateDeductionResult::SubstitutionFailure:
843     // FIXME: Destroy the template argument list?
844     Data = nullptr;
845     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
846       Diag->~PartialDiagnosticAt();
847       HasDiagnostic = false;
848     }
849     break;
850 
851   case TemplateDeductionResult::ConstraintsNotSatisfied:
852     // FIXME: Destroy the template argument list?
853     Data = nullptr;
854     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
855       Diag->~PartialDiagnosticAt();
856       HasDiagnostic = false;
857     }
858     break;
859 
860   // Unhandled
861   case TemplateDeductionResult::MiscellaneousDeductionFailure:
862   case TemplateDeductionResult::AlreadyDiagnosed:
863     break;
864   }
865 }
866 
getSFINAEDiagnostic()867 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
868   if (HasDiagnostic)
869     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
870   return nullptr;
871 }
872 
getTemplateParameter()873 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
874   switch (static_cast<TemplateDeductionResult>(Result)) {
875   case TemplateDeductionResult::Success:
876   case TemplateDeductionResult::Invalid:
877   case TemplateDeductionResult::InstantiationDepth:
878   case TemplateDeductionResult::TooManyArguments:
879   case TemplateDeductionResult::TooFewArguments:
880   case TemplateDeductionResult::SubstitutionFailure:
881   case TemplateDeductionResult::DeducedMismatch:
882   case TemplateDeductionResult::DeducedMismatchNested:
883   case TemplateDeductionResult::NonDeducedMismatch:
884   case TemplateDeductionResult::CUDATargetMismatch:
885   case TemplateDeductionResult::NonDependentConversionFailure:
886   case TemplateDeductionResult::ConstraintsNotSatisfied:
887     return TemplateParameter();
888 
889   case TemplateDeductionResult::Incomplete:
890   case TemplateDeductionResult::InvalidExplicitArguments:
891     return TemplateParameter::getFromOpaqueValue(Data);
892 
893   case TemplateDeductionResult::IncompletePack:
894   case TemplateDeductionResult::Inconsistent:
895   case TemplateDeductionResult::Underqualified:
896     return static_cast<DFIParamWithArguments*>(Data)->Param;
897 
898   // Unhandled
899   case TemplateDeductionResult::MiscellaneousDeductionFailure:
900   case TemplateDeductionResult::AlreadyDiagnosed:
901     break;
902   }
903 
904   return TemplateParameter();
905 }
906 
getTemplateArgumentList()907 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
908   switch (static_cast<TemplateDeductionResult>(Result)) {
909   case TemplateDeductionResult::Success:
910   case TemplateDeductionResult::Invalid:
911   case TemplateDeductionResult::InstantiationDepth:
912   case TemplateDeductionResult::TooManyArguments:
913   case TemplateDeductionResult::TooFewArguments:
914   case TemplateDeductionResult::Incomplete:
915   case TemplateDeductionResult::IncompletePack:
916   case TemplateDeductionResult::InvalidExplicitArguments:
917   case TemplateDeductionResult::Inconsistent:
918   case TemplateDeductionResult::Underqualified:
919   case TemplateDeductionResult::NonDeducedMismatch:
920   case TemplateDeductionResult::CUDATargetMismatch:
921   case TemplateDeductionResult::NonDependentConversionFailure:
922     return nullptr;
923 
924   case TemplateDeductionResult::DeducedMismatch:
925   case TemplateDeductionResult::DeducedMismatchNested:
926     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
927 
928   case TemplateDeductionResult::SubstitutionFailure:
929     return static_cast<TemplateArgumentList*>(Data);
930 
931   case TemplateDeductionResult::ConstraintsNotSatisfied:
932     return static_cast<CNSInfo*>(Data)->TemplateArgs;
933 
934   // Unhandled
935   case TemplateDeductionResult::MiscellaneousDeductionFailure:
936   case TemplateDeductionResult::AlreadyDiagnosed:
937     break;
938   }
939 
940   return nullptr;
941 }
942 
getFirstArg()943 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
944   switch (static_cast<TemplateDeductionResult>(Result)) {
945   case TemplateDeductionResult::Success:
946   case TemplateDeductionResult::Invalid:
947   case TemplateDeductionResult::InstantiationDepth:
948   case TemplateDeductionResult::Incomplete:
949   case TemplateDeductionResult::TooManyArguments:
950   case TemplateDeductionResult::TooFewArguments:
951   case TemplateDeductionResult::InvalidExplicitArguments:
952   case TemplateDeductionResult::SubstitutionFailure:
953   case TemplateDeductionResult::CUDATargetMismatch:
954   case TemplateDeductionResult::NonDependentConversionFailure:
955   case TemplateDeductionResult::ConstraintsNotSatisfied:
956     return nullptr;
957 
958   case TemplateDeductionResult::IncompletePack:
959   case TemplateDeductionResult::Inconsistent:
960   case TemplateDeductionResult::Underqualified:
961   case TemplateDeductionResult::DeducedMismatch:
962   case TemplateDeductionResult::DeducedMismatchNested:
963   case TemplateDeductionResult::NonDeducedMismatch:
964     return &static_cast<DFIArguments*>(Data)->FirstArg;
965 
966   // Unhandled
967   case TemplateDeductionResult::MiscellaneousDeductionFailure:
968   case TemplateDeductionResult::AlreadyDiagnosed:
969     break;
970   }
971 
972   return nullptr;
973 }
974 
getSecondArg()975 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
976   switch (static_cast<TemplateDeductionResult>(Result)) {
977   case TemplateDeductionResult::Success:
978   case TemplateDeductionResult::Invalid:
979   case TemplateDeductionResult::InstantiationDepth:
980   case TemplateDeductionResult::Incomplete:
981   case TemplateDeductionResult::IncompletePack:
982   case TemplateDeductionResult::TooManyArguments:
983   case TemplateDeductionResult::TooFewArguments:
984   case TemplateDeductionResult::InvalidExplicitArguments:
985   case TemplateDeductionResult::SubstitutionFailure:
986   case TemplateDeductionResult::CUDATargetMismatch:
987   case TemplateDeductionResult::NonDependentConversionFailure:
988   case TemplateDeductionResult::ConstraintsNotSatisfied:
989     return nullptr;
990 
991   case TemplateDeductionResult::Inconsistent:
992   case TemplateDeductionResult::Underqualified:
993   case TemplateDeductionResult::DeducedMismatch:
994   case TemplateDeductionResult::DeducedMismatchNested:
995   case TemplateDeductionResult::NonDeducedMismatch:
996     return &static_cast<DFIArguments*>(Data)->SecondArg;
997 
998   // Unhandled
999   case TemplateDeductionResult::MiscellaneousDeductionFailure:
1000   case TemplateDeductionResult::AlreadyDiagnosed:
1001     break;
1002   }
1003 
1004   return nullptr;
1005 }
1006 
getCallArgIndex()1007 UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1008   switch (static_cast<TemplateDeductionResult>(Result)) {
1009   case TemplateDeductionResult::DeducedMismatch:
1010   case TemplateDeductionResult::DeducedMismatchNested:
1011     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1012 
1013   default:
1014     return std::nullopt;
1015   }
1016 }
1017 
FunctionsCorrespond(ASTContext & Ctx,const FunctionDecl * X,const FunctionDecl * Y)1018 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1019                                 const FunctionDecl *Y) {
1020   if (!X || !Y)
1021     return false;
1022   if (X->getNumParams() != Y->getNumParams())
1023     return false;
1024   // FIXME: when do rewritten comparison operators
1025   // with explicit object parameters correspond?
1026   // https://cplusplus.github.io/CWG/issues/2797.html
1027   for (unsigned I = 0; I < X->getNumParams(); ++I)
1028     if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1029                                     Y->getParamDecl(I)->getType()))
1030       return false;
1031   if (auto *FTX = X->getDescribedFunctionTemplate()) {
1032     auto *FTY = Y->getDescribedFunctionTemplate();
1033     if (!FTY)
1034       return false;
1035     if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1036                                          FTY->getTemplateParameters()))
1037       return false;
1038   }
1039   return true;
1040 }
1041 
shouldAddReversedEqEq(Sema & S,SourceLocation OpLoc,Expr * FirstOperand,FunctionDecl * EqFD)1042 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1043                                   Expr *FirstOperand, FunctionDecl *EqFD) {
1044   assert(EqFD->getOverloadedOperator() ==
1045          OverloadedOperatorKind::OO_EqualEqual);
1046   // C++2a [over.match.oper]p4:
1047   // A non-template function or function template F named operator== is a
1048   // rewrite target with first operand o unless a search for the name operator!=
1049   // in the scope S from the instantiation context of the operator expression
1050   // finds a function or function template that would correspond
1051   // ([basic.scope.scope]) to F if its name were operator==, where S is the
1052   // scope of the class type of o if F is a class member, and the namespace
1053   // scope of which F is a member otherwise. A function template specialization
1054   // named operator== is a rewrite target if its function template is a rewrite
1055   // target.
1056   DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1057       OverloadedOperatorKind::OO_ExclaimEqual);
1058   if (isa<CXXMethodDecl>(EqFD)) {
1059     // If F is a class member, search scope is class type of first operand.
1060     QualType RHS = FirstOperand->getType();
1061     auto *RHSRec = RHS->getAs<RecordType>();
1062     if (!RHSRec)
1063       return true;
1064     LookupResult Members(S, NotEqOp, OpLoc,
1065                          Sema::LookupNameKind::LookupMemberName);
1066     S.LookupQualifiedName(Members, RHSRec->getDecl());
1067     Members.suppressAccessDiagnostics();
1068     for (NamedDecl *Op : Members)
1069       if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1070         return false;
1071     return true;
1072   }
1073   // Otherwise the search scope is the namespace scope of which F is a member.
1074   for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1075     auto *NotEqFD = Op->getAsFunction();
1076     if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1077       NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1078     if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1079         declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
1080                            cast<Decl>(Op->getLexicalDeclContext())))
1081       return false;
1082   }
1083   return true;
1084 }
1085 
allowsReversed(OverloadedOperatorKind Op)1086 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1087     OverloadedOperatorKind Op) {
1088   if (!AllowRewrittenCandidates)
1089     return false;
1090   return Op == OO_EqualEqual || Op == OO_Spaceship;
1091 }
1092 
shouldAddReversed(Sema & S,ArrayRef<Expr * > OriginalArgs,FunctionDecl * FD)1093 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1094     Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1095   auto Op = FD->getOverloadedOperator();
1096   if (!allowsReversed(Op))
1097     return false;
1098   if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1099     assert(OriginalArgs.size() == 2);
1100     if (!shouldAddReversedEqEq(
1101             S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1102       return false;
1103   }
1104   // Don't bother adding a reversed candidate that can never be a better
1105   // match than the non-reversed version.
1106   return FD->getNumNonObjectParams() != 2 ||
1107          !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
1108                                            FD->getParamDecl(1)->getType()) ||
1109          FD->hasAttr<EnableIfAttr>();
1110 }
1111 
destroyCandidates()1112 void OverloadCandidateSet::destroyCandidates() {
1113   for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1114     for (auto &C : i->Conversions)
1115       C.~ImplicitConversionSequence();
1116     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1117       i->DeductionFailure.Destroy();
1118   }
1119 }
1120 
clear(CandidateSetKind CSK)1121 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1122   destroyCandidates();
1123   SlabAllocator.Reset();
1124   NumInlineBytesUsed = 0;
1125   Candidates.clear();
1126   Functions.clear();
1127   Kind = CSK;
1128   FirstDeferredCandidate = nullptr;
1129   DeferredCandidatesCount = 0;
1130   HasDeferredTemplateConstructors = false;
1131   ResolutionByPerfectCandidateIsDisabled = false;
1132 }
1133 
1134 namespace {
1135   class UnbridgedCastsSet {
1136     struct Entry {
1137       Expr **Addr;
1138       Expr *Saved;
1139     };
1140     SmallVector<Entry, 2> Entries;
1141 
1142   public:
save(Sema & S,Expr * & E)1143     void save(Sema &S, Expr *&E) {
1144       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1145       Entry entry = { &E, E };
1146       Entries.push_back(entry);
1147       E = S.ObjC().stripARCUnbridgedCast(E);
1148     }
1149 
restore()1150     void restore() {
1151       for (SmallVectorImpl<Entry>::iterator
1152              i = Entries.begin(), e = Entries.end(); i != e; ++i)
1153         *i->Addr = i->Saved;
1154     }
1155   };
1156 }
1157 
1158 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1159 /// preprocessing on the given expression.
1160 ///
1161 /// \param unbridgedCasts a collection to which to add unbridged casts;
1162 ///   without this, they will be immediately diagnosed as errors
1163 ///
1164 /// Return true on unrecoverable error.
1165 static bool
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=nullptr)1166 checkPlaceholderForOverload(Sema &S, Expr *&E,
1167                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
1168   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
1169     // We can't handle overloaded expressions here because overload
1170     // resolution might reasonably tweak them.
1171     if (placeholder->getKind() == BuiltinType::Overload) return false;
1172 
1173     // If the context potentially accepts unbridged ARC casts, strip
1174     // the unbridged cast and add it to the collection for later restoration.
1175     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1176         unbridgedCasts) {
1177       unbridgedCasts->save(S, E);
1178       return false;
1179     }
1180 
1181     // Go ahead and check everything else.
1182     ExprResult result = S.CheckPlaceholderExpr(E);
1183     if (result.isInvalid())
1184       return true;
1185 
1186     E = result.get();
1187     return false;
1188   }
1189 
1190   // Nothing to do.
1191   return false;
1192 }
1193 
1194 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1195 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,MultiExprArg Args,UnbridgedCastsSet & unbridged)1196 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1197                                             UnbridgedCastsSet &unbridged) {
1198   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1199     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1200       return true;
1201 
1202   return false;
1203 }
1204 
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)1205 OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1206                                  const LookupResult &Old, NamedDecl *&Match,
1207                                  bool NewIsUsingDecl) {
1208   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1209          I != E; ++I) {
1210     NamedDecl *OldD = *I;
1211 
1212     bool OldIsUsingDecl = false;
1213     if (isa<UsingShadowDecl>(OldD)) {
1214       OldIsUsingDecl = true;
1215 
1216       // We can always introduce two using declarations into the same
1217       // context, even if they have identical signatures.
1218       if (NewIsUsingDecl) continue;
1219 
1220       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1221     }
1222 
1223     // A using-declaration does not conflict with another declaration
1224     // if one of them is hidden.
1225     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1226       continue;
1227 
1228     // If either declaration was introduced by a using declaration,
1229     // we'll need to use slightly different rules for matching.
1230     // Essentially, these rules are the normal rules, except that
1231     // function templates hide function templates with different
1232     // return types or template parameter lists.
1233     bool UseMemberUsingDeclRules =
1234       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1235       !New->getFriendObjectKind();
1236 
1237     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1238       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1239         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1240           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1241           continue;
1242         }
1243 
1244         if (!isa<FunctionTemplateDecl>(OldD) &&
1245             !shouldLinkPossiblyHiddenDecl(*I, New))
1246           continue;
1247 
1248         Match = *I;
1249         return OverloadKind::Match;
1250       }
1251 
1252       // Builtins that have custom typechecking or have a reference should
1253       // not be overloadable or redeclarable.
1254       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1255         Match = *I;
1256         return OverloadKind::NonFunction;
1257       }
1258     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1259       // We can overload with these, which can show up when doing
1260       // redeclaration checks for UsingDecls.
1261       assert(Old.getLookupKind() == LookupUsingDeclName);
1262     } else if (isa<TagDecl>(OldD)) {
1263       // We can always overload with tags by hiding them.
1264     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1265       // Optimistically assume that an unresolved using decl will
1266       // overload; if it doesn't, we'll have to diagnose during
1267       // template instantiation.
1268       //
1269       // Exception: if the scope is dependent and this is not a class
1270       // member, the using declaration can only introduce an enumerator.
1271       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1272         Match = *I;
1273         return OverloadKind::NonFunction;
1274       }
1275     } else {
1276       // (C++ 13p1):
1277       //   Only function declarations can be overloaded; object and type
1278       //   declarations cannot be overloaded.
1279       Match = *I;
1280       return OverloadKind::NonFunction;
1281     }
1282   }
1283 
1284   // C++ [temp.friend]p1:
1285   //   For a friend function declaration that is not a template declaration:
1286   //    -- if the name of the friend is a qualified or unqualified template-id,
1287   //       [...], otherwise
1288   //    -- if the name of the friend is a qualified-id and a matching
1289   //       non-template function is found in the specified class or namespace,
1290   //       the friend declaration refers to that function, otherwise,
1291   //    -- if the name of the friend is a qualified-id and a matching function
1292   //       template is found in the specified class or namespace, the friend
1293   //       declaration refers to the deduced specialization of that function
1294   //       template, otherwise
1295   //    -- the name shall be an unqualified-id [...]
1296   // If we get here for a qualified friend declaration, we've just reached the
1297   // third bullet. If the type of the friend is dependent, skip this lookup
1298   // until instantiation.
1299   if (New->getFriendObjectKind() && New->getQualifier() &&
1300       !New->getDescribedFunctionTemplate() &&
1301       !New->getDependentSpecializationInfo() &&
1302       !New->getType()->isDependentType()) {
1303     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1304     TemplateSpecResult.addAllDecls(Old);
1305     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1306                                             /*QualifiedFriend*/true)) {
1307       New->setInvalidDecl();
1308       return OverloadKind::Overload;
1309     }
1310 
1311     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1312     return OverloadKind::Match;
1313   }
1314 
1315   return OverloadKind::Overload;
1316 }
1317 
hasExplicitAttr(const FunctionDecl * D)1318 template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1319   assert(D && "function decl should not be null");
1320   if (auto *A = D->getAttr<AttrT>())
1321     return !A->isImplicit();
1322   return false;
1323 }
1324 
IsOverloadOrOverrideImpl(Sema & SemaRef,FunctionDecl * New,FunctionDecl * Old,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs,bool UseOverrideRules=false)1325 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1326                                      FunctionDecl *Old,
1327                                      bool UseMemberUsingDeclRules,
1328                                      bool ConsiderCudaAttrs,
1329                                      bool UseOverrideRules = false) {
1330   // C++ [basic.start.main]p2: This function shall not be overloaded.
1331   if (New->isMain())
1332     return false;
1333 
1334   // MSVCRT user defined entry points cannot be overloaded.
1335   if (New->isMSVCRTEntryPoint())
1336     return false;
1337 
1338   NamedDecl *OldDecl = Old;
1339   NamedDecl *NewDecl = New;
1340   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1341   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1342 
1343   // C++ [temp.fct]p2:
1344   //   A function template can be overloaded with other function templates
1345   //   and with normal (non-template) functions.
1346   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1347     return true;
1348 
1349   // Is the function New an overload of the function Old?
1350   QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1351   QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1352 
1353   // Compare the signatures (C++ 1.3.10) of the two functions to
1354   // determine whether they are overloads. If we find any mismatch
1355   // in the signature, they are overloads.
1356 
1357   // If either of these functions is a K&R-style function (no
1358   // prototype), then we consider them to have matching signatures.
1359   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1360       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1361     return false;
1362 
1363   const auto *OldType = cast<FunctionProtoType>(OldQType);
1364   const auto *NewType = cast<FunctionProtoType>(NewQType);
1365 
1366   // The signature of a function includes the types of its
1367   // parameters (C++ 1.3.10), which includes the presence or absence
1368   // of the ellipsis; see C++ DR 357).
1369   if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1370     return true;
1371 
1372   // For member-like friends, the enclosing class is part of the signature.
1373   if ((New->isMemberLikeConstrainedFriend() ||
1374        Old->isMemberLikeConstrainedFriend()) &&
1375       !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1376     return true;
1377 
1378   // Compare the parameter lists.
1379   // This can only be done once we have establish that friend functions
1380   // inhabit the same context, otherwise we might tried to instantiate
1381   // references to non-instantiated entities during constraint substitution.
1382   // GH78101.
1383   if (NewTemplate) {
1384     OldDecl = OldTemplate;
1385     NewDecl = NewTemplate;
1386     // C++ [temp.over.link]p4:
1387     //   The signature of a function template consists of its function
1388     //   signature, its return type and its template parameter list. The names
1389     //   of the template parameters are significant only for establishing the
1390     //   relationship between the template parameters and the rest of the
1391     //   signature.
1392     //
1393     // We check the return type and template parameter lists for function
1394     // templates first; the remaining checks follow.
1395     bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1396         NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1397         OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1398     bool SameReturnType = SemaRef.Context.hasSameType(
1399         Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1400     // FIXME(GH58571): Match template parameter list even for non-constrained
1401     // template heads. This currently ensures that the code prior to C++20 is
1402     // not newly broken.
1403     bool ConstraintsInTemplateHead =
1404         NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1405         OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1406     // C++ [namespace.udecl]p11:
1407     //   The set of declarations named by a using-declarator that inhabits a
1408     //   class C does not include member functions and member function
1409     //   templates of a base class that "correspond" to (and thus would
1410     //   conflict with) a declaration of a function or function template in
1411     //   C.
1412     // Comparing return types is not required for the "correspond" check to
1413     // decide whether a member introduced by a shadow declaration is hidden.
1414     if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1415         !SameTemplateParameterList)
1416       return true;
1417     if (!UseMemberUsingDeclRules &&
1418         (!SameTemplateParameterList || !SameReturnType))
1419       return true;
1420   }
1421 
1422   const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1423   const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1424 
1425   int OldParamsOffset = 0;
1426   int NewParamsOffset = 0;
1427 
1428   // When determining if a method is an overload from a base class, act as if
1429   // the implicit object parameter are of the same type.
1430 
1431   auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1432     if (M->isExplicitObjectMemberFunction()) {
1433       auto ThisType = M->getFunctionObjectParameterReferenceType();
1434       if (ThisType.isConstQualified())
1435         Q.removeConst();
1436       return Q;
1437     }
1438 
1439     // We do not allow overloading based off of '__restrict'.
1440     Q.removeRestrict();
1441 
1442     // We may not have applied the implicit const for a constexpr member
1443     // function yet (because we haven't yet resolved whether this is a static
1444     // or non-static member function). Add it now, on the assumption that this
1445     // is a redeclaration of OldMethod.
1446     if (!SemaRef.getLangOpts().CPlusPlus14 &&
1447         (M->isConstexpr() || M->isConsteval()) &&
1448         !isa<CXXConstructorDecl>(NewMethod))
1449       Q.addConst();
1450     return Q;
1451   };
1452 
1453   auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1454     BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1455     DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1456 
1457     if (OldMethod->isExplicitObjectMemberFunction()) {
1458       BS.Quals.removeVolatile();
1459       DS.Quals.removeVolatile();
1460     }
1461 
1462     return BS.Quals == DS.Quals;
1463   };
1464 
1465   auto CompareType = [&](QualType Base, QualType D) {
1466     auto BS = Base.getNonReferenceType().getCanonicalType().split();
1467     auto DS = D.getNonReferenceType().getCanonicalType().split();
1468 
1469     if (!AreQualifiersEqual(BS, DS))
1470       return false;
1471 
1472     if (OldMethod->isImplicitObjectMemberFunction() &&
1473         OldMethod->getParent() != NewMethod->getParent()) {
1474       QualType ParentType =
1475           SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1476               .getCanonicalType();
1477       if (ParentType.getTypePtr() != BS.Ty)
1478         return false;
1479       BS.Ty = DS.Ty;
1480     }
1481 
1482     // FIXME: should we ignore some type attributes here?
1483     if (BS.Ty != DS.Ty)
1484       return false;
1485 
1486     if (Base->isLValueReferenceType())
1487       return D->isLValueReferenceType();
1488     return Base->isRValueReferenceType() == D->isRValueReferenceType();
1489   };
1490 
1491   // If the function is a class member, its signature includes the
1492   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1493   auto DiagnoseInconsistentRefQualifiers = [&]() {
1494     if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1495       return false;
1496     if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1497       return false;
1498     if (OldMethod->isExplicitObjectMemberFunction() ||
1499         NewMethod->isExplicitObjectMemberFunction())
1500       return false;
1501     if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1502                                      NewMethod->getRefQualifier() == RQ_None)) {
1503       SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1504           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1505       SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1506       return true;
1507     }
1508     return false;
1509   };
1510 
1511   if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1512     OldParamsOffset++;
1513   if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1514     NewParamsOffset++;
1515 
1516   if (OldType->getNumParams() - OldParamsOffset !=
1517           NewType->getNumParams() - NewParamsOffset ||
1518       !SemaRef.FunctionParamTypesAreEqual(
1519           {OldType->param_type_begin() + OldParamsOffset,
1520            OldType->param_type_end()},
1521           {NewType->param_type_begin() + NewParamsOffset,
1522            NewType->param_type_end()},
1523           nullptr)) {
1524     return true;
1525   }
1526 
1527   if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1528       !NewMethod->isStatic()) {
1529     bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1530                                                  const CXXMethodDecl *New) {
1531       auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1532       auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1533 
1534       auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1535         return F->getRefQualifier() == RQ_None &&
1536                !F->isExplicitObjectMemberFunction();
1537       };
1538 
1539       if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1540           CompareType(OldObjectType.getNonReferenceType(),
1541                       NewObjectType.getNonReferenceType()))
1542         return true;
1543       return CompareType(OldObjectType, NewObjectType);
1544     }(OldMethod, NewMethod);
1545 
1546     if (!HaveCorrespondingObjectParameters) {
1547       if (DiagnoseInconsistentRefQualifiers())
1548         return true;
1549       // CWG2554
1550       // and, if at least one is an explicit object member function, ignoring
1551       // object parameters
1552       if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1553                                 !OldMethod->isExplicitObjectMemberFunction()))
1554         return true;
1555     }
1556   }
1557 
1558   if (!UseOverrideRules &&
1559       New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1560     AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1561                          OldRC = Old->getTrailingRequiresClause();
1562     if (!NewRC != !OldRC)
1563       return true;
1564     if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1565       return true;
1566     if (NewRC &&
1567         !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1568                                                NewDecl, NewRC.ConstraintExpr))
1569       return true;
1570   }
1571 
1572   if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1573       NewMethod->isImplicitObjectMemberFunction()) {
1574     if (DiagnoseInconsistentRefQualifiers())
1575       return true;
1576   }
1577 
1578   // Though pass_object_size is placed on parameters and takes an argument, we
1579   // consider it to be a function-level modifier for the sake of function
1580   // identity. Either the function has one or more parameters with
1581   // pass_object_size or it doesn't.
1582   if (functionHasPassObjectSizeParams(New) !=
1583       functionHasPassObjectSizeParams(Old))
1584     return true;
1585 
1586   // enable_if attributes are an order-sensitive part of the signature.
1587   for (specific_attr_iterator<EnableIfAttr>
1588          NewI = New->specific_attr_begin<EnableIfAttr>(),
1589          NewE = New->specific_attr_end<EnableIfAttr>(),
1590          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1591          OldE = Old->specific_attr_end<EnableIfAttr>();
1592        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1593     if (NewI == NewE || OldI == OldE)
1594       return true;
1595     llvm::FoldingSetNodeID NewID, OldID;
1596     NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1597     OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1598     if (NewID != OldID)
1599       return true;
1600   }
1601 
1602   // At this point, it is known that the two functions have the same signature.
1603   if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1604     // Don't allow overloading of destructors.  (In theory we could, but it
1605     // would be a giant change to clang.)
1606     if (!isa<CXXDestructorDecl>(New)) {
1607       CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1608                          OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1609       if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1610         assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1611                "Unexpected invalid target.");
1612 
1613         // Allow overloading of functions with same signature and different CUDA
1614         // target attributes.
1615         if (NewTarget != OldTarget) {
1616           // Special case: non-constexpr function is allowed to override
1617           // constexpr virtual function
1618           if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1619               OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1620               !hasExplicitAttr<CUDAHostAttr>(Old) &&
1621               !hasExplicitAttr<CUDADeviceAttr>(Old) &&
1622               !hasExplicitAttr<CUDAHostAttr>(New) &&
1623               !hasExplicitAttr<CUDADeviceAttr>(New)) {
1624             return false;
1625           }
1626           return true;
1627         }
1628       }
1629     }
1630   }
1631 
1632   // The signatures match; this is not an overload.
1633   return false;
1634 }
1635 
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs)1636 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1637                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1638   return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1639                                   ConsiderCudaAttrs);
1640 }
1641 
IsOverride(FunctionDecl * MD,FunctionDecl * BaseMD,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs)1642 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1643                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1644   return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1645                                   /*UseMemberUsingDeclRules=*/false,
1646                                   /*ConsiderCudaAttrs=*/true,
1647                                   /*UseOverrideRules=*/true);
1648 }
1649 
1650 /// Tries a user-defined conversion from From to ToType.
1651 ///
1652 /// Produces an implicit conversion sequence for when a standard conversion
1653 /// is not an option. See TryImplicitConversion for more information.
1654 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1655 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1656                          bool SuppressUserConversions,
1657                          AllowedExplicit AllowExplicit,
1658                          bool InOverloadResolution,
1659                          bool CStyle,
1660                          bool AllowObjCWritebackConversion,
1661                          bool AllowObjCConversionOnExplicit) {
1662   ImplicitConversionSequence ICS;
1663 
1664   if (SuppressUserConversions) {
1665     // We're not in the case above, so there is no conversion that
1666     // we can perform.
1667     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1668     return ICS;
1669   }
1670 
1671   // Attempt user-defined conversion.
1672   OverloadCandidateSet Conversions(From->getExprLoc(),
1673                                    OverloadCandidateSet::CSK_Normal);
1674   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1675                                   Conversions, AllowExplicit,
1676                                   AllowObjCConversionOnExplicit)) {
1677   case OR_Success:
1678   case OR_Deleted:
1679     ICS.setUserDefined();
1680     // C++ [over.ics.user]p4:
1681     //   A conversion of an expression of class type to the same class
1682     //   type is given Exact Match rank, and a conversion of an
1683     //   expression of class type to a base class of that type is
1684     //   given Conversion rank, in spite of the fact that a copy
1685     //   constructor (i.e., a user-defined conversion function) is
1686     //   called for those cases.
1687     if (CXXConstructorDecl *Constructor
1688           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1689       QualType FromType;
1690       SourceLocation FromLoc;
1691       // C++11 [over.ics.list]p6, per DR2137:
1692       // C++17 [over.ics.list]p6:
1693       //   If C is not an initializer-list constructor and the initializer list
1694       //   has a single element of type cv U, where U is X or a class derived
1695       //   from X, the implicit conversion sequence has Exact Match rank if U is
1696       //   X, or Conversion rank if U is derived from X.
1697       bool FromListInit = false;
1698       if (const auto *InitList = dyn_cast<InitListExpr>(From);
1699           InitList && InitList->getNumInits() == 1 &&
1700           !S.isInitListConstructor(Constructor)) {
1701         const Expr *SingleInit = InitList->getInit(0);
1702         FromType = SingleInit->getType();
1703         FromLoc = SingleInit->getBeginLoc();
1704         FromListInit = true;
1705       } else {
1706         FromType = From->getType();
1707         FromLoc = From->getBeginLoc();
1708       }
1709       QualType FromCanon =
1710           S.Context.getCanonicalType(FromType.getUnqualifiedType());
1711       QualType ToCanon
1712         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1713       if ((FromCanon == ToCanon ||
1714            S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1715         // Turn this into a "standard" conversion sequence, so that it
1716         // gets ranked with standard conversion sequences.
1717         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1718         ICS.setStandard();
1719         ICS.Standard.setAsIdentityConversion();
1720         ICS.Standard.setFromType(FromType);
1721         ICS.Standard.setAllToTypes(ToType);
1722         ICS.Standard.FromBracedInitList = FromListInit;
1723         ICS.Standard.CopyConstructor = Constructor;
1724         ICS.Standard.FoundCopyConstructor = Found;
1725         if (ToCanon != FromCanon)
1726           ICS.Standard.Second = ICK_Derived_To_Base;
1727       }
1728     }
1729     break;
1730 
1731   case OR_Ambiguous:
1732     ICS.setAmbiguous();
1733     ICS.Ambiguous.setFromType(From->getType());
1734     ICS.Ambiguous.setToType(ToType);
1735     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1736          Cand != Conversions.end(); ++Cand)
1737       if (Cand->Best)
1738         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1739     break;
1740 
1741     // Fall through.
1742   case OR_No_Viable_Function:
1743     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1744     break;
1745   }
1746 
1747   return ICS;
1748 }
1749 
1750 /// TryImplicitConversion - Attempt to perform an implicit conversion
1751 /// from the given expression (Expr) to the given type (ToType). This
1752 /// function returns an implicit conversion sequence that can be used
1753 /// to perform the initialization. Given
1754 ///
1755 ///   void f(float f);
1756 ///   void g(int i) { f(i); }
1757 ///
1758 /// this routine would produce an implicit conversion sequence to
1759 /// describe the initialization of f from i, which will be a standard
1760 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1761 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1762 //
1763 /// Note that this routine only determines how the conversion can be
1764 /// performed; it does not actually perform the conversion. As such,
1765 /// it will not produce any diagnostics if no conversion is available,
1766 /// but will instead return an implicit conversion sequence of kind
1767 /// "BadConversion".
1768 ///
1769 /// If @p SuppressUserConversions, then user-defined conversions are
1770 /// not permitted.
1771 /// If @p AllowExplicit, then explicit user-defined conversions are
1772 /// permitted.
1773 ///
1774 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1775 /// writeback conversion, which allows __autoreleasing id* parameters to
1776 /// be initialized with __strong id* or __weak id* arguments.
1777 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1778 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1779                       bool SuppressUserConversions,
1780                       AllowedExplicit AllowExplicit,
1781                       bool InOverloadResolution,
1782                       bool CStyle,
1783                       bool AllowObjCWritebackConversion,
1784                       bool AllowObjCConversionOnExplicit) {
1785   ImplicitConversionSequence ICS;
1786   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1787                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1788     ICS.setStandard();
1789     return ICS;
1790   }
1791 
1792   if (!S.getLangOpts().CPlusPlus) {
1793     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1794     return ICS;
1795   }
1796 
1797   // C++ [over.ics.user]p4:
1798   //   A conversion of an expression of class type to the same class
1799   //   type is given Exact Match rank, and a conversion of an
1800   //   expression of class type to a base class of that type is
1801   //   given Conversion rank, in spite of the fact that a copy/move
1802   //   constructor (i.e., a user-defined conversion function) is
1803   //   called for those cases.
1804   QualType FromType = From->getType();
1805   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1806       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1807        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1808     ICS.setStandard();
1809     ICS.Standard.setAsIdentityConversion();
1810     ICS.Standard.setFromType(FromType);
1811     ICS.Standard.setAllToTypes(ToType);
1812 
1813     // We don't actually check at this point whether there is a valid
1814     // copy/move constructor, since overloading just assumes that it
1815     // exists. When we actually perform initialization, we'll find the
1816     // appropriate constructor to copy the returned object, if needed.
1817     ICS.Standard.CopyConstructor = nullptr;
1818 
1819     // Determine whether this is considered a derived-to-base conversion.
1820     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1821       ICS.Standard.Second = ICK_Derived_To_Base;
1822 
1823     return ICS;
1824   }
1825 
1826   if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1827       FromType->isHLSLAttributedResourceType()) {
1828     auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1829     auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1830     if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1831                                          FromResType->getWrappedType()) &&
1832         S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1833                                          FromResType->getContainedType()) &&
1834         ToResType->getAttrs() == FromResType->getAttrs()) {
1835       ICS.setStandard();
1836       ICS.Standard.setAsIdentityConversion();
1837       ICS.Standard.setFromType(FromType);
1838       ICS.Standard.setAllToTypes(ToType);
1839       return ICS;
1840     }
1841   }
1842 
1843   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1844                                   AllowExplicit, InOverloadResolution, CStyle,
1845                                   AllowObjCWritebackConversion,
1846                                   AllowObjCConversionOnExplicit);
1847 }
1848 
1849 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,AllowedExplicit AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1850 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1851                             bool SuppressUserConversions,
1852                             AllowedExplicit AllowExplicit,
1853                             bool InOverloadResolution,
1854                             bool CStyle,
1855                             bool AllowObjCWritebackConversion) {
1856   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1857                                  AllowExplicit, InOverloadResolution, CStyle,
1858                                  AllowObjCWritebackConversion,
1859                                  /*AllowObjCConversionOnExplicit=*/false);
1860 }
1861 
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1862 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1863                                            AssignmentAction Action,
1864                                            bool AllowExplicit) {
1865   if (checkPlaceholderForOverload(*this, From))
1866     return ExprError();
1867 
1868   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1869   bool AllowObjCWritebackConversion =
1870       getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1871                                          Action == AssignmentAction::Sending);
1872   if (getLangOpts().ObjC)
1873     ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1874                                              From->getType(), From);
1875   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1876       *this, From, ToType,
1877       /*SuppressUserConversions=*/false,
1878       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1879       /*InOverloadResolution=*/false,
1880       /*CStyle=*/false, AllowObjCWritebackConversion,
1881       /*AllowObjCConversionOnExplicit=*/false);
1882   return PerformImplicitConversion(From, ToType, ICS, Action);
1883 }
1884 
TryFunctionConversion(QualType FromType,QualType ToType,QualType & ResultTy) const1885 bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1886                                  QualType &ResultTy) const {
1887   bool Changed = IsFunctionConversion(FromType, ToType);
1888   if (Changed)
1889     ResultTy = ToType;
1890   return Changed;
1891 }
1892 
IsFunctionConversion(QualType FromType,QualType ToType,bool * DiscardingCFIUncheckedCallee,bool * AddingCFIUncheckedCallee) const1893 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1894                                 bool *DiscardingCFIUncheckedCallee,
1895                                 bool *AddingCFIUncheckedCallee) const {
1896   if (DiscardingCFIUncheckedCallee)
1897     *DiscardingCFIUncheckedCallee = false;
1898   if (AddingCFIUncheckedCallee)
1899     *AddingCFIUncheckedCallee = false;
1900 
1901   if (Context.hasSameUnqualifiedType(FromType, ToType))
1902     return false;
1903 
1904   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1905   //                    or F(t noexcept) -> F(t)
1906   // where F adds one of the following at most once:
1907   //   - a pointer
1908   //   - a member pointer
1909   //   - a block pointer
1910   // Changes here need matching changes in FindCompositePointerType.
1911   CanQualType CanTo = Context.getCanonicalType(ToType);
1912   CanQualType CanFrom = Context.getCanonicalType(FromType);
1913   Type::TypeClass TyClass = CanTo->getTypeClass();
1914   if (TyClass != CanFrom->getTypeClass()) return false;
1915   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1916     if (TyClass == Type::Pointer) {
1917       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1918       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1919     } else if (TyClass == Type::BlockPointer) {
1920       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1921       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1922     } else if (TyClass == Type::MemberPointer) {
1923       auto ToMPT = CanTo.castAs<MemberPointerType>();
1924       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1925       // A function pointer conversion cannot change the class of the function.
1926       if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1927                               FromMPT->getMostRecentCXXRecordDecl()))
1928         return false;
1929       CanTo = ToMPT->getPointeeType();
1930       CanFrom = FromMPT->getPointeeType();
1931     } else {
1932       return false;
1933     }
1934 
1935     TyClass = CanTo->getTypeClass();
1936     if (TyClass != CanFrom->getTypeClass()) return false;
1937     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1938       return false;
1939   }
1940 
1941   const auto *FromFn = cast<FunctionType>(CanFrom);
1942   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1943 
1944   const auto *ToFn = cast<FunctionType>(CanTo);
1945   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1946 
1947   bool Changed = false;
1948 
1949   // Drop 'noreturn' if not present in target type.
1950   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1951     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1952     Changed = true;
1953   }
1954 
1955   const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1956   const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1957 
1958   if (FromFPT && ToFPT) {
1959     if (FromFPT->hasCFIUncheckedCallee() && !ToFPT->hasCFIUncheckedCallee()) {
1960       QualType NewTy = Context.getFunctionType(
1961           FromFPT->getReturnType(), FromFPT->getParamTypes(),
1962           FromFPT->getExtProtoInfo().withCFIUncheckedCallee(false));
1963       FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1964       FromFn = FromFPT;
1965       Changed = true;
1966       if (DiscardingCFIUncheckedCallee)
1967         *DiscardingCFIUncheckedCallee = true;
1968     } else if (!FromFPT->hasCFIUncheckedCallee() &&
1969                ToFPT->hasCFIUncheckedCallee()) {
1970       QualType NewTy = Context.getFunctionType(
1971           FromFPT->getReturnType(), FromFPT->getParamTypes(),
1972           FromFPT->getExtProtoInfo().withCFIUncheckedCallee(true));
1973       FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1974       FromFn = FromFPT;
1975       Changed = true;
1976       if (AddingCFIUncheckedCallee)
1977         *AddingCFIUncheckedCallee = true;
1978     }
1979   }
1980 
1981   // Drop 'noexcept' if not present in target type.
1982   if (FromFPT) {
1983     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1984       FromFn = cast<FunctionType>(
1985           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1986                                                    EST_None)
1987                  .getTypePtr());
1988       Changed = true;
1989     }
1990 
1991     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1992     // only if the ExtParameterInfo lists of the two function prototypes can be
1993     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1994     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1995     bool CanUseToFPT, CanUseFromFPT;
1996     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1997                                       CanUseFromFPT, NewParamInfos) &&
1998         CanUseToFPT && !CanUseFromFPT) {
1999       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2000       ExtInfo.ExtParameterInfos =
2001           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2002       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2003                                             FromFPT->getParamTypes(), ExtInfo);
2004       FromFn = QT->getAs<FunctionType>();
2005       Changed = true;
2006     }
2007 
2008     // For C, when called from checkPointerTypesForAssignment,
2009     // we need to not alter FromFn, or else even an innocuous cast
2010     // like dropping effects will fail. In C++ however we do want to
2011     // alter FromFn (because of the way PerformImplicitConversion works).
2012     if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
2013       FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2014 
2015       // Transparently add/drop effects; here we are concerned with
2016       // language rules/canonicalization. Adding/dropping effects is a warning.
2017       const auto FromFX = FromFPT->getFunctionEffects();
2018       const auto ToFX = ToFPT->getFunctionEffects();
2019       if (FromFX != ToFX) {
2020         FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2021         ExtInfo.FunctionEffects = ToFX;
2022         QualType QT = Context.getFunctionType(
2023             FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2024         FromFn = QT->getAs<FunctionType>();
2025         Changed = true;
2026       }
2027     }
2028   }
2029 
2030   if (!Changed)
2031     return false;
2032 
2033   assert(QualType(FromFn, 0).isCanonical());
2034   if (QualType(FromFn, 0) != CanTo) return false;
2035 
2036   return true;
2037 }
2038 
2039 /// Determine whether the conversion from FromType to ToType is a valid
2040 /// floating point conversion.
2041 ///
IsFloatingPointConversion(Sema & S,QualType FromType,QualType ToType)2042 static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2043                                       QualType ToType) {
2044   if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2045     return false;
2046   // FIXME: disable conversions between long double, __ibm128 and __float128
2047   // if their representation is different until there is back end support
2048   // We of course allow this conversion if long double is really double.
2049 
2050   // Conversions between bfloat16 and float16 are currently not supported.
2051   if ((FromType->isBFloat16Type() &&
2052        (ToType->isFloat16Type() || ToType->isHalfType())) ||
2053       (ToType->isBFloat16Type() &&
2054        (FromType->isFloat16Type() || FromType->isHalfType())))
2055     return false;
2056 
2057   // Conversions between IEEE-quad and IBM-extended semantics are not
2058   // permitted.
2059   const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2060   const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2061   if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2062        &ToSem == &llvm::APFloat::IEEEquad()) ||
2063       (&FromSem == &llvm::APFloat::IEEEquad() &&
2064        &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2065     return false;
2066   return true;
2067 }
2068 
IsVectorElementConversion(Sema & S,QualType FromType,QualType ToType,ImplicitConversionKind & ICK,Expr * From)2069 static bool IsVectorElementConversion(Sema &S, QualType FromType,
2070                                       QualType ToType,
2071                                       ImplicitConversionKind &ICK, Expr *From) {
2072   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2073     return true;
2074 
2075   if (S.IsFloatingPointPromotion(FromType, ToType)) {
2076     ICK = ICK_Floating_Promotion;
2077     return true;
2078   }
2079 
2080   if (IsFloatingPointConversion(S, FromType, ToType)) {
2081     ICK = ICK_Floating_Conversion;
2082     return true;
2083   }
2084 
2085   if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2086     ICK = ICK_Boolean_Conversion;
2087     return true;
2088   }
2089 
2090   if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2091       (FromType->isIntegralOrUnscopedEnumerationType() &&
2092        ToType->isRealFloatingType())) {
2093     ICK = ICK_Floating_Integral;
2094     return true;
2095   }
2096 
2097   if (S.IsIntegralPromotion(From, FromType, ToType)) {
2098     ICK = ICK_Integral_Promotion;
2099     return true;
2100   }
2101 
2102   if (FromType->isIntegralOrUnscopedEnumerationType() &&
2103       ToType->isIntegralType(S.Context)) {
2104     ICK = ICK_Integral_Conversion;
2105     return true;
2106   }
2107 
2108   return false;
2109 }
2110 
2111 /// Determine whether the conversion from FromType to ToType is a valid
2112 /// vector conversion.
2113 ///
2114 /// \param ICK Will be set to the vector conversion kind, if this is a vector
2115 /// conversion.
IsVectorConversion(Sema & S,QualType FromType,QualType ToType,ImplicitConversionKind & ICK,ImplicitConversionKind & ElConv,Expr * From,bool InOverloadResolution,bool CStyle)2116 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2117                                ImplicitConversionKind &ICK,
2118                                ImplicitConversionKind &ElConv, Expr *From,
2119                                bool InOverloadResolution, bool CStyle) {
2120   // We need at least one of these types to be a vector type to have a vector
2121   // conversion.
2122   if (!ToType->isVectorType() && !FromType->isVectorType())
2123     return false;
2124 
2125   // Identical types require no conversions.
2126   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2127     return false;
2128 
2129   // HLSL allows implicit truncation of vector types.
2130   if (S.getLangOpts().HLSL) {
2131     auto *ToExtType = ToType->getAs<ExtVectorType>();
2132     auto *FromExtType = FromType->getAs<ExtVectorType>();
2133 
2134     // If both arguments are vectors, handle possible vector truncation and
2135     // element conversion.
2136     if (ToExtType && FromExtType) {
2137       unsigned FromElts = FromExtType->getNumElements();
2138       unsigned ToElts = ToExtType->getNumElements();
2139       if (FromElts < ToElts)
2140         return false;
2141       if (FromElts == ToElts)
2142         ElConv = ICK_Identity;
2143       else
2144         ElConv = ICK_HLSL_Vector_Truncation;
2145 
2146       QualType FromElTy = FromExtType->getElementType();
2147       QualType ToElTy = ToExtType->getElementType();
2148       if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2149         return true;
2150       return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2151     }
2152     if (FromExtType && !ToExtType) {
2153       ElConv = ICK_HLSL_Vector_Truncation;
2154       QualType FromElTy = FromExtType->getElementType();
2155       if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2156         return true;
2157       return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2158     }
2159     // Fallthrough for the case where ToType is a vector and FromType is not.
2160   }
2161 
2162   // There are no conversions between extended vector types, only identity.
2163   if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2164     if (FromType->getAs<ExtVectorType>()) {
2165       // There are no conversions between extended vector types other than the
2166       // identity conversion.
2167       return false;
2168     }
2169 
2170     // Vector splat from any arithmetic type to a vector.
2171     if (FromType->isArithmeticType()) {
2172       if (S.getLangOpts().HLSL) {
2173         ElConv = ICK_HLSL_Vector_Splat;
2174         QualType ToElTy = ToExtType->getElementType();
2175         return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2176       }
2177       ICK = ICK_Vector_Splat;
2178       return true;
2179     }
2180   }
2181 
2182   if (ToType->isSVESizelessBuiltinType() ||
2183       FromType->isSVESizelessBuiltinType())
2184     if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2185         S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2186       ICK = ICK_SVE_Vector_Conversion;
2187       return true;
2188     }
2189 
2190   if (ToType->isRVVSizelessBuiltinType() ||
2191       FromType->isRVVSizelessBuiltinType())
2192     if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2193         S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2194       ICK = ICK_RVV_Vector_Conversion;
2195       return true;
2196     }
2197 
2198   // We can perform the conversion between vector types in the following cases:
2199   // 1)vector types are equivalent AltiVec and GCC vector types
2200   // 2)lax vector conversions are permitted and the vector types are of the
2201   //   same size
2202   // 3)the destination type does not have the ARM MVE strict-polymorphism
2203   //   attribute, which inhibits lax vector conversion for overload resolution
2204   //   only
2205   if (ToType->isVectorType() && FromType->isVectorType()) {
2206     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2207         (S.isLaxVectorConversion(FromType, ToType) &&
2208          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2209       if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2210           S.isLaxVectorConversion(FromType, ToType) &&
2211           S.anyAltivecTypes(FromType, ToType) &&
2212           !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2213           !InOverloadResolution && !CStyle) {
2214         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2215             << FromType << ToType;
2216       }
2217       ICK = ICK_Vector_Conversion;
2218       return true;
2219     }
2220   }
2221 
2222   return false;
2223 }
2224 
2225 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2226                                 bool InOverloadResolution,
2227                                 StandardConversionSequence &SCS,
2228                                 bool CStyle);
2229 
2230 /// IsStandardConversion - Determines whether there is a standard
2231 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2232 /// expression From to the type ToType. Standard conversion sequences
2233 /// only consider non-class types; for conversions that involve class
2234 /// types, use TryImplicitConversion. If a conversion exists, SCS will
2235 /// contain the standard conversion sequence required to perform this
2236 /// conversion and this routine will return true. Otherwise, this
2237 /// 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)2238 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2239                                  bool InOverloadResolution,
2240                                  StandardConversionSequence &SCS,
2241                                  bool CStyle,
2242                                  bool AllowObjCWritebackConversion) {
2243   QualType FromType = From->getType();
2244 
2245   // Standard conversions (C++ [conv])
2246   SCS.setAsIdentityConversion();
2247   SCS.IncompatibleObjC = false;
2248   SCS.setFromType(FromType);
2249   SCS.CopyConstructor = nullptr;
2250 
2251   // There are no standard conversions for class types in C++, so
2252   // abort early. When overloading in C, however, we do permit them.
2253   if (S.getLangOpts().CPlusPlus &&
2254       (FromType->isRecordType() || ToType->isRecordType()))
2255     return false;
2256 
2257   // The first conversion can be an lvalue-to-rvalue conversion,
2258   // array-to-pointer conversion, or function-to-pointer conversion
2259   // (C++ 4p1).
2260 
2261   if (FromType == S.Context.OverloadTy) {
2262     DeclAccessPair AccessPair;
2263     if (FunctionDecl *Fn
2264           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2265                                                  AccessPair)) {
2266       // We were able to resolve the address of the overloaded function,
2267       // so we can convert to the type of that function.
2268       FromType = Fn->getType();
2269       SCS.setFromType(FromType);
2270 
2271       // we can sometimes resolve &foo<int> regardless of ToType, so check
2272       // if the type matches (identity) or we are converting to bool
2273       if (!S.Context.hasSameUnqualifiedType(
2274               S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2275         // if the function type matches except for [[noreturn]], it's ok
2276         if (!S.IsFunctionConversion(FromType,
2277                                     S.ExtractUnqualifiedFunctionType(ToType)))
2278           // otherwise, only a boolean conversion is standard
2279           if (!ToType->isBooleanType())
2280             return false;
2281       }
2282 
2283       // Check if the "from" expression is taking the address of an overloaded
2284       // function and recompute the FromType accordingly. Take advantage of the
2285       // fact that non-static member functions *must* have such an address-of
2286       // expression.
2287       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2288       if (Method && !Method->isStatic() &&
2289           !Method->isExplicitObjectMemberFunction()) {
2290         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2291                "Non-unary operator on non-static member address");
2292         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2293                == UO_AddrOf &&
2294                "Non-address-of operator on non-static member address");
2295         FromType = S.Context.getMemberPointerType(
2296             FromType, /*Qualifier=*/nullptr, Method->getParent());
2297       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2298         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2299                UO_AddrOf &&
2300                "Non-address-of operator for overloaded function expression");
2301         FromType = S.Context.getPointerType(FromType);
2302       }
2303     } else {
2304       return false;
2305     }
2306   }
2307 
2308   bool argIsLValue = From->isGLValue();
2309   // To handle conversion from ArrayParameterType to ConstantArrayType
2310   // this block must be above the one below because Array parameters
2311   // do not decay and when handling HLSLOutArgExprs and
2312   // the From expression is an LValue.
2313   if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2314       ToType->isConstantArrayType()) {
2315     // HLSL constant array parameters do not decay, so if the argument is a
2316     // constant array and the parameter is an ArrayParameterType we have special
2317     // handling here.
2318     if (ToType->isArrayParameterType()) {
2319       FromType = S.Context.getArrayParameterType(FromType);
2320     } else if (FromType->isArrayParameterType()) {
2321       const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2322       FromType = APT->getConstantArrayType(S.Context);
2323     }
2324 
2325     SCS.First = ICK_HLSL_Array_RValue;
2326 
2327     // Don't consider qualifiers, which include things like address spaces
2328     if (FromType.getCanonicalType().getUnqualifiedType() !=
2329         ToType.getCanonicalType().getUnqualifiedType())
2330       return false;
2331 
2332     SCS.setAllToTypes(ToType);
2333     return true;
2334   } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2335              S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2336     // Lvalue-to-rvalue conversion (C++11 4.1):
2337     //   A glvalue (3.10) of a non-function, non-array type T can
2338     //   be converted to a prvalue.
2339 
2340     SCS.First = ICK_Lvalue_To_Rvalue;
2341 
2342     // C11 6.3.2.1p2:
2343     //   ... if the lvalue has atomic type, the value has the non-atomic version
2344     //   of the type of the lvalue ...
2345     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2346       FromType = Atomic->getValueType();
2347 
2348     // If T is a non-class type, the type of the rvalue is the
2349     // cv-unqualified version of T. Otherwise, the type of the rvalue
2350     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2351     // just strip the qualifiers because they don't matter.
2352     FromType = FromType.getUnqualifiedType();
2353   } else if (FromType->isArrayType()) {
2354     // Array-to-pointer conversion (C++ 4.2)
2355     SCS.First = ICK_Array_To_Pointer;
2356 
2357     // An lvalue or rvalue of type "array of N T" or "array of unknown
2358     // bound of T" can be converted to an rvalue of type "pointer to
2359     // T" (C++ 4.2p1).
2360     FromType = S.Context.getArrayDecayedType(FromType);
2361 
2362     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2363       // This conversion is deprecated in C++03 (D.4)
2364       SCS.DeprecatedStringLiteralToCharPtr = true;
2365 
2366       // For the purpose of ranking in overload resolution
2367       // (13.3.3.1.1), this conversion is considered an
2368       // array-to-pointer conversion followed by a qualification
2369       // conversion (4.4). (C++ 4.2p2)
2370       SCS.Second = ICK_Identity;
2371       SCS.Third = ICK_Qualification;
2372       SCS.QualificationIncludesObjCLifetime = false;
2373       SCS.setAllToTypes(FromType);
2374       return true;
2375     }
2376   } else if (FromType->isFunctionType() && argIsLValue) {
2377     // Function-to-pointer conversion (C++ 4.3).
2378     SCS.First = ICK_Function_To_Pointer;
2379 
2380     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2381       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2382         if (!S.checkAddressOfFunctionIsAvailable(FD))
2383           return false;
2384 
2385     // An lvalue of function type T can be converted to an rvalue of
2386     // type "pointer to T." The result is a pointer to the
2387     // function. (C++ 4.3p1).
2388     FromType = S.Context.getPointerType(FromType);
2389   } else {
2390     // We don't require any conversions for the first step.
2391     SCS.First = ICK_Identity;
2392   }
2393   SCS.setToType(0, FromType);
2394 
2395   // The second conversion can be an integral promotion, floating
2396   // point promotion, integral conversion, floating point conversion,
2397   // floating-integral conversion, pointer conversion,
2398   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2399   // For overloading in C, this can also be a "compatible-type"
2400   // conversion.
2401   bool IncompatibleObjC = false;
2402   ImplicitConversionKind SecondICK = ICK_Identity;
2403   ImplicitConversionKind DimensionICK = ICK_Identity;
2404   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2405     // The unqualified versions of the types are the same: there's no
2406     // conversion to do.
2407     SCS.Second = ICK_Identity;
2408   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2409     // Integral promotion (C++ 4.5).
2410     SCS.Second = ICK_Integral_Promotion;
2411     FromType = ToType.getUnqualifiedType();
2412   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2413     // Floating point promotion (C++ 4.6).
2414     SCS.Second = ICK_Floating_Promotion;
2415     FromType = ToType.getUnqualifiedType();
2416   } else if (S.IsComplexPromotion(FromType, ToType)) {
2417     // Complex promotion (Clang extension)
2418     SCS.Second = ICK_Complex_Promotion;
2419     FromType = ToType.getUnqualifiedType();
2420   } else if (ToType->isBooleanType() &&
2421              (FromType->isArithmeticType() ||
2422               FromType->isAnyPointerType() ||
2423               FromType->isBlockPointerType() ||
2424               FromType->isMemberPointerType())) {
2425     // Boolean conversions (C++ 4.12).
2426     SCS.Second = ICK_Boolean_Conversion;
2427     FromType = S.Context.BoolTy;
2428   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2429              ToType->isIntegralType(S.Context)) {
2430     // Integral conversions (C++ 4.7).
2431     SCS.Second = ICK_Integral_Conversion;
2432     FromType = ToType.getUnqualifiedType();
2433   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2434     // Complex conversions (C99 6.3.1.6)
2435     SCS.Second = ICK_Complex_Conversion;
2436     FromType = ToType.getUnqualifiedType();
2437   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2438              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2439     // Complex-real conversions (C99 6.3.1.7)
2440     SCS.Second = ICK_Complex_Real;
2441     FromType = ToType.getUnqualifiedType();
2442   } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2443     // Floating point conversions (C++ 4.8).
2444     SCS.Second = ICK_Floating_Conversion;
2445     FromType = ToType.getUnqualifiedType();
2446   } else if ((FromType->isRealFloatingType() &&
2447               ToType->isIntegralType(S.Context)) ||
2448              (FromType->isIntegralOrUnscopedEnumerationType() &&
2449               ToType->isRealFloatingType())) {
2450 
2451     // Floating-integral conversions (C++ 4.9).
2452     SCS.Second = ICK_Floating_Integral;
2453     FromType = ToType.getUnqualifiedType();
2454   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2455     SCS.Second = ICK_Block_Pointer_Conversion;
2456   } else if (AllowObjCWritebackConversion &&
2457              S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2458     SCS.Second = ICK_Writeback_Conversion;
2459   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2460                                    FromType, IncompatibleObjC)) {
2461     // Pointer conversions (C++ 4.10).
2462     SCS.Second = ICK_Pointer_Conversion;
2463     SCS.IncompatibleObjC = IncompatibleObjC;
2464     FromType = FromType.getUnqualifiedType();
2465   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2466                                          InOverloadResolution, FromType)) {
2467     // Pointer to member conversions (4.11).
2468     SCS.Second = ICK_Pointer_Member;
2469   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2470                                 From, InOverloadResolution, CStyle)) {
2471     SCS.Second = SecondICK;
2472     SCS.Dimension = DimensionICK;
2473     FromType = ToType.getUnqualifiedType();
2474   } else if (!S.getLangOpts().CPlusPlus &&
2475              S.Context.typesAreCompatible(ToType, FromType)) {
2476     // Compatible conversions (Clang extension for C function overloading)
2477     SCS.Second = ICK_Compatible_Conversion;
2478     FromType = ToType.getUnqualifiedType();
2479   } else if (IsTransparentUnionStandardConversion(
2480                  S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2481     SCS.Second = ICK_TransparentUnionConversion;
2482     FromType = ToType;
2483   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2484                                  CStyle)) {
2485     // tryAtomicConversion has updated the standard conversion sequence
2486     // appropriately.
2487     return true;
2488   } else if (ToType->isEventT() &&
2489              From->isIntegerConstantExpr(S.getASTContext()) &&
2490              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2491     SCS.Second = ICK_Zero_Event_Conversion;
2492     FromType = ToType;
2493   } else if (ToType->isQueueT() &&
2494              From->isIntegerConstantExpr(S.getASTContext()) &&
2495              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2496     SCS.Second = ICK_Zero_Queue_Conversion;
2497     FromType = ToType;
2498   } else if (ToType->isSamplerT() &&
2499              From->isIntegerConstantExpr(S.getASTContext())) {
2500     SCS.Second = ICK_Compatible_Conversion;
2501     FromType = ToType;
2502   } else if ((ToType->isFixedPointType() &&
2503               FromType->isConvertibleToFixedPointType()) ||
2504              (FromType->isFixedPointType() &&
2505               ToType->isConvertibleToFixedPointType())) {
2506     SCS.Second = ICK_Fixed_Point_Conversion;
2507     FromType = ToType;
2508   } else {
2509     // No second conversion required.
2510     SCS.Second = ICK_Identity;
2511   }
2512   SCS.setToType(1, FromType);
2513 
2514   // The third conversion can be a function pointer conversion or a
2515   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2516   bool ObjCLifetimeConversion;
2517   if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2518     // Function pointer conversions (removing 'noexcept') including removal of
2519     // 'noreturn' (Clang extension).
2520     SCS.Third = ICK_Function_Conversion;
2521   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2522                                          ObjCLifetimeConversion)) {
2523     SCS.Third = ICK_Qualification;
2524     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2525     FromType = ToType;
2526   } else {
2527     // No conversion required
2528     SCS.Third = ICK_Identity;
2529   }
2530 
2531   // C++ [over.best.ics]p6:
2532   //   [...] Any difference in top-level cv-qualification is
2533   //   subsumed by the initialization itself and does not constitute
2534   //   a conversion. [...]
2535   QualType CanonFrom = S.Context.getCanonicalType(FromType);
2536   QualType CanonTo = S.Context.getCanonicalType(ToType);
2537   if (CanonFrom.getLocalUnqualifiedType()
2538                                      == CanonTo.getLocalUnqualifiedType() &&
2539       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2540     FromType = ToType;
2541     CanonFrom = CanonTo;
2542   }
2543 
2544   SCS.setToType(2, FromType);
2545 
2546   // If we have not converted the argument type to the parameter type,
2547   // this is a bad conversion sequence, unless we're resolving an overload in C.
2548   //
2549   // Permit conversions from a function without `cfi_unchecked_callee` to a
2550   // function with `cfi_unchecked_callee`.
2551   if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(CanonFrom, CanonTo))
2552     return true;
2553 
2554   if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2555     return false;
2556 
2557   ExprResult ER = ExprResult{From};
2558   AssignConvertType Conv =
2559       S.CheckSingleAssignmentConstraints(ToType, ER,
2560                                          /*Diagnose=*/false,
2561                                          /*DiagnoseCFAudited=*/false,
2562                                          /*ConvertRHS=*/false);
2563   ImplicitConversionKind SecondConv;
2564   switch (Conv) {
2565   case AssignConvertType::Compatible:
2566   case AssignConvertType::
2567       CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2568     SecondConv = ICK_C_Only_Conversion;
2569     break;
2570   // For our purposes, discarding qualifiers is just as bad as using an
2571   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2572   // qualifiers, as well.
2573   case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2574   case AssignConvertType::IncompatiblePointer:
2575   case AssignConvertType::IncompatiblePointerSign:
2576     SecondConv = ICK_Incompatible_Pointer_Conversion;
2577     break;
2578   default:
2579     return false;
2580   }
2581 
2582   // First can only be an lvalue conversion, so we pretend that this was the
2583   // second conversion. First should already be valid from earlier in the
2584   // function.
2585   SCS.Second = SecondConv;
2586   SCS.setToType(1, ToType);
2587 
2588   // Third is Identity, because Second should rank us worse than any other
2589   // conversion. This could also be ICK_Qualification, but it's simpler to just
2590   // lump everything in with the second conversion, and we don't gain anything
2591   // from making this ICK_Qualification.
2592   SCS.Third = ICK_Identity;
2593   SCS.setToType(2, ToType);
2594   return true;
2595 }
2596 
2597 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)2598 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2599                                      QualType &ToType,
2600                                      bool InOverloadResolution,
2601                                      StandardConversionSequence &SCS,
2602                                      bool CStyle) {
2603 
2604   const RecordType *UT = ToType->getAsUnionType();
2605   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2606     return false;
2607   // The field to initialize within the transparent union.
2608   RecordDecl *UD = UT->getDecl();
2609   // It's compatible if the expression matches any of the fields.
2610   for (const auto *it : UD->fields()) {
2611     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2612                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2613       ToType = it->getType();
2614       return true;
2615     }
2616   }
2617   return false;
2618 }
2619 
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)2620 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2621   const BuiltinType *To = ToType->getAs<BuiltinType>();
2622   // All integers are built-in.
2623   if (!To) {
2624     return false;
2625   }
2626 
2627   // An rvalue of type char, signed char, unsigned char, short int, or
2628   // unsigned short int can be converted to an rvalue of type int if
2629   // int can represent all the values of the source type; otherwise,
2630   // the source rvalue can be converted to an rvalue of type unsigned
2631   // int (C++ 4.5p1).
2632   if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2633       !FromType->isEnumeralType()) {
2634     if ( // We can promote any signed, promotable integer type to an int
2635         (FromType->isSignedIntegerType() ||
2636          // We can promote any unsigned integer type whose size is
2637          // less than int to an int.
2638          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2639       return To->getKind() == BuiltinType::Int;
2640     }
2641 
2642     return To->getKind() == BuiltinType::UInt;
2643   }
2644 
2645   // C++11 [conv.prom]p3:
2646   //   A prvalue of an unscoped enumeration type whose underlying type is not
2647   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2648   //   following types that can represent all the values of the enumeration
2649   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2650   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2651   //   long long int. If none of the types in that list can represent all the
2652   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2653   //   type can be converted to an rvalue a prvalue of the extended integer type
2654   //   with lowest integer conversion rank (4.13) greater than the rank of long
2655   //   long in which all the values of the enumeration can be represented. If
2656   //   there are two such extended types, the signed one is chosen.
2657   // C++11 [conv.prom]p4:
2658   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2659   //   can be converted to a prvalue of its underlying type. Moreover, if
2660   //   integral promotion can be applied to its underlying type, a prvalue of an
2661   //   unscoped enumeration type whose underlying type is fixed can also be
2662   //   converted to a prvalue of the promoted underlying type.
2663   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2664     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2665     // provided for a scoped enumeration.
2666     if (FromEnumType->getDecl()->isScoped())
2667       return false;
2668 
2669     // We can perform an integral promotion to the underlying type of the enum,
2670     // even if that's not the promoted type. Note that the check for promoting
2671     // the underlying type is based on the type alone, and does not consider
2672     // the bitfield-ness of the actual source expression.
2673     if (FromEnumType->getDecl()->isFixed()) {
2674       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2675       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2676              IsIntegralPromotion(nullptr, Underlying, ToType);
2677     }
2678 
2679     // We have already pre-calculated the promotion type, so this is trivial.
2680     if (ToType->isIntegerType() &&
2681         isCompleteType(From->getBeginLoc(), FromType))
2682       return Context.hasSameUnqualifiedType(
2683           ToType, FromEnumType->getDecl()->getPromotionType());
2684 
2685     // C++ [conv.prom]p5:
2686     //   If the bit-field has an enumerated type, it is treated as any other
2687     //   value of that type for promotion purposes.
2688     //
2689     // ... so do not fall through into the bit-field checks below in C++.
2690     if (getLangOpts().CPlusPlus)
2691       return false;
2692   }
2693 
2694   // C++0x [conv.prom]p2:
2695   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2696   //   to an rvalue a prvalue of the first of the following types that can
2697   //   represent all the values of its underlying type: int, unsigned int,
2698   //   long int, unsigned long int, long long int, or unsigned long long int.
2699   //   If none of the types in that list can represent all the values of its
2700   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2701   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2702   //   type.
2703   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2704       ToType->isIntegerType()) {
2705     // Determine whether the type we're converting from is signed or
2706     // unsigned.
2707     bool FromIsSigned = FromType->isSignedIntegerType();
2708     uint64_t FromSize = Context.getTypeSize(FromType);
2709 
2710     // The types we'll try to promote to, in the appropriate
2711     // order. Try each of these types.
2712     QualType PromoteTypes[6] = {
2713       Context.IntTy, Context.UnsignedIntTy,
2714       Context.LongTy, Context.UnsignedLongTy ,
2715       Context.LongLongTy, Context.UnsignedLongLongTy
2716     };
2717     for (int Idx = 0; Idx < 6; ++Idx) {
2718       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2719       if (FromSize < ToSize ||
2720           (FromSize == ToSize &&
2721            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2722         // We found the type that we can promote to. If this is the
2723         // type we wanted, we have a promotion. Otherwise, no
2724         // promotion.
2725         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2726       }
2727     }
2728   }
2729 
2730   // An rvalue for an integral bit-field (9.6) can be converted to an
2731   // rvalue of type int if int can represent all the values of the
2732   // bit-field; otherwise, it can be converted to unsigned int if
2733   // unsigned int can represent all the values of the bit-field. If
2734   // the bit-field is larger yet, no integral promotion applies to
2735   // it. If the bit-field has an enumerated type, it is treated as any
2736   // other value of that type for promotion purposes (C++ 4.5p3).
2737   // FIXME: We should delay checking of bit-fields until we actually perform the
2738   // conversion.
2739   //
2740   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2741   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2742   // bit-fields and those whose underlying type is larger than int) for GCC
2743   // compatibility.
2744   if (From) {
2745     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2746       std::optional<llvm::APSInt> BitWidth;
2747       if (FromType->isIntegralType(Context) &&
2748           (BitWidth =
2749                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2750         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2751         ToSize = Context.getTypeSize(ToType);
2752 
2753         // Are we promoting to an int from a bitfield that fits in an int?
2754         if (*BitWidth < ToSize ||
2755             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2756           return To->getKind() == BuiltinType::Int;
2757         }
2758 
2759         // Are we promoting to an unsigned int from an unsigned bitfield
2760         // that fits into an unsigned int?
2761         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2762           return To->getKind() == BuiltinType::UInt;
2763         }
2764 
2765         return false;
2766       }
2767     }
2768   }
2769 
2770   // An rvalue of type bool can be converted to an rvalue of type int,
2771   // with false becoming zero and true becoming one (C++ 4.5p4).
2772   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2773     return true;
2774   }
2775 
2776   // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2777   // integral type.
2778   if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2779       ToType->isIntegerType())
2780     return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2781 
2782   return false;
2783 }
2784 
IsFloatingPointPromotion(QualType FromType,QualType ToType)2785 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2786   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2787     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2788       /// An rvalue of type float can be converted to an rvalue of type
2789       /// double. (C++ 4.6p1).
2790       if (FromBuiltin->getKind() == BuiltinType::Float &&
2791           ToBuiltin->getKind() == BuiltinType::Double)
2792         return true;
2793 
2794       // C99 6.3.1.5p1:
2795       //   When a float is promoted to double or long double, or a
2796       //   double is promoted to long double [...].
2797       if (!getLangOpts().CPlusPlus &&
2798           (FromBuiltin->getKind() == BuiltinType::Float ||
2799            FromBuiltin->getKind() == BuiltinType::Double) &&
2800           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2801            ToBuiltin->getKind() == BuiltinType::Float128 ||
2802            ToBuiltin->getKind() == BuiltinType::Ibm128))
2803         return true;
2804 
2805       // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2806       // or not native half types are enabled.
2807       if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2808           (ToBuiltin->getKind() == BuiltinType::Float ||
2809            ToBuiltin->getKind() == BuiltinType::Double))
2810         return true;
2811 
2812       // Half can be promoted to float.
2813       if (!getLangOpts().NativeHalfType &&
2814            FromBuiltin->getKind() == BuiltinType::Half &&
2815           ToBuiltin->getKind() == BuiltinType::Float)
2816         return true;
2817     }
2818 
2819   return false;
2820 }
2821 
IsComplexPromotion(QualType FromType,QualType ToType)2822 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2823   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2824   if (!FromComplex)
2825     return false;
2826 
2827   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2828   if (!ToComplex)
2829     return false;
2830 
2831   return IsFloatingPointPromotion(FromComplex->getElementType(),
2832                                   ToComplex->getElementType()) ||
2833     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2834                         ToComplex->getElementType());
2835 }
2836 
2837 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2838 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2839 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2840 /// if non-empty, will be a pointer to ToType that may or may not have
2841 /// the right set of qualifiers on its pointee.
2842 ///
2843 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)2844 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2845                                    QualType ToPointee, QualType ToType,
2846                                    ASTContext &Context,
2847                                    bool StripObjCLifetime = false) {
2848   assert((FromPtr->getTypeClass() == Type::Pointer ||
2849           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2850          "Invalid similarly-qualified pointer type");
2851 
2852   /// Conversions to 'id' subsume cv-qualifier conversions.
2853   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2854     return ToType.getUnqualifiedType();
2855 
2856   QualType CanonFromPointee
2857     = Context.getCanonicalType(FromPtr->getPointeeType());
2858   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2859   Qualifiers Quals = CanonFromPointee.getQualifiers();
2860 
2861   if (StripObjCLifetime)
2862     Quals.removeObjCLifetime();
2863 
2864   // Exact qualifier match -> return the pointer type we're converting to.
2865   if (CanonToPointee.getLocalQualifiers() == Quals) {
2866     // ToType is exactly what we need. Return it.
2867     if (!ToType.isNull())
2868       return ToType.getUnqualifiedType();
2869 
2870     // Build a pointer to ToPointee. It has the right qualifiers
2871     // already.
2872     if (isa<ObjCObjectPointerType>(ToType))
2873       return Context.getObjCObjectPointerType(ToPointee);
2874     return Context.getPointerType(ToPointee);
2875   }
2876 
2877   // Just build a canonical type that has the right qualifiers.
2878   QualType QualifiedCanonToPointee
2879     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2880 
2881   if (isa<ObjCObjectPointerType>(ToType))
2882     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2883   return Context.getPointerType(QualifiedCanonToPointee);
2884 }
2885 
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)2886 static bool isNullPointerConstantForConversion(Expr *Expr,
2887                                                bool InOverloadResolution,
2888                                                ASTContext &Context) {
2889   // Handle value-dependent integral null pointer constants correctly.
2890   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2891   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2892       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2893     return !InOverloadResolution;
2894 
2895   return Expr->isNullPointerConstant(Context,
2896                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2897                                         : Expr::NPC_ValueDependentIsNull);
2898 }
2899 
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)2900 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2901                                bool InOverloadResolution,
2902                                QualType& ConvertedType,
2903                                bool &IncompatibleObjC) {
2904   IncompatibleObjC = false;
2905   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2906                               IncompatibleObjC))
2907     return true;
2908 
2909   // Conversion from a null pointer constant to any Objective-C pointer type.
2910   if (ToType->isObjCObjectPointerType() &&
2911       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2912     ConvertedType = ToType;
2913     return true;
2914   }
2915 
2916   // Blocks: Block pointers can be converted to void*.
2917   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2918       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2919     ConvertedType = ToType;
2920     return true;
2921   }
2922   // Blocks: A null pointer constant can be converted to a block
2923   // pointer type.
2924   if (ToType->isBlockPointerType() &&
2925       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2926     ConvertedType = ToType;
2927     return true;
2928   }
2929 
2930   // If the left-hand-side is nullptr_t, the right side can be a null
2931   // pointer constant.
2932   if (ToType->isNullPtrType() &&
2933       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2934     ConvertedType = ToType;
2935     return true;
2936   }
2937 
2938   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2939   if (!ToTypePtr)
2940     return false;
2941 
2942   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2943   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2944     ConvertedType = ToType;
2945     return true;
2946   }
2947 
2948   // Beyond this point, both types need to be pointers
2949   // , including objective-c pointers.
2950   QualType ToPointeeType = ToTypePtr->getPointeeType();
2951   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2952       !getLangOpts().ObjCAutoRefCount) {
2953     ConvertedType = BuildSimilarlyQualifiedPointerType(
2954         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2955         Context);
2956     return true;
2957   }
2958   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2959   if (!FromTypePtr)
2960     return false;
2961 
2962   QualType FromPointeeType = FromTypePtr->getPointeeType();
2963 
2964   // If the unqualified pointee types are the same, this can't be a
2965   // pointer conversion, so don't do all of the work below.
2966   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2967     return false;
2968 
2969   // An rvalue of type "pointer to cv T," where T is an object type,
2970   // can be converted to an rvalue of type "pointer to cv void" (C++
2971   // 4.10p2).
2972   if (FromPointeeType->isIncompleteOrObjectType() &&
2973       ToPointeeType->isVoidType()) {
2974     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2975                                                        ToPointeeType,
2976                                                        ToType, Context,
2977                                                    /*StripObjCLifetime=*/true);
2978     return true;
2979   }
2980 
2981   // MSVC allows implicit function to void* type conversion.
2982   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2983       ToPointeeType->isVoidType()) {
2984     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2985                                                        ToPointeeType,
2986                                                        ToType, Context);
2987     return true;
2988   }
2989 
2990   // When we're overloading in C, we allow a special kind of pointer
2991   // conversion for compatible-but-not-identical pointee types.
2992   if (!getLangOpts().CPlusPlus &&
2993       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2994     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2995                                                        ToPointeeType,
2996                                                        ToType, Context);
2997     return true;
2998   }
2999 
3000   // C++ [conv.ptr]p3:
3001   //
3002   //   An rvalue of type "pointer to cv D," where D is a class type,
3003   //   can be converted to an rvalue of type "pointer to cv B," where
3004   //   B is a base class (clause 10) of D. If B is an inaccessible
3005   //   (clause 11) or ambiguous (10.2) base class of D, a program that
3006   //   necessitates this conversion is ill-formed. The result of the
3007   //   conversion is a pointer to the base class sub-object of the
3008   //   derived class object. The null pointer value is converted to
3009   //   the null pointer value of the destination type.
3010   //
3011   // Note that we do not check for ambiguity or inaccessibility
3012   // here. That is handled by CheckPointerConversion.
3013   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3014       ToPointeeType->isRecordType() &&
3015       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3016       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3017     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3018                                                        ToPointeeType,
3019                                                        ToType, Context);
3020     return true;
3021   }
3022 
3023   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3024       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3025     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3026                                                        ToPointeeType,
3027                                                        ToType, Context);
3028     return true;
3029   }
3030 
3031   return false;
3032 }
3033 
3034 /// Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)3035 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3036   Qualifiers TQs = T.getQualifiers();
3037 
3038   // Check whether qualifiers already match.
3039   if (TQs == Qs)
3040     return T;
3041 
3042   if (Qs.compatiblyIncludes(TQs, Context))
3043     return Context.getQualifiedType(T, Qs);
3044 
3045   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3046 }
3047 
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)3048 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3049                                    QualType& ConvertedType,
3050                                    bool &IncompatibleObjC) {
3051   if (!getLangOpts().ObjC)
3052     return false;
3053 
3054   // The set of qualifiers on the type we're converting from.
3055   Qualifiers FromQualifiers = FromType.getQualifiers();
3056 
3057   // First, we handle all conversions on ObjC object pointer types.
3058   const ObjCObjectPointerType* ToObjCPtr =
3059     ToType->getAs<ObjCObjectPointerType>();
3060   const ObjCObjectPointerType *FromObjCPtr =
3061     FromType->getAs<ObjCObjectPointerType>();
3062 
3063   if (ToObjCPtr && FromObjCPtr) {
3064     // If the pointee types are the same (ignoring qualifications),
3065     // then this is not a pointer conversion.
3066     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3067                                        FromObjCPtr->getPointeeType()))
3068       return false;
3069 
3070     // Conversion between Objective-C pointers.
3071     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3072       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3073       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3074       if (getLangOpts().CPlusPlus && LHS && RHS &&
3075           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3076               FromObjCPtr->getPointeeType(), getASTContext()))
3077         return false;
3078       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3079                                                    ToObjCPtr->getPointeeType(),
3080                                                          ToType, Context);
3081       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3082       return true;
3083     }
3084 
3085     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3086       // Okay: this is some kind of implicit downcast of Objective-C
3087       // interfaces, which is permitted. However, we're going to
3088       // complain about it.
3089       IncompatibleObjC = true;
3090       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3091                                                    ToObjCPtr->getPointeeType(),
3092                                                          ToType, Context);
3093       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3094       return true;
3095     }
3096   }
3097   // Beyond this point, both types need to be C pointers or block pointers.
3098   QualType ToPointeeType;
3099   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3100     ToPointeeType = ToCPtr->getPointeeType();
3101   else if (const BlockPointerType *ToBlockPtr =
3102             ToType->getAs<BlockPointerType>()) {
3103     // Objective C++: We're able to convert from a pointer to any object
3104     // to a block pointer type.
3105     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3106       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3107       return true;
3108     }
3109     ToPointeeType = ToBlockPtr->getPointeeType();
3110   }
3111   else if (FromType->getAs<BlockPointerType>() &&
3112            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3113     // Objective C++: We're able to convert from a block pointer type to a
3114     // pointer to any object.
3115     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3116     return true;
3117   }
3118   else
3119     return false;
3120 
3121   QualType FromPointeeType;
3122   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3123     FromPointeeType = FromCPtr->getPointeeType();
3124   else if (const BlockPointerType *FromBlockPtr =
3125            FromType->getAs<BlockPointerType>())
3126     FromPointeeType = FromBlockPtr->getPointeeType();
3127   else
3128     return false;
3129 
3130   // If we have pointers to pointers, recursively check whether this
3131   // is an Objective-C conversion.
3132   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3133       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3134                               IncompatibleObjC)) {
3135     // We always complain about this conversion.
3136     IncompatibleObjC = true;
3137     ConvertedType = Context.getPointerType(ConvertedType);
3138     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3139     return true;
3140   }
3141   // Allow conversion of pointee being objective-c pointer to another one;
3142   // as in I* to id.
3143   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3144       ToPointeeType->getAs<ObjCObjectPointerType>() &&
3145       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3146                               IncompatibleObjC)) {
3147 
3148     ConvertedType = Context.getPointerType(ConvertedType);
3149     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3150     return true;
3151   }
3152 
3153   // If we have pointers to functions or blocks, check whether the only
3154   // differences in the argument and result types are in Objective-C
3155   // pointer conversions. If so, we permit the conversion (but
3156   // complain about it).
3157   const FunctionProtoType *FromFunctionType
3158     = FromPointeeType->getAs<FunctionProtoType>();
3159   const FunctionProtoType *ToFunctionType
3160     = ToPointeeType->getAs<FunctionProtoType>();
3161   if (FromFunctionType && ToFunctionType) {
3162     // If the function types are exactly the same, this isn't an
3163     // Objective-C pointer conversion.
3164     if (Context.getCanonicalType(FromPointeeType)
3165           == Context.getCanonicalType(ToPointeeType))
3166       return false;
3167 
3168     // Perform the quick checks that will tell us whether these
3169     // function types are obviously different.
3170     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3171         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3172         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3173       return false;
3174 
3175     bool HasObjCConversion = false;
3176     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3177         Context.getCanonicalType(ToFunctionType->getReturnType())) {
3178       // Okay, the types match exactly. Nothing to do.
3179     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3180                                        ToFunctionType->getReturnType(),
3181                                        ConvertedType, IncompatibleObjC)) {
3182       // Okay, we have an Objective-C pointer conversion.
3183       HasObjCConversion = true;
3184     } else {
3185       // Function types are too different. Abort.
3186       return false;
3187     }
3188 
3189     // Check argument types.
3190     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3191          ArgIdx != NumArgs; ++ArgIdx) {
3192       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3193       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3194       if (Context.getCanonicalType(FromArgType)
3195             == Context.getCanonicalType(ToArgType)) {
3196         // Okay, the types match exactly. Nothing to do.
3197       } else if (isObjCPointerConversion(FromArgType, ToArgType,
3198                                          ConvertedType, IncompatibleObjC)) {
3199         // Okay, we have an Objective-C pointer conversion.
3200         HasObjCConversion = true;
3201       } else {
3202         // Argument types are too different. Abort.
3203         return false;
3204       }
3205     }
3206 
3207     if (HasObjCConversion) {
3208       // We had an Objective-C conversion. Allow this pointer
3209       // conversion, but complain about it.
3210       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3211       IncompatibleObjC = true;
3212       return true;
3213     }
3214   }
3215 
3216   return false;
3217 }
3218 
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)3219 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3220                                     QualType& ConvertedType) {
3221   QualType ToPointeeType;
3222   if (const BlockPointerType *ToBlockPtr =
3223         ToType->getAs<BlockPointerType>())
3224     ToPointeeType = ToBlockPtr->getPointeeType();
3225   else
3226     return false;
3227 
3228   QualType FromPointeeType;
3229   if (const BlockPointerType *FromBlockPtr =
3230       FromType->getAs<BlockPointerType>())
3231     FromPointeeType = FromBlockPtr->getPointeeType();
3232   else
3233     return false;
3234   // We have pointer to blocks, check whether the only
3235   // differences in the argument and result types are in Objective-C
3236   // pointer conversions. If so, we permit the conversion.
3237 
3238   const FunctionProtoType *FromFunctionType
3239     = FromPointeeType->getAs<FunctionProtoType>();
3240   const FunctionProtoType *ToFunctionType
3241     = ToPointeeType->getAs<FunctionProtoType>();
3242 
3243   if (!FromFunctionType || !ToFunctionType)
3244     return false;
3245 
3246   if (Context.hasSameType(FromPointeeType, ToPointeeType))
3247     return true;
3248 
3249   // Perform the quick checks that will tell us whether these
3250   // function types are obviously different.
3251   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3252       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3253     return false;
3254 
3255   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3256   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3257   if (FromEInfo != ToEInfo)
3258     return false;
3259 
3260   bool IncompatibleObjC = false;
3261   if (Context.hasSameType(FromFunctionType->getReturnType(),
3262                           ToFunctionType->getReturnType())) {
3263     // Okay, the types match exactly. Nothing to do.
3264   } else {
3265     QualType RHS = FromFunctionType->getReturnType();
3266     QualType LHS = ToFunctionType->getReturnType();
3267     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3268         !RHS.hasQualifiers() && LHS.hasQualifiers())
3269        LHS = LHS.getUnqualifiedType();
3270 
3271      if (Context.hasSameType(RHS,LHS)) {
3272        // OK exact match.
3273      } else if (isObjCPointerConversion(RHS, LHS,
3274                                         ConvertedType, IncompatibleObjC)) {
3275      if (IncompatibleObjC)
3276        return false;
3277      // Okay, we have an Objective-C pointer conversion.
3278      }
3279      else
3280        return false;
3281    }
3282 
3283    // Check argument types.
3284    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3285         ArgIdx != NumArgs; ++ArgIdx) {
3286      IncompatibleObjC = false;
3287      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3288      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3289      if (Context.hasSameType(FromArgType, ToArgType)) {
3290        // Okay, the types match exactly. Nothing to do.
3291      } else if (isObjCPointerConversion(ToArgType, FromArgType,
3292                                         ConvertedType, IncompatibleObjC)) {
3293        if (IncompatibleObjC)
3294          return false;
3295        // Okay, we have an Objective-C pointer conversion.
3296      } else
3297        // Argument types are too different. Abort.
3298        return false;
3299    }
3300 
3301    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3302    bool CanUseToFPT, CanUseFromFPT;
3303    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3304                                       CanUseToFPT, CanUseFromFPT,
3305                                       NewParamInfos))
3306      return false;
3307 
3308    ConvertedType = ToType;
3309    return true;
3310 }
3311 
3312 enum {
3313   ft_default,
3314   ft_different_class,
3315   ft_parameter_arity,
3316   ft_parameter_mismatch,
3317   ft_return_type,
3318   ft_qualifer_mismatch,
3319   ft_noexcept
3320 };
3321 
3322 /// Attempts to get the FunctionProtoType from a Type. Handles
3323 /// MemberFunctionPointers properly.
tryGetFunctionProtoType(QualType FromType)3324 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3325   if (auto *FPT = FromType->getAs<FunctionProtoType>())
3326     return FPT;
3327 
3328   if (auto *MPT = FromType->getAs<MemberPointerType>())
3329     return MPT->getPointeeType()->getAs<FunctionProtoType>();
3330 
3331   return nullptr;
3332 }
3333 
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)3334 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3335                                       QualType FromType, QualType ToType) {
3336   // If either type is not valid, include no extra info.
3337   if (FromType.isNull() || ToType.isNull()) {
3338     PDiag << ft_default;
3339     return;
3340   }
3341 
3342   // Get the function type from the pointers.
3343   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3344     const auto *FromMember = FromType->castAs<MemberPointerType>(),
3345                *ToMember = ToType->castAs<MemberPointerType>();
3346     if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3347                             ToMember->getMostRecentCXXRecordDecl())) {
3348       PDiag << ft_different_class;
3349       if (ToMember->isSugared())
3350         PDiag << Context.getTypeDeclType(
3351             ToMember->getMostRecentCXXRecordDecl());
3352       else
3353         PDiag << ToMember->getQualifier();
3354       if (FromMember->isSugared())
3355         PDiag << Context.getTypeDeclType(
3356             FromMember->getMostRecentCXXRecordDecl());
3357       else
3358         PDiag << FromMember->getQualifier();
3359       return;
3360     }
3361     FromType = FromMember->getPointeeType();
3362     ToType = ToMember->getPointeeType();
3363   }
3364 
3365   if (FromType->isPointerType())
3366     FromType = FromType->getPointeeType();
3367   if (ToType->isPointerType())
3368     ToType = ToType->getPointeeType();
3369 
3370   // Remove references.
3371   FromType = FromType.getNonReferenceType();
3372   ToType = ToType.getNonReferenceType();
3373 
3374   // Don't print extra info for non-specialized template functions.
3375   if (FromType->isInstantiationDependentType() &&
3376       !FromType->getAs<TemplateSpecializationType>()) {
3377     PDiag << ft_default;
3378     return;
3379   }
3380 
3381   // No extra info for same types.
3382   if (Context.hasSameType(FromType, ToType)) {
3383     PDiag << ft_default;
3384     return;
3385   }
3386 
3387   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3388                           *ToFunction = tryGetFunctionProtoType(ToType);
3389 
3390   // Both types need to be function types.
3391   if (!FromFunction || !ToFunction) {
3392     PDiag << ft_default;
3393     return;
3394   }
3395 
3396   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3397     PDiag << ft_parameter_arity << ToFunction->getNumParams()
3398           << FromFunction->getNumParams();
3399     return;
3400   }
3401 
3402   // Handle different parameter types.
3403   unsigned ArgPos;
3404   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3405     PDiag << ft_parameter_mismatch << ArgPos + 1
3406           << ToFunction->getParamType(ArgPos)
3407           << FromFunction->getParamType(ArgPos);
3408     return;
3409   }
3410 
3411   // Handle different return type.
3412   if (!Context.hasSameType(FromFunction->getReturnType(),
3413                            ToFunction->getReturnType())) {
3414     PDiag << ft_return_type << ToFunction->getReturnType()
3415           << FromFunction->getReturnType();
3416     return;
3417   }
3418 
3419   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3420     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3421           << FromFunction->getMethodQuals();
3422     return;
3423   }
3424 
3425   // Handle exception specification differences on canonical type (in C++17
3426   // onwards).
3427   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3428           ->isNothrow() !=
3429       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3430           ->isNothrow()) {
3431     PDiag << ft_noexcept;
3432     return;
3433   }
3434 
3435   // Unable to find a difference, so add no extra info.
3436   PDiag << ft_default;
3437 }
3438 
FunctionParamTypesAreEqual(ArrayRef<QualType> Old,ArrayRef<QualType> New,unsigned * ArgPos,bool Reversed)3439 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3440                                       ArrayRef<QualType> New, unsigned *ArgPos,
3441                                       bool Reversed) {
3442   assert(llvm::size(Old) == llvm::size(New) &&
3443          "Can't compare parameters of functions with different number of "
3444          "parameters!");
3445 
3446   for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3447     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3448     size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3449 
3450     // Ignore address spaces in pointee type. This is to disallow overloading
3451     // on __ptr32/__ptr64 address spaces.
3452     QualType OldType =
3453         Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3454     QualType NewType =
3455         Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3456 
3457     if (!Context.hasSameType(OldType, NewType)) {
3458       if (ArgPos)
3459         *ArgPos = Idx;
3460       return false;
3461     }
3462   }
3463   return true;
3464 }
3465 
FunctionParamTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos,bool Reversed)3466 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3467                                       const FunctionProtoType *NewType,
3468                                       unsigned *ArgPos, bool Reversed) {
3469   return FunctionParamTypesAreEqual(OldType->param_types(),
3470                                     NewType->param_types(), ArgPos, Reversed);
3471 }
3472 
FunctionNonObjectParamTypesAreEqual(const FunctionDecl * OldFunction,const FunctionDecl * NewFunction,unsigned * ArgPos,bool Reversed)3473 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3474                                                const FunctionDecl *NewFunction,
3475                                                unsigned *ArgPos,
3476                                                bool Reversed) {
3477 
3478   if (OldFunction->getNumNonObjectParams() !=
3479       NewFunction->getNumNonObjectParams())
3480     return false;
3481 
3482   unsigned OldIgnore =
3483       unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3484   unsigned NewIgnore =
3485       unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3486 
3487   auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3488   auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3489 
3490   return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3491                                     NewPT->param_types().slice(NewIgnore),
3492                                     ArgPos, Reversed);
3493 }
3494 
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess,bool Diagnose)3495 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3496                                   CastKind &Kind,
3497                                   CXXCastPath& BasePath,
3498                                   bool IgnoreBaseAccess,
3499                                   bool Diagnose) {
3500   QualType FromType = From->getType();
3501   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3502 
3503   Kind = CK_BitCast;
3504 
3505   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3506       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3507           Expr::NPCK_ZeroExpression) {
3508     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3509       DiagRuntimeBehavior(From->getExprLoc(), From,
3510                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3511                             << ToType << From->getSourceRange());
3512     else if (!isUnevaluatedContext())
3513       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3514         << ToType << From->getSourceRange();
3515   }
3516   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3517     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3518       QualType FromPointeeType = FromPtrType->getPointeeType(),
3519                ToPointeeType   = ToPtrType->getPointeeType();
3520 
3521       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3522           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3523         // We must have a derived-to-base conversion. Check an
3524         // ambiguous or inaccessible conversion.
3525         unsigned InaccessibleID = 0;
3526         unsigned AmbiguousID = 0;
3527         if (Diagnose) {
3528           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3529           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3530         }
3531         if (CheckDerivedToBaseConversion(
3532                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3533                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3534                 &BasePath, IgnoreBaseAccess))
3535           return true;
3536 
3537         // The conversion was successful.
3538         Kind = CK_DerivedToBase;
3539       }
3540 
3541       if (Diagnose && !IsCStyleOrFunctionalCast &&
3542           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3543         assert(getLangOpts().MSVCCompat &&
3544                "this should only be possible with MSVCCompat!");
3545         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3546             << From->getSourceRange();
3547       }
3548     }
3549   } else if (const ObjCObjectPointerType *ToPtrType =
3550                ToType->getAs<ObjCObjectPointerType>()) {
3551     if (const ObjCObjectPointerType *FromPtrType =
3552           FromType->getAs<ObjCObjectPointerType>()) {
3553       // Objective-C++ conversions are always okay.
3554       // FIXME: We should have a different class of conversions for the
3555       // Objective-C++ implicit conversions.
3556       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3557         return false;
3558     } else if (FromType->isBlockPointerType()) {
3559       Kind = CK_BlockPointerToObjCPointerCast;
3560     } else {
3561       Kind = CK_CPointerToObjCPointerCast;
3562     }
3563   } else if (ToType->isBlockPointerType()) {
3564     if (!FromType->isBlockPointerType())
3565       Kind = CK_AnyPointerToBlockPointerCast;
3566   }
3567 
3568   // We shouldn't fall into this case unless it's valid for other
3569   // reasons.
3570   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3571     Kind = CK_NullToPointer;
3572 
3573   return false;
3574 }
3575 
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)3576 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3577                                      QualType ToType,
3578                                      bool InOverloadResolution,
3579                                      QualType &ConvertedType) {
3580   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3581   if (!ToTypePtr)
3582     return false;
3583 
3584   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3585   if (From->isNullPointerConstant(Context,
3586                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3587                                         : Expr::NPC_ValueDependentIsNull)) {
3588     ConvertedType = ToType;
3589     return true;
3590   }
3591 
3592   // Otherwise, both types have to be member pointers.
3593   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3594   if (!FromTypePtr)
3595     return false;
3596 
3597   // A pointer to member of B can be converted to a pointer to member of D,
3598   // where D is derived from B (C++ 4.11p2).
3599   CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3600   CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3601 
3602   if (!declaresSameEntity(FromClass, ToClass) &&
3603       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3604     ConvertedType = Context.getMemberPointerType(
3605         FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3606     return true;
3607   }
3608 
3609   return false;
3610 }
3611 
CheckMemberPointerConversion(QualType FromType,const MemberPointerType * ToPtrType,CastKind & Kind,CXXCastPath & BasePath,SourceLocation CheckLoc,SourceRange OpRange,bool IgnoreBaseAccess,MemberPointerConversionDirection Direction)3612 Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3613     QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3614     CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3615     bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3616   // Lock down the inheritance model right now in MS ABI, whether or not the
3617   // pointee types are the same.
3618   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3619     (void)isCompleteType(CheckLoc, FromType);
3620     (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3621   }
3622 
3623   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3624   if (!FromPtrType) {
3625     // This must be a null pointer to member pointer conversion
3626     Kind = CK_NullToMemberPointer;
3627     return MemberPointerConversionResult::Success;
3628   }
3629 
3630   // T == T, modulo cv
3631   if (Direction == MemberPointerConversionDirection::Upcast &&
3632       !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3633                                       ToPtrType->getPointeeType()))
3634     return MemberPointerConversionResult::DifferentPointee;
3635 
3636   CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3637                 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3638 
3639   auto DiagCls = [](PartialDiagnostic &PD, NestedNameSpecifier *Qual,
3640                     const CXXRecordDecl *Cls) {
3641     if (declaresSameEntity(Qual->getAsRecordDecl(), Cls))
3642       PD << Qual;
3643     else
3644       PD << QualType(Cls->getTypeForDecl(), 0);
3645   };
3646   auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3647     DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3648     DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3649     return PD;
3650   };
3651 
3652   CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3653   if (Direction == MemberPointerConversionDirection::Upcast)
3654     std::swap(Base, Derived);
3655 
3656   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3657                      /*DetectVirtual=*/true);
3658   if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3659     return MemberPointerConversionResult::NotDerived;
3660 
3661   if (Paths.isAmbiguous(
3662           Base->getTypeForDecl()->getCanonicalTypeUnqualified())) {
3663     PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3664     PD << int(Direction);
3665     DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3666     Diag(CheckLoc, PD);
3667     return MemberPointerConversionResult::Ambiguous;
3668   }
3669 
3670   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3671     PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3672     DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3673     Diag(CheckLoc, PD);
3674     return MemberPointerConversionResult::Virtual;
3675   }
3676 
3677   // Must be a base to derived member conversion.
3678   BuildBasePathArray(Paths, BasePath);
3679   Kind = Direction == MemberPointerConversionDirection::Upcast
3680              ? CK_DerivedToBaseMemberPointer
3681              : CK_BaseToDerivedMemberPointer;
3682 
3683   if (!IgnoreBaseAccess)
3684     switch (CheckBaseClassAccess(
3685         CheckLoc, Base, Derived, Paths.front(),
3686         Direction == MemberPointerConversionDirection::Upcast
3687             ? diag::err_upcast_to_inaccessible_base
3688             : diag::err_downcast_from_inaccessible_base,
3689         [&](PartialDiagnostic &PD) {
3690           NestedNameSpecifier *BaseQual = FromPtrType->getQualifier(),
3691                               *DerivedQual = ToPtrType->getQualifier();
3692           if (Direction == MemberPointerConversionDirection::Upcast)
3693             std::swap(BaseQual, DerivedQual);
3694           DiagCls(PD, DerivedQual, Derived);
3695           DiagCls(PD, BaseQual, Base);
3696         })) {
3697     case Sema::AR_accessible:
3698     case Sema::AR_delayed:
3699     case Sema::AR_dependent:
3700       // Optimistically assume that the delayed and dependent cases
3701       // will work out.
3702       break;
3703 
3704     case Sema::AR_inaccessible:
3705       return MemberPointerConversionResult::Inaccessible;
3706     }
3707 
3708   return MemberPointerConversionResult::Success;
3709 }
3710 
3711 /// Determine whether the lifetime conversion between the two given
3712 /// qualifiers sets is nontrivial.
isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,Qualifiers ToQuals)3713 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3714                                                Qualifiers ToQuals) {
3715   // Converting anything to const __unsafe_unretained is trivial.
3716   if (ToQuals.hasConst() &&
3717       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3718     return false;
3719 
3720   return true;
3721 }
3722 
3723 /// Perform a single iteration of the loop for checking if a qualification
3724 /// conversion is valid.
3725 ///
3726 /// Specifically, check whether any change between the qualifiers of \p
3727 /// FromType and \p ToType is permissible, given knowledge about whether every
3728 /// outer layer is const-qualified.
isQualificationConversionStep(QualType FromType,QualType ToType,bool CStyle,bool IsTopLevel,bool & PreviousToQualsIncludeConst,bool & ObjCLifetimeConversion,const ASTContext & Ctx)3729 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3730                                           bool CStyle, bool IsTopLevel,
3731                                           bool &PreviousToQualsIncludeConst,
3732                                           bool &ObjCLifetimeConversion,
3733                                           const ASTContext &Ctx) {
3734   Qualifiers FromQuals = FromType.getQualifiers();
3735   Qualifiers ToQuals = ToType.getQualifiers();
3736 
3737   // Ignore __unaligned qualifier.
3738   FromQuals.removeUnaligned();
3739 
3740   // Objective-C ARC:
3741   //   Check Objective-C lifetime conversions.
3742   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3743     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3744       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3745         ObjCLifetimeConversion = true;
3746       FromQuals.removeObjCLifetime();
3747       ToQuals.removeObjCLifetime();
3748     } else {
3749       // Qualification conversions cannot cast between different
3750       // Objective-C lifetime qualifiers.
3751       return false;
3752     }
3753   }
3754 
3755   // Allow addition/removal of GC attributes but not changing GC attributes.
3756   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3757       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3758     FromQuals.removeObjCGCAttr();
3759     ToQuals.removeObjCGCAttr();
3760   }
3761 
3762   // __ptrauth qualifiers must match exactly.
3763   if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3764     return false;
3765 
3766   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3767   //      2,j, and similarly for volatile.
3768   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3769     return false;
3770 
3771   // If address spaces mismatch:
3772   //  - in top level it is only valid to convert to addr space that is a
3773   //    superset in all cases apart from C-style casts where we allow
3774   //    conversions between overlapping address spaces.
3775   //  - in non-top levels it is not a valid conversion.
3776   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3777       (!IsTopLevel ||
3778        !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3779          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3780     return false;
3781 
3782   //   -- if the cv 1,j and cv 2,j are different, then const is in
3783   //      every cv for 0 < k < j.
3784   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3785       !PreviousToQualsIncludeConst)
3786     return false;
3787 
3788   // The following wording is from C++20, where the result of the conversion
3789   // is T3, not T2.
3790   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3791   //      "array of unknown bound of"
3792   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3793     return false;
3794 
3795   //   -- if the resulting P3,i is different from P1,i [...], then const is
3796   //      added to every cv 3_k for 0 < k < i.
3797   if (!CStyle && FromType->isConstantArrayType() &&
3798       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3799     return false;
3800 
3801   // Keep track of whether all prior cv-qualifiers in the "to" type
3802   // include const.
3803   PreviousToQualsIncludeConst =
3804       PreviousToQualsIncludeConst && ToQuals.hasConst();
3805   return true;
3806 }
3807 
3808 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)3809 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3810                                 bool CStyle, bool &ObjCLifetimeConversion) {
3811   FromType = Context.getCanonicalType(FromType);
3812   ToType = Context.getCanonicalType(ToType);
3813   ObjCLifetimeConversion = false;
3814 
3815   // If FromType and ToType are the same type, this is not a
3816   // qualification conversion.
3817   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3818     return false;
3819 
3820   // (C++ 4.4p4):
3821   //   A conversion can add cv-qualifiers at levels other than the first
3822   //   in multi-level pointers, subject to the following rules: [...]
3823   bool PreviousToQualsIncludeConst = true;
3824   bool UnwrappedAnyPointer = false;
3825   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3826     if (!isQualificationConversionStep(FromType, ToType, CStyle,
3827                                        !UnwrappedAnyPointer,
3828                                        PreviousToQualsIncludeConst,
3829                                        ObjCLifetimeConversion, getASTContext()))
3830       return false;
3831     UnwrappedAnyPointer = true;
3832   }
3833 
3834   // We are left with FromType and ToType being the pointee types
3835   // after unwrapping the original FromType and ToType the same number
3836   // of times. If we unwrapped any pointers, and if FromType and
3837   // ToType have the same unqualified type (since we checked
3838   // qualifiers above), then this is a qualification conversion.
3839   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3840 }
3841 
3842 /// - Determine whether this is a conversion from a scalar type to an
3843 /// atomic type.
3844 ///
3845 /// If successful, updates \c SCS's second and third steps in the conversion
3846 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)3847 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3848                                 bool InOverloadResolution,
3849                                 StandardConversionSequence &SCS,
3850                                 bool CStyle) {
3851   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3852   if (!ToAtomic)
3853     return false;
3854 
3855   StandardConversionSequence InnerSCS;
3856   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3857                             InOverloadResolution, InnerSCS,
3858                             CStyle, /*AllowObjCWritebackConversion=*/false))
3859     return false;
3860 
3861   SCS.Second = InnerSCS.Second;
3862   SCS.setToType(1, InnerSCS.getToType(1));
3863   SCS.Third = InnerSCS.Third;
3864   SCS.QualificationIncludesObjCLifetime
3865     = InnerSCS.QualificationIncludesObjCLifetime;
3866   SCS.setToType(2, InnerSCS.getToType(2));
3867   return true;
3868 }
3869 
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)3870 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3871                                               CXXConstructorDecl *Constructor,
3872                                               QualType Type) {
3873   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3874   if (CtorType->getNumParams() > 0) {
3875     QualType FirstArg = CtorType->getParamType(0);
3876     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3877       return true;
3878   }
3879   return false;
3880 }
3881 
3882 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)3883 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3884                                        CXXRecordDecl *To,
3885                                        UserDefinedConversionSequence &User,
3886                                        OverloadCandidateSet &CandidateSet,
3887                                        bool AllowExplicit) {
3888   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3889   for (auto *D : S.LookupConstructors(To)) {
3890     auto Info = getConstructorInfo(D);
3891     if (!Info)
3892       continue;
3893 
3894     bool Usable = !Info.Constructor->isInvalidDecl() &&
3895                   S.isInitListConstructor(Info.Constructor);
3896     if (Usable) {
3897       bool SuppressUserConversions = false;
3898       if (Info.ConstructorTmpl)
3899         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3900                                        /*ExplicitArgs*/ nullptr, From,
3901                                        CandidateSet, SuppressUserConversions,
3902                                        /*PartialOverloading*/ false,
3903                                        AllowExplicit);
3904       else
3905         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3906                                CandidateSet, SuppressUserConversions,
3907                                /*PartialOverloading*/ false, AllowExplicit);
3908     }
3909   }
3910 
3911   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3912 
3913   OverloadCandidateSet::iterator Best;
3914   switch (auto Result =
3915               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3916   case OR_Deleted:
3917   case OR_Success: {
3918     // Record the standard conversion we used and the conversion function.
3919     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3920     QualType ThisType = Constructor->getFunctionObjectParameterType();
3921     // Initializer lists don't have conversions as such.
3922     User.Before.setAsIdentityConversion();
3923     User.HadMultipleCandidates = HadMultipleCandidates;
3924     User.ConversionFunction = Constructor;
3925     User.FoundConversionFunction = Best->FoundDecl;
3926     User.After.setAsIdentityConversion();
3927     User.After.setFromType(ThisType);
3928     User.After.setAllToTypes(ToType);
3929     return Result;
3930   }
3931 
3932   case OR_No_Viable_Function:
3933     return OR_No_Viable_Function;
3934   case OR_Ambiguous:
3935     return OR_Ambiguous;
3936   }
3937 
3938   llvm_unreachable("Invalid OverloadResult!");
3939 }
3940 
3941 /// Determines whether there is a user-defined conversion sequence
3942 /// (C++ [over.ics.user]) that converts expression From to the type
3943 /// ToType. If such a conversion exists, User will contain the
3944 /// user-defined conversion sequence that performs such a conversion
3945 /// and this routine will return true. Otherwise, this routine returns
3946 /// false and User is unspecified.
3947 ///
3948 /// \param AllowExplicit  true if the conversion should consider C++0x
3949 /// "explicit" conversion functions as well as non-explicit conversion
3950 /// functions (C++0x [class.conv.fct]p2).
3951 ///
3952 /// \param AllowObjCConversionOnExplicit true if the conversion should
3953 /// allow an extra Objective-C pointer conversion on uses of explicit
3954 /// constructors. Requires \c AllowExplicit to also be set.
3955 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,AllowedExplicit AllowExplicit,bool AllowObjCConversionOnExplicit)3956 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3957                         UserDefinedConversionSequence &User,
3958                         OverloadCandidateSet &CandidateSet,
3959                         AllowedExplicit AllowExplicit,
3960                         bool AllowObjCConversionOnExplicit) {
3961   assert(AllowExplicit != AllowedExplicit::None ||
3962          !AllowObjCConversionOnExplicit);
3963   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3964 
3965   // Whether we will only visit constructors.
3966   bool ConstructorsOnly = false;
3967 
3968   // If the type we are conversion to is a class type, enumerate its
3969   // constructors.
3970   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3971     // C++ [over.match.ctor]p1:
3972     //   When objects of class type are direct-initialized (8.5), or
3973     //   copy-initialized from an expression of the same or a
3974     //   derived class type (8.5), overload resolution selects the
3975     //   constructor. [...] For copy-initialization, the candidate
3976     //   functions are all the converting constructors (12.3.1) of
3977     //   that class. The argument list is the expression-list within
3978     //   the parentheses of the initializer.
3979     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3980         (From->getType()->getAs<RecordType>() &&
3981          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3982       ConstructorsOnly = true;
3983 
3984     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3985       // We're not going to find any constructors.
3986     } else if (CXXRecordDecl *ToRecordDecl
3987                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3988 
3989       Expr **Args = &From;
3990       unsigned NumArgs = 1;
3991       bool ListInitializing = false;
3992       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3993         // But first, see if there is an init-list-constructor that will work.
3994         OverloadingResult Result = IsInitializerListConstructorConversion(
3995             S, From, ToType, ToRecordDecl, User, CandidateSet,
3996             AllowExplicit == AllowedExplicit::All);
3997         if (Result != OR_No_Viable_Function)
3998           return Result;
3999         // Never mind.
4000         CandidateSet.clear(
4001             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4002 
4003         // If we're list-initializing, we pass the individual elements as
4004         // arguments, not the entire list.
4005         Args = InitList->getInits();
4006         NumArgs = InitList->getNumInits();
4007         ListInitializing = true;
4008       }
4009 
4010       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4011         auto Info = getConstructorInfo(D);
4012         if (!Info)
4013           continue;
4014 
4015         bool Usable = !Info.Constructor->isInvalidDecl();
4016         if (!ListInitializing)
4017           Usable = Usable && Info.Constructor->isConvertingConstructor(
4018                                  /*AllowExplicit*/ true);
4019         if (Usable) {
4020           bool SuppressUserConversions = !ConstructorsOnly;
4021           // C++20 [over.best.ics.general]/4.5:
4022           //   if the target is the first parameter of a constructor [of class
4023           //   X] and the constructor [...] is a candidate by [...] the second
4024           //   phase of [over.match.list] when the initializer list has exactly
4025           //   one element that is itself an initializer list, [...] and the
4026           //   conversion is to X or reference to cv X, user-defined conversion
4027           //   sequences are not considered.
4028           if (SuppressUserConversions && ListInitializing) {
4029             SuppressUserConversions =
4030                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4031                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4032                                                   ToType);
4033           }
4034           if (Info.ConstructorTmpl)
4035             S.AddTemplateOverloadCandidate(
4036                 Info.ConstructorTmpl, Info.FoundDecl,
4037                 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4038                 CandidateSet, SuppressUserConversions,
4039                 /*PartialOverloading*/ false,
4040                 AllowExplicit == AllowedExplicit::All);
4041           else
4042             // Allow one user-defined conversion when user specifies a
4043             // From->ToType conversion via an static cast (c-style, etc).
4044             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4045                                    llvm::ArrayRef(Args, NumArgs), CandidateSet,
4046                                    SuppressUserConversions,
4047                                    /*PartialOverloading*/ false,
4048                                    AllowExplicit == AllowedExplicit::All);
4049         }
4050       }
4051     }
4052   }
4053 
4054   // Enumerate conversion functions, if we're allowed to.
4055   if (ConstructorsOnly || isa<InitListExpr>(From)) {
4056   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4057     // No conversion functions from incomplete types.
4058   } else if (const RecordType *FromRecordType =
4059                  From->getType()->getAs<RecordType>()) {
4060     if (CXXRecordDecl *FromRecordDecl
4061          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4062       // Add all of the conversion functions as candidates.
4063       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4064       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4065         DeclAccessPair FoundDecl = I.getPair();
4066         NamedDecl *D = FoundDecl.getDecl();
4067         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4068         if (isa<UsingShadowDecl>(D))
4069           D = cast<UsingShadowDecl>(D)->getTargetDecl();
4070 
4071         CXXConversionDecl *Conv;
4072         FunctionTemplateDecl *ConvTemplate;
4073         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4074           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4075         else
4076           Conv = cast<CXXConversionDecl>(D);
4077 
4078         if (ConvTemplate)
4079           S.AddTemplateConversionCandidate(
4080               ConvTemplate, FoundDecl, ActingContext, From, ToType,
4081               CandidateSet, AllowObjCConversionOnExplicit,
4082               AllowExplicit != AllowedExplicit::None);
4083         else
4084           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4085                                    CandidateSet, AllowObjCConversionOnExplicit,
4086                                    AllowExplicit != AllowedExplicit::None);
4087       }
4088     }
4089   }
4090 
4091   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4092 
4093   OverloadCandidateSet::iterator Best;
4094   switch (auto Result =
4095               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4096   case OR_Success:
4097   case OR_Deleted:
4098     // Record the standard conversion we used and the conversion function.
4099     if (CXXConstructorDecl *Constructor
4100           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4101       // C++ [over.ics.user]p1:
4102       //   If the user-defined conversion is specified by a
4103       //   constructor (12.3.1), the initial standard conversion
4104       //   sequence converts the source type to the type required by
4105       //   the argument of the constructor.
4106       //
4107       if (isa<InitListExpr>(From)) {
4108         // Initializer lists don't have conversions as such.
4109         User.Before.setAsIdentityConversion();
4110         User.Before.FromBracedInitList = true;
4111       } else {
4112         if (Best->Conversions[0].isEllipsis())
4113           User.EllipsisConversion = true;
4114         else {
4115           User.Before = Best->Conversions[0].Standard;
4116           User.EllipsisConversion = false;
4117         }
4118       }
4119       User.HadMultipleCandidates = HadMultipleCandidates;
4120       User.ConversionFunction = Constructor;
4121       User.FoundConversionFunction = Best->FoundDecl;
4122       User.After.setAsIdentityConversion();
4123       User.After.setFromType(Constructor->getFunctionObjectParameterType());
4124       User.After.setAllToTypes(ToType);
4125       return Result;
4126     }
4127     if (CXXConversionDecl *Conversion
4128                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
4129 
4130       assert(Best->HasFinalConversion);
4131 
4132       // C++ [over.ics.user]p1:
4133       //
4134       //   [...] If the user-defined conversion is specified by a
4135       //   conversion function (12.3.2), the initial standard
4136       //   conversion sequence converts the source type to the
4137       //   implicit object parameter of the conversion function.
4138       User.Before = Best->Conversions[0].Standard;
4139       User.HadMultipleCandidates = HadMultipleCandidates;
4140       User.ConversionFunction = Conversion;
4141       User.FoundConversionFunction = Best->FoundDecl;
4142       User.EllipsisConversion = false;
4143 
4144       // C++ [over.ics.user]p2:
4145       //   The second standard conversion sequence converts the
4146       //   result of the user-defined conversion to the target type
4147       //   for the sequence. Since an implicit conversion sequence
4148       //   is an initialization, the special rules for
4149       //   initialization by user-defined conversion apply when
4150       //   selecting the best user-defined conversion for a
4151       //   user-defined conversion sequence (see 13.3.3 and
4152       //   13.3.3.1).
4153       User.After = Best->FinalConversion;
4154       return Result;
4155     }
4156     llvm_unreachable("Not a constructor or conversion function?");
4157 
4158   case OR_No_Viable_Function:
4159     return OR_No_Viable_Function;
4160 
4161   case OR_Ambiguous:
4162     return OR_Ambiguous;
4163   }
4164 
4165   llvm_unreachable("Invalid OverloadResult!");
4166 }
4167 
4168 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)4169 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4170   ImplicitConversionSequence ICS;
4171   OverloadCandidateSet CandidateSet(From->getExprLoc(),
4172                                     OverloadCandidateSet::CSK_Normal);
4173   OverloadingResult OvResult =
4174     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4175                             CandidateSet, AllowedExplicit::None, false);
4176 
4177   if (!(OvResult == OR_Ambiguous ||
4178         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4179     return false;
4180 
4181   auto Cands = CandidateSet.CompleteCandidates(
4182       *this,
4183       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4184       From);
4185   if (OvResult == OR_Ambiguous)
4186     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4187         << From->getType() << ToType << From->getSourceRange();
4188   else { // OR_No_Viable_Function && !CandidateSet.empty()
4189     if (!RequireCompleteType(From->getBeginLoc(), ToType,
4190                              diag::err_typecheck_nonviable_condition_incomplete,
4191                              From->getType(), From->getSourceRange()))
4192       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4193           << false << From->getType() << From->getSourceRange() << ToType;
4194   }
4195 
4196   CandidateSet.NoteCandidates(
4197                               *this, From, Cands);
4198   return true;
4199 }
4200 
4201 // Helper for compareConversionFunctions that gets the FunctionType that the
4202 // conversion-operator return  value 'points' to, or nullptr.
4203 static const FunctionType *
getConversionOpReturnTyAsFunction(CXXConversionDecl * Conv)4204 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4205   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4206   const PointerType *RetPtrTy =
4207       ConvFuncTy->getReturnType()->getAs<PointerType>();
4208 
4209   if (!RetPtrTy)
4210     return nullptr;
4211 
4212   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4213 }
4214 
4215 /// Compare the user-defined conversion functions or constructors
4216 /// of two user-defined conversion sequences to determine whether any ordering
4217 /// is possible.
4218 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)4219 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4220                            FunctionDecl *Function2) {
4221   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4222   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4223   if (!Conv1 || !Conv2)
4224     return ImplicitConversionSequence::Indistinguishable;
4225 
4226   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4227     return ImplicitConversionSequence::Indistinguishable;
4228 
4229   // Objective-C++:
4230   //   If both conversion functions are implicitly-declared conversions from
4231   //   a lambda closure type to a function pointer and a block pointer,
4232   //   respectively, always prefer the conversion to a function pointer,
4233   //   because the function pointer is more lightweight and is more likely
4234   //   to keep code working.
4235   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4236     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4237     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4238     if (Block1 != Block2)
4239       return Block1 ? ImplicitConversionSequence::Worse
4240                     : ImplicitConversionSequence::Better;
4241   }
4242 
4243   // In order to support multiple calling conventions for the lambda conversion
4244   // operator (such as when the free and member function calling convention is
4245   // different), prefer the 'free' mechanism, followed by the calling-convention
4246   // of operator(). The latter is in place to support the MSVC-like solution of
4247   // defining ALL of the possible conversions in regards to calling-convention.
4248   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4249   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4250 
4251   if (Conv1FuncRet && Conv2FuncRet &&
4252       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4253     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4254     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4255 
4256     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4257     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4258 
4259     CallingConv CallOpCC =
4260         CallOp->getType()->castAs<FunctionType>()->getCallConv();
4261     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4262         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4263     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4264         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4265 
4266     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4267     for (CallingConv CC : PrefOrder) {
4268       if (Conv1CC == CC)
4269         return ImplicitConversionSequence::Better;
4270       if (Conv2CC == CC)
4271         return ImplicitConversionSequence::Worse;
4272     }
4273   }
4274 
4275   return ImplicitConversionSequence::Indistinguishable;
4276 }
4277 
hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence & ICS)4278 static bool hasDeprecatedStringLiteralToCharPtrConversion(
4279     const ImplicitConversionSequence &ICS) {
4280   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4281          (ICS.isUserDefined() &&
4282           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4283 }
4284 
4285 /// CompareImplicitConversionSequences - Compare two implicit
4286 /// conversion sequences to determine whether one is better than the
4287 /// other or if they are indistinguishable (C++ 13.3.3.2).
4288 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,SourceLocation Loc,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)4289 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4290                                    const ImplicitConversionSequence& ICS1,
4291                                    const ImplicitConversionSequence& ICS2)
4292 {
4293   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4294   // conversion sequences (as defined in 13.3.3.1)
4295   //   -- a standard conversion sequence (13.3.3.1.1) is a better
4296   //      conversion sequence than a user-defined conversion sequence or
4297   //      an ellipsis conversion sequence, and
4298   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
4299   //      conversion sequence than an ellipsis conversion sequence
4300   //      (13.3.3.1.3).
4301   //
4302   // C++0x [over.best.ics]p10:
4303   //   For the purpose of ranking implicit conversion sequences as
4304   //   described in 13.3.3.2, the ambiguous conversion sequence is
4305   //   treated as a user-defined sequence that is indistinguishable
4306   //   from any other user-defined conversion sequence.
4307 
4308   // String literal to 'char *' conversion has been deprecated in C++03. It has
4309   // been removed from C++11. We still accept this conversion, if it happens at
4310   // the best viable function. Otherwise, this conversion is considered worse
4311   // than ellipsis conversion. Consider this as an extension; this is not in the
4312   // standard. For example:
4313   //
4314   // int &f(...);    // #1
4315   // void f(char*);  // #2
4316   // void g() { int &r = f("foo"); }
4317   //
4318   // In C++03, we pick #2 as the best viable function.
4319   // In C++11, we pick #1 as the best viable function, because ellipsis
4320   // conversion is better than string-literal to char* conversion (since there
4321   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4322   // convert arguments, #2 would be the best viable function in C++11.
4323   // If the best viable function has this conversion, a warning will be issued
4324   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4325 
4326   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4327       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
4328           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
4329       // Ill-formedness must not differ
4330       ICS1.isBad() == ICS2.isBad())
4331     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
4332                ? ImplicitConversionSequence::Worse
4333                : ImplicitConversionSequence::Better;
4334 
4335   if (ICS1.getKindRank() < ICS2.getKindRank())
4336     return ImplicitConversionSequence::Better;
4337   if (ICS2.getKindRank() < ICS1.getKindRank())
4338     return ImplicitConversionSequence::Worse;
4339 
4340   // The following checks require both conversion sequences to be of
4341   // the same kind.
4342   if (ICS1.getKind() != ICS2.getKind())
4343     return ImplicitConversionSequence::Indistinguishable;
4344 
4345   ImplicitConversionSequence::CompareKind Result =
4346       ImplicitConversionSequence::Indistinguishable;
4347 
4348   // Two implicit conversion sequences of the same form are
4349   // indistinguishable conversion sequences unless one of the
4350   // following rules apply: (C++ 13.3.3.2p3):
4351 
4352   // List-initialization sequence L1 is a better conversion sequence than
4353   // list-initialization sequence L2 if:
4354   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4355   //   if not that,
4356   // — L1 and L2 convert to arrays of the same element type, and either the
4357   //   number of elements n_1 initialized by L1 is less than the number of
4358   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4359   //   an array of unknown bound and L1 does not,
4360   // even if one of the other rules in this paragraph would otherwise apply.
4361   if (!ICS1.isBad()) {
4362     bool StdInit1 = false, StdInit2 = false;
4363     if (ICS1.hasInitializerListContainerType())
4364       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
4365                                         nullptr);
4366     if (ICS2.hasInitializerListContainerType())
4367       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
4368                                         nullptr);
4369     if (StdInit1 != StdInit2)
4370       return StdInit1 ? ImplicitConversionSequence::Better
4371                       : ImplicitConversionSequence::Worse;
4372 
4373     if (ICS1.hasInitializerListContainerType() &&
4374         ICS2.hasInitializerListContainerType())
4375       if (auto *CAT1 = S.Context.getAsConstantArrayType(
4376               ICS1.getInitializerListContainerType()))
4377         if (auto *CAT2 = S.Context.getAsConstantArrayType(
4378                 ICS2.getInitializerListContainerType())) {
4379           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4380                                                CAT2->getElementType())) {
4381             // Both to arrays of the same element type
4382             if (CAT1->getSize() != CAT2->getSize())
4383               // Different sized, the smaller wins
4384               return CAT1->getSize().ult(CAT2->getSize())
4385                          ? ImplicitConversionSequence::Better
4386                          : ImplicitConversionSequence::Worse;
4387             if (ICS1.isInitializerListOfIncompleteArray() !=
4388                 ICS2.isInitializerListOfIncompleteArray())
4389               // One is incomplete, it loses
4390               return ICS2.isInitializerListOfIncompleteArray()
4391                          ? ImplicitConversionSequence::Better
4392                          : ImplicitConversionSequence::Worse;
4393           }
4394         }
4395   }
4396 
4397   if (ICS1.isStandard())
4398     // Standard conversion sequence S1 is a better conversion sequence than
4399     // standard conversion sequence S2 if [...]
4400     Result = CompareStandardConversionSequences(S, Loc,
4401                                                 ICS1.Standard, ICS2.Standard);
4402   else if (ICS1.isUserDefined()) {
4403     // User-defined conversion sequence U1 is a better conversion
4404     // sequence than another user-defined conversion sequence U2 if
4405     // they contain the same user-defined conversion function or
4406     // constructor and if the second standard conversion sequence of
4407     // U1 is better than the second standard conversion sequence of
4408     // U2 (C++ 13.3.3.2p3).
4409     if (ICS1.UserDefined.ConversionFunction ==
4410           ICS2.UserDefined.ConversionFunction)
4411       Result = CompareStandardConversionSequences(S, Loc,
4412                                                   ICS1.UserDefined.After,
4413                                                   ICS2.UserDefined.After);
4414     else
4415       Result = compareConversionFunctions(S,
4416                                           ICS1.UserDefined.ConversionFunction,
4417                                           ICS2.UserDefined.ConversionFunction);
4418   }
4419 
4420   return Result;
4421 }
4422 
4423 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4424 // determine if one is a proper subset of the other.
4425 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4426 compareStandardConversionSubsets(ASTContext &Context,
4427                                  const StandardConversionSequence& SCS1,
4428                                  const StandardConversionSequence& SCS2) {
4429   ImplicitConversionSequence::CompareKind Result
4430     = ImplicitConversionSequence::Indistinguishable;
4431 
4432   // the identity conversion sequence is considered to be a subsequence of
4433   // any non-identity conversion sequence
4434   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4435     return ImplicitConversionSequence::Better;
4436   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4437     return ImplicitConversionSequence::Worse;
4438 
4439   if (SCS1.Second != SCS2.Second) {
4440     if (SCS1.Second == ICK_Identity)
4441       Result = ImplicitConversionSequence::Better;
4442     else if (SCS2.Second == ICK_Identity)
4443       Result = ImplicitConversionSequence::Worse;
4444     else
4445       return ImplicitConversionSequence::Indistinguishable;
4446   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4447     return ImplicitConversionSequence::Indistinguishable;
4448 
4449   if (SCS1.Third == SCS2.Third) {
4450     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4451                              : ImplicitConversionSequence::Indistinguishable;
4452   }
4453 
4454   if (SCS1.Third == ICK_Identity)
4455     return Result == ImplicitConversionSequence::Worse
4456              ? ImplicitConversionSequence::Indistinguishable
4457              : ImplicitConversionSequence::Better;
4458 
4459   if (SCS2.Third == ICK_Identity)
4460     return Result == ImplicitConversionSequence::Better
4461              ? ImplicitConversionSequence::Indistinguishable
4462              : ImplicitConversionSequence::Worse;
4463 
4464   return ImplicitConversionSequence::Indistinguishable;
4465 }
4466 
4467 /// Determine whether one of the given reference bindings is better
4468 /// than the other based on what kind of bindings they are.
4469 static bool
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4470 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4471                              const StandardConversionSequence &SCS2) {
4472   // C++0x [over.ics.rank]p3b4:
4473   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4474   //      implicit object parameter of a non-static member function declared
4475   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
4476   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
4477   //      lvalue reference to a function lvalue and S2 binds an rvalue
4478   //      reference*.
4479   //
4480   // FIXME: Rvalue references. We're going rogue with the above edits,
4481   // because the semantics in the current C++0x working paper (N3225 at the
4482   // time of this writing) break the standard definition of std::forward
4483   // and std::reference_wrapper when dealing with references to functions.
4484   // Proposed wording changes submitted to CWG for consideration.
4485   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4486       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4487     return false;
4488 
4489   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4490           SCS2.IsLvalueReference) ||
4491          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4492           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4493 }
4494 
4495 enum class FixedEnumPromotion {
4496   None,
4497   ToUnderlyingType,
4498   ToPromotedUnderlyingType
4499 };
4500 
4501 /// Returns kind of fixed enum promotion the \a SCS uses.
4502 static FixedEnumPromotion
getFixedEnumPromtion(Sema & S,const StandardConversionSequence & SCS)4503 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4504 
4505   if (SCS.Second != ICK_Integral_Promotion)
4506     return FixedEnumPromotion::None;
4507 
4508   QualType FromType = SCS.getFromType();
4509   if (!FromType->isEnumeralType())
4510     return FixedEnumPromotion::None;
4511 
4512   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4513   if (!Enum->isFixed())
4514     return FixedEnumPromotion::None;
4515 
4516   QualType UnderlyingType = Enum->getIntegerType();
4517   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4518     return FixedEnumPromotion::ToUnderlyingType;
4519 
4520   return FixedEnumPromotion::ToPromotedUnderlyingType;
4521 }
4522 
4523 /// CompareStandardConversionSequences - Compare two standard
4524 /// conversion sequences to determine whether one is better than the
4525 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4526 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4527 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4528                                    const StandardConversionSequence& SCS1,
4529                                    const StandardConversionSequence& SCS2)
4530 {
4531   // Standard conversion sequence S1 is a better conversion sequence
4532   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4533 
4534   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4535   //     sequences in the canonical form defined by 13.3.3.1.1,
4536   //     excluding any Lvalue Transformation; the identity conversion
4537   //     sequence is considered to be a subsequence of any
4538   //     non-identity conversion sequence) or, if not that,
4539   if (ImplicitConversionSequence::CompareKind CK
4540         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4541     return CK;
4542 
4543   //  -- the rank of S1 is better than the rank of S2 (by the rules
4544   //     defined below), or, if not that,
4545   ImplicitConversionRank Rank1 = SCS1.getRank();
4546   ImplicitConversionRank Rank2 = SCS2.getRank();
4547   if (Rank1 < Rank2)
4548     return ImplicitConversionSequence::Better;
4549   else if (Rank2 < Rank1)
4550     return ImplicitConversionSequence::Worse;
4551 
4552   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4553   // are indistinguishable unless one of the following rules
4554   // applies:
4555 
4556   //   A conversion that is not a conversion of a pointer, or
4557   //   pointer to member, to bool is better than another conversion
4558   //   that is such a conversion.
4559   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4560     return SCS2.isPointerConversionToBool()
4561              ? ImplicitConversionSequence::Better
4562              : ImplicitConversionSequence::Worse;
4563 
4564   // C++14 [over.ics.rank]p4b2:
4565   // This is retroactively applied to C++11 by CWG 1601.
4566   //
4567   //   A conversion that promotes an enumeration whose underlying type is fixed
4568   //   to its underlying type is better than one that promotes to the promoted
4569   //   underlying type, if the two are different.
4570   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4571   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4572   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4573       FEP1 != FEP2)
4574     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4575                ? ImplicitConversionSequence::Better
4576                : ImplicitConversionSequence::Worse;
4577 
4578   // C++ [over.ics.rank]p4b2:
4579   //
4580   //   If class B is derived directly or indirectly from class A,
4581   //   conversion of B* to A* is better than conversion of B* to
4582   //   void*, and conversion of A* to void* is better than conversion
4583   //   of B* to void*.
4584   bool SCS1ConvertsToVoid
4585     = SCS1.isPointerConversionToVoidPointer(S.Context);
4586   bool SCS2ConvertsToVoid
4587     = SCS2.isPointerConversionToVoidPointer(S.Context);
4588   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4589     // Exactly one of the conversion sequences is a conversion to
4590     // a void pointer; it's the worse conversion.
4591     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4592                               : ImplicitConversionSequence::Worse;
4593   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4594     // Neither conversion sequence converts to a void pointer; compare
4595     // their derived-to-base conversions.
4596     if (ImplicitConversionSequence::CompareKind DerivedCK
4597           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4598       return DerivedCK;
4599   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4600              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4601     // Both conversion sequences are conversions to void
4602     // pointers. Compare the source types to determine if there's an
4603     // inheritance relationship in their sources.
4604     QualType FromType1 = SCS1.getFromType();
4605     QualType FromType2 = SCS2.getFromType();
4606 
4607     // Adjust the types we're converting from via the array-to-pointer
4608     // conversion, if we need to.
4609     if (SCS1.First == ICK_Array_To_Pointer)
4610       FromType1 = S.Context.getArrayDecayedType(FromType1);
4611     if (SCS2.First == ICK_Array_To_Pointer)
4612       FromType2 = S.Context.getArrayDecayedType(FromType2);
4613 
4614     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4615     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4616 
4617     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4618       return ImplicitConversionSequence::Better;
4619     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4620       return ImplicitConversionSequence::Worse;
4621 
4622     // Objective-C++: If one interface is more specific than the
4623     // other, it is the better one.
4624     const ObjCObjectPointerType* FromObjCPtr1
4625       = FromType1->getAs<ObjCObjectPointerType>();
4626     const ObjCObjectPointerType* FromObjCPtr2
4627       = FromType2->getAs<ObjCObjectPointerType>();
4628     if (FromObjCPtr1 && FromObjCPtr2) {
4629       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4630                                                           FromObjCPtr2);
4631       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4632                                                            FromObjCPtr1);
4633       if (AssignLeft != AssignRight) {
4634         return AssignLeft? ImplicitConversionSequence::Better
4635                          : ImplicitConversionSequence::Worse;
4636       }
4637     }
4638   }
4639 
4640   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4641     // Check for a better reference binding based on the kind of bindings.
4642     if (isBetterReferenceBindingKind(SCS1, SCS2))
4643       return ImplicitConversionSequence::Better;
4644     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4645       return ImplicitConversionSequence::Worse;
4646   }
4647 
4648   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4649   // bullet 3).
4650   if (ImplicitConversionSequence::CompareKind QualCK
4651         = CompareQualificationConversions(S, SCS1, SCS2))
4652     return QualCK;
4653 
4654   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4655     // C++ [over.ics.rank]p3b4:
4656     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4657     //      which the references refer are the same type except for
4658     //      top-level cv-qualifiers, and the type to which the reference
4659     //      initialized by S2 refers is more cv-qualified than the type
4660     //      to which the reference initialized by S1 refers.
4661     QualType T1 = SCS1.getToType(2);
4662     QualType T2 = SCS2.getToType(2);
4663     T1 = S.Context.getCanonicalType(T1);
4664     T2 = S.Context.getCanonicalType(T2);
4665     Qualifiers T1Quals, T2Quals;
4666     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4667     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4668     if (UnqualT1 == UnqualT2) {
4669       // Objective-C++ ARC: If the references refer to objects with different
4670       // lifetimes, prefer bindings that don't change lifetime.
4671       if (SCS1.ObjCLifetimeConversionBinding !=
4672                                           SCS2.ObjCLifetimeConversionBinding) {
4673         return SCS1.ObjCLifetimeConversionBinding
4674                                            ? ImplicitConversionSequence::Worse
4675                                            : ImplicitConversionSequence::Better;
4676       }
4677 
4678       // If the type is an array type, promote the element qualifiers to the
4679       // type for comparison.
4680       if (isa<ArrayType>(T1) && T1Quals)
4681         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4682       if (isa<ArrayType>(T2) && T2Quals)
4683         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4684       if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4685         return ImplicitConversionSequence::Better;
4686       if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4687         return ImplicitConversionSequence::Worse;
4688     }
4689   }
4690 
4691   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4692   // floating-to-integral conversion if the integral conversion
4693   // is between types of the same size.
4694   // For example:
4695   // void f(float);
4696   // void f(int);
4697   // int main {
4698   //    long a;
4699   //    f(a);
4700   // }
4701   // Here, MSVC will call f(int) instead of generating a compile error
4702   // as clang will do in standard mode.
4703   if (S.getLangOpts().MSVCCompat &&
4704       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4705       SCS1.Second == ICK_Integral_Conversion &&
4706       SCS2.Second == ICK_Floating_Integral &&
4707       S.Context.getTypeSize(SCS1.getFromType()) ==
4708           S.Context.getTypeSize(SCS1.getToType(2)))
4709     return ImplicitConversionSequence::Better;
4710 
4711   // Prefer a compatible vector conversion over a lax vector conversion
4712   // For example:
4713   //
4714   // typedef float __v4sf __attribute__((__vector_size__(16)));
4715   // void f(vector float);
4716   // void f(vector signed int);
4717   // int main() {
4718   //   __v4sf a;
4719   //   f(a);
4720   // }
4721   // Here, we'd like to choose f(vector float) and not
4722   // report an ambiguous call error
4723   if (SCS1.Second == ICK_Vector_Conversion &&
4724       SCS2.Second == ICK_Vector_Conversion) {
4725     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4726         SCS1.getFromType(), SCS1.getToType(2));
4727     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4728         SCS2.getFromType(), SCS2.getToType(2));
4729 
4730     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4731       return SCS1IsCompatibleVectorConversion
4732                  ? ImplicitConversionSequence::Better
4733                  : ImplicitConversionSequence::Worse;
4734   }
4735 
4736   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4737       SCS2.Second == ICK_SVE_Vector_Conversion) {
4738     bool SCS1IsCompatibleSVEVectorConversion =
4739         S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4740     bool SCS2IsCompatibleSVEVectorConversion =
4741         S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4742 
4743     if (SCS1IsCompatibleSVEVectorConversion !=
4744         SCS2IsCompatibleSVEVectorConversion)
4745       return SCS1IsCompatibleSVEVectorConversion
4746                  ? ImplicitConversionSequence::Better
4747                  : ImplicitConversionSequence::Worse;
4748   }
4749 
4750   if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4751       SCS2.Second == ICK_RVV_Vector_Conversion) {
4752     bool SCS1IsCompatibleRVVVectorConversion =
4753         S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4754     bool SCS2IsCompatibleRVVVectorConversion =
4755         S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4756 
4757     if (SCS1IsCompatibleRVVVectorConversion !=
4758         SCS2IsCompatibleRVVVectorConversion)
4759       return SCS1IsCompatibleRVVVectorConversion
4760                  ? ImplicitConversionSequence::Better
4761                  : ImplicitConversionSequence::Worse;
4762   }
4763   return ImplicitConversionSequence::Indistinguishable;
4764 }
4765 
4766 /// CompareQualificationConversions - Compares two standard conversion
4767 /// sequences to determine whether they can be ranked based on their
4768 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4769 static ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4770 CompareQualificationConversions(Sema &S,
4771                                 const StandardConversionSequence& SCS1,
4772                                 const StandardConversionSequence& SCS2) {
4773   // C++ [over.ics.rank]p3:
4774   //  -- S1 and S2 differ only in their qualification conversion and
4775   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4776   // [C++98]
4777   //     [...] and the cv-qualification signature of type T1 is a proper subset
4778   //     of the cv-qualification signature of type T2, and S1 is not the
4779   //     deprecated string literal array-to-pointer conversion (4.2).
4780   // [C++2a]
4781   //     [...] where T1 can be converted to T2 by a qualification conversion.
4782   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4783       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4784     return ImplicitConversionSequence::Indistinguishable;
4785 
4786   // FIXME: the example in the standard doesn't use a qualification
4787   // conversion (!)
4788   QualType T1 = SCS1.getToType(2);
4789   QualType T2 = SCS2.getToType(2);
4790   T1 = S.Context.getCanonicalType(T1);
4791   T2 = S.Context.getCanonicalType(T2);
4792   assert(!T1->isReferenceType() && !T2->isReferenceType());
4793   Qualifiers T1Quals, T2Quals;
4794   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4795   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4796 
4797   // If the types are the same, we won't learn anything by unwrapping
4798   // them.
4799   if (UnqualT1 == UnqualT2)
4800     return ImplicitConversionSequence::Indistinguishable;
4801 
4802   // Don't ever prefer a standard conversion sequence that uses the deprecated
4803   // string literal array to pointer conversion.
4804   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4805   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4806 
4807   // Objective-C++ ARC:
4808   //   Prefer qualification conversions not involving a change in lifetime
4809   //   to qualification conversions that do change lifetime.
4810   if (SCS1.QualificationIncludesObjCLifetime &&
4811       !SCS2.QualificationIncludesObjCLifetime)
4812     CanPick1 = false;
4813   if (SCS2.QualificationIncludesObjCLifetime &&
4814       !SCS1.QualificationIncludesObjCLifetime)
4815     CanPick2 = false;
4816 
4817   bool ObjCLifetimeConversion;
4818   if (CanPick1 &&
4819       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4820     CanPick1 = false;
4821   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4822   // directions, so we can't short-cut this second check in general.
4823   if (CanPick2 &&
4824       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4825     CanPick2 = false;
4826 
4827   if (CanPick1 != CanPick2)
4828     return CanPick1 ? ImplicitConversionSequence::Better
4829                     : ImplicitConversionSequence::Worse;
4830   return ImplicitConversionSequence::Indistinguishable;
4831 }
4832 
4833 /// CompareDerivedToBaseConversions - Compares two standard conversion
4834 /// sequences to determine whether they can be ranked based on their
4835 /// various kinds of derived-to-base conversions (C++
4836 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4837 /// conversions between Objective-C interface types.
4838 static ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)4839 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4840                                 const StandardConversionSequence& SCS1,
4841                                 const StandardConversionSequence& SCS2) {
4842   QualType FromType1 = SCS1.getFromType();
4843   QualType ToType1 = SCS1.getToType(1);
4844   QualType FromType2 = SCS2.getFromType();
4845   QualType ToType2 = SCS2.getToType(1);
4846 
4847   // Adjust the types we're converting from via the array-to-pointer
4848   // conversion, if we need to.
4849   if (SCS1.First == ICK_Array_To_Pointer)
4850     FromType1 = S.Context.getArrayDecayedType(FromType1);
4851   if (SCS2.First == ICK_Array_To_Pointer)
4852     FromType2 = S.Context.getArrayDecayedType(FromType2);
4853 
4854   // Canonicalize all of the types.
4855   FromType1 = S.Context.getCanonicalType(FromType1);
4856   ToType1 = S.Context.getCanonicalType(ToType1);
4857   FromType2 = S.Context.getCanonicalType(FromType2);
4858   ToType2 = S.Context.getCanonicalType(ToType2);
4859 
4860   // C++ [over.ics.rank]p4b3:
4861   //
4862   //   If class B is derived directly or indirectly from class A and
4863   //   class C is derived directly or indirectly from B,
4864   //
4865   // Compare based on pointer conversions.
4866   if (SCS1.Second == ICK_Pointer_Conversion &&
4867       SCS2.Second == ICK_Pointer_Conversion &&
4868       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4869       FromType1->isPointerType() && FromType2->isPointerType() &&
4870       ToType1->isPointerType() && ToType2->isPointerType()) {
4871     QualType FromPointee1 =
4872         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4873     QualType ToPointee1 =
4874         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4875     QualType FromPointee2 =
4876         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4877     QualType ToPointee2 =
4878         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4879 
4880     //   -- conversion of C* to B* is better than conversion of C* to A*,
4881     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4882       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4883         return ImplicitConversionSequence::Better;
4884       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4885         return ImplicitConversionSequence::Worse;
4886     }
4887 
4888     //   -- conversion of B* to A* is better than conversion of C* to A*,
4889     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4890       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4891         return ImplicitConversionSequence::Better;
4892       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4893         return ImplicitConversionSequence::Worse;
4894     }
4895   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4896              SCS2.Second == ICK_Pointer_Conversion) {
4897     const ObjCObjectPointerType *FromPtr1
4898       = FromType1->getAs<ObjCObjectPointerType>();
4899     const ObjCObjectPointerType *FromPtr2
4900       = FromType2->getAs<ObjCObjectPointerType>();
4901     const ObjCObjectPointerType *ToPtr1
4902       = ToType1->getAs<ObjCObjectPointerType>();
4903     const ObjCObjectPointerType *ToPtr2
4904       = ToType2->getAs<ObjCObjectPointerType>();
4905 
4906     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4907       // Apply the same conversion ranking rules for Objective-C pointer types
4908       // that we do for C++ pointers to class types. However, we employ the
4909       // Objective-C pseudo-subtyping relationship used for assignment of
4910       // Objective-C pointer types.
4911       bool FromAssignLeft
4912         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4913       bool FromAssignRight
4914         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4915       bool ToAssignLeft
4916         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4917       bool ToAssignRight
4918         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4919 
4920       // A conversion to an a non-id object pointer type or qualified 'id'
4921       // type is better than a conversion to 'id'.
4922       if (ToPtr1->isObjCIdType() &&
4923           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4924         return ImplicitConversionSequence::Worse;
4925       if (ToPtr2->isObjCIdType() &&
4926           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4927         return ImplicitConversionSequence::Better;
4928 
4929       // A conversion to a non-id object pointer type is better than a
4930       // conversion to a qualified 'id' type
4931       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4932         return ImplicitConversionSequence::Worse;
4933       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4934         return ImplicitConversionSequence::Better;
4935 
4936       // A conversion to an a non-Class object pointer type or qualified 'Class'
4937       // type is better than a conversion to 'Class'.
4938       if (ToPtr1->isObjCClassType() &&
4939           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4940         return ImplicitConversionSequence::Worse;
4941       if (ToPtr2->isObjCClassType() &&
4942           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4943         return ImplicitConversionSequence::Better;
4944 
4945       // A conversion to a non-Class object pointer type is better than a
4946       // conversion to a qualified 'Class' type.
4947       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4948         return ImplicitConversionSequence::Worse;
4949       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4950         return ImplicitConversionSequence::Better;
4951 
4952       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4953       if (S.Context.hasSameType(FromType1, FromType2) &&
4954           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4955           (ToAssignLeft != ToAssignRight)) {
4956         if (FromPtr1->isSpecialized()) {
4957           // "conversion of B<A> * to B * is better than conversion of B * to
4958           // C *.
4959           bool IsFirstSame =
4960               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4961           bool IsSecondSame =
4962               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4963           if (IsFirstSame) {
4964             if (!IsSecondSame)
4965               return ImplicitConversionSequence::Better;
4966           } else if (IsSecondSame)
4967             return ImplicitConversionSequence::Worse;
4968         }
4969         return ToAssignLeft? ImplicitConversionSequence::Worse
4970                            : ImplicitConversionSequence::Better;
4971       }
4972 
4973       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4974       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4975           (FromAssignLeft != FromAssignRight))
4976         return FromAssignLeft? ImplicitConversionSequence::Better
4977         : ImplicitConversionSequence::Worse;
4978     }
4979   }
4980 
4981   // Ranking of member-pointer types.
4982   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4983       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4984       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4985     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4986     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4987     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4988     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4989     CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
4990     CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
4991     CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
4992     CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
4993     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4994     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4995       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4996         return ImplicitConversionSequence::Worse;
4997       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4998         return ImplicitConversionSequence::Better;
4999     }
5000     // conversion of B::* to C::* is better than conversion of A::* to C::*
5001     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5002       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5003         return ImplicitConversionSequence::Better;
5004       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5005         return ImplicitConversionSequence::Worse;
5006     }
5007   }
5008 
5009   if (SCS1.Second == ICK_Derived_To_Base) {
5010     //   -- conversion of C to B is better than conversion of C to A,
5011     //   -- binding of an expression of type C to a reference of type
5012     //      B& is better than binding an expression of type C to a
5013     //      reference of type A&,
5014     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5015         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5016       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5017         return ImplicitConversionSequence::Better;
5018       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5019         return ImplicitConversionSequence::Worse;
5020     }
5021 
5022     //   -- conversion of B to A is better than conversion of C to A.
5023     //   -- binding of an expression of type B to a reference of type
5024     //      A& is better than binding an expression of type C to a
5025     //      reference of type A&,
5026     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5027         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5028       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5029         return ImplicitConversionSequence::Better;
5030       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5031         return ImplicitConversionSequence::Worse;
5032     }
5033   }
5034 
5035   return ImplicitConversionSequence::Indistinguishable;
5036 }
5037 
withoutUnaligned(ASTContext & Ctx,QualType T)5038 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5039   if (!T.getQualifiers().hasUnaligned())
5040     return T;
5041 
5042   Qualifiers Q;
5043   T = Ctx.getUnqualifiedArrayType(T, Q);
5044   Q.removeUnaligned();
5045   return Ctx.getQualifiedType(T, Q);
5046 }
5047 
5048 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,ReferenceConversions * ConvOut)5049 Sema::CompareReferenceRelationship(SourceLocation Loc,
5050                                    QualType OrigT1, QualType OrigT2,
5051                                    ReferenceConversions *ConvOut) {
5052   assert(!OrigT1->isReferenceType() &&
5053     "T1 must be the pointee type of the reference type");
5054   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5055 
5056   QualType T1 = Context.getCanonicalType(OrigT1);
5057   QualType T2 = Context.getCanonicalType(OrigT2);
5058   Qualifiers T1Quals, T2Quals;
5059   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5060   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5061 
5062   ReferenceConversions ConvTmp;
5063   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5064   Conv = ReferenceConversions();
5065 
5066   // C++2a [dcl.init.ref]p4:
5067   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5068   //   reference-related to "cv2 T2" if T1 is similar to T2, or
5069   //   T1 is a base class of T2.
5070   //   "cv1 T1" is reference-compatible with "cv2 T2" if
5071   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
5072   //   "pointer to cv1 T1" via a standard conversion sequence.
5073 
5074   // Check for standard conversions we can apply to pointers: derived-to-base
5075   // conversions, ObjC pointer conversions, and function pointer conversions.
5076   // (Qualification conversions are checked last.)
5077   if (UnqualT1 == UnqualT2) {
5078     // Nothing to do.
5079   } else if (isCompleteType(Loc, OrigT2) &&
5080              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5081     Conv |= ReferenceConversions::DerivedToBase;
5082   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5083            UnqualT2->isObjCObjectOrInterfaceType() &&
5084            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5085     Conv |= ReferenceConversions::ObjC;
5086   else if (UnqualT2->isFunctionType() &&
5087            IsFunctionConversion(UnqualT2, UnqualT1)) {
5088     Conv |= ReferenceConversions::Function;
5089     // No need to check qualifiers; function types don't have them.
5090     return Ref_Compatible;
5091   }
5092   bool ConvertedReferent = Conv != 0;
5093 
5094   // We can have a qualification conversion. Compute whether the types are
5095   // similar at the same time.
5096   bool PreviousToQualsIncludeConst = true;
5097   bool TopLevel = true;
5098   do {
5099     if (T1 == T2)
5100       break;
5101 
5102     // We will need a qualification conversion.
5103     Conv |= ReferenceConversions::Qualification;
5104 
5105     // Track whether we performed a qualification conversion anywhere other
5106     // than the top level. This matters for ranking reference bindings in
5107     // overload resolution.
5108     if (!TopLevel)
5109       Conv |= ReferenceConversions::NestedQualification;
5110 
5111     // MS compiler ignores __unaligned qualifier for references; do the same.
5112     T1 = withoutUnaligned(Context, T1);
5113     T2 = withoutUnaligned(Context, T2);
5114 
5115     // If we find a qualifier mismatch, the types are not reference-compatible,
5116     // but are still be reference-related if they're similar.
5117     bool ObjCLifetimeConversion = false;
5118     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5119                                        PreviousToQualsIncludeConst,
5120                                        ObjCLifetimeConversion, getASTContext()))
5121       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5122                  ? Ref_Related
5123                  : Ref_Incompatible;
5124 
5125     // FIXME: Should we track this for any level other than the first?
5126     if (ObjCLifetimeConversion)
5127       Conv |= ReferenceConversions::ObjCLifetime;
5128 
5129     TopLevel = false;
5130   } while (Context.UnwrapSimilarTypes(T1, T2));
5131 
5132   // At this point, if the types are reference-related, we must either have the
5133   // same inner type (ignoring qualifiers), or must have already worked out how
5134   // to convert the referent.
5135   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5136              ? Ref_Compatible
5137              : Ref_Incompatible;
5138 }
5139 
5140 /// Look for a user-defined conversion to a value reference-compatible
5141 ///        with DeclType. Return true if something definite is found.
5142 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)5143 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5144                          QualType DeclType, SourceLocation DeclLoc,
5145                          Expr *Init, QualType T2, bool AllowRvalues,
5146                          bool AllowExplicit) {
5147   assert(T2->isRecordType() && "Can only find conversions of record types.");
5148   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5149 
5150   OverloadCandidateSet CandidateSet(
5151       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5152   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5153   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5154     NamedDecl *D = *I;
5155     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5156     if (isa<UsingShadowDecl>(D))
5157       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5158 
5159     FunctionTemplateDecl *ConvTemplate
5160       = dyn_cast<FunctionTemplateDecl>(D);
5161     CXXConversionDecl *Conv;
5162     if (ConvTemplate)
5163       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5164     else
5165       Conv = cast<CXXConversionDecl>(D);
5166 
5167     if (AllowRvalues) {
5168       // If we are initializing an rvalue reference, don't permit conversion
5169       // functions that return lvalues.
5170       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5171         const ReferenceType *RefType
5172           = Conv->getConversionType()->getAs<LValueReferenceType>();
5173         if (RefType && !RefType->getPointeeType()->isFunctionType())
5174           continue;
5175       }
5176 
5177       if (!ConvTemplate &&
5178           S.CompareReferenceRelationship(
5179               DeclLoc,
5180               Conv->getConversionType()
5181                   .getNonReferenceType()
5182                   .getUnqualifiedType(),
5183               DeclType.getNonReferenceType().getUnqualifiedType()) ==
5184               Sema::Ref_Incompatible)
5185         continue;
5186     } else {
5187       // If the conversion function doesn't return a reference type,
5188       // it can't be considered for this conversion. An rvalue reference
5189       // is only acceptable if its referencee is a function type.
5190 
5191       const ReferenceType *RefType =
5192         Conv->getConversionType()->getAs<ReferenceType>();
5193       if (!RefType ||
5194           (!RefType->isLValueReferenceType() &&
5195            !RefType->getPointeeType()->isFunctionType()))
5196         continue;
5197     }
5198 
5199     if (ConvTemplate)
5200       S.AddTemplateConversionCandidate(
5201           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5202           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5203     else
5204       S.AddConversionCandidate(
5205           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5206           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5207   }
5208 
5209   bool HadMultipleCandidates = (CandidateSet.size() > 1);
5210 
5211   OverloadCandidateSet::iterator Best;
5212   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5213   case OR_Success:
5214 
5215     assert(Best->HasFinalConversion);
5216 
5217     // C++ [over.ics.ref]p1:
5218     //
5219     //   [...] If the parameter binds directly to the result of
5220     //   applying a conversion function to the argument
5221     //   expression, the implicit conversion sequence is a
5222     //   user-defined conversion sequence (13.3.3.1.2), with the
5223     //   second standard conversion sequence either an identity
5224     //   conversion or, if the conversion function returns an
5225     //   entity of a type that is a derived class of the parameter
5226     //   type, a derived-to-base Conversion.
5227     if (!Best->FinalConversion.DirectBinding)
5228       return false;
5229 
5230     ICS.setUserDefined();
5231     ICS.UserDefined.Before = Best->Conversions[0].Standard;
5232     ICS.UserDefined.After = Best->FinalConversion;
5233     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5234     ICS.UserDefined.ConversionFunction = Best->Function;
5235     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5236     ICS.UserDefined.EllipsisConversion = false;
5237     assert(ICS.UserDefined.After.ReferenceBinding &&
5238            ICS.UserDefined.After.DirectBinding &&
5239            "Expected a direct reference binding!");
5240     return true;
5241 
5242   case OR_Ambiguous:
5243     ICS.setAmbiguous();
5244     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5245          Cand != CandidateSet.end(); ++Cand)
5246       if (Cand->Best)
5247         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5248     return true;
5249 
5250   case OR_No_Viable_Function:
5251   case OR_Deleted:
5252     // There was no suitable conversion, or we found a deleted
5253     // conversion; continue with other checks.
5254     return false;
5255   }
5256 
5257   llvm_unreachable("Invalid OverloadResult!");
5258 }
5259 
5260 /// Compute an implicit conversion sequence for reference
5261 /// initialization.
5262 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)5263 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5264                  SourceLocation DeclLoc,
5265                  bool SuppressUserConversions,
5266                  bool AllowExplicit) {
5267   assert(DeclType->isReferenceType() && "Reference init needs a reference");
5268 
5269   // Most paths end in a failed conversion.
5270   ImplicitConversionSequence ICS;
5271   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5272 
5273   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5274   QualType T2 = Init->getType();
5275 
5276   // If the initializer is the address of an overloaded function, try
5277   // to resolve the overloaded function. If all goes well, T2 is the
5278   // type of the resulting function.
5279   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5280     DeclAccessPair Found;
5281     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
5282                                                                 false, Found))
5283       T2 = Fn->getType();
5284   }
5285 
5286   // Compute some basic properties of the types and the initializer.
5287   bool isRValRef = DeclType->isRValueReferenceType();
5288   Expr::Classification InitCategory = Init->Classify(S.Context);
5289 
5290   Sema::ReferenceConversions RefConv;
5291   Sema::ReferenceCompareResult RefRelationship =
5292       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5293 
5294   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5295     ICS.setStandard();
5296     ICS.Standard.First = ICK_Identity;
5297     // FIXME: A reference binding can be a function conversion too. We should
5298     // consider that when ordering reference-to-function bindings.
5299     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5300                               ? ICK_Derived_To_Base
5301                               : (RefConv & Sema::ReferenceConversions::ObjC)
5302                                     ? ICK_Compatible_Conversion
5303                                     : ICK_Identity;
5304     ICS.Standard.Dimension = ICK_Identity;
5305     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5306     // a reference binding that performs a non-top-level qualification
5307     // conversion as a qualification conversion, not as an identity conversion.
5308     ICS.Standard.Third = (RefConv &
5309                               Sema::ReferenceConversions::NestedQualification)
5310                              ? ICK_Qualification
5311                              : ICK_Identity;
5312     ICS.Standard.setFromType(T2);
5313     ICS.Standard.setToType(0, T2);
5314     ICS.Standard.setToType(1, T1);
5315     ICS.Standard.setToType(2, T1);
5316     ICS.Standard.ReferenceBinding = true;
5317     ICS.Standard.DirectBinding = BindsDirectly;
5318     ICS.Standard.IsLvalueReference = !isRValRef;
5319     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5320     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5321     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5322     ICS.Standard.ObjCLifetimeConversionBinding =
5323         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5324     ICS.Standard.FromBracedInitList = false;
5325     ICS.Standard.CopyConstructor = nullptr;
5326     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5327   };
5328 
5329   // C++0x [dcl.init.ref]p5:
5330   //   A reference to type "cv1 T1" is initialized by an expression
5331   //   of type "cv2 T2" as follows:
5332 
5333   //     -- If reference is an lvalue reference and the initializer expression
5334   if (!isRValRef) {
5335     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5336     //        reference-compatible with "cv2 T2," or
5337     //
5338     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5339     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5340       // C++ [over.ics.ref]p1:
5341       //   When a parameter of reference type binds directly (8.5.3)
5342       //   to an argument expression, the implicit conversion sequence
5343       //   is the identity conversion, unless the argument expression
5344       //   has a type that is a derived class of the parameter type,
5345       //   in which case the implicit conversion sequence is a
5346       //   derived-to-base Conversion (13.3.3.1).
5347       SetAsReferenceBinding(/*BindsDirectly=*/true);
5348 
5349       // Nothing more to do: the inaccessibility/ambiguity check for
5350       // derived-to-base conversions is suppressed when we're
5351       // computing the implicit conversion sequence (C++
5352       // [over.best.ics]p2).
5353       return ICS;
5354     }
5355 
5356     //       -- has a class type (i.e., T2 is a class type), where T1 is
5357     //          not reference-related to T2, and can be implicitly
5358     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
5359     //          is reference-compatible with "cv3 T3" 92) (this
5360     //          conversion is selected by enumerating the applicable
5361     //          conversion functions (13.3.1.6) and choosing the best
5362     //          one through overload resolution (13.3)),
5363     if (!SuppressUserConversions && T2->isRecordType() &&
5364         S.isCompleteType(DeclLoc, T2) &&
5365         RefRelationship == Sema::Ref_Incompatible) {
5366       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5367                                    Init, T2, /*AllowRvalues=*/false,
5368                                    AllowExplicit))
5369         return ICS;
5370     }
5371   }
5372 
5373   //     -- Otherwise, the reference shall be an lvalue reference to a
5374   //        non-volatile const type (i.e., cv1 shall be const), or the reference
5375   //        shall be an rvalue reference.
5376   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5377     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5378       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
5379     return ICS;
5380   }
5381 
5382   //       -- If the initializer expression
5383   //
5384   //            -- is an xvalue, class prvalue, array prvalue or function
5385   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5386   if (RefRelationship == Sema::Ref_Compatible &&
5387       (InitCategory.isXValue() ||
5388        (InitCategory.isPRValue() &&
5389           (T2->isRecordType() || T2->isArrayType())) ||
5390        (InitCategory.isLValue() && T2->isFunctionType()))) {
5391     // In C++11, this is always a direct binding. In C++98/03, it's a direct
5392     // binding unless we're binding to a class prvalue.
5393     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5394     // allow the use of rvalue references in C++98/03 for the benefit of
5395     // standard library implementors; therefore, we need the xvalue check here.
5396     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5397                           !(InitCategory.isPRValue() || T2->isRecordType()));
5398     return ICS;
5399   }
5400 
5401   //            -- has a class type (i.e., T2 is a class type), where T1 is not
5402   //               reference-related to T2, and can be implicitly converted to
5403   //               an xvalue, class prvalue, or function lvalue of type
5404   //               "cv3 T3", where "cv1 T1" is reference-compatible with
5405   //               "cv3 T3",
5406   //
5407   //          then the reference is bound to the value of the initializer
5408   //          expression in the first case and to the result of the conversion
5409   //          in the second case (or, in either case, to an appropriate base
5410   //          class subobject).
5411   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5412       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5413       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5414                                Init, T2, /*AllowRvalues=*/true,
5415                                AllowExplicit)) {
5416     // In the second case, if the reference is an rvalue reference
5417     // and the second standard conversion sequence of the
5418     // user-defined conversion sequence includes an lvalue-to-rvalue
5419     // conversion, the program is ill-formed.
5420     if (ICS.isUserDefined() && isRValRef &&
5421         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5422       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5423 
5424     return ICS;
5425   }
5426 
5427   // A temporary of function type cannot be created; don't even try.
5428   if (T1->isFunctionType())
5429     return ICS;
5430 
5431   //       -- Otherwise, a temporary of type "cv1 T1" is created and
5432   //          initialized from the initializer expression using the
5433   //          rules for a non-reference copy initialization (8.5). The
5434   //          reference is then bound to the temporary. If T1 is
5435   //          reference-related to T2, cv1 must be the same
5436   //          cv-qualification as, or greater cv-qualification than,
5437   //          cv2; otherwise, the program is ill-formed.
5438   if (RefRelationship == Sema::Ref_Related) {
5439     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5440     // we would be reference-compatible or reference-compatible with
5441     // added qualification. But that wasn't the case, so the reference
5442     // initialization fails.
5443     //
5444     // Note that we only want to check address spaces and cvr-qualifiers here.
5445     // ObjC GC, lifetime and unaligned qualifiers aren't important.
5446     Qualifiers T1Quals = T1.getQualifiers();
5447     Qualifiers T2Quals = T2.getQualifiers();
5448     T1Quals.removeObjCGCAttr();
5449     T1Quals.removeObjCLifetime();
5450     T2Quals.removeObjCGCAttr();
5451     T2Quals.removeObjCLifetime();
5452     // MS compiler ignores __unaligned qualifier for references; do the same.
5453     T1Quals.removeUnaligned();
5454     T2Quals.removeUnaligned();
5455     if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5456       return ICS;
5457   }
5458 
5459   // If at least one of the types is a class type, the types are not
5460   // related, and we aren't allowed any user conversions, the
5461   // reference binding fails. This case is important for breaking
5462   // recursion, since TryImplicitConversion below will attempt to
5463   // create a temporary through the use of a copy constructor.
5464   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5465       (T1->isRecordType() || T2->isRecordType()))
5466     return ICS;
5467 
5468   // If T1 is reference-related to T2 and the reference is an rvalue
5469   // reference, the initializer expression shall not be an lvalue.
5470   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5471       Init->Classify(S.Context).isLValue()) {
5472     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5473     return ICS;
5474   }
5475 
5476   // C++ [over.ics.ref]p2:
5477   //   When a parameter of reference type is not bound directly to
5478   //   an argument expression, the conversion sequence is the one
5479   //   required to convert the argument expression to the
5480   //   underlying type of the reference according to
5481   //   13.3.3.1. Conceptually, this conversion sequence corresponds
5482   //   to copy-initializing a temporary of the underlying type with
5483   //   the argument expression. Any difference in top-level
5484   //   cv-qualification is subsumed by the initialization itself
5485   //   and does not constitute a conversion.
5486   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5487                               AllowedExplicit::None,
5488                               /*InOverloadResolution=*/false,
5489                               /*CStyle=*/false,
5490                               /*AllowObjCWritebackConversion=*/false,
5491                               /*AllowObjCConversionOnExplicit=*/false);
5492 
5493   // Of course, that's still a reference binding.
5494   if (ICS.isStandard()) {
5495     ICS.Standard.ReferenceBinding = true;
5496     ICS.Standard.IsLvalueReference = !isRValRef;
5497     ICS.Standard.BindsToFunctionLvalue = false;
5498     ICS.Standard.BindsToRvalue = true;
5499     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5500     ICS.Standard.ObjCLifetimeConversionBinding = false;
5501   } else if (ICS.isUserDefined()) {
5502     const ReferenceType *LValRefType =
5503         ICS.UserDefined.ConversionFunction->getReturnType()
5504             ->getAs<LValueReferenceType>();
5505 
5506     // C++ [over.ics.ref]p3:
5507     //   Except for an implicit object parameter, for which see 13.3.1, a
5508     //   standard conversion sequence cannot be formed if it requires [...]
5509     //   binding an rvalue reference to an lvalue other than a function
5510     //   lvalue.
5511     // Note that the function case is not possible here.
5512     if (isRValRef && LValRefType) {
5513       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5514       return ICS;
5515     }
5516 
5517     ICS.UserDefined.After.ReferenceBinding = true;
5518     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5519     ICS.UserDefined.After.BindsToFunctionLvalue = false;
5520     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5521     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5522     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5523     ICS.UserDefined.After.FromBracedInitList = false;
5524   }
5525 
5526   return ICS;
5527 }
5528 
5529 static ImplicitConversionSequence
5530 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5531                       bool SuppressUserConversions,
5532                       bool InOverloadResolution,
5533                       bool AllowObjCWritebackConversion,
5534                       bool AllowExplicit = false);
5535 
5536 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5537 /// initializer list From.
5538 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)5539 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5540                   bool SuppressUserConversions,
5541                   bool InOverloadResolution,
5542                   bool AllowObjCWritebackConversion) {
5543   // C++11 [over.ics.list]p1:
5544   //   When an argument is an initializer list, it is not an expression and
5545   //   special rules apply for converting it to a parameter type.
5546 
5547   ImplicitConversionSequence Result;
5548   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5549 
5550   // We need a complete type for what follows.  With one C++20 exception,
5551   // incomplete types can never be initialized from init lists.
5552   QualType InitTy = ToType;
5553   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5554   if (AT && S.getLangOpts().CPlusPlus20)
5555     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5556       // C++20 allows list initialization of an incomplete array type.
5557       InitTy = IAT->getElementType();
5558   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5559     return Result;
5560 
5561   // C++20 [over.ics.list]/2:
5562   //   If the initializer list is a designated-initializer-list, a conversion
5563   //   is only possible if the parameter has an aggregate type
5564   //
5565   // FIXME: The exception for reference initialization here is not part of the
5566   // language rules, but follow other compilers in adding it as a tentative DR
5567   // resolution.
5568   bool IsDesignatedInit = From->hasDesignatedInit();
5569   if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5570       IsDesignatedInit)
5571     return Result;
5572 
5573   // Per DR1467 and DR2137:
5574   //   If the parameter type is an aggregate class X and the initializer list
5575   //   has a single element of type cv U, where U is X or a class derived from
5576   //   X, the implicit conversion sequence is the one required to convert the
5577   //   element to the parameter type.
5578   //
5579   //   Otherwise, if the parameter type is a character array [... ]
5580   //   and the initializer list has a single element that is an
5581   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5582   //   implicit conversion sequence is the identity conversion.
5583   if (From->getNumInits() == 1 && !IsDesignatedInit) {
5584     if (ToType->isRecordType() && ToType->isAggregateType()) {
5585       QualType InitType = From->getInit(0)->getType();
5586       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5587           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5588         return TryCopyInitialization(S, From->getInit(0), ToType,
5589                                      SuppressUserConversions,
5590                                      InOverloadResolution,
5591                                      AllowObjCWritebackConversion);
5592     }
5593 
5594     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5595       InitializedEntity Entity =
5596           InitializedEntity::InitializeParameter(S.Context, ToType,
5597                                                  /*Consumed=*/false);
5598       if (S.CanPerformCopyInitialization(Entity, From)) {
5599         Result.setStandard();
5600         Result.Standard.setAsIdentityConversion();
5601         Result.Standard.setFromType(ToType);
5602         Result.Standard.setAllToTypes(ToType);
5603         return Result;
5604       }
5605     }
5606   }
5607 
5608   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5609   // C++11 [over.ics.list]p2:
5610   //   If the parameter type is std::initializer_list<X> or "array of X" and
5611   //   all the elements can be implicitly converted to X, the implicit
5612   //   conversion sequence is the worst conversion necessary to convert an
5613   //   element of the list to X.
5614   //
5615   // C++14 [over.ics.list]p3:
5616   //   Otherwise, if the parameter type is "array of N X", if the initializer
5617   //   list has exactly N elements or if it has fewer than N elements and X is
5618   //   default-constructible, and if all the elements of the initializer list
5619   //   can be implicitly converted to X, the implicit conversion sequence is
5620   //   the worst conversion necessary to convert an element of the list to X.
5621   if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5622     unsigned e = From->getNumInits();
5623     ImplicitConversionSequence DfltElt;
5624     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5625                    QualType());
5626     QualType ContTy = ToType;
5627     bool IsUnbounded = false;
5628     if (AT) {
5629       InitTy = AT->getElementType();
5630       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5631         if (CT->getSize().ult(e)) {
5632           // Too many inits, fatally bad
5633           Result.setBad(BadConversionSequence::too_many_initializers, From,
5634                         ToType);
5635           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5636           return Result;
5637         }
5638         if (CT->getSize().ugt(e)) {
5639           // Need an init from empty {}, is there one?
5640           InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5641                                  From->getEndLoc());
5642           EmptyList.setType(S.Context.VoidTy);
5643           DfltElt = TryListConversion(
5644               S, &EmptyList, InitTy, SuppressUserConversions,
5645               InOverloadResolution, AllowObjCWritebackConversion);
5646           if (DfltElt.isBad()) {
5647             // No {} init, fatally bad
5648             Result.setBad(BadConversionSequence::too_few_initializers, From,
5649                           ToType);
5650             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5651             return Result;
5652           }
5653         }
5654       } else {
5655         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5656         IsUnbounded = true;
5657         if (!e) {
5658           // Cannot convert to zero-sized.
5659           Result.setBad(BadConversionSequence::too_few_initializers, From,
5660                         ToType);
5661           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5662           return Result;
5663         }
5664         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5665         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5666                                                 ArraySizeModifier::Normal, 0);
5667       }
5668     }
5669 
5670     Result.setStandard();
5671     Result.Standard.setAsIdentityConversion();
5672     Result.Standard.setFromType(InitTy);
5673     Result.Standard.setAllToTypes(InitTy);
5674     for (unsigned i = 0; i < e; ++i) {
5675       Expr *Init = From->getInit(i);
5676       ImplicitConversionSequence ICS = TryCopyInitialization(
5677           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5678           AllowObjCWritebackConversion);
5679 
5680       // Keep the worse conversion seen so far.
5681       // FIXME: Sequences are not totally ordered, so 'worse' can be
5682       // ambiguous. CWG has been informed.
5683       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5684                                              Result) ==
5685           ImplicitConversionSequence::Worse) {
5686         Result = ICS;
5687         // Bail as soon as we find something unconvertible.
5688         if (Result.isBad()) {
5689           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5690           return Result;
5691         }
5692       }
5693     }
5694 
5695     // If we needed any implicit {} initialization, compare that now.
5696     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5697     // has been informed that this might not be the best thing.
5698     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5699                                 S, From->getEndLoc(), DfltElt, Result) ==
5700                                 ImplicitConversionSequence::Worse)
5701       Result = DfltElt;
5702     // Record the type being initialized so that we may compare sequences
5703     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5704     return Result;
5705   }
5706 
5707   // C++14 [over.ics.list]p4:
5708   // C++11 [over.ics.list]p3:
5709   //   Otherwise, if the parameter is a non-aggregate class X and overload
5710   //   resolution chooses a single best constructor [...] the implicit
5711   //   conversion sequence is a user-defined conversion sequence. If multiple
5712   //   constructors are viable but none is better than the others, the
5713   //   implicit conversion sequence is a user-defined conversion sequence.
5714   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5715     // This function can deal with initializer lists.
5716     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5717                                     AllowedExplicit::None,
5718                                     InOverloadResolution, /*CStyle=*/false,
5719                                     AllowObjCWritebackConversion,
5720                                     /*AllowObjCConversionOnExplicit=*/false);
5721   }
5722 
5723   // C++14 [over.ics.list]p5:
5724   // C++11 [over.ics.list]p4:
5725   //   Otherwise, if the parameter has an aggregate type which can be
5726   //   initialized from the initializer list [...] the implicit conversion
5727   //   sequence is a user-defined conversion sequence.
5728   if (ToType->isAggregateType()) {
5729     // Type is an aggregate, argument is an init list. At this point it comes
5730     // down to checking whether the initialization works.
5731     // FIXME: Find out whether this parameter is consumed or not.
5732     InitializedEntity Entity =
5733         InitializedEntity::InitializeParameter(S.Context, ToType,
5734                                                /*Consumed=*/false);
5735     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5736                                                                  From)) {
5737       Result.setUserDefined();
5738       Result.UserDefined.Before.setAsIdentityConversion();
5739       // Initializer lists don't have a type.
5740       Result.UserDefined.Before.setFromType(QualType());
5741       Result.UserDefined.Before.setAllToTypes(QualType());
5742 
5743       Result.UserDefined.After.setAsIdentityConversion();
5744       Result.UserDefined.After.setFromType(ToType);
5745       Result.UserDefined.After.setAllToTypes(ToType);
5746       Result.UserDefined.ConversionFunction = nullptr;
5747     }
5748     return Result;
5749   }
5750 
5751   // C++14 [over.ics.list]p6:
5752   // C++11 [over.ics.list]p5:
5753   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5754   if (ToType->isReferenceType()) {
5755     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5756     // mention initializer lists in any way. So we go by what list-
5757     // initialization would do and try to extrapolate from that.
5758 
5759     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5760 
5761     // If the initializer list has a single element that is reference-related
5762     // to the parameter type, we initialize the reference from that.
5763     if (From->getNumInits() == 1 && !IsDesignatedInit) {
5764       Expr *Init = From->getInit(0);
5765 
5766       QualType T2 = Init->getType();
5767 
5768       // If the initializer is the address of an overloaded function, try
5769       // to resolve the overloaded function. If all goes well, T2 is the
5770       // type of the resulting function.
5771       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5772         DeclAccessPair Found;
5773         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5774                                    Init, ToType, false, Found))
5775           T2 = Fn->getType();
5776       }
5777 
5778       // Compute some basic properties of the types and the initializer.
5779       Sema::ReferenceCompareResult RefRelationship =
5780           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5781 
5782       if (RefRelationship >= Sema::Ref_Related) {
5783         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5784                                 SuppressUserConversions,
5785                                 /*AllowExplicit=*/false);
5786       }
5787     }
5788 
5789     // Otherwise, we bind the reference to a temporary created from the
5790     // initializer list.
5791     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5792                                InOverloadResolution,
5793                                AllowObjCWritebackConversion);
5794     if (Result.isFailure())
5795       return Result;
5796     assert(!Result.isEllipsis() &&
5797            "Sub-initialization cannot result in ellipsis conversion.");
5798 
5799     // Can we even bind to a temporary?
5800     if (ToType->isRValueReferenceType() ||
5801         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5802       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5803                                             Result.UserDefined.After;
5804       SCS.ReferenceBinding = true;
5805       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5806       SCS.BindsToRvalue = true;
5807       SCS.BindsToFunctionLvalue = false;
5808       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5809       SCS.ObjCLifetimeConversionBinding = false;
5810       SCS.FromBracedInitList = false;
5811 
5812     } else
5813       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5814                     From, ToType);
5815     return Result;
5816   }
5817 
5818   // C++14 [over.ics.list]p7:
5819   // C++11 [over.ics.list]p6:
5820   //   Otherwise, if the parameter type is not a class:
5821   if (!ToType->isRecordType()) {
5822     //    - if the initializer list has one element that is not itself an
5823     //      initializer list, the implicit conversion sequence is the one
5824     //      required to convert the element to the parameter type.
5825     // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5826     // single integer.
5827     unsigned NumInits = From->getNumInits();
5828     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5829         !isa<EmbedExpr>(From->getInit(0))) {
5830       Result = TryCopyInitialization(
5831           S, From->getInit(0), ToType, SuppressUserConversions,
5832           InOverloadResolution, AllowObjCWritebackConversion);
5833       if (Result.isStandard())
5834         Result.Standard.FromBracedInitList = true;
5835     }
5836     //    - if the initializer list has no elements, the implicit conversion
5837     //      sequence is the identity conversion.
5838     else if (NumInits == 0) {
5839       Result.setStandard();
5840       Result.Standard.setAsIdentityConversion();
5841       Result.Standard.setFromType(ToType);
5842       Result.Standard.setAllToTypes(ToType);
5843     }
5844     return Result;
5845   }
5846 
5847   // C++14 [over.ics.list]p8:
5848   // C++11 [over.ics.list]p7:
5849   //   In all cases other than those enumerated above, no conversion is possible
5850   return Result;
5851 }
5852 
5853 /// TryCopyInitialization - Try to copy-initialize a value of type
5854 /// ToType from the expression From. Return the implicit conversion
5855 /// sequence required to pass this argument, which may be a bad
5856 /// conversion sequence (meaning that the argument cannot be passed to
5857 /// a parameter of this type). If @p SuppressUserConversions, then we
5858 /// do not permit any user-defined conversion sequences.
5859 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)5860 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5861                       bool SuppressUserConversions,
5862                       bool InOverloadResolution,
5863                       bool AllowObjCWritebackConversion,
5864                       bool AllowExplicit) {
5865   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5866     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5867                              InOverloadResolution,AllowObjCWritebackConversion);
5868 
5869   if (ToType->isReferenceType())
5870     return TryReferenceInit(S, From, ToType,
5871                             /*FIXME:*/ From->getBeginLoc(),
5872                             SuppressUserConversions, AllowExplicit);
5873 
5874   return TryImplicitConversion(S, From, ToType,
5875                                SuppressUserConversions,
5876                                AllowedExplicit::None,
5877                                InOverloadResolution,
5878                                /*CStyle=*/false,
5879                                AllowObjCWritebackConversion,
5880                                /*AllowObjCConversionOnExplicit=*/false);
5881 }
5882 
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)5883 static bool TryCopyInitialization(const CanQualType FromQTy,
5884                                   const CanQualType ToQTy,
5885                                   Sema &S,
5886                                   SourceLocation Loc,
5887                                   ExprValueKind FromVK) {
5888   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5889   ImplicitConversionSequence ICS =
5890     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5891 
5892   return !ICS.isBad();
5893 }
5894 
5895 /// TryObjectArgumentInitialization - Try to initialize the object
5896 /// parameter of the given member function (@c Method) from the
5897 /// 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)5898 static ImplicitConversionSequence TryObjectArgumentInitialization(
5899     Sema &S, SourceLocation Loc, QualType FromType,
5900     Expr::Classification FromClassification, CXXMethodDecl *Method,
5901     const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5902     QualType ExplicitParameterType = QualType(),
5903     bool SuppressUserConversion = false) {
5904 
5905   // We need to have an object of class type.
5906   if (const auto *PT = FromType->getAs<PointerType>()) {
5907     FromType = PT->getPointeeType();
5908 
5909     // When we had a pointer, it's implicitly dereferenced, so we
5910     // better have an lvalue.
5911     assert(FromClassification.isLValue());
5912   }
5913 
5914   auto ValueKindFromClassification = [](Expr::Classification C) {
5915     if (C.isPRValue())
5916       return clang::VK_PRValue;
5917     if (C.isXValue())
5918       return VK_XValue;
5919     return clang::VK_LValue;
5920   };
5921 
5922   if (Method->isExplicitObjectMemberFunction()) {
5923     if (ExplicitParameterType.isNull())
5924       ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5925     OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5926                             ValueKindFromClassification(FromClassification));
5927     ImplicitConversionSequence ICS = TryCopyInitialization(
5928         S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5929         /*InOverloadResolution=*/true, false);
5930     if (ICS.isBad())
5931       ICS.Bad.FromExpr = nullptr;
5932     return ICS;
5933   }
5934 
5935   assert(FromType->isRecordType());
5936 
5937   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5938   // C++98 [class.dtor]p2:
5939   //   A destructor can be invoked for a const, volatile or const volatile
5940   //   object.
5941   // C++98 [over.match.funcs]p4:
5942   //   For static member functions, the implicit object parameter is considered
5943   //   to match any object (since if the function is selected, the object is
5944   //   discarded).
5945   Qualifiers Quals = Method->getMethodQualifiers();
5946   if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5947     Quals.addConst();
5948     Quals.addVolatile();
5949   }
5950 
5951   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5952 
5953   // Set up the conversion sequence as a "bad" conversion, to allow us
5954   // to exit early.
5955   ImplicitConversionSequence ICS;
5956 
5957   // C++0x [over.match.funcs]p4:
5958   //   For non-static member functions, the type of the implicit object
5959   //   parameter is
5960   //
5961   //     - "lvalue reference to cv X" for functions declared without a
5962   //        ref-qualifier or with the & ref-qualifier
5963   //     - "rvalue reference to cv X" for functions declared with the &&
5964   //        ref-qualifier
5965   //
5966   // where X is the class of which the function is a member and cv is the
5967   // cv-qualification on the member function declaration.
5968   //
5969   // However, when finding an implicit conversion sequence for the argument, we
5970   // are not allowed to perform user-defined conversions
5971   // (C++ [over.match.funcs]p5). We perform a simplified version of
5972   // reference binding here, that allows class rvalues to bind to
5973   // non-constant references.
5974 
5975   // First check the qualifiers.
5976   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5977   // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5978   if (ImplicitParamType.getCVRQualifiers() !=
5979           FromTypeCanon.getLocalCVRQualifiers() &&
5980       !ImplicitParamType.isAtLeastAsQualifiedAs(
5981           withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5982     ICS.setBad(BadConversionSequence::bad_qualifiers,
5983                FromType, ImplicitParamType);
5984     return ICS;
5985   }
5986 
5987   if (FromTypeCanon.hasAddressSpace()) {
5988     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5989     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5990     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5991                                                          S.getASTContext())) {
5992       ICS.setBad(BadConversionSequence::bad_qualifiers,
5993                  FromType, ImplicitParamType);
5994       return ICS;
5995     }
5996   }
5997 
5998   // Check that we have either the same type or a derived type. It
5999   // affects the conversion rank.
6000   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6001   ImplicitConversionKind SecondKind;
6002   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6003     SecondKind = ICK_Identity;
6004   } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6005     SecondKind = ICK_Derived_To_Base;
6006   } else if (!Method->isExplicitObjectMemberFunction()) {
6007     ICS.setBad(BadConversionSequence::unrelated_class,
6008                FromType, ImplicitParamType);
6009     return ICS;
6010   }
6011 
6012   // Check the ref-qualifier.
6013   switch (Method->getRefQualifier()) {
6014   case RQ_None:
6015     // Do nothing; we don't care about lvalueness or rvalueness.
6016     break;
6017 
6018   case RQ_LValue:
6019     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6020       // non-const lvalue reference cannot bind to an rvalue
6021       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6022                  ImplicitParamType);
6023       return ICS;
6024     }
6025     break;
6026 
6027   case RQ_RValue:
6028     if (!FromClassification.isRValue()) {
6029       // rvalue reference cannot bind to an lvalue
6030       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6031                  ImplicitParamType);
6032       return ICS;
6033     }
6034     break;
6035   }
6036 
6037   // Success. Mark this as a reference binding.
6038   ICS.setStandard();
6039   ICS.Standard.setAsIdentityConversion();
6040   ICS.Standard.Second = SecondKind;
6041   ICS.Standard.setFromType(FromType);
6042   ICS.Standard.setAllToTypes(ImplicitParamType);
6043   ICS.Standard.ReferenceBinding = true;
6044   ICS.Standard.DirectBinding = true;
6045   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6046   ICS.Standard.BindsToFunctionLvalue = false;
6047   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6048   ICS.Standard.FromBracedInitList = false;
6049   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6050     = (Method->getRefQualifier() == RQ_None);
6051   return ICS;
6052 }
6053 
6054 /// PerformObjectArgumentInitialization - Perform initialization of
6055 /// the implicit object parameter for the given Method with the given
6056 /// expression.
PerformImplicitObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)6057 ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6058     Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
6059     CXXMethodDecl *Method) {
6060   QualType FromRecordType, DestType;
6061   QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6062 
6063   Expr::Classification FromClassification;
6064   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6065     FromRecordType = PT->getPointeeType();
6066     DestType = Method->getThisType();
6067     FromClassification = Expr::Classification::makeSimpleLValue();
6068   } else {
6069     FromRecordType = From->getType();
6070     DestType = ImplicitParamRecordType;
6071     FromClassification = From->Classify(Context);
6072 
6073     // CWG2813 [expr.call]p6:
6074     //   If the function is an implicit object member function, the object
6075     //   expression of the class member access shall be a glvalue [...]
6076     if (From->isPRValue()) {
6077       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6078                                             Method->getRefQualifier() !=
6079                                                 RefQualifierKind::RQ_RValue);
6080     }
6081   }
6082 
6083   // Note that we always use the true parent context when performing
6084   // the actual argument initialization.
6085   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6086       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6087       Method->getParent());
6088   if (ICS.isBad()) {
6089     switch (ICS.Bad.Kind) {
6090     case BadConversionSequence::bad_qualifiers: {
6091       Qualifiers FromQs = FromRecordType.getQualifiers();
6092       Qualifiers ToQs = DestType.getQualifiers();
6093       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6094       if (CVR) {
6095         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6096             << Method->getDeclName() << FromRecordType << (CVR - 1)
6097             << From->getSourceRange();
6098         Diag(Method->getLocation(), diag::note_previous_decl)
6099           << Method->getDeclName();
6100         return ExprError();
6101       }
6102       break;
6103     }
6104 
6105     case BadConversionSequence::lvalue_ref_to_rvalue:
6106     case BadConversionSequence::rvalue_ref_to_lvalue: {
6107       bool IsRValueQualified =
6108         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6109       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6110           << Method->getDeclName() << FromClassification.isRValue()
6111           << IsRValueQualified;
6112       Diag(Method->getLocation(), diag::note_previous_decl)
6113         << Method->getDeclName();
6114       return ExprError();
6115     }
6116 
6117     case BadConversionSequence::no_conversion:
6118     case BadConversionSequence::unrelated_class:
6119       break;
6120 
6121     case BadConversionSequence::too_few_initializers:
6122     case BadConversionSequence::too_many_initializers:
6123       llvm_unreachable("Lists are not objects");
6124     }
6125 
6126     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6127            << ImplicitParamRecordType << FromRecordType
6128            << From->getSourceRange();
6129   }
6130 
6131   if (ICS.Standard.Second == ICK_Derived_To_Base) {
6132     ExprResult FromRes =
6133       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6134     if (FromRes.isInvalid())
6135       return ExprError();
6136     From = FromRes.get();
6137   }
6138 
6139   if (!Context.hasSameType(From->getType(), DestType)) {
6140     CastKind CK;
6141     QualType PteeTy = DestType->getPointeeType();
6142     LangAS DestAS =
6143         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6144     if (FromRecordType.getAddressSpace() != DestAS)
6145       CK = CK_AddressSpaceConversion;
6146     else
6147       CK = CK_NoOp;
6148     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6149   }
6150   return From;
6151 }
6152 
6153 /// TryContextuallyConvertToBool - Attempt to contextually convert the
6154 /// expression From to bool (C++0x [conv]p3).
6155 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)6156 TryContextuallyConvertToBool(Sema &S, Expr *From) {
6157   // C++ [dcl.init]/17.8:
6158   //   - Otherwise, if the initialization is direct-initialization, the source
6159   //     type is std::nullptr_t, and the destination type is bool, the initial
6160   //     value of the object being initialized is false.
6161   if (From->getType()->isNullPtrType())
6162     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
6163                                                         S.Context.BoolTy,
6164                                                         From->isGLValue());
6165 
6166   // All other direct-initialization of bool is equivalent to an implicit
6167   // conversion to bool in which explicit conversions are permitted.
6168   return TryImplicitConversion(S, From, S.Context.BoolTy,
6169                                /*SuppressUserConversions=*/false,
6170                                AllowedExplicit::Conversions,
6171                                /*InOverloadResolution=*/false,
6172                                /*CStyle=*/false,
6173                                /*AllowObjCWritebackConversion=*/false,
6174                                /*AllowObjCConversionOnExplicit=*/false);
6175 }
6176 
PerformContextuallyConvertToBool(Expr * From)6177 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6178   if (checkPlaceholderForOverload(*this, From))
6179     return ExprError();
6180 
6181   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
6182   if (!ICS.isBad())
6183     return PerformImplicitConversion(From, Context.BoolTy, ICS,
6184                                      AssignmentAction::Converting);
6185 
6186   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6187     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6188            << From->getType() << From->getSourceRange();
6189   return ExprError();
6190 }
6191 
6192 /// Check that the specified conversion is permitted in a converted constant
6193 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
6194 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)6195 static bool CheckConvertedConstantConversions(Sema &S,
6196                                               StandardConversionSequence &SCS) {
6197   // Since we know that the target type is an integral or unscoped enumeration
6198   // type, most conversion kinds are impossible. All possible First and Third
6199   // conversions are fine.
6200   switch (SCS.Second) {
6201   case ICK_Identity:
6202   case ICK_Integral_Promotion:
6203   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6204   case ICK_Zero_Queue_Conversion:
6205     return true;
6206 
6207   case ICK_Boolean_Conversion:
6208     // Conversion from an integral or unscoped enumeration type to bool is
6209     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6210     // conversion, so we allow it in a converted constant expression.
6211     //
6212     // FIXME: Per core issue 1407, we should not allow this, but that breaks
6213     // a lot of popular code. We should at least add a warning for this
6214     // (non-conforming) extension.
6215     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6216            SCS.getToType(2)->isBooleanType();
6217 
6218   case ICK_Pointer_Conversion:
6219   case ICK_Pointer_Member:
6220     // C++1z: null pointer conversions and null member pointer conversions are
6221     // only permitted if the source type is std::nullptr_t.
6222     return SCS.getFromType()->isNullPtrType();
6223 
6224   case ICK_Floating_Promotion:
6225   case ICK_Complex_Promotion:
6226   case ICK_Floating_Conversion:
6227   case ICK_Complex_Conversion:
6228   case ICK_Floating_Integral:
6229   case ICK_Compatible_Conversion:
6230   case ICK_Derived_To_Base:
6231   case ICK_Vector_Conversion:
6232   case ICK_SVE_Vector_Conversion:
6233   case ICK_RVV_Vector_Conversion:
6234   case ICK_HLSL_Vector_Splat:
6235   case ICK_Vector_Splat:
6236   case ICK_Complex_Real:
6237   case ICK_Block_Pointer_Conversion:
6238   case ICK_TransparentUnionConversion:
6239   case ICK_Writeback_Conversion:
6240   case ICK_Zero_Event_Conversion:
6241   case ICK_C_Only_Conversion:
6242   case ICK_Incompatible_Pointer_Conversion:
6243   case ICK_Fixed_Point_Conversion:
6244   case ICK_HLSL_Vector_Truncation:
6245     return false;
6246 
6247   case ICK_Lvalue_To_Rvalue:
6248   case ICK_Array_To_Pointer:
6249   case ICK_Function_To_Pointer:
6250   case ICK_HLSL_Array_RValue:
6251     llvm_unreachable("found a first conversion kind in Second");
6252 
6253   case ICK_Function_Conversion:
6254   case ICK_Qualification:
6255     llvm_unreachable("found a third conversion kind in Second");
6256 
6257   case ICK_Num_Conversion_Kinds:
6258     break;
6259   }
6260 
6261   llvm_unreachable("unknown conversion kind");
6262 }
6263 
6264 /// BuildConvertedConstantExpression - Check that the expression From is a
6265 /// converted constant expression of type T, perform the conversion but
6266 /// does not evaluate the expression
BuildConvertedConstantExpression(Sema & S,Expr * From,QualType T,CCEKind CCE,NamedDecl * Dest,APValue & PreNarrowingValue)6267 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6268                                                    QualType T, CCEKind CCE,
6269                                                    NamedDecl *Dest,
6270                                                    APValue &PreNarrowingValue) {
6271   assert((S.getLangOpts().CPlusPlus11 || CCE == CCEKind::TempArgStrict) &&
6272          "converted constant expression outside C++11 or TTP matching");
6273 
6274   if (checkPlaceholderForOverload(S, From))
6275     return ExprError();
6276 
6277   // C++1z [expr.const]p3:
6278   //  A converted constant expression of type T is an expression,
6279   //  implicitly converted to type T, where the converted
6280   //  expression is a constant expression and the implicit conversion
6281   //  sequence contains only [... list of conversions ...].
6282   ImplicitConversionSequence ICS =
6283       (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6284           ? TryContextuallyConvertToBool(S, From)
6285           : TryCopyInitialization(S, From, T,
6286                                   /*SuppressUserConversions=*/false,
6287                                   /*InOverloadResolution=*/false,
6288                                   /*AllowObjCWritebackConversion=*/false,
6289                                   /*AllowExplicit=*/false);
6290   StandardConversionSequence *SCS = nullptr;
6291   switch (ICS.getKind()) {
6292   case ImplicitConversionSequence::StandardConversion:
6293     SCS = &ICS.Standard;
6294     break;
6295   case ImplicitConversionSequence::UserDefinedConversion:
6296     if (T->isRecordType())
6297       SCS = &ICS.UserDefined.Before;
6298     else
6299       SCS = &ICS.UserDefined.After;
6300     break;
6301   case ImplicitConversionSequence::AmbiguousConversion:
6302   case ImplicitConversionSequence::BadConversion:
6303     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
6304       return S.Diag(From->getBeginLoc(),
6305                     diag::err_typecheck_converted_constant_expression)
6306              << From->getType() << From->getSourceRange() << T;
6307     return ExprError();
6308 
6309   case ImplicitConversionSequence::EllipsisConversion:
6310   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6311     llvm_unreachable("bad conversion in converted constant expression");
6312   }
6313 
6314   // Check that we would only use permitted conversions.
6315   if (!CheckConvertedConstantConversions(S, *SCS)) {
6316     return S.Diag(From->getBeginLoc(),
6317                   diag::err_typecheck_converted_constant_expression_disallowed)
6318            << From->getType() << From->getSourceRange() << T;
6319   }
6320   // [...] and where the reference binding (if any) binds directly.
6321   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6322     return S.Diag(From->getBeginLoc(),
6323                   diag::err_typecheck_converted_constant_expression_indirect)
6324            << From->getType() << From->getSourceRange() << T;
6325   }
6326   // 'TryCopyInitialization' returns incorrect info for attempts to bind
6327   // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6328   // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6329   // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6330   // case explicitly.
6331   if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6332     return S.Diag(From->getBeginLoc(),
6333                   diag::err_reference_bind_to_bitfield_in_cce)
6334            << From->getSourceRange();
6335   }
6336 
6337   // Usually we can simply apply the ImplicitConversionSequence we formed
6338   // earlier, but that's not guaranteed to work when initializing an object of
6339   // class type.
6340   ExprResult Result;
6341   bool IsTemplateArgument =
6342       CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6343   if (T->isRecordType()) {
6344     assert(IsTemplateArgument &&
6345            "unexpected class type converted constant expr");
6346     Result = S.PerformCopyInitialization(
6347         InitializedEntity::InitializeTemplateParameter(
6348             T, cast<NonTypeTemplateParmDecl>(Dest)),
6349         SourceLocation(), From);
6350   } else {
6351     Result =
6352         S.PerformImplicitConversion(From, T, ICS, AssignmentAction::Converting);
6353   }
6354   if (Result.isInvalid())
6355     return Result;
6356 
6357   // C++2a [intro.execution]p5:
6358   //   A full-expression is [...] a constant-expression [...]
6359   Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6360                                  /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6361                                  IsTemplateArgument);
6362   if (Result.isInvalid())
6363     return Result;
6364 
6365   // Check for a narrowing implicit conversion.
6366   bool ReturnPreNarrowingValue = false;
6367   QualType PreNarrowingType;
6368   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6369                                 PreNarrowingType)) {
6370   case NK_Variable_Narrowing:
6371     // Implicit conversion to a narrower type, and the value is not a constant
6372     // expression. We'll diagnose this in a moment.
6373   case NK_Not_Narrowing:
6374     break;
6375 
6376   case NK_Constant_Narrowing:
6377     if (CCE == CCEKind::ArrayBound &&
6378         PreNarrowingType->isIntegralOrEnumerationType() &&
6379         PreNarrowingValue.isInt()) {
6380       // Don't diagnose array bound narrowing here; we produce more precise
6381       // errors by allowing the un-narrowed value through.
6382       ReturnPreNarrowingValue = true;
6383       break;
6384     }
6385     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6386         << CCE << /*Constant*/ 1
6387         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6388     break;
6389 
6390   case NK_Dependent_Narrowing:
6391     // Implicit conversion to a narrower type, but the expression is
6392     // value-dependent so we can't tell whether it's actually narrowing.
6393     // For matching the parameters of a TTP, the conversion is ill-formed
6394     // if it may narrow.
6395     if (CCE != CCEKind::TempArgStrict)
6396       break;
6397     [[fallthrough]];
6398   case NK_Type_Narrowing:
6399     // FIXME: It would be better to diagnose that the expression is not a
6400     // constant expression.
6401     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6402         << CCE << /*Constant*/ 0 << From->getType() << T;
6403     break;
6404   }
6405   if (!ReturnPreNarrowingValue)
6406     PreNarrowingValue = {};
6407 
6408   return Result;
6409 }
6410 
6411 /// CheckConvertedConstantExpression - Check that the expression From is a
6412 /// converted constant expression of type T, perform the conversion and produce
6413 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Sema & S,Expr * From,QualType T,APValue & Value,CCEKind CCE,bool RequireInt,NamedDecl * Dest)6414 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6415                                                    QualType T, APValue &Value,
6416                                                    CCEKind CCE, bool RequireInt,
6417                                                    NamedDecl *Dest) {
6418 
6419   APValue PreNarrowingValue;
6420   ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6421                                                        PreNarrowingValue);
6422   if (Result.isInvalid() || Result.get()->isValueDependent()) {
6423     Value = APValue();
6424     return Result;
6425   }
6426   return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6427                                                RequireInt, PreNarrowingValue);
6428 }
6429 
BuildConvertedConstantExpression(Expr * From,QualType T,CCEKind CCE,NamedDecl * Dest)6430 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6431                                                   CCEKind CCE,
6432                                                   NamedDecl *Dest) {
6433   APValue PreNarrowingValue;
6434   return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6435                                             PreNarrowingValue);
6436 }
6437 
CheckConvertedConstantExpression(Expr * From,QualType T,APValue & Value,CCEKind CCE,NamedDecl * Dest)6438 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6439                                                   APValue &Value, CCEKind CCE,
6440                                                   NamedDecl *Dest) {
6441   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6442                                             Dest);
6443 }
6444 
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)6445 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6446                                                   llvm::APSInt &Value,
6447                                                   CCEKind CCE) {
6448   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6449 
6450   APValue V;
6451   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6452                                               /*Dest=*/nullptr);
6453   if (!R.isInvalid() && !R.get()->isValueDependent())
6454     Value = V.getInt();
6455   return R;
6456 }
6457 
6458 ExprResult
EvaluateConvertedConstantExpression(Expr * E,QualType T,APValue & Value,CCEKind CCE,bool RequireInt,const APValue & PreNarrowingValue)6459 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6460                                           CCEKind CCE, bool RequireInt,
6461                                           const APValue &PreNarrowingValue) {
6462 
6463   ExprResult Result = E;
6464   // Check the expression is a constant expression.
6465   SmallVector<PartialDiagnosticAt, 8> Notes;
6466   Expr::EvalResult Eval;
6467   Eval.Diag = &Notes;
6468 
6469   assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6470 
6471   ConstantExprKind Kind;
6472   if (CCE == CCEKind::TemplateArg && T->isRecordType())
6473     Kind = ConstantExprKind::ClassTemplateArgument;
6474   else if (CCE == CCEKind::TemplateArg)
6475     Kind = ConstantExprKind::NonClassTemplateArgument;
6476   else
6477     Kind = ConstantExprKind::Normal;
6478 
6479   if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6480       (RequireInt && !Eval.Val.isInt())) {
6481     // The expression can't be folded, so we can't keep it at this position in
6482     // the AST.
6483     Result = ExprError();
6484   } else {
6485     Value = Eval.Val;
6486 
6487     if (Notes.empty()) {
6488       // It's a constant expression.
6489       Expr *E = Result.get();
6490       if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6491         // We expect a ConstantExpr to have a value associated with it
6492         // by this point.
6493         assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6494                "ConstantExpr has no value associated with it");
6495         (void)CE;
6496       } else {
6497         E = ConstantExpr::Create(Context, Result.get(), Value);
6498       }
6499       if (!PreNarrowingValue.isAbsent())
6500         Value = std::move(PreNarrowingValue);
6501       return E;
6502     }
6503   }
6504 
6505   // It's not a constant expression. Produce an appropriate diagnostic.
6506   if (Notes.size() == 1 &&
6507       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6508     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6509   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6510                                    diag::note_constexpr_invalid_template_arg) {
6511     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6512     for (unsigned I = 0; I < Notes.size(); ++I)
6513       Diag(Notes[I].first, Notes[I].second);
6514   } else {
6515     Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6516         << CCE << E->getSourceRange();
6517     for (unsigned I = 0; I < Notes.size(); ++I)
6518       Diag(Notes[I].first, Notes[I].second);
6519   }
6520   return ExprError();
6521 }
6522 
6523 /// dropPointerConversions - If the given standard conversion sequence
6524 /// involves any pointer conversions, remove them.  This may change
6525 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)6526 static void dropPointerConversion(StandardConversionSequence &SCS) {
6527   if (SCS.Second == ICK_Pointer_Conversion) {
6528     SCS.Second = ICK_Identity;
6529     SCS.Dimension = ICK_Identity;
6530     SCS.Third = ICK_Identity;
6531     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6532   }
6533 }
6534 
6535 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6536 /// convert the expression From to an Objective-C pointer type.
6537 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)6538 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6539   // Do an implicit conversion to 'id'.
6540   QualType Ty = S.Context.getObjCIdType();
6541   ImplicitConversionSequence ICS
6542     = TryImplicitConversion(S, From, Ty,
6543                             // FIXME: Are these flags correct?
6544                             /*SuppressUserConversions=*/false,
6545                             AllowedExplicit::Conversions,
6546                             /*InOverloadResolution=*/false,
6547                             /*CStyle=*/false,
6548                             /*AllowObjCWritebackConversion=*/false,
6549                             /*AllowObjCConversionOnExplicit=*/true);
6550 
6551   // Strip off any final conversions to 'id'.
6552   switch (ICS.getKind()) {
6553   case ImplicitConversionSequence::BadConversion:
6554   case ImplicitConversionSequence::AmbiguousConversion:
6555   case ImplicitConversionSequence::EllipsisConversion:
6556   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6557     break;
6558 
6559   case ImplicitConversionSequence::UserDefinedConversion:
6560     dropPointerConversion(ICS.UserDefined.After);
6561     break;
6562 
6563   case ImplicitConversionSequence::StandardConversion:
6564     dropPointerConversion(ICS.Standard);
6565     break;
6566   }
6567 
6568   return ICS;
6569 }
6570 
PerformContextuallyConvertToObjCPointer(Expr * From)6571 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6572   if (checkPlaceholderForOverload(*this, From))
6573     return ExprError();
6574 
6575   QualType Ty = Context.getObjCIdType();
6576   ImplicitConversionSequence ICS =
6577     TryContextuallyConvertToObjCPointer(*this, From);
6578   if (!ICS.isBad())
6579     return PerformImplicitConversion(From, Ty, ICS,
6580                                      AssignmentAction::Converting);
6581   return ExprResult();
6582 }
6583 
GetExplicitObjectType(Sema & S,const Expr * MemExprE)6584 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6585   const Expr *Base = nullptr;
6586   assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6587          "expected a member expression");
6588 
6589   if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6590       M && !M->isImplicitAccess())
6591     Base = M->getBase();
6592   else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6593            M && !M->isImplicitAccess())
6594     Base = M->getBase();
6595 
6596   QualType T = Base ? Base->getType() : S.getCurrentThisType();
6597 
6598   if (T->isPointerType())
6599     T = T->getPointeeType();
6600 
6601   return T;
6602 }
6603 
GetExplicitObjectExpr(Sema & S,Expr * Obj,const FunctionDecl * Fun)6604 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6605                                    const FunctionDecl *Fun) {
6606   QualType ObjType = Obj->getType();
6607   if (ObjType->isPointerType()) {
6608     ObjType = ObjType->getPointeeType();
6609     Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6610                                 VK_LValue, OK_Ordinary, SourceLocation(),
6611                                 /*CanOverflow=*/false, FPOptionsOverride());
6612   }
6613   return Obj;
6614 }
6615 
InitializeExplicitObjectArgument(Sema & S,Expr * Obj,FunctionDecl * Fun)6616 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6617                                                   FunctionDecl *Fun) {
6618   Obj = GetExplicitObjectExpr(S, Obj, Fun);
6619   return S.PerformCopyInitialization(
6620       InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)),
6621       Obj->getExprLoc(), Obj);
6622 }
6623 
PrepareExplicitObjectArgument(Sema & S,CXXMethodDecl * Method,Expr * Object,MultiExprArg & Args,SmallVectorImpl<Expr * > & NewArgs)6624 static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6625                                           Expr *Object, MultiExprArg &Args,
6626                                           SmallVectorImpl<Expr *> &NewArgs) {
6627   assert(Method->isExplicitObjectMemberFunction() &&
6628          "Method is not an explicit member function");
6629   assert(NewArgs.empty() && "NewArgs should be empty");
6630 
6631   NewArgs.reserve(Args.size() + 1);
6632   Expr *This = GetExplicitObjectExpr(S, Object, Method);
6633   NewArgs.push_back(This);
6634   NewArgs.append(Args.begin(), Args.end());
6635   Args = NewArgs;
6636   return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6637       Method, Object->getBeginLoc());
6638 }
6639 
6640 /// Determine whether the provided type is an integral type, or an enumeration
6641 /// type of a permitted flavor.
match(QualType T)6642 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6643   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6644                                  : T->isIntegralOrUnscopedEnumerationType();
6645 }
6646 
6647 static ExprResult
diagnoseAmbiguousConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter,QualType T,UnresolvedSetImpl & ViableConversions)6648 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6649                             Sema::ContextualImplicitConverter &Converter,
6650                             QualType T, UnresolvedSetImpl &ViableConversions) {
6651 
6652   if (Converter.Suppress)
6653     return ExprError();
6654 
6655   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6656   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6657     CXXConversionDecl *Conv =
6658         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6659     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6660     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6661   }
6662   return From;
6663 }
6664 
6665 static bool
diagnoseNoViableConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,UnresolvedSetImpl & ExplicitConversions)6666 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6667                            Sema::ContextualImplicitConverter &Converter,
6668                            QualType T, bool HadMultipleCandidates,
6669                            UnresolvedSetImpl &ExplicitConversions) {
6670   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6671     DeclAccessPair Found = ExplicitConversions[0];
6672     CXXConversionDecl *Conversion =
6673         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6674 
6675     // The user probably meant to invoke the given explicit
6676     // conversion; use it.
6677     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6678     std::string TypeStr;
6679     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6680 
6681     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6682         << FixItHint::CreateInsertion(From->getBeginLoc(),
6683                                       "static_cast<" + TypeStr + ">(")
6684         << FixItHint::CreateInsertion(
6685                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6686     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6687 
6688     // If we aren't in a SFINAE context, build a call to the
6689     // explicit conversion function.
6690     if (SemaRef.isSFINAEContext())
6691       return true;
6692 
6693     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6694     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6695                                                        HadMultipleCandidates);
6696     if (Result.isInvalid())
6697       return true;
6698 
6699     // Replace the conversion with a RecoveryExpr, so we don't try to
6700     // instantiate it later, but can further diagnose here.
6701     Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6702                                         From, Result.get()->getType());
6703     if (Result.isInvalid())
6704       return true;
6705     From = Result.get();
6706   }
6707   return false;
6708 }
6709 
recordConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,DeclAccessPair & Found)6710 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6711                              Sema::ContextualImplicitConverter &Converter,
6712                              QualType T, bool HadMultipleCandidates,
6713                              DeclAccessPair &Found) {
6714   CXXConversionDecl *Conversion =
6715       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6716   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6717 
6718   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6719   if (!Converter.SuppressConversion) {
6720     if (SemaRef.isSFINAEContext())
6721       return true;
6722 
6723     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6724         << From->getSourceRange();
6725   }
6726 
6727   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6728                                                      HadMultipleCandidates);
6729   if (Result.isInvalid())
6730     return true;
6731   // Record usage of conversion in an implicit cast.
6732   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6733                                   CK_UserDefinedConversion, Result.get(),
6734                                   nullptr, Result.get()->getValueKind(),
6735                                   SemaRef.CurFPFeatureOverrides());
6736   return false;
6737 }
6738 
finishContextualImplicitConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter)6739 static ExprResult finishContextualImplicitConversion(
6740     Sema &SemaRef, SourceLocation Loc, Expr *From,
6741     Sema::ContextualImplicitConverter &Converter) {
6742   if (!Converter.match(From->getType()) && !Converter.Suppress)
6743     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6744         << From->getSourceRange();
6745 
6746   return SemaRef.DefaultLvalueConversion(From);
6747 }
6748 
6749 static void
collectViableConversionCandidates(Sema & SemaRef,Expr * From,QualType ToType,UnresolvedSetImpl & ViableConversions,OverloadCandidateSet & CandidateSet)6750 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6751                                   UnresolvedSetImpl &ViableConversions,
6752                                   OverloadCandidateSet &CandidateSet) {
6753   for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6754     NamedDecl *D = FoundDecl.getDecl();
6755     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6756     if (isa<UsingShadowDecl>(D))
6757       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6758 
6759     if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6760       SemaRef.AddTemplateConversionCandidate(
6761           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6762           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6763       continue;
6764     }
6765     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6766     SemaRef.AddConversionCandidate(
6767         Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6768         /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6769   }
6770 }
6771 
6772 /// Attempt to convert the given expression to a type which is accepted
6773 /// by the given converter.
6774 ///
6775 /// This routine will attempt to convert an expression of class type to a
6776 /// type accepted by the specified converter. In C++11 and before, the class
6777 /// must have a single non-explicit conversion function converting to a matching
6778 /// type. In C++1y, there can be multiple such conversion functions, but only
6779 /// one target type.
6780 ///
6781 /// \param Loc The source location of the construct that requires the
6782 /// conversion.
6783 ///
6784 /// \param From The expression we're converting from.
6785 ///
6786 /// \param Converter Used to control and diagnose the conversion process.
6787 ///
6788 /// \returns The expression, converted to an integral or enumeration type if
6789 /// successful.
PerformContextualImplicitConversion(SourceLocation Loc,Expr * From,ContextualImplicitConverter & Converter)6790 ExprResult Sema::PerformContextualImplicitConversion(
6791     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6792   // We can't perform any more checking for type-dependent expressions.
6793   if (From->isTypeDependent())
6794     return From;
6795 
6796   // Process placeholders immediately.
6797   if (From->hasPlaceholderType()) {
6798     ExprResult result = CheckPlaceholderExpr(From);
6799     if (result.isInvalid())
6800       return result;
6801     From = result.get();
6802   }
6803 
6804   // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6805   ExprResult Converted = DefaultLvalueConversion(From);
6806   QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6807   // If the expression already has a matching type, we're golden.
6808   if (Converter.match(T))
6809     return Converted;
6810 
6811   // FIXME: Check for missing '()' if T is a function type?
6812 
6813   // We can only perform contextual implicit conversions on objects of class
6814   // type.
6815   const RecordType *RecordTy = T->getAs<RecordType>();
6816   if (!RecordTy || !getLangOpts().CPlusPlus) {
6817     if (!Converter.Suppress)
6818       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6819     return From;
6820   }
6821 
6822   // We must have a complete class type.
6823   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6824     ContextualImplicitConverter &Converter;
6825     Expr *From;
6826 
6827     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6828         : Converter(Converter), From(From) {}
6829 
6830     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6831       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6832     }
6833   } IncompleteDiagnoser(Converter, From);
6834 
6835   if (Converter.Suppress ? !isCompleteType(Loc, T)
6836                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6837     return From;
6838 
6839   // Look for a conversion to an integral or enumeration type.
6840   UnresolvedSet<4>
6841       ViableConversions; // These are *potentially* viable in C++1y.
6842   UnresolvedSet<4> ExplicitConversions;
6843   const auto &Conversions =
6844       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6845 
6846   bool HadMultipleCandidates =
6847       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6848 
6849   // To check that there is only one target type, in C++1y:
6850   QualType ToType;
6851   bool HasUniqueTargetType = true;
6852 
6853   // Collect explicit or viable (potentially in C++1y) conversions.
6854   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6855     NamedDecl *D = (*I)->getUnderlyingDecl();
6856     CXXConversionDecl *Conversion;
6857     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6858     if (ConvTemplate) {
6859       if (getLangOpts().CPlusPlus14)
6860         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6861       else
6862         continue; // C++11 does not consider conversion operator templates(?).
6863     } else
6864       Conversion = cast<CXXConversionDecl>(D);
6865 
6866     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6867            "Conversion operator templates are considered potentially "
6868            "viable in C++1y");
6869 
6870     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6871     if (Converter.match(CurToType) || ConvTemplate) {
6872 
6873       if (Conversion->isExplicit()) {
6874         // FIXME: For C++1y, do we need this restriction?
6875         // cf. diagnoseNoViableConversion()
6876         if (!ConvTemplate)
6877           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6878       } else {
6879         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6880           if (ToType.isNull())
6881             ToType = CurToType.getUnqualifiedType();
6882           else if (HasUniqueTargetType &&
6883                    (CurToType.getUnqualifiedType() != ToType))
6884             HasUniqueTargetType = false;
6885         }
6886         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6887       }
6888     }
6889   }
6890 
6891   if (getLangOpts().CPlusPlus14) {
6892     // C++1y [conv]p6:
6893     // ... An expression e of class type E appearing in such a context
6894     // is said to be contextually implicitly converted to a specified
6895     // type T and is well-formed if and only if e can be implicitly
6896     // converted to a type T that is determined as follows: E is searched
6897     // for conversion functions whose return type is cv T or reference to
6898     // cv T such that T is allowed by the context. There shall be
6899     // exactly one such T.
6900 
6901     // If no unique T is found:
6902     if (ToType.isNull()) {
6903       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6904                                      HadMultipleCandidates,
6905                                      ExplicitConversions))
6906         return ExprError();
6907       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6908     }
6909 
6910     // If more than one unique Ts are found:
6911     if (!HasUniqueTargetType)
6912       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6913                                          ViableConversions);
6914 
6915     // If one unique T is found:
6916     // First, build a candidate set from the previously recorded
6917     // potentially viable conversions.
6918     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6919     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6920                                       CandidateSet);
6921 
6922     // Then, perform overload resolution over the candidate set.
6923     OverloadCandidateSet::iterator Best;
6924     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6925     case OR_Success: {
6926       // Apply this conversion.
6927       DeclAccessPair Found =
6928           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6929       if (recordConversion(*this, Loc, From, Converter, T,
6930                            HadMultipleCandidates, Found))
6931         return ExprError();
6932       break;
6933     }
6934     case OR_Ambiguous:
6935       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6936                                          ViableConversions);
6937     case OR_No_Viable_Function:
6938       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6939                                      HadMultipleCandidates,
6940                                      ExplicitConversions))
6941         return ExprError();
6942       [[fallthrough]];
6943     case OR_Deleted:
6944       // We'll complain below about a non-integral condition type.
6945       break;
6946     }
6947   } else {
6948     switch (ViableConversions.size()) {
6949     case 0: {
6950       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6951                                      HadMultipleCandidates,
6952                                      ExplicitConversions))
6953         return ExprError();
6954 
6955       // We'll complain below about a non-integral condition type.
6956       break;
6957     }
6958     case 1: {
6959       // Apply this conversion.
6960       DeclAccessPair Found = ViableConversions[0];
6961       if (recordConversion(*this, Loc, From, Converter, T,
6962                            HadMultipleCandidates, Found))
6963         return ExprError();
6964       break;
6965     }
6966     default:
6967       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6968                                          ViableConversions);
6969     }
6970   }
6971 
6972   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6973 }
6974 
6975 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6976 /// an acceptable non-member overloaded operator for a call whose
6977 /// arguments have types T1 (and, if non-empty, T2). This routine
6978 /// implements the check in C++ [over.match.oper]p3b2 concerning
6979 /// enumeration types.
IsAcceptableNonMemberOperatorCandidate(ASTContext & Context,FunctionDecl * Fn,ArrayRef<Expr * > Args)6980 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6981                                                    FunctionDecl *Fn,
6982                                                    ArrayRef<Expr *> Args) {
6983   QualType T1 = Args[0]->getType();
6984   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6985 
6986   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6987     return true;
6988 
6989   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6990     return true;
6991 
6992   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6993   if (Proto->getNumParams() < 1)
6994     return false;
6995 
6996   if (T1->isEnumeralType()) {
6997     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6998     if (Context.hasSameUnqualifiedType(T1, ArgType))
6999       return true;
7000   }
7001 
7002   if (Proto->getNumParams() < 2)
7003     return false;
7004 
7005   if (!T2.isNull() && T2->isEnumeralType()) {
7006     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7007     if (Context.hasSameUnqualifiedType(T2, ArgType))
7008       return true;
7009   }
7010 
7011   return false;
7012 }
7013 
isNonViableMultiVersionOverload(FunctionDecl * FD)7014 static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7015   if (FD->isTargetMultiVersionDefault())
7016     return false;
7017 
7018   if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7019     return FD->isTargetMultiVersion();
7020 
7021   if (!FD->isMultiVersion())
7022     return false;
7023 
7024   // Among multiple target versions consider either the default,
7025   // or the first non-default in the absence of default version.
7026   unsigned SeenAt = 0;
7027   unsigned I = 0;
7028   bool HasDefault = false;
7029   FD->getASTContext().forEachMultiversionedFunctionVersion(
7030       FD, [&](const FunctionDecl *CurFD) {
7031         if (FD == CurFD)
7032           SeenAt = I;
7033         else if (CurFD->isTargetMultiVersionDefault())
7034           HasDefault = true;
7035         ++I;
7036       });
7037   return HasDefault || SeenAt != 0;
7038 }
7039 
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,bool StrictPackMatch)7040 void Sema::AddOverloadCandidate(
7041     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7042     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7043     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7044     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7045     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7046     bool StrictPackMatch) {
7047   const FunctionProtoType *Proto
7048     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7049   assert(Proto && "Functions without a prototype cannot be overloaded");
7050   assert(!Function->getDescribedFunctionTemplate() &&
7051          "Use AddTemplateOverloadCandidate for function templates");
7052 
7053   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7054     if (!isa<CXXConstructorDecl>(Method)) {
7055       // If we get here, it's because we're calling a member function
7056       // that is named without a member access expression (e.g.,
7057       // "this->f") that was either written explicitly or created
7058       // implicitly. This can happen with a qualified call to a member
7059       // function, e.g., X::f(). We use an empty type for the implied
7060       // object argument (C++ [over.call.func]p3), and the acting context
7061       // is irrelevant.
7062       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7063                          Expr::Classification::makeSimpleLValue(), Args,
7064                          CandidateSet, SuppressUserConversions,
7065                          PartialOverloading, EarlyConversions, PO,
7066                          StrictPackMatch);
7067       return;
7068     }
7069     // We treat a constructor like a non-member function, since its object
7070     // argument doesn't participate in overload resolution.
7071   }
7072 
7073   if (!CandidateSet.isNewCandidate(Function, PO))
7074     return;
7075 
7076   // C++11 [class.copy]p11: [DR1402]
7077   //   A defaulted move constructor that is defined as deleted is ignored by
7078   //   overload resolution.
7079   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7080   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7081       Constructor->isMoveConstructor())
7082     return;
7083 
7084   // Overload resolution is always an unevaluated context.
7085   EnterExpressionEvaluationContext Unevaluated(
7086       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7087 
7088   // C++ [over.match.oper]p3:
7089   //   if no operand has a class type, only those non-member functions in the
7090   //   lookup set that have a first parameter of type T1 or "reference to
7091   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7092   //   is a right operand) a second parameter of type T2 or "reference to
7093   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
7094   //   candidate functions.
7095   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7096       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
7097     return;
7098 
7099   // Add this candidate
7100   OverloadCandidate &Candidate =
7101       CandidateSet.addCandidate(Args.size(), EarlyConversions);
7102   Candidate.FoundDecl = FoundDecl;
7103   Candidate.Function = Function;
7104   Candidate.Viable = true;
7105   Candidate.RewriteKind =
7106       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7107   Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7108   Candidate.ExplicitCallArguments = Args.size();
7109   Candidate.StrictPackMatch = StrictPackMatch;
7110 
7111   // Explicit functions are not actually candidates at all if we're not
7112   // allowing them in this context, but keep them around so we can point
7113   // to them in diagnostics.
7114   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7115     Candidate.Viable = false;
7116     Candidate.FailureKind = ovl_fail_explicit;
7117     return;
7118   }
7119 
7120   // Functions with internal linkage are only viable in the same module unit.
7121   if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7122     /// FIXME: Currently, the semantics of linkage in clang is slightly
7123     /// different from the semantics in C++ spec. In C++ spec, only names
7124     /// have linkage. So that all entities of the same should share one
7125     /// linkage. But in clang, different entities of the same could have
7126     /// different linkage.
7127     const NamedDecl *ND = Function;
7128     bool IsImplicitlyInstantiated = false;
7129     if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7130       ND = SpecInfo->getTemplate();
7131       IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7132                                  TSK_ImplicitInstantiation;
7133     }
7134 
7135     /// Don't remove inline functions with internal linkage from the overload
7136     /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7137     /// However:
7138     /// - Inline functions with internal linkage are a common pattern in
7139     ///   headers to avoid ODR issues.
7140     /// - The global module is meant to be a transition mechanism for C and C++
7141     ///   headers, and the current rules as written work against that goal.
7142     const bool IsInlineFunctionInGMF =
7143         Function->isFromGlobalModule() &&
7144         (IsImplicitlyInstantiated || Function->isInlined());
7145 
7146     if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7147       Candidate.Viable = false;
7148       Candidate.FailureKind = ovl_fail_module_mismatched;
7149       return;
7150     }
7151   }
7152 
7153   if (isNonViableMultiVersionOverload(Function)) {
7154     Candidate.Viable = false;
7155     Candidate.FailureKind = ovl_non_default_multiversion_function;
7156     return;
7157   }
7158 
7159   if (Constructor) {
7160     // C++ [class.copy]p3:
7161     //   A member function template is never instantiated to perform the copy
7162     //   of a class object to an object of its class type.
7163     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7164     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7165         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7166          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7167                        ClassType))) {
7168       Candidate.Viable = false;
7169       Candidate.FailureKind = ovl_fail_illegal_constructor;
7170       return;
7171     }
7172 
7173     // C++ [over.match.funcs]p8: (proposed DR resolution)
7174     //   A constructor inherited from class type C that has a first parameter
7175     //   of type "reference to P" (including such a constructor instantiated
7176     //   from a template) is excluded from the set of candidate functions when
7177     //   constructing an object of type cv D if the argument list has exactly
7178     //   one argument and D is reference-related to P and P is reference-related
7179     //   to C.
7180     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7181     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7182         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7183       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7184       QualType C = Context.getRecordType(Constructor->getParent());
7185       QualType D = Context.getRecordType(Shadow->getParent());
7186       SourceLocation Loc = Args.front()->getExprLoc();
7187       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7188           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7189         Candidate.Viable = false;
7190         Candidate.FailureKind = ovl_fail_inhctor_slice;
7191         return;
7192       }
7193     }
7194 
7195     // Check that the constructor is capable of constructing an object in the
7196     // destination address space.
7197     if (!Qualifiers::isAddressSpaceSupersetOf(
7198             Constructor->getMethodQualifiers().getAddressSpace(),
7199             CandidateSet.getDestAS(), getASTContext())) {
7200       Candidate.Viable = false;
7201       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7202     }
7203   }
7204 
7205   unsigned NumParams = Proto->getNumParams();
7206 
7207   // (C++ 13.3.2p2): A candidate function having fewer than m
7208   // parameters is viable only if it has an ellipsis in its parameter
7209   // list (8.3.5).
7210   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7211       !Proto->isVariadic() &&
7212       shouldEnforceArgLimit(PartialOverloading, Function)) {
7213     Candidate.Viable = false;
7214     Candidate.FailureKind = ovl_fail_too_many_arguments;
7215     return;
7216   }
7217 
7218   // (C++ 13.3.2p2): A candidate function having more than m parameters
7219   // is viable only if the (m+1)st parameter has a default argument
7220   // (8.3.6). For the purposes of overload resolution, the
7221   // parameter list is truncated on the right, so that there are
7222   // exactly m parameters.
7223   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7224   if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7225       !PartialOverloading) {
7226     // Not enough arguments.
7227     Candidate.Viable = false;
7228     Candidate.FailureKind = ovl_fail_too_few_arguments;
7229     return;
7230   }
7231 
7232   // (CUDA B.1): Check for invalid calls between targets.
7233   if (getLangOpts().CUDA) {
7234     const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7235     // Skip the check for callers that are implicit members, because in this
7236     // case we may not yet know what the member's target is; the target is
7237     // inferred for the member automatically, based on the bases and fields of
7238     // the class.
7239     if (!(Caller && Caller->isImplicit()) &&
7240         !CUDA().IsAllowedCall(Caller, Function)) {
7241       Candidate.Viable = false;
7242       Candidate.FailureKind = ovl_fail_bad_target;
7243       return;
7244     }
7245   }
7246 
7247   if (Function->getTrailingRequiresClause()) {
7248     ConstraintSatisfaction Satisfaction;
7249     if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7250                                  /*ForOverloadResolution*/ true) ||
7251         !Satisfaction.IsSatisfied) {
7252       Candidate.Viable = false;
7253       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7254       return;
7255     }
7256   }
7257 
7258   assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7259   // Determine the implicit conversion sequences for each of the
7260   // arguments.
7261   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7262     unsigned ConvIdx =
7263         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7264     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7265       // We already formed a conversion sequence for this parameter during
7266       // template argument deduction.
7267     } else if (ArgIdx < NumParams) {
7268       // (C++ 13.3.2p3): for F to be a viable function, there shall
7269       // exist for each argument an implicit conversion sequence
7270       // (13.3.3.1) that converts that argument to the corresponding
7271       // parameter of F.
7272       QualType ParamType = Proto->getParamType(ArgIdx);
7273       auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7274       if (ParamABI == ParameterABI::HLSLOut ||
7275           ParamABI == ParameterABI::HLSLInOut)
7276         ParamType = ParamType.getNonReferenceType();
7277       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7278           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7279           /*InOverloadResolution=*/true,
7280           /*AllowObjCWritebackConversion=*/
7281           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7282       if (Candidate.Conversions[ConvIdx].isBad()) {
7283         Candidate.Viable = false;
7284         Candidate.FailureKind = ovl_fail_bad_conversion;
7285         return;
7286       }
7287     } else {
7288       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7289       // argument for which there is no corresponding parameter is
7290       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7291       Candidate.Conversions[ConvIdx].setEllipsis();
7292     }
7293   }
7294 
7295   if (EnableIfAttr *FailedAttr =
7296           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7297     Candidate.Viable = false;
7298     Candidate.FailureKind = ovl_fail_enable_if;
7299     Candidate.DeductionFailure.Data = FailedAttr;
7300     return;
7301   }
7302 }
7303 
7304 ObjCMethodDecl *
SelectBestMethod(Selector Sel,MultiExprArg Args,bool IsInstance,SmallVectorImpl<ObjCMethodDecl * > & Methods)7305 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7306                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7307   if (Methods.size() <= 1)
7308     return nullptr;
7309 
7310   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7311     bool Match = true;
7312     ObjCMethodDecl *Method = Methods[b];
7313     unsigned NumNamedArgs = Sel.getNumArgs();
7314     // Method might have more arguments than selector indicates. This is due
7315     // to addition of c-style arguments in method.
7316     if (Method->param_size() > NumNamedArgs)
7317       NumNamedArgs = Method->param_size();
7318     if (Args.size() < NumNamedArgs)
7319       continue;
7320 
7321     for (unsigned i = 0; i < NumNamedArgs; i++) {
7322       // We can't do any type-checking on a type-dependent argument.
7323       if (Args[i]->isTypeDependent()) {
7324         Match = false;
7325         break;
7326       }
7327 
7328       ParmVarDecl *param = Method->parameters()[i];
7329       Expr *argExpr = Args[i];
7330       assert(argExpr && "SelectBestMethod(): missing expression");
7331 
7332       // Strip the unbridged-cast placeholder expression off unless it's
7333       // a consumed argument.
7334       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7335           !param->hasAttr<CFConsumedAttr>())
7336         argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7337 
7338       // If the parameter is __unknown_anytype, move on to the next method.
7339       if (param->getType() == Context.UnknownAnyTy) {
7340         Match = false;
7341         break;
7342       }
7343 
7344       ImplicitConversionSequence ConversionState
7345         = TryCopyInitialization(*this, argExpr, param->getType(),
7346                                 /*SuppressUserConversions*/false,
7347                                 /*InOverloadResolution=*/true,
7348                                 /*AllowObjCWritebackConversion=*/
7349                                 getLangOpts().ObjCAutoRefCount,
7350                                 /*AllowExplicit*/false);
7351       // This function looks for a reasonably-exact match, so we consider
7352       // incompatible pointer conversions to be a failure here.
7353       if (ConversionState.isBad() ||
7354           (ConversionState.isStandard() &&
7355            ConversionState.Standard.Second ==
7356                ICK_Incompatible_Pointer_Conversion)) {
7357         Match = false;
7358         break;
7359       }
7360     }
7361     // Promote additional arguments to variadic methods.
7362     if (Match && Method->isVariadic()) {
7363       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7364         if (Args[i]->isTypeDependent()) {
7365           Match = false;
7366           break;
7367         }
7368         ExprResult Arg = DefaultVariadicArgumentPromotion(
7369             Args[i], VariadicCallType::Method, nullptr);
7370         if (Arg.isInvalid()) {
7371           Match = false;
7372           break;
7373         }
7374       }
7375     } else {
7376       // Check for extra arguments to non-variadic methods.
7377       if (Args.size() != NumNamedArgs)
7378         Match = false;
7379       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7380         // Special case when selectors have no argument. In this case, select
7381         // one with the most general result type of 'id'.
7382         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7383           QualType ReturnT = Methods[b]->getReturnType();
7384           if (ReturnT->isObjCIdType())
7385             return Methods[b];
7386         }
7387       }
7388     }
7389 
7390     if (Match)
7391       return Method;
7392   }
7393   return nullptr;
7394 }
7395 
convertArgsForAvailabilityChecks(Sema & S,FunctionDecl * Function,Expr * ThisArg,SourceLocation CallLoc,ArrayRef<Expr * > Args,Sema::SFINAETrap & Trap,bool MissingImplicitThis,Expr * & ConvertedThis,SmallVectorImpl<Expr * > & ConvertedArgs)7396 static bool convertArgsForAvailabilityChecks(
7397     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7398     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7399     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7400   if (ThisArg) {
7401     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7402     assert(!isa<CXXConstructorDecl>(Method) &&
7403            "Shouldn't have `this` for ctors!");
7404     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7405     ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7406         ThisArg, /*Qualifier=*/nullptr, Method, Method);
7407     if (R.isInvalid())
7408       return false;
7409     ConvertedThis = R.get();
7410   } else {
7411     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7412       (void)MD;
7413       assert((MissingImplicitThis || MD->isStatic() ||
7414               isa<CXXConstructorDecl>(MD)) &&
7415              "Expected `this` for non-ctor instance methods");
7416     }
7417     ConvertedThis = nullptr;
7418   }
7419 
7420   // Ignore any variadic arguments. Converting them is pointless, since the
7421   // user can't refer to them in the function condition.
7422   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7423 
7424   // Convert the arguments.
7425   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7426     ExprResult R;
7427     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
7428                                         S.Context, Function->getParamDecl(I)),
7429                                     SourceLocation(), Args[I]);
7430 
7431     if (R.isInvalid())
7432       return false;
7433 
7434     ConvertedArgs.push_back(R.get());
7435   }
7436 
7437   if (Trap.hasErrorOccurred())
7438     return false;
7439 
7440   // Push default arguments if needed.
7441   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7442     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7443       ParmVarDecl *P = Function->getParamDecl(i);
7444       if (!P->hasDefaultArg())
7445         return false;
7446       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7447       if (R.isInvalid())
7448         return false;
7449       ConvertedArgs.push_back(R.get());
7450     }
7451 
7452     if (Trap.hasErrorOccurred())
7453       return false;
7454   }
7455   return true;
7456 }
7457 
CheckEnableIf(FunctionDecl * Function,SourceLocation CallLoc,ArrayRef<Expr * > Args,bool MissingImplicitThis)7458 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7459                                   SourceLocation CallLoc,
7460                                   ArrayRef<Expr *> Args,
7461                                   bool MissingImplicitThis) {
7462   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7463   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7464     return nullptr;
7465 
7466   SFINAETrap Trap(*this);
7467   SmallVector<Expr *, 16> ConvertedArgs;
7468   // FIXME: We should look into making enable_if late-parsed.
7469   Expr *DiscardedThis;
7470   if (!convertArgsForAvailabilityChecks(
7471           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7472           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7473     return *EnableIfAttrs.begin();
7474 
7475   for (auto *EIA : EnableIfAttrs) {
7476     APValue Result;
7477     // FIXME: This doesn't consider value-dependent cases, because doing so is
7478     // very difficult. Ideally, we should handle them more gracefully.
7479     if (EIA->getCond()->isValueDependent() ||
7480         !EIA->getCond()->EvaluateWithSubstitution(
7481             Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7482       return EIA;
7483 
7484     if (!Result.isInt() || !Result.getInt().getBoolValue())
7485       return EIA;
7486   }
7487   return nullptr;
7488 }
7489 
7490 template <typename CheckFn>
diagnoseDiagnoseIfAttrsWith(Sema & S,const NamedDecl * ND,bool ArgDependent,SourceLocation Loc,CheckFn && IsSuccessful)7491 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7492                                         bool ArgDependent, SourceLocation Loc,
7493                                         CheckFn &&IsSuccessful) {
7494   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7495   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7496     if (ArgDependent == DIA->getArgDependent())
7497       Attrs.push_back(DIA);
7498   }
7499 
7500   // Common case: No diagnose_if attributes, so we can quit early.
7501   if (Attrs.empty())
7502     return false;
7503 
7504   auto WarningBegin = std::stable_partition(
7505       Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7506         return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7507                DIA->getWarningGroup().empty();
7508       });
7509 
7510   // Note that diagnose_if attributes are late-parsed, so they appear in the
7511   // correct order (unlike enable_if attributes).
7512   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7513                                IsSuccessful);
7514   if (ErrAttr != WarningBegin) {
7515     const DiagnoseIfAttr *DIA = *ErrAttr;
7516     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7517     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7518         << DIA->getParent() << DIA->getCond()->getSourceRange();
7519     return true;
7520   }
7521 
7522   auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7523     switch (Sev) {
7524     case DiagnoseIfAttr::DS_warning:
7525       return diag::Severity::Warning;
7526     case DiagnoseIfAttr::DS_error:
7527       return diag::Severity::Error;
7528     }
7529     llvm_unreachable("Fully covered switch above!");
7530   };
7531 
7532   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7533     if (IsSuccessful(DIA)) {
7534       if (DIA->getWarningGroup().empty() &&
7535           DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7536         S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7537         S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7538             << DIA->getParent() << DIA->getCond()->getSourceRange();
7539       } else {
7540         auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7541             DIA->getWarningGroup());
7542         assert(DiagGroup);
7543         auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7544             {ToSeverity(DIA->getDefaultSeverity()), "%0",
7545              DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7546         S.Diag(Loc, DiagID) << DIA->getMessage();
7547       }
7548     }
7549 
7550   return false;
7551 }
7552 
diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl * Function,const Expr * ThisArg,ArrayRef<const Expr * > Args,SourceLocation Loc)7553 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7554                                                const Expr *ThisArg,
7555                                                ArrayRef<const Expr *> Args,
7556                                                SourceLocation Loc) {
7557   return diagnoseDiagnoseIfAttrsWith(
7558       *this, Function, /*ArgDependent=*/true, Loc,
7559       [&](const DiagnoseIfAttr *DIA) {
7560         APValue Result;
7561         // It's sane to use the same Args for any redecl of this function, since
7562         // EvaluateWithSubstitution only cares about the position of each
7563         // argument in the arg list, not the ParmVarDecl* it maps to.
7564         if (!DIA->getCond()->EvaluateWithSubstitution(
7565                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7566           return false;
7567         return Result.isInt() && Result.getInt().getBoolValue();
7568       });
7569 }
7570 
diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl * ND,SourceLocation Loc)7571 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7572                                                  SourceLocation Loc) {
7573   return diagnoseDiagnoseIfAttrsWith(
7574       *this, ND, /*ArgDependent=*/false, Loc,
7575       [&](const DiagnoseIfAttr *DIA) {
7576         bool Result;
7577         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7578                Result;
7579       });
7580 }
7581 
AddFunctionCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs,bool SuppressUserConversions,bool PartialOverloading,bool FirstArgumentIsBase)7582 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7583                                  ArrayRef<Expr *> Args,
7584                                  OverloadCandidateSet &CandidateSet,
7585                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7586                                  bool SuppressUserConversions,
7587                                  bool PartialOverloading,
7588                                  bool FirstArgumentIsBase) {
7589   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7590     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7591     ArrayRef<Expr *> FunctionArgs = Args;
7592 
7593     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7594     FunctionDecl *FD =
7595         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7596 
7597     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7598       QualType ObjectType;
7599       Expr::Classification ObjectClassification;
7600       if (Args.size() > 0) {
7601         if (Expr *E = Args[0]) {
7602           // Use the explicit base to restrict the lookup:
7603           ObjectType = E->getType();
7604           // Pointers in the object arguments are implicitly dereferenced, so we
7605           // always classify them as l-values.
7606           if (!ObjectType.isNull() && ObjectType->isPointerType())
7607             ObjectClassification = Expr::Classification::makeSimpleLValue();
7608           else
7609             ObjectClassification = E->Classify(Context);
7610         } // .. else there is an implicit base.
7611         FunctionArgs = Args.slice(1);
7612       }
7613       if (FunTmpl) {
7614         AddMethodTemplateCandidate(
7615             FunTmpl, F.getPair(),
7616             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7617             ExplicitTemplateArgs, ObjectType, ObjectClassification,
7618             FunctionArgs, CandidateSet, SuppressUserConversions,
7619             PartialOverloading);
7620       } else {
7621         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7622                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7623                            ObjectClassification, FunctionArgs, CandidateSet,
7624                            SuppressUserConversions, PartialOverloading);
7625       }
7626     } else {
7627       // This branch handles both standalone functions and static methods.
7628 
7629       // Slice the first argument (which is the base) when we access
7630       // static method as non-static.
7631       if (Args.size() > 0 &&
7632           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7633                         !isa<CXXConstructorDecl>(FD)))) {
7634         assert(cast<CXXMethodDecl>(FD)->isStatic());
7635         FunctionArgs = Args.slice(1);
7636       }
7637       if (FunTmpl) {
7638         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7639                                      ExplicitTemplateArgs, FunctionArgs,
7640                                      CandidateSet, SuppressUserConversions,
7641                                      PartialOverloading);
7642       } else {
7643         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7644                              SuppressUserConversions, PartialOverloading);
7645       }
7646     }
7647   }
7648 }
7649 
AddMethodCandidate(DeclAccessPair FoundDecl,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,OverloadCandidateParamOrder PO)7650 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7651                               Expr::Classification ObjectClassification,
7652                               ArrayRef<Expr *> Args,
7653                               OverloadCandidateSet &CandidateSet,
7654                               bool SuppressUserConversions,
7655                               OverloadCandidateParamOrder PO) {
7656   NamedDecl *Decl = FoundDecl.getDecl();
7657   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7658 
7659   if (isa<UsingShadowDecl>(Decl))
7660     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7661 
7662   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7663     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7664            "Expected a member function template");
7665     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7666                                /*ExplicitArgs*/ nullptr, ObjectType,
7667                                ObjectClassification, Args, CandidateSet,
7668                                SuppressUserConversions, false, PO);
7669   } else {
7670     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7671                        ObjectType, ObjectClassification, Args, CandidateSet,
7672                        SuppressUserConversions, false, {}, PO);
7673   }
7674 }
7675 
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,bool StrictPackMatch)7676 void Sema::AddMethodCandidate(
7677     CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7678     CXXRecordDecl *ActingContext, QualType ObjectType,
7679     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7680     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7681     bool PartialOverloading, ConversionSequenceList EarlyConversions,
7682     OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7683   const FunctionProtoType *Proto
7684     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7685   assert(Proto && "Methods without a prototype cannot be overloaded");
7686   assert(!isa<CXXConstructorDecl>(Method) &&
7687          "Use AddOverloadCandidate for constructors");
7688 
7689   if (!CandidateSet.isNewCandidate(Method, PO))
7690     return;
7691 
7692   // C++11 [class.copy]p23: [DR1402]
7693   //   A defaulted move assignment operator that is defined as deleted is
7694   //   ignored by overload resolution.
7695   if (Method->isDefaulted() && Method->isDeleted() &&
7696       Method->isMoveAssignmentOperator())
7697     return;
7698 
7699   // Overload resolution is always an unevaluated context.
7700   EnterExpressionEvaluationContext Unevaluated(
7701       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7702 
7703   bool IgnoreExplicitObject =
7704       (Method->isExplicitObjectMemberFunction() &&
7705        CandidateSet.getKind() ==
7706            OverloadCandidateSet::CSK_AddressOfOverloadSet);
7707   bool ImplicitObjectMethodTreatedAsStatic =
7708       CandidateSet.getKind() ==
7709           OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7710       Method->isImplicitObjectMemberFunction();
7711 
7712   unsigned ExplicitOffset =
7713       !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7714 
7715   unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7716                        int(ImplicitObjectMethodTreatedAsStatic);
7717 
7718   unsigned ExtraArgs =
7719       CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7720           ? 0
7721           : 1;
7722 
7723   // Add this candidate
7724   OverloadCandidate &Candidate =
7725       CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7726   Candidate.FoundDecl = FoundDecl;
7727   Candidate.Function = Method;
7728   Candidate.RewriteKind =
7729       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7730   Candidate.TookAddressOfOverload =
7731       CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7732   Candidate.ExplicitCallArguments = Args.size();
7733   Candidate.StrictPackMatch = StrictPackMatch;
7734 
7735   // (C++ 13.3.2p2): A candidate function having fewer than m
7736   // parameters is viable only if it has an ellipsis in its parameter
7737   // list (8.3.5).
7738   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7739       !Proto->isVariadic() &&
7740       shouldEnforceArgLimit(PartialOverloading, Method)) {
7741     Candidate.Viable = false;
7742     Candidate.FailureKind = ovl_fail_too_many_arguments;
7743     return;
7744   }
7745 
7746   // (C++ 13.3.2p2): A candidate function having more than m parameters
7747   // is viable only if the (m+1)st parameter has a default argument
7748   // (8.3.6). For the purposes of overload resolution, the
7749   // parameter list is truncated on the right, so that there are
7750   // exactly m parameters.
7751   unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7752                              ExplicitOffset +
7753                              int(ImplicitObjectMethodTreatedAsStatic);
7754 
7755   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7756     // Not enough arguments.
7757     Candidate.Viable = false;
7758     Candidate.FailureKind = ovl_fail_too_few_arguments;
7759     return;
7760   }
7761 
7762   Candidate.Viable = true;
7763 
7764   unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7765   if (!IgnoreExplicitObject) {
7766     if (ObjectType.isNull())
7767       Candidate.IgnoreObjectArgument = true;
7768     else if (Method->isStatic()) {
7769       // [over.best.ics.general]p8
7770       // When the parameter is the implicit object parameter of a static member
7771       // function, the implicit conversion sequence is a standard conversion
7772       // sequence that is neither better nor worse than any other standard
7773       // conversion sequence.
7774       //
7775       // This is a rule that was introduced in C++23 to support static lambdas.
7776       // We apply it retroactively because we want to support static lambdas as
7777       // an extension and it doesn't hurt previous code.
7778       Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7779     } else {
7780       // Determine the implicit conversion sequence for the object
7781       // parameter.
7782       Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7783           *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7784           Method, ActingContext, /*InOverloadResolution=*/true);
7785       if (Candidate.Conversions[FirstConvIdx].isBad()) {
7786         Candidate.Viable = false;
7787         Candidate.FailureKind = ovl_fail_bad_conversion;
7788         return;
7789       }
7790     }
7791   }
7792 
7793   // (CUDA B.1): Check for invalid calls between targets.
7794   if (getLangOpts().CUDA)
7795     if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7796                               Method)) {
7797       Candidate.Viable = false;
7798       Candidate.FailureKind = ovl_fail_bad_target;
7799       return;
7800     }
7801 
7802   if (Method->getTrailingRequiresClause()) {
7803     ConstraintSatisfaction Satisfaction;
7804     if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7805                                  /*ForOverloadResolution*/ true) ||
7806         !Satisfaction.IsSatisfied) {
7807       Candidate.Viable = false;
7808       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7809       return;
7810     }
7811   }
7812 
7813   // Determine the implicit conversion sequences for each of the
7814   // arguments.
7815   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7816     unsigned ConvIdx =
7817         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7818     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7819       // We already formed a conversion sequence for this parameter during
7820       // template argument deduction.
7821     } else if (ArgIdx < NumParams) {
7822       // (C++ 13.3.2p3): for F to be a viable function, there shall
7823       // exist for each argument an implicit conversion sequence
7824       // (13.3.3.1) that converts that argument to the corresponding
7825       // parameter of F.
7826       QualType ParamType;
7827       if (ImplicitObjectMethodTreatedAsStatic) {
7828         ParamType = ArgIdx == 0
7829                         ? Method->getFunctionObjectParameterReferenceType()
7830                         : Proto->getParamType(ArgIdx - 1);
7831       } else {
7832         ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7833       }
7834       Candidate.Conversions[ConvIdx]
7835         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7836                                 SuppressUserConversions,
7837                                 /*InOverloadResolution=*/true,
7838                                 /*AllowObjCWritebackConversion=*/
7839                                   getLangOpts().ObjCAutoRefCount);
7840       if (Candidate.Conversions[ConvIdx].isBad()) {
7841         Candidate.Viable = false;
7842         Candidate.FailureKind = ovl_fail_bad_conversion;
7843         return;
7844       }
7845     } else {
7846       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7847       // argument for which there is no corresponding parameter is
7848       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7849       Candidate.Conversions[ConvIdx].setEllipsis();
7850     }
7851   }
7852 
7853   if (EnableIfAttr *FailedAttr =
7854           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7855     Candidate.Viable = false;
7856     Candidate.FailureKind = ovl_fail_enable_if;
7857     Candidate.DeductionFailure.Data = FailedAttr;
7858     return;
7859   }
7860 
7861   if (isNonViableMultiVersionOverload(Method)) {
7862     Candidate.Viable = false;
7863     Candidate.FailureKind = ovl_non_default_multiversion_function;
7864   }
7865 }
7866 
AddMethodTemplateCandidateImmediately(Sema & S,OverloadCandidateSet & CandidateSet,FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,bool SuppressUserConversions,bool PartialOverloading,OverloadCandidateParamOrder PO)7867 static void AddMethodTemplateCandidateImmediately(
7868     Sema &S, OverloadCandidateSet &CandidateSet,
7869     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7870     CXXRecordDecl *ActingContext,
7871     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7872     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7873     bool SuppressUserConversions, bool PartialOverloading,
7874     OverloadCandidateParamOrder PO) {
7875 
7876   // C++ [over.match.funcs]p7:
7877   //   In each case where a candidate is a function template, candidate
7878   //   function template specializations are generated using template argument
7879   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7880   //   candidate functions in the usual way.113) A given name can refer to one
7881   //   or more function templates and also to a set of overloaded non-template
7882   //   functions. In such a case, the candidate functions generated from each
7883   //   function template are combined with the set of non-template candidate
7884   //   functions.
7885   TemplateDeductionInfo Info(CandidateSet.getLocation());
7886   auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7887   FunctionDecl *Specialization = nullptr;
7888   ConversionSequenceList Conversions;
7889   if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
7890           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7891           PartialOverloading, /*AggregateDeductionCandidate=*/false,
7892           /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7893           CandidateSet.getKind() ==
7894               clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
7895           [&](ArrayRef<QualType> ParamTypes,
7896               bool OnlyInitializeNonUserDefinedConversions) {
7897             return S.CheckNonDependentConversions(
7898                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7899                 Sema::CheckNonDependentConversionsFlag(
7900                     SuppressUserConversions,
7901                     OnlyInitializeNonUserDefinedConversions),
7902                 ActingContext, ObjectType, ObjectClassification, PO);
7903           });
7904       Result != TemplateDeductionResult::Success) {
7905     OverloadCandidate &Candidate =
7906         CandidateSet.addCandidate(Conversions.size(), Conversions);
7907     Candidate.FoundDecl = FoundDecl;
7908     Candidate.Function = Method;
7909     Candidate.Viable = false;
7910     Candidate.RewriteKind =
7911       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7912     Candidate.IsSurrogate = false;
7913     Candidate.TookAddressOfOverload =
7914         CandidateSet.getKind() ==
7915         OverloadCandidateSet::CSK_AddressOfOverloadSet;
7916 
7917     Candidate.IgnoreObjectArgument =
7918         Method->isStatic() ||
7919         (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7920     Candidate.ExplicitCallArguments = Args.size();
7921     if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7922       Candidate.FailureKind = ovl_fail_bad_conversion;
7923     else {
7924       Candidate.FailureKind = ovl_fail_bad_deduction;
7925       Candidate.DeductionFailure =
7926           MakeDeductionFailureInfo(S.Context, Result, Info);
7927     }
7928     return;
7929   }
7930 
7931   // Add the function template specialization produced by template argument
7932   // deduction as a candidate.
7933   assert(Specialization && "Missing member function template specialization?");
7934   assert(isa<CXXMethodDecl>(Specialization) &&
7935          "Specialization is not a member function?");
7936   S.AddMethodCandidate(
7937       cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7938       ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7939       PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7940 }
7941 
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)7942 void Sema::AddMethodTemplateCandidate(
7943     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7944     CXXRecordDecl *ActingContext,
7945     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7946     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7947     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7948     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7949   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7950     return;
7951 
7952   if (ExplicitTemplateArgs ||
7953       !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts())) {
7954     AddMethodTemplateCandidateImmediately(
7955         *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7956         ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7957         SuppressUserConversions, PartialOverloading, PO);
7958     return;
7959   }
7960 
7961   CandidateSet.AddDeferredMethodTemplateCandidate(
7962       MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7963       Args, SuppressUserConversions, PartialOverloading, PO);
7964 }
7965 
7966 /// Determine whether a given function template has a simple explicit specifier
7967 /// or a non-value-dependent explicit-specification that evaluates to true.
isNonDependentlyExplicit(FunctionTemplateDecl * FTD)7968 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7969   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7970 }
7971 
hasDependentExplicit(FunctionTemplateDecl * FTD)7972 static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
7973   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).getKind() ==
7974          ExplicitSpecKind::Unresolved;
7975 }
7976 
AddTemplateOverloadCandidateImmediately(Sema & S,OverloadCandidateSet & CandidateSet,FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit,Sema::ADLCallKind IsADLCandidate,OverloadCandidateParamOrder PO,bool AggregateCandidateDeduction)7977 static void AddTemplateOverloadCandidateImmediately(
7978     Sema &S, OverloadCandidateSet &CandidateSet,
7979     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7980     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7981     bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7982     Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
7983     bool AggregateCandidateDeduction) {
7984 
7985   // If the function template has a non-dependent explicit specification,
7986   // exclude it now if appropriate; we are not permitted to perform deduction
7987   // and substitution in this case.
7988   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7989     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7990     Candidate.FoundDecl = FoundDecl;
7991     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7992     Candidate.Viable = false;
7993     Candidate.FailureKind = ovl_fail_explicit;
7994     return;
7995   }
7996 
7997   // C++ [over.match.funcs]p7:
7998   //   In each case where a candidate is a function template, candidate
7999   //   function template specializations are generated using template argument
8000   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
8001   //   candidate functions in the usual way.113) A given name can refer to one
8002   //   or more function templates and also to a set of overloaded non-template
8003   //   functions. In such a case, the candidate functions generated from each
8004   //   function template are combined with the set of non-template candidate
8005   //   functions.
8006   TemplateDeductionInfo Info(CandidateSet.getLocation(),
8007                              FunctionTemplate->getTemplateDepth());
8008   FunctionDecl *Specialization = nullptr;
8009   ConversionSequenceList Conversions;
8010   if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8011           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8012           PartialOverloading, AggregateCandidateDeduction,
8013           /*PartialOrdering=*/false,
8014           /*ObjectType=*/QualType(),
8015           /*ObjectClassification=*/Expr::Classification(),
8016           CandidateSet.getKind() ==
8017               OverloadCandidateSet::CSK_AddressOfOverloadSet,
8018           [&](ArrayRef<QualType> ParamTypes,
8019               bool OnlyInitializeNonUserDefinedConversions) {
8020             return S.CheckNonDependentConversions(
8021                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8022                 Sema::CheckNonDependentConversionsFlag(
8023                     SuppressUserConversions,
8024                     OnlyInitializeNonUserDefinedConversions),
8025                 nullptr, QualType(), {}, PO);
8026           });
8027       Result != TemplateDeductionResult::Success) {
8028     OverloadCandidate &Candidate =
8029         CandidateSet.addCandidate(Conversions.size(), Conversions);
8030     Candidate.FoundDecl = FoundDecl;
8031     Candidate.Function = FunctionTemplate->getTemplatedDecl();
8032     Candidate.Viable = false;
8033     Candidate.RewriteKind =
8034       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8035     Candidate.IsSurrogate = false;
8036     Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8037     // Ignore the object argument if there is one, since we don't have an object
8038     // type.
8039     Candidate.TookAddressOfOverload =
8040         CandidateSet.getKind() ==
8041         OverloadCandidateSet::CSK_AddressOfOverloadSet;
8042 
8043     Candidate.IgnoreObjectArgument =
8044         isa<CXXMethodDecl>(Candidate.Function) &&
8045         !cast<CXXMethodDecl>(Candidate.Function)
8046              ->isExplicitObjectMemberFunction() &&
8047         !isa<CXXConstructorDecl>(Candidate.Function);
8048 
8049     Candidate.ExplicitCallArguments = Args.size();
8050     if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8051       Candidate.FailureKind = ovl_fail_bad_conversion;
8052     else {
8053       Candidate.FailureKind = ovl_fail_bad_deduction;
8054       Candidate.DeductionFailure =
8055           MakeDeductionFailureInfo(S.Context, Result, Info);
8056     }
8057     return;
8058   }
8059 
8060   // Add the function template specialization produced by template argument
8061   // deduction as a candidate.
8062   assert(Specialization && "Missing function template specialization?");
8063   S.AddOverloadCandidate(
8064       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8065       PartialOverloading, AllowExplicit,
8066       /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8067       Info.AggregateDeductionCandidateHasMismatchedArity,
8068       Info.hasStrictPackMatch());
8069 }
8070 
AddTemplateOverloadCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit,ADLCallKind IsADLCandidate,OverloadCandidateParamOrder PO,bool AggregateCandidateDeduction)8071 void Sema::AddTemplateOverloadCandidate(
8072     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8073     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8074     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8075     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8076     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8077   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8078     return;
8079 
8080   bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8081 
8082   if (ExplicitTemplateArgs ||
8083       !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||
8084       (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8085        DependentExplicitSpecifier)) {
8086 
8087     AddTemplateOverloadCandidateImmediately(
8088         *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8089         Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8090         IsADLCandidate, PO, AggregateCandidateDeduction);
8091 
8092     if (DependentExplicitSpecifier)
8093       CandidateSet.DisableResolutionByPerfectCandidate();
8094     return;
8095   }
8096 
8097   CandidateSet.AddDeferredTemplateCandidate(
8098       FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8099       PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8100       AggregateCandidateDeduction);
8101 }
8102 
CheckNonDependentConversions(FunctionTemplateDecl * FunctionTemplate,ArrayRef<QualType> ParamTypes,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,ConversionSequenceList & Conversions,CheckNonDependentConversionsFlag UserConversionFlag,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,OverloadCandidateParamOrder PO)8103 bool Sema::CheckNonDependentConversions(
8104     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8105     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8106     ConversionSequenceList &Conversions,
8107     CheckNonDependentConversionsFlag UserConversionFlag,
8108     CXXRecordDecl *ActingContext, QualType ObjectType,
8109     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8110   // FIXME: The cases in which we allow explicit conversions for constructor
8111   // arguments never consider calling a constructor template. It's not clear
8112   // that is correct.
8113   const bool AllowExplicit = false;
8114 
8115   bool ForOverloadSetAddressResolution =
8116       CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8117   auto *FD = FunctionTemplate->getTemplatedDecl();
8118   auto *Method = dyn_cast<CXXMethodDecl>(FD);
8119   bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8120                            !isa<CXXConstructorDecl>(Method);
8121   unsigned ThisConversions = HasThisConversion ? 1 : 0;
8122 
8123   if (Conversions.empty())
8124     Conversions =
8125         CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8126 
8127   // Overload resolution is always an unevaluated context.
8128   EnterExpressionEvaluationContext Unevaluated(
8129       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8130 
8131   // For a method call, check the 'this' conversion here too. DR1391 doesn't
8132   // require that, but this check should never result in a hard error, and
8133   // overload resolution is permitted to sidestep instantiations.
8134   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8135       !ObjectType.isNull()) {
8136     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8137     if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8138         !ParamTypes[0]->isDependentType()) {
8139       Conversions[ConvIdx] = TryObjectArgumentInitialization(
8140           *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8141           Method, ActingContext, /*InOverloadResolution=*/true,
8142           FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8143                                                       : QualType());
8144       if (Conversions[ConvIdx].isBad())
8145         return true;
8146     }
8147   }
8148 
8149   // A speculative workaround for self-dependent constraint bugs that manifest
8150   // after CWG2369.
8151   // FIXME: Add references to the standard once P3606 is adopted.
8152   auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8153                                                QualType ArgType) {
8154     ParamType = ParamType.getNonReferenceType();
8155     ArgType = ArgType.getNonReferenceType();
8156     bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8157     if (PointerConv) {
8158       ParamType = ParamType->getPointeeType();
8159       ArgType = ArgType->getPointeeType();
8160     }
8161 
8162     if (auto *RT = ParamType->getAs<RecordType>())
8163       if (auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8164           RD && RD->hasDefinition()) {
8165         if (llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8166               auto Info = getConstructorInfo(ND);
8167               if (!Info)
8168                 return false;
8169               CXXConstructorDecl *Ctor = Info.Constructor;
8170               /// isConvertingConstructor takes copy/move constructors into
8171               /// account!
8172               return !Ctor->isCopyOrMoveConstructor() &&
8173                      Ctor->isConvertingConstructor(
8174                          /*AllowExplicit=*/true);
8175             }))
8176           return true;
8177       }
8178 
8179     if (auto *RT = ArgType->getAs<RecordType>())
8180       if (auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8181           RD && RD->hasDefinition() &&
8182           !RD->getVisibleConversionFunctions().empty()) {
8183         return true;
8184       }
8185 
8186     return false;
8187   };
8188 
8189   unsigned Offset =
8190       HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8191                                                                            : 0;
8192 
8193   for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8194        I != N; ++I) {
8195     QualType ParamType = ParamTypes[I + Offset];
8196     if (!ParamType->isDependentType()) {
8197       unsigned ConvIdx;
8198       if (PO == OverloadCandidateParamOrder::Reversed) {
8199         ConvIdx = Args.size() - 1 - I;
8200         assert(Args.size() + ThisConversions == 2 &&
8201                "number of args (including 'this') must be exactly 2 for "
8202                "reversed order");
8203         // For members, there would be only one arg 'Args[0]' whose ConvIdx
8204         // would also be 0. 'this' got ConvIdx = 1 previously.
8205         assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8206       } else {
8207         // For members, 'this' got ConvIdx = 0 previously.
8208         ConvIdx = ThisConversions + I;
8209       }
8210       if (Conversions[ConvIdx].isInitialized())
8211         continue;
8212       if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8213           MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8214         continue;
8215       Conversions[ConvIdx] = TryCopyInitialization(
8216           *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8217           /*InOverloadResolution=*/true,
8218           /*AllowObjCWritebackConversion=*/
8219           getLangOpts().ObjCAutoRefCount, AllowExplicit);
8220       if (Conversions[ConvIdx].isBad())
8221         return true;
8222     }
8223   }
8224 
8225   return false;
8226 }
8227 
8228 /// Determine whether this is an allowable conversion from the result
8229 /// of an explicit conversion operator to the expected type, per C++
8230 /// [over.match.conv]p1 and [over.match.ref]p1.
8231 ///
8232 /// \param ConvType The return type of the conversion function.
8233 ///
8234 /// \param ToType The type we are converting to.
8235 ///
8236 /// \param AllowObjCPointerConversion Allow a conversion from one
8237 /// Objective-C pointer to another.
8238 ///
8239 /// \returns true if the conversion is allowable, false otherwise.
isAllowableExplicitConversion(Sema & S,QualType ConvType,QualType ToType,bool AllowObjCPointerConversion)8240 static bool isAllowableExplicitConversion(Sema &S,
8241                                           QualType ConvType, QualType ToType,
8242                                           bool AllowObjCPointerConversion) {
8243   QualType ToNonRefType = ToType.getNonReferenceType();
8244 
8245   // Easy case: the types are the same.
8246   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8247     return true;
8248 
8249   // Allow qualification conversions.
8250   bool ObjCLifetimeConversion;
8251   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8252                                   ObjCLifetimeConversion))
8253     return true;
8254 
8255   // If we're not allowed to consider Objective-C pointer conversions,
8256   // we're done.
8257   if (!AllowObjCPointerConversion)
8258     return false;
8259 
8260   // Is this an Objective-C pointer conversion?
8261   bool IncompatibleObjC = false;
8262   QualType ConvertedType;
8263   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8264                                    IncompatibleObjC);
8265 }
8266 
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion,bool StrictPackMatch)8267 void Sema::AddConversionCandidate(
8268     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8269     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8270     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8271     bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8272   assert(!Conversion->getDescribedFunctionTemplate() &&
8273          "Conversion function templates use AddTemplateConversionCandidate");
8274   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8275   if (!CandidateSet.isNewCandidate(Conversion))
8276     return;
8277 
8278   // If the conversion function has an undeduced return type, trigger its
8279   // deduction now.
8280   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8281     if (DeduceReturnType(Conversion, From->getExprLoc()))
8282       return;
8283     ConvType = Conversion->getConversionType().getNonReferenceType();
8284   }
8285 
8286   // If we don't allow any conversion of the result type, ignore conversion
8287   // functions that don't convert to exactly (possibly cv-qualified) T.
8288   if (!AllowResultConversion &&
8289       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8290     return;
8291 
8292   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8293   // operator is only a candidate if its return type is the target type or
8294   // can be converted to the target type with a qualification conversion.
8295   //
8296   // FIXME: Include such functions in the candidate list and explain why we
8297   // can't select them.
8298   if (Conversion->isExplicit() &&
8299       !isAllowableExplicitConversion(*this, ConvType, ToType,
8300                                      AllowObjCConversionOnExplicit))
8301     return;
8302 
8303   // Overload resolution is always an unevaluated context.
8304   EnterExpressionEvaluationContext Unevaluated(
8305       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8306 
8307   // Add this candidate
8308   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8309   Candidate.FoundDecl = FoundDecl;
8310   Candidate.Function = Conversion;
8311   Candidate.FinalConversion.setAsIdentityConversion();
8312   Candidate.FinalConversion.setFromType(ConvType);
8313   Candidate.FinalConversion.setAllToTypes(ToType);
8314   Candidate.HasFinalConversion = true;
8315   Candidate.Viable = true;
8316   Candidate.ExplicitCallArguments = 1;
8317   Candidate.StrictPackMatch = StrictPackMatch;
8318 
8319   // Explicit functions are not actually candidates at all if we're not
8320   // allowing them in this context, but keep them around so we can point
8321   // to them in diagnostics.
8322   if (!AllowExplicit && Conversion->isExplicit()) {
8323     Candidate.Viable = false;
8324     Candidate.FailureKind = ovl_fail_explicit;
8325     return;
8326   }
8327 
8328   // C++ [over.match.funcs]p4:
8329   //   For conversion functions, the function is considered to be a member of
8330   //   the class of the implicit implied object argument for the purpose of
8331   //   defining the type of the implicit object parameter.
8332   //
8333   // Determine the implicit conversion sequence for the implicit
8334   // object parameter.
8335   QualType ObjectType = From->getType();
8336   if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8337     ObjectType = FromPtrType->getPointeeType();
8338   const auto *ConversionContext =
8339       cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8340 
8341   // C++23 [over.best.ics.general]
8342   // However, if the target is [...]
8343   // - the object parameter of a user-defined conversion function
8344   // [...] user-defined conversion sequences are not considered.
8345   Candidate.Conversions[0] = TryObjectArgumentInitialization(
8346       *this, CandidateSet.getLocation(), From->getType(),
8347       From->Classify(Context), Conversion, ConversionContext,
8348       /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8349       /*SuppressUserConversion*/ true);
8350 
8351   if (Candidate.Conversions[0].isBad()) {
8352     Candidate.Viable = false;
8353     Candidate.FailureKind = ovl_fail_bad_conversion;
8354     return;
8355   }
8356 
8357   if (Conversion->getTrailingRequiresClause()) {
8358     ConstraintSatisfaction Satisfaction;
8359     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8360         !Satisfaction.IsSatisfied) {
8361       Candidate.Viable = false;
8362       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8363       return;
8364     }
8365   }
8366 
8367   // We won't go through a user-defined type conversion function to convert a
8368   // derived to base as such conversions are given Conversion Rank. They only
8369   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8370   QualType FromCanon
8371     = Context.getCanonicalType(From->getType().getUnqualifiedType());
8372   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8373   if (FromCanon == ToCanon ||
8374       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8375     Candidate.Viable = false;
8376     Candidate.FailureKind = ovl_fail_trivial_conversion;
8377     return;
8378   }
8379 
8380   // To determine what the conversion from the result of calling the
8381   // conversion function to the type we're eventually trying to
8382   // convert to (ToType), we need to synthesize a call to the
8383   // conversion function and attempt copy initialization from it. This
8384   // makes sure that we get the right semantics with respect to
8385   // lvalues/rvalues and the type. Fortunately, we can allocate this
8386   // call on the stack and we don't need its arguments to be
8387   // well-formed.
8388   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8389                             VK_LValue, From->getBeginLoc());
8390   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8391                                 Context.getPointerType(Conversion->getType()),
8392                                 CK_FunctionToPointerDecay, &ConversionRef,
8393                                 VK_PRValue, FPOptionsOverride());
8394 
8395   QualType ConversionType = Conversion->getConversionType();
8396   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8397     Candidate.Viable = false;
8398     Candidate.FailureKind = ovl_fail_bad_final_conversion;
8399     return;
8400   }
8401 
8402   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8403 
8404   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8405 
8406   // Introduce a temporary expression with the right type and value category
8407   // that we can use for deduction purposes.
8408   OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8409 
8410   ImplicitConversionSequence ICS =
8411       TryCopyInitialization(*this, &FakeCall, ToType,
8412                             /*SuppressUserConversions=*/true,
8413                             /*InOverloadResolution=*/false,
8414                             /*AllowObjCWritebackConversion=*/false);
8415 
8416   switch (ICS.getKind()) {
8417   case ImplicitConversionSequence::StandardConversion:
8418     Candidate.FinalConversion = ICS.Standard;
8419     Candidate.HasFinalConversion = true;
8420 
8421     // C++ [over.ics.user]p3:
8422     //   If the user-defined conversion is specified by a specialization of a
8423     //   conversion function template, the second standard conversion sequence
8424     //   shall have exact match rank.
8425     if (Conversion->getPrimaryTemplate() &&
8426         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
8427       Candidate.Viable = false;
8428       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8429       return;
8430     }
8431 
8432     // C++0x [dcl.init.ref]p5:
8433     //    In the second case, if the reference is an rvalue reference and
8434     //    the second standard conversion sequence of the user-defined
8435     //    conversion sequence includes an lvalue-to-rvalue conversion, the
8436     //    program is ill-formed.
8437     if (ToType->isRValueReferenceType() &&
8438         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8439       Candidate.Viable = false;
8440       Candidate.FailureKind = ovl_fail_bad_final_conversion;
8441       return;
8442     }
8443     break;
8444 
8445   case ImplicitConversionSequence::BadConversion:
8446     Candidate.Viable = false;
8447     Candidate.FailureKind = ovl_fail_bad_final_conversion;
8448     return;
8449 
8450   default:
8451     llvm_unreachable(
8452            "Can only end up with a standard conversion sequence or failure");
8453   }
8454 
8455   if (EnableIfAttr *FailedAttr =
8456           CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8457     Candidate.Viable = false;
8458     Candidate.FailureKind = ovl_fail_enable_if;
8459     Candidate.DeductionFailure.Data = FailedAttr;
8460     return;
8461   }
8462 
8463   if (isNonViableMultiVersionOverload(Conversion)) {
8464     Candidate.Viable = false;
8465     Candidate.FailureKind = ovl_non_default_multiversion_function;
8466   }
8467 }
8468 
AddTemplateConversionCandidateImmediately(Sema & S,OverloadCandidateSet & CandidateSet,FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion)8469 static void AddTemplateConversionCandidateImmediately(
8470     Sema &S, OverloadCandidateSet &CandidateSet,
8471     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8472     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8473     bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8474     bool AllowResultConversion) {
8475 
8476   // If the function template has a non-dependent explicit specification,
8477   // exclude it now if appropriate; we are not permitted to perform deduction
8478   // and substitution in this case.
8479   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8480     OverloadCandidate &Candidate = CandidateSet.addCandidate();
8481     Candidate.FoundDecl = FoundDecl;
8482     Candidate.Function = FunctionTemplate->getTemplatedDecl();
8483     Candidate.Viable = false;
8484     Candidate.FailureKind = ovl_fail_explicit;
8485     return;
8486   }
8487 
8488   QualType ObjectType = From->getType();
8489   Expr::Classification ObjectClassification = From->Classify(S.Context);
8490 
8491   TemplateDeductionInfo Info(CandidateSet.getLocation());
8492   CXXConversionDecl *Specialization = nullptr;
8493   if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8494           FunctionTemplate, ObjectType, ObjectClassification, ToType,
8495           Specialization, Info);
8496       Result != TemplateDeductionResult::Success) {
8497     OverloadCandidate &Candidate = CandidateSet.addCandidate();
8498     Candidate.FoundDecl = FoundDecl;
8499     Candidate.Function = FunctionTemplate->getTemplatedDecl();
8500     Candidate.Viable = false;
8501     Candidate.FailureKind = ovl_fail_bad_deduction;
8502     Candidate.ExplicitCallArguments = 1;
8503     Candidate.DeductionFailure =
8504         MakeDeductionFailureInfo(S.Context, Result, Info);
8505     return;
8506   }
8507 
8508   // Add the conversion function template specialization produced by
8509   // template argument deduction as a candidate.
8510   assert(Specialization && "Missing function template specialization?");
8511   S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8512                            ToType, CandidateSet, AllowObjCConversionOnExplicit,
8513                            AllowExplicit, AllowResultConversion,
8514                            Info.hasStrictPackMatch());
8515 }
8516 
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion)8517 void Sema::AddTemplateConversionCandidate(
8518     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8519     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8520     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8521     bool AllowExplicit, bool AllowResultConversion) {
8522   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8523          "Only conversion function templates permitted here");
8524 
8525   if (!CandidateSet.isNewCandidate(FunctionTemplate))
8526     return;
8527 
8528   if (!CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||
8529       CandidateSet.getKind() ==
8530           OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8531       CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8532     AddTemplateConversionCandidateImmediately(
8533         *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8534         ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8535         AllowResultConversion);
8536 
8537     CandidateSet.DisableResolutionByPerfectCandidate();
8538     return;
8539   }
8540 
8541   CandidateSet.AddDeferredConversionTemplateCandidate(
8542       FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8543       AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8544 }
8545 
AddSurrogateCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,const FunctionProtoType * Proto,Expr * Object,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)8546 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8547                                  DeclAccessPair FoundDecl,
8548                                  CXXRecordDecl *ActingContext,
8549                                  const FunctionProtoType *Proto,
8550                                  Expr *Object,
8551                                  ArrayRef<Expr *> Args,
8552                                  OverloadCandidateSet& CandidateSet) {
8553   if (!CandidateSet.isNewCandidate(Conversion))
8554     return;
8555 
8556   // Overload resolution is always an unevaluated context.
8557   EnterExpressionEvaluationContext Unevaluated(
8558       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8559 
8560   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8561   Candidate.FoundDecl = FoundDecl;
8562   Candidate.Function = nullptr;
8563   Candidate.Surrogate = Conversion;
8564   Candidate.IsSurrogate = true;
8565   Candidate.Viable = true;
8566   Candidate.ExplicitCallArguments = Args.size();
8567 
8568   // Determine the implicit conversion sequence for the implicit
8569   // object parameter.
8570   ImplicitConversionSequence ObjectInit;
8571   if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8572     ObjectInit = TryCopyInitialization(*this, Object,
8573                                        Conversion->getParamDecl(0)->getType(),
8574                                        /*SuppressUserConversions=*/false,
8575                                        /*InOverloadResolution=*/true, false);
8576   } else {
8577     ObjectInit = TryObjectArgumentInitialization(
8578         *this, CandidateSet.getLocation(), Object->getType(),
8579         Object->Classify(Context), Conversion, ActingContext);
8580   }
8581 
8582   if (ObjectInit.isBad()) {
8583     Candidate.Viable = false;
8584     Candidate.FailureKind = ovl_fail_bad_conversion;
8585     Candidate.Conversions[0] = ObjectInit;
8586     return;
8587   }
8588 
8589   // The first conversion is actually a user-defined conversion whose
8590   // first conversion is ObjectInit's standard conversion (which is
8591   // effectively a reference binding). Record it as such.
8592   Candidate.Conversions[0].setUserDefined();
8593   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8594   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8595   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8596   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8597   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8598   Candidate.Conversions[0].UserDefined.After
8599     = Candidate.Conversions[0].UserDefined.Before;
8600   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8601 
8602   // Find the
8603   unsigned NumParams = Proto->getNumParams();
8604 
8605   // (C++ 13.3.2p2): A candidate function having fewer than m
8606   // parameters is viable only if it has an ellipsis in its parameter
8607   // list (8.3.5).
8608   if (Args.size() > NumParams && !Proto->isVariadic()) {
8609     Candidate.Viable = false;
8610     Candidate.FailureKind = ovl_fail_too_many_arguments;
8611     return;
8612   }
8613 
8614   // Function types don't have any default arguments, so just check if
8615   // we have enough arguments.
8616   if (Args.size() < NumParams) {
8617     // Not enough arguments.
8618     Candidate.Viable = false;
8619     Candidate.FailureKind = ovl_fail_too_few_arguments;
8620     return;
8621   }
8622 
8623   // Determine the implicit conversion sequences for each of the
8624   // arguments.
8625   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8626     if (ArgIdx < NumParams) {
8627       // (C++ 13.3.2p3): for F to be a viable function, there shall
8628       // exist for each argument an implicit conversion sequence
8629       // (13.3.3.1) that converts that argument to the corresponding
8630       // parameter of F.
8631       QualType ParamType = Proto->getParamType(ArgIdx);
8632       Candidate.Conversions[ArgIdx + 1]
8633         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8634                                 /*SuppressUserConversions=*/false,
8635                                 /*InOverloadResolution=*/false,
8636                                 /*AllowObjCWritebackConversion=*/
8637                                   getLangOpts().ObjCAutoRefCount);
8638       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8639         Candidate.Viable = false;
8640         Candidate.FailureKind = ovl_fail_bad_conversion;
8641         return;
8642       }
8643     } else {
8644       // (C++ 13.3.2p2): For the purposes of overload resolution, any
8645       // argument for which there is no corresponding parameter is
8646       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8647       Candidate.Conversions[ArgIdx + 1].setEllipsis();
8648     }
8649   }
8650 
8651   if (Conversion->getTrailingRequiresClause()) {
8652     ConstraintSatisfaction Satisfaction;
8653     if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8654                                  /*ForOverloadResolution*/ true) ||
8655         !Satisfaction.IsSatisfied) {
8656       Candidate.Viable = false;
8657       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8658       return;
8659     }
8660   }
8661 
8662   if (EnableIfAttr *FailedAttr =
8663           CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8664     Candidate.Viable = false;
8665     Candidate.FailureKind = ovl_fail_enable_if;
8666     Candidate.DeductionFailure.Data = FailedAttr;
8667     return;
8668   }
8669 }
8670 
AddNonMemberOperatorCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs)8671 void Sema::AddNonMemberOperatorCandidates(
8672     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8673     OverloadCandidateSet &CandidateSet,
8674     TemplateArgumentListInfo *ExplicitTemplateArgs) {
8675   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8676     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8677     ArrayRef<Expr *> FunctionArgs = Args;
8678 
8679     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8680     FunctionDecl *FD =
8681         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8682 
8683     // Don't consider rewritten functions if we're not rewriting.
8684     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8685       continue;
8686 
8687     assert(!isa<CXXMethodDecl>(FD) &&
8688            "unqualified operator lookup found a member function");
8689 
8690     if (FunTmpl) {
8691       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8692                                    FunctionArgs, CandidateSet);
8693       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8694 
8695         // As template candidates are not deduced immediately,
8696         // persist the array in the overload set.
8697         ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8698             FunctionArgs[1], FunctionArgs[0]);
8699         AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8700                                      Reversed, CandidateSet, false, false, true,
8701                                      ADLCallKind::NotADL,
8702                                      OverloadCandidateParamOrder::Reversed);
8703       }
8704     } else {
8705       if (ExplicitTemplateArgs)
8706         continue;
8707       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8708       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8709         AddOverloadCandidate(FD, F.getPair(),
8710                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8711                              false, false, true, false, ADLCallKind::NotADL, {},
8712                              OverloadCandidateParamOrder::Reversed);
8713     }
8714   }
8715 }
8716 
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,OverloadCandidateParamOrder PO)8717 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8718                                        SourceLocation OpLoc,
8719                                        ArrayRef<Expr *> Args,
8720                                        OverloadCandidateSet &CandidateSet,
8721                                        OverloadCandidateParamOrder PO) {
8722   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8723 
8724   // C++ [over.match.oper]p3:
8725   //   For a unary operator @ with an operand of a type whose
8726   //   cv-unqualified version is T1, and for a binary operator @ with
8727   //   a left operand of a type whose cv-unqualified version is T1 and
8728   //   a right operand of a type whose cv-unqualified version is T2,
8729   //   three sets of candidate functions, designated member
8730   //   candidates, non-member candidates and built-in candidates, are
8731   //   constructed as follows:
8732   QualType T1 = Args[0]->getType();
8733 
8734   //     -- If T1 is a complete class type or a class currently being
8735   //        defined, the set of member candidates is the result of the
8736   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8737   //        the set of member candidates is empty.
8738   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8739     // Complete the type if it can be completed.
8740     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8741       return;
8742     // If the type is neither complete nor being defined, bail out now.
8743     if (!T1Rec->getDecl()->getDefinition())
8744       return;
8745 
8746     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8747     LookupQualifiedName(Operators, T1Rec->getDecl());
8748     Operators.suppressAccessDiagnostics();
8749 
8750     for (LookupResult::iterator Oper = Operators.begin(),
8751                                 OperEnd = Operators.end();
8752          Oper != OperEnd; ++Oper) {
8753       if (Oper->getAsFunction() &&
8754           PO == OverloadCandidateParamOrder::Reversed &&
8755           !CandidateSet.getRewriteInfo().shouldAddReversed(
8756               *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8757         continue;
8758       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8759                          Args[0]->Classify(Context), Args.slice(1),
8760                          CandidateSet, /*SuppressUserConversion=*/false, PO);
8761     }
8762   }
8763 }
8764 
AddBuiltinCandidate(QualType * ParamTys,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)8765 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8766                                OverloadCandidateSet& CandidateSet,
8767                                bool IsAssignmentOperator,
8768                                unsigned NumContextualBoolArguments) {
8769   // Overload resolution is always an unevaluated context.
8770   EnterExpressionEvaluationContext Unevaluated(
8771       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8772 
8773   // Add this candidate
8774   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8775   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8776   Candidate.Function = nullptr;
8777   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8778 
8779   // Determine the implicit conversion sequences for each of the
8780   // arguments.
8781   Candidate.Viable = true;
8782   Candidate.ExplicitCallArguments = Args.size();
8783   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8784     // C++ [over.match.oper]p4:
8785     //   For the built-in assignment operators, conversions of the
8786     //   left operand are restricted as follows:
8787     //     -- no temporaries are introduced to hold the left operand, and
8788     //     -- no user-defined conversions are applied to the left
8789     //        operand to achieve a type match with the left-most
8790     //        parameter of a built-in candidate.
8791     //
8792     // We block these conversions by turning off user-defined
8793     // conversions, since that is the only way that initialization of
8794     // a reference to a non-class type can occur from something that
8795     // is not of the same type.
8796     if (ArgIdx < NumContextualBoolArguments) {
8797       assert(ParamTys[ArgIdx] == Context.BoolTy &&
8798              "Contextual conversion to bool requires bool type");
8799       Candidate.Conversions[ArgIdx]
8800         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8801     } else {
8802       Candidate.Conversions[ArgIdx]
8803         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8804                                 ArgIdx == 0 && IsAssignmentOperator,
8805                                 /*InOverloadResolution=*/false,
8806                                 /*AllowObjCWritebackConversion=*/
8807                                   getLangOpts().ObjCAutoRefCount);
8808     }
8809     if (Candidate.Conversions[ArgIdx].isBad()) {
8810       Candidate.Viable = false;
8811       Candidate.FailureKind = ovl_fail_bad_conversion;
8812       break;
8813     }
8814   }
8815 }
8816 
8817 namespace {
8818 
8819 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8820 /// candidate operator functions for built-in operators (C++
8821 /// [over.built]). The types are separated into pointer types and
8822 /// enumeration types.
8823 class BuiltinCandidateTypeSet  {
8824   /// TypeSet - A set of types.
8825   typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8826 
8827   /// PointerTypes - The set of pointer types that will be used in the
8828   /// built-in candidates.
8829   TypeSet PointerTypes;
8830 
8831   /// MemberPointerTypes - The set of member pointer types that will be
8832   /// used in the built-in candidates.
8833   TypeSet MemberPointerTypes;
8834 
8835   /// EnumerationTypes - The set of enumeration types that will be
8836   /// used in the built-in candidates.
8837   TypeSet EnumerationTypes;
8838 
8839   /// The set of vector types that will be used in the built-in
8840   /// candidates.
8841   TypeSet VectorTypes;
8842 
8843   /// The set of matrix types that will be used in the built-in
8844   /// candidates.
8845   TypeSet MatrixTypes;
8846 
8847   /// The set of _BitInt types that will be used in the built-in candidates.
8848   TypeSet BitIntTypes;
8849 
8850   /// A flag indicating non-record types are viable candidates
8851   bool HasNonRecordTypes;
8852 
8853   /// A flag indicating whether either arithmetic or enumeration types
8854   /// were present in the candidate set.
8855   bool HasArithmeticOrEnumeralTypes;
8856 
8857   /// A flag indicating whether the nullptr type was present in the
8858   /// candidate set.
8859   bool HasNullPtrType;
8860 
8861   /// Sema - The semantic analysis instance where we are building the
8862   /// candidate type set.
8863   Sema &SemaRef;
8864 
8865   /// Context - The AST context in which we will build the type sets.
8866   ASTContext &Context;
8867 
8868   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8869                                                const Qualifiers &VisibleQuals);
8870   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8871 
8872 public:
8873   /// iterator - Iterates through the types that are part of the set.
8874   typedef TypeSet::iterator iterator;
8875 
BuiltinCandidateTypeSet(Sema & SemaRef)8876   BuiltinCandidateTypeSet(Sema &SemaRef)
8877     : HasNonRecordTypes(false),
8878       HasArithmeticOrEnumeralTypes(false),
8879       HasNullPtrType(false),
8880       SemaRef(SemaRef),
8881       Context(SemaRef.Context) { }
8882 
8883   void AddTypesConvertedFrom(QualType Ty,
8884                              SourceLocation Loc,
8885                              bool AllowUserConversions,
8886                              bool AllowExplicitConversions,
8887                              const Qualifiers &VisibleTypeConversionsQuals);
8888 
pointer_types()8889   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
member_pointer_types()8890   llvm::iterator_range<iterator> member_pointer_types() {
8891     return MemberPointerTypes;
8892   }
enumeration_types()8893   llvm::iterator_range<iterator> enumeration_types() {
8894     return EnumerationTypes;
8895   }
vector_types()8896   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
matrix_types()8897   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
bitint_types()8898   llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8899 
containsMatrixType(QualType Ty) const8900   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
hasNonRecordTypes()8901   bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()8902   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const8903   bool hasNullPtrType() const { return HasNullPtrType; }
8904 };
8905 
8906 } // end anonymous namespace
8907 
8908 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8909 /// the set of pointer types along with any more-qualified variants of
8910 /// that type. For example, if @p Ty is "int const *", this routine
8911 /// will add "int const *", "int const volatile *", "int const
8912 /// restrict *", and "int const volatile restrict *" to the set of
8913 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8914 /// false otherwise.
8915 ///
8916 /// FIXME: what to do about extended qualifiers?
8917 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)8918 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8919                                              const Qualifiers &VisibleQuals) {
8920 
8921   // Insert this type.
8922   if (!PointerTypes.insert(Ty))
8923     return false;
8924 
8925   QualType PointeeTy;
8926   const PointerType *PointerTy = Ty->getAs<PointerType>();
8927   bool buildObjCPtr = false;
8928   if (!PointerTy) {
8929     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8930     PointeeTy = PTy->getPointeeType();
8931     buildObjCPtr = true;
8932   } else {
8933     PointeeTy = PointerTy->getPointeeType();
8934   }
8935 
8936   // Don't add qualified variants of arrays. For one, they're not allowed
8937   // (the qualifier would sink to the element type), and for another, the
8938   // only overload situation where it matters is subscript or pointer +- int,
8939   // and those shouldn't have qualifier variants anyway.
8940   if (PointeeTy->isArrayType())
8941     return true;
8942 
8943   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8944   bool hasVolatile = VisibleQuals.hasVolatile();
8945   bool hasRestrict = VisibleQuals.hasRestrict();
8946 
8947   // Iterate through all strict supersets of BaseCVR.
8948   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8949     if ((CVR | BaseCVR) != CVR) continue;
8950     // Skip over volatile if no volatile found anywhere in the types.
8951     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8952 
8953     // Skip over restrict if no restrict found anywhere in the types, or if
8954     // the type cannot be restrict-qualified.
8955     if ((CVR & Qualifiers::Restrict) &&
8956         (!hasRestrict ||
8957          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8958       continue;
8959 
8960     // Build qualified pointee type.
8961     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8962 
8963     // Build qualified pointer type.
8964     QualType QPointerTy;
8965     if (!buildObjCPtr)
8966       QPointerTy = Context.getPointerType(QPointeeTy);
8967     else
8968       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8969 
8970     // Insert qualified pointer type.
8971     PointerTypes.insert(QPointerTy);
8972   }
8973 
8974   return true;
8975 }
8976 
8977 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8978 /// to the set of pointer types along with any more-qualified variants of
8979 /// that type. For example, if @p Ty is "int const *", this routine
8980 /// will add "int const *", "int const volatile *", "int const
8981 /// restrict *", and "int const volatile restrict *" to the set of
8982 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8983 /// false otherwise.
8984 ///
8985 /// FIXME: what to do about extended qualifiers?
8986 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)8987 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8988     QualType Ty) {
8989   // Insert this type.
8990   if (!MemberPointerTypes.insert(Ty))
8991     return false;
8992 
8993   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8994   assert(PointerTy && "type was not a member pointer type!");
8995 
8996   QualType PointeeTy = PointerTy->getPointeeType();
8997   // Don't add qualified variants of arrays. For one, they're not allowed
8998   // (the qualifier would sink to the element type), and for another, the
8999   // only overload situation where it matters is subscript or pointer +- int,
9000   // and those shouldn't have qualifier variants anyway.
9001   if (PointeeTy->isArrayType())
9002     return true;
9003   CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9004 
9005   // Iterate through all strict supersets of the pointee type's CVR
9006   // qualifiers.
9007   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9008   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9009     if ((CVR | BaseCVR) != CVR) continue;
9010 
9011     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9012     MemberPointerTypes.insert(
9013         Context.getMemberPointerType(QPointeeTy, /*Qualifier=*/nullptr, Cls));
9014   }
9015 
9016   return true;
9017 }
9018 
9019 /// AddTypesConvertedFrom - Add each of the types to which the type @p
9020 /// Ty can be implicit converted to the given set of @p Types. We're
9021 /// primarily interested in pointer types and enumeration types. We also
9022 /// take member pointer types, for the conditional operator.
9023 /// AllowUserConversions is true if we should look at the conversion
9024 /// functions of a class type, and AllowExplicitConversions if we
9025 /// should also include the explicit conversion functions of a class
9026 /// type.
9027 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)9028 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9029                                                SourceLocation Loc,
9030                                                bool AllowUserConversions,
9031                                                bool AllowExplicitConversions,
9032                                                const Qualifiers &VisibleQuals) {
9033   // Only deal with canonical types.
9034   Ty = Context.getCanonicalType(Ty);
9035 
9036   // Look through reference types; they aren't part of the type of an
9037   // expression for the purposes of conversions.
9038   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9039     Ty = RefTy->getPointeeType();
9040 
9041   // If we're dealing with an array type, decay to the pointer.
9042   if (Ty->isArrayType())
9043     Ty = SemaRef.Context.getArrayDecayedType(Ty);
9044 
9045   // Otherwise, we don't care about qualifiers on the type.
9046   Ty = Ty.getLocalUnqualifiedType();
9047 
9048   // Flag if we ever add a non-record type.
9049   const RecordType *TyRec = Ty->getAs<RecordType>();
9050   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
9051 
9052   // Flag if we encounter an arithmetic type.
9053   HasArithmeticOrEnumeralTypes =
9054     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9055 
9056   if (Ty->isObjCIdType() || Ty->isObjCClassType())
9057     PointerTypes.insert(Ty);
9058   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9059     // Insert our type, and its more-qualified variants, into the set
9060     // of types.
9061     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9062       return;
9063   } else if (Ty->isMemberPointerType()) {
9064     // Member pointers are far easier, since the pointee can't be converted.
9065     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9066       return;
9067   } else if (Ty->isEnumeralType()) {
9068     HasArithmeticOrEnumeralTypes = true;
9069     EnumerationTypes.insert(Ty);
9070   } else if (Ty->isBitIntType()) {
9071     HasArithmeticOrEnumeralTypes = true;
9072     BitIntTypes.insert(Ty);
9073   } else if (Ty->isVectorType()) {
9074     // We treat vector types as arithmetic types in many contexts as an
9075     // extension.
9076     HasArithmeticOrEnumeralTypes = true;
9077     VectorTypes.insert(Ty);
9078   } else if (Ty->isMatrixType()) {
9079     // Similar to vector types, we treat vector types as arithmetic types in
9080     // many contexts as an extension.
9081     HasArithmeticOrEnumeralTypes = true;
9082     MatrixTypes.insert(Ty);
9083   } else if (Ty->isNullPtrType()) {
9084     HasNullPtrType = true;
9085   } else if (AllowUserConversions && TyRec) {
9086     // No conversion functions in incomplete types.
9087     if (!SemaRef.isCompleteType(Loc, Ty))
9088       return;
9089 
9090     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
9091     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9092       if (isa<UsingShadowDecl>(D))
9093         D = cast<UsingShadowDecl>(D)->getTargetDecl();
9094 
9095       // Skip conversion function templates; they don't tell us anything
9096       // about which builtin types we can convert to.
9097       if (isa<FunctionTemplateDecl>(D))
9098         continue;
9099 
9100       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9101       if (AllowExplicitConversions || !Conv->isExplicit()) {
9102         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9103                               VisibleQuals);
9104       }
9105     }
9106   }
9107 }
9108 /// Helper function for adjusting address spaces for the pointer or reference
9109 /// operands of builtin operators depending on the argument.
AdjustAddressSpaceForBuiltinOperandType(Sema & S,QualType T,Expr * Arg)9110 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9111                                                         Expr *Arg) {
9112   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
9113 }
9114 
9115 /// Helper function for AddBuiltinOperatorCandidates() that adds
9116 /// the volatile- and non-volatile-qualified assignment operators for the
9117 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)9118 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9119                                                    QualType T,
9120                                                    ArrayRef<Expr *> Args,
9121                                     OverloadCandidateSet &CandidateSet) {
9122   QualType ParamTypes[2];
9123 
9124   // T& operator=(T&, T)
9125   ParamTypes[0] = S.Context.getLValueReferenceType(
9126       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
9127   ParamTypes[1] = T;
9128   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9129                         /*IsAssignmentOperator=*/true);
9130 
9131   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9132     // volatile T& operator=(volatile T&, T)
9133     ParamTypes[0] = S.Context.getLValueReferenceType(
9134         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
9135                                                 Args[0]));
9136     ParamTypes[1] = T;
9137     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9138                           /*IsAssignmentOperator=*/true);
9139   }
9140 }
9141 
9142 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9143 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)9144 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9145     Qualifiers VRQuals;
9146     CXXRecordDecl *ClassDecl;
9147     if (const MemberPointerType *RHSMPType =
9148             ArgExpr->getType()->getAs<MemberPointerType>())
9149       ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9150     else
9151       ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9152     if (!ClassDecl) {
9153       // Just to be safe, assume the worst case.
9154       VRQuals.addVolatile();
9155       VRQuals.addRestrict();
9156       return VRQuals;
9157     }
9158     if (!ClassDecl->hasDefinition())
9159       return VRQuals;
9160 
9161     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9162       if (isa<UsingShadowDecl>(D))
9163         D = cast<UsingShadowDecl>(D)->getTargetDecl();
9164       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9165         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9166         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9167           CanTy = ResTypeRef->getPointeeType();
9168         // Need to go down the pointer/mempointer chain and add qualifiers
9169         // as see them.
9170         bool done = false;
9171         while (!done) {
9172           if (CanTy.isRestrictQualified())
9173             VRQuals.addRestrict();
9174           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9175             CanTy = ResTypePtr->getPointeeType();
9176           else if (const MemberPointerType *ResTypeMPtr =
9177                 CanTy->getAs<MemberPointerType>())
9178             CanTy = ResTypeMPtr->getPointeeType();
9179           else
9180             done = true;
9181           if (CanTy.isVolatileQualified())
9182             VRQuals.addVolatile();
9183           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9184             return VRQuals;
9185         }
9186       }
9187     }
9188     return VRQuals;
9189 }
9190 
9191 // Note: We're currently only handling qualifiers that are meaningful for the
9192 // LHS of compound assignment overloading.
forAllQualifierCombinationsImpl(QualifiersAndAtomic Available,QualifiersAndAtomic Applied,llvm::function_ref<void (QualifiersAndAtomic)> Callback)9193 static void forAllQualifierCombinationsImpl(
9194     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9195     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9196   // _Atomic
9197   if (Available.hasAtomic()) {
9198     Available.removeAtomic();
9199     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9200     forAllQualifierCombinationsImpl(Available, Applied, Callback);
9201     return;
9202   }
9203 
9204   // volatile
9205   if (Available.hasVolatile()) {
9206     Available.removeVolatile();
9207     assert(!Applied.hasVolatile());
9208     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9209                                     Callback);
9210     forAllQualifierCombinationsImpl(Available, Applied, Callback);
9211     return;
9212   }
9213 
9214   Callback(Applied);
9215 }
9216 
forAllQualifierCombinations(QualifiersAndAtomic Quals,llvm::function_ref<void (QualifiersAndAtomic)> Callback)9217 static void forAllQualifierCombinations(
9218     QualifiersAndAtomic Quals,
9219     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9220   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
9221                                          Callback);
9222 }
9223 
makeQualifiedLValueReferenceType(QualType Base,QualifiersAndAtomic Quals,Sema & S)9224 static QualType makeQualifiedLValueReferenceType(QualType Base,
9225                                                  QualifiersAndAtomic Quals,
9226                                                  Sema &S) {
9227   if (Quals.hasAtomic())
9228     Base = S.Context.getAtomicType(Base);
9229   if (Quals.hasVolatile())
9230     Base = S.Context.getVolatileType(Base);
9231   return S.Context.getLValueReferenceType(Base);
9232 }
9233 
9234 namespace {
9235 
9236 /// Helper class to manage the addition of builtin operator overload
9237 /// candidates. It provides shared state and utility methods used throughout
9238 /// the process, as well as a helper method to add each group of builtin
9239 /// operator overloads from the standard to a candidate set.
9240 class BuiltinOperatorOverloadBuilder {
9241   // Common instance state available to all overload candidate addition methods.
9242   Sema &S;
9243   ArrayRef<Expr *> Args;
9244   QualifiersAndAtomic VisibleTypeConversionsQuals;
9245   bool HasArithmeticOrEnumeralCandidateType;
9246   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9247   OverloadCandidateSet &CandidateSet;
9248 
9249   static constexpr int ArithmeticTypesCap = 26;
9250   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9251 
9252   // Define some indices used to iterate over the arithmetic types in
9253   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
9254   // types are that preserved by promotion (C++ [over.built]p2).
9255   unsigned FirstIntegralType,
9256            LastIntegralType;
9257   unsigned FirstPromotedIntegralType,
9258            LastPromotedIntegralType;
9259   unsigned FirstPromotedArithmeticType,
9260            LastPromotedArithmeticType;
9261   unsigned NumArithmeticTypes;
9262 
InitArithmeticTypes()9263   void InitArithmeticTypes() {
9264     // Start of promoted types.
9265     FirstPromotedArithmeticType = 0;
9266     ArithmeticTypes.push_back(S.Context.FloatTy);
9267     ArithmeticTypes.push_back(S.Context.DoubleTy);
9268     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9269     if (S.Context.getTargetInfo().hasFloat128Type())
9270       ArithmeticTypes.push_back(S.Context.Float128Ty);
9271     if (S.Context.getTargetInfo().hasIbm128Type())
9272       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9273 
9274     // Start of integral types.
9275     FirstIntegralType = ArithmeticTypes.size();
9276     FirstPromotedIntegralType = ArithmeticTypes.size();
9277     ArithmeticTypes.push_back(S.Context.IntTy);
9278     ArithmeticTypes.push_back(S.Context.LongTy);
9279     ArithmeticTypes.push_back(S.Context.LongLongTy);
9280     if (S.Context.getTargetInfo().hasInt128Type() ||
9281         (S.Context.getAuxTargetInfo() &&
9282          S.Context.getAuxTargetInfo()->hasInt128Type()))
9283       ArithmeticTypes.push_back(S.Context.Int128Ty);
9284     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9285     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9286     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9287     if (S.Context.getTargetInfo().hasInt128Type() ||
9288         (S.Context.getAuxTargetInfo() &&
9289          S.Context.getAuxTargetInfo()->hasInt128Type()))
9290       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9291 
9292     /// We add candidates for the unique, unqualified _BitInt types present in
9293     /// the candidate type set. The candidate set already handled ensuring the
9294     /// type is unqualified and canonical, but because we're adding from N
9295     /// different sets, we need to do some extra work to unique things. Insert
9296     /// the candidates into a unique set, then move from that set into the list
9297     /// of arithmetic types.
9298     llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9299     for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9300       for (QualType BitTy : Candidate.bitint_types())
9301         BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9302     }
9303     llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9304     LastPromotedIntegralType = ArithmeticTypes.size();
9305     LastPromotedArithmeticType = ArithmeticTypes.size();
9306     // End of promoted types.
9307 
9308     ArithmeticTypes.push_back(S.Context.BoolTy);
9309     ArithmeticTypes.push_back(S.Context.CharTy);
9310     ArithmeticTypes.push_back(S.Context.WCharTy);
9311     if (S.Context.getLangOpts().Char8)
9312       ArithmeticTypes.push_back(S.Context.Char8Ty);
9313     ArithmeticTypes.push_back(S.Context.Char16Ty);
9314     ArithmeticTypes.push_back(S.Context.Char32Ty);
9315     ArithmeticTypes.push_back(S.Context.SignedCharTy);
9316     ArithmeticTypes.push_back(S.Context.ShortTy);
9317     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9318     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9319     LastIntegralType = ArithmeticTypes.size();
9320     NumArithmeticTypes = ArithmeticTypes.size();
9321     // End of integral types.
9322     // FIXME: What about complex? What about half?
9323 
9324     // We don't know for sure how many bit-precise candidates were involved, so
9325     // we subtract those from the total when testing whether we're under the
9326     // cap or not.
9327     assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9328                ArithmeticTypesCap &&
9329            "Enough inline storage for all arithmetic types.");
9330   }
9331 
9332   /// Helper method to factor out the common pattern of adding overloads
9333   /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile,bool HasRestrict)9334   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9335                                            bool HasVolatile,
9336                                            bool HasRestrict) {
9337     QualType ParamTypes[2] = {
9338       S.Context.getLValueReferenceType(CandidateTy),
9339       S.Context.IntTy
9340     };
9341 
9342     // Non-volatile version.
9343     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9344 
9345     // Use a heuristic to reduce number of builtin candidates in the set:
9346     // add volatile version only if there are conversions to a volatile type.
9347     if (HasVolatile) {
9348       ParamTypes[0] =
9349         S.Context.getLValueReferenceType(
9350           S.Context.getVolatileType(CandidateTy));
9351       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9352     }
9353 
9354     // Add restrict version only if there are conversions to a restrict type
9355     // and our candidate type is a non-restrict-qualified pointer.
9356     if (HasRestrict && CandidateTy->isAnyPointerType() &&
9357         !CandidateTy.isRestrictQualified()) {
9358       ParamTypes[0]
9359         = S.Context.getLValueReferenceType(
9360             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
9361       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9362 
9363       if (HasVolatile) {
9364         ParamTypes[0]
9365           = S.Context.getLValueReferenceType(
9366               S.Context.getCVRQualifiedType(CandidateTy,
9367                                             (Qualifiers::Volatile |
9368                                              Qualifiers::Restrict)));
9369         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9370       }
9371     }
9372 
9373   }
9374 
9375   /// Helper to add an overload candidate for a binary builtin with types \p L
9376   /// and \p R.
AddCandidate(QualType L,QualType R)9377   void AddCandidate(QualType L, QualType R) {
9378     QualType LandR[2] = {L, R};
9379     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9380   }
9381 
9382 public:
BuiltinOperatorOverloadBuilder(Sema & S,ArrayRef<Expr * > Args,QualifiersAndAtomic VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)9383   BuiltinOperatorOverloadBuilder(
9384     Sema &S, ArrayRef<Expr *> Args,
9385     QualifiersAndAtomic VisibleTypeConversionsQuals,
9386     bool HasArithmeticOrEnumeralCandidateType,
9387     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9388     OverloadCandidateSet &CandidateSet)
9389     : S(S), Args(Args),
9390       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9391       HasArithmeticOrEnumeralCandidateType(
9392         HasArithmeticOrEnumeralCandidateType),
9393       CandidateTypes(CandidateTypes),
9394       CandidateSet(CandidateSet) {
9395 
9396     InitArithmeticTypes();
9397   }
9398 
9399   // Increment is deprecated for bool since C++17.
9400   //
9401   // C++ [over.built]p3:
9402   //
9403   //   For every pair (T, VQ), where T is an arithmetic type other
9404   //   than bool, and VQ is either volatile or empty, there exist
9405   //   candidate operator functions of the form
9406   //
9407   //       VQ T&      operator++(VQ T&);
9408   //       T          operator++(VQ T&, int);
9409   //
9410   // C++ [over.built]p4:
9411   //
9412   //   For every pair (T, VQ), where T is an arithmetic type other
9413   //   than bool, and VQ is either volatile or empty, there exist
9414   //   candidate operator functions of the form
9415   //
9416   //       VQ T&      operator--(VQ T&);
9417   //       T          operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)9418   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9419     if (!HasArithmeticOrEnumeralCandidateType)
9420       return;
9421 
9422     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9423       const auto TypeOfT = ArithmeticTypes[Arith];
9424       if (TypeOfT == S.Context.BoolTy) {
9425         if (Op == OO_MinusMinus)
9426           continue;
9427         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9428           continue;
9429       }
9430       addPlusPlusMinusMinusStyleOverloads(
9431         TypeOfT,
9432         VisibleTypeConversionsQuals.hasVolatile(),
9433         VisibleTypeConversionsQuals.hasRestrict());
9434     }
9435   }
9436 
9437   // C++ [over.built]p5:
9438   //
9439   //   For every pair (T, VQ), where T is a cv-qualified or
9440   //   cv-unqualified object type, and VQ is either volatile or
9441   //   empty, there exist candidate operator functions of the form
9442   //
9443   //       T*VQ&      operator++(T*VQ&);
9444   //       T*VQ&      operator--(T*VQ&);
9445   //       T*         operator++(T*VQ&, int);
9446   //       T*         operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()9447   void addPlusPlusMinusMinusPointerOverloads() {
9448     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9449       // Skip pointer types that aren't pointers to object types.
9450       if (!PtrTy->getPointeeType()->isObjectType())
9451         continue;
9452 
9453       addPlusPlusMinusMinusStyleOverloads(
9454           PtrTy,
9455           (!PtrTy.isVolatileQualified() &&
9456            VisibleTypeConversionsQuals.hasVolatile()),
9457           (!PtrTy.isRestrictQualified() &&
9458            VisibleTypeConversionsQuals.hasRestrict()));
9459     }
9460   }
9461 
9462   // C++ [over.built]p6:
9463   //   For every cv-qualified or cv-unqualified object type T, there
9464   //   exist candidate operator functions of the form
9465   //
9466   //       T&         operator*(T*);
9467   //
9468   // C++ [over.built]p7:
9469   //   For every function type T that does not have cv-qualifiers or a
9470   //   ref-qualifier, there exist candidate operator functions of the form
9471   //       T&         operator*(T*);
addUnaryStarPointerOverloads()9472   void addUnaryStarPointerOverloads() {
9473     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9474       QualType PointeeTy = ParamTy->getPointeeType();
9475       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9476         continue;
9477 
9478       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9479         if (Proto->getMethodQuals() || Proto->getRefQualifier())
9480           continue;
9481 
9482       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9483     }
9484   }
9485 
9486   // C++ [over.built]p9:
9487   //  For every promoted arithmetic type T, there exist candidate
9488   //  operator functions of the form
9489   //
9490   //       T         operator+(T);
9491   //       T         operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()9492   void addUnaryPlusOrMinusArithmeticOverloads() {
9493     if (!HasArithmeticOrEnumeralCandidateType)
9494       return;
9495 
9496     for (unsigned Arith = FirstPromotedArithmeticType;
9497          Arith < LastPromotedArithmeticType; ++Arith) {
9498       QualType ArithTy = ArithmeticTypes[Arith];
9499       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9500     }
9501 
9502     // Extension: We also add these operators for vector types.
9503     for (QualType VecTy : CandidateTypes[0].vector_types())
9504       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9505   }
9506 
9507   // C++ [over.built]p8:
9508   //   For every type T, there exist candidate operator functions of
9509   //   the form
9510   //
9511   //       T*         operator+(T*);
addUnaryPlusPointerOverloads()9512   void addUnaryPlusPointerOverloads() {
9513     for (QualType ParamTy : CandidateTypes[0].pointer_types())
9514       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9515   }
9516 
9517   // C++ [over.built]p10:
9518   //   For every promoted integral type T, there exist candidate
9519   //   operator functions of the form
9520   //
9521   //        T         operator~(T);
addUnaryTildePromotedIntegralOverloads()9522   void addUnaryTildePromotedIntegralOverloads() {
9523     if (!HasArithmeticOrEnumeralCandidateType)
9524       return;
9525 
9526     for (unsigned Int = FirstPromotedIntegralType;
9527          Int < LastPromotedIntegralType; ++Int) {
9528       QualType IntTy = ArithmeticTypes[Int];
9529       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9530     }
9531 
9532     // Extension: We also add this operator for vector types.
9533     for (QualType VecTy : CandidateTypes[0].vector_types())
9534       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9535   }
9536 
9537   // C++ [over.match.oper]p16:
9538   //   For every pointer to member type T or type std::nullptr_t, there
9539   //   exist candidate operator functions of the form
9540   //
9541   //        bool operator==(T,T);
9542   //        bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads()9543   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9544     /// Set of (canonical) types that we've already handled.
9545     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9546 
9547     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9548       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9549         // Don't add the same builtin candidate twice.
9550         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9551           continue;
9552 
9553         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9554         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9555       }
9556 
9557       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9558         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
9559         if (AddedTypes.insert(NullPtrTy).second) {
9560           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9561           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9562         }
9563       }
9564     }
9565   }
9566 
9567   // C++ [over.built]p15:
9568   //
9569   //   For every T, where T is an enumeration type or a pointer type,
9570   //   there exist candidate operator functions of the form
9571   //
9572   //        bool       operator<(T, T);
9573   //        bool       operator>(T, T);
9574   //        bool       operator<=(T, T);
9575   //        bool       operator>=(T, T);
9576   //        bool       operator==(T, T);
9577   //        bool       operator!=(T, T);
9578   //           R       operator<=>(T, T)
addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship)9579   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9580     // C++ [over.match.oper]p3:
9581     //   [...]the built-in candidates include all of the candidate operator
9582     //   functions defined in 13.6 that, compared to the given operator, [...]
9583     //   do not have the same parameter-type-list as any non-template non-member
9584     //   candidate.
9585     //
9586     // Note that in practice, this only affects enumeration types because there
9587     // aren't any built-in candidates of record type, and a user-defined operator
9588     // must have an operand of record or enumeration type. Also, the only other
9589     // overloaded operator with enumeration arguments, operator=,
9590     // cannot be overloaded for enumeration types, so this is the only place
9591     // where we must suppress candidates like this.
9592     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9593       UserDefinedBinaryOperators;
9594 
9595     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9596       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9597         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9598                                          CEnd = CandidateSet.end();
9599              C != CEnd; ++C) {
9600           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9601             continue;
9602 
9603           if (C->Function->isFunctionTemplateSpecialization())
9604             continue;
9605 
9606           // We interpret "same parameter-type-list" as applying to the
9607           // "synthesized candidate, with the order of the two parameters
9608           // reversed", not to the original function.
9609           bool Reversed = C->isReversed();
9610           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9611                                         ->getType()
9612                                         .getUnqualifiedType();
9613           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9614                                          ->getType()
9615                                          .getUnqualifiedType();
9616 
9617           // Skip if either parameter isn't of enumeral type.
9618           if (!FirstParamType->isEnumeralType() ||
9619               !SecondParamType->isEnumeralType())
9620             continue;
9621 
9622           // Add this operator to the set of known user-defined operators.
9623           UserDefinedBinaryOperators.insert(
9624             std::make_pair(S.Context.getCanonicalType(FirstParamType),
9625                            S.Context.getCanonicalType(SecondParamType)));
9626         }
9627       }
9628     }
9629 
9630     /// Set of (canonical) types that we've already handled.
9631     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9632 
9633     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9634       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9635         // Don't add the same builtin candidate twice.
9636         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9637           continue;
9638         if (IsSpaceship && PtrTy->isFunctionPointerType())
9639           continue;
9640 
9641         QualType ParamTypes[2] = {PtrTy, PtrTy};
9642         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9643       }
9644       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9645         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9646 
9647         // Don't add the same builtin candidate twice, or if a user defined
9648         // candidate exists.
9649         if (!AddedTypes.insert(CanonType).second ||
9650             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9651                                                             CanonType)))
9652           continue;
9653         QualType ParamTypes[2] = {EnumTy, EnumTy};
9654         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9655       }
9656     }
9657   }
9658 
9659   // C++ [over.built]p13:
9660   //
9661   //   For every cv-qualified or cv-unqualified object type T
9662   //   there exist candidate operator functions of the form
9663   //
9664   //      T*         operator+(T*, ptrdiff_t);
9665   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
9666   //      T*         operator-(T*, ptrdiff_t);
9667   //      T*         operator+(ptrdiff_t, T*);
9668   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
9669   //
9670   // C++ [over.built]p14:
9671   //
9672   //   For every T, where T is a pointer to object type, there
9673   //   exist candidate operator functions of the form
9674   //
9675   //      ptrdiff_t  operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)9676   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9677     /// Set of (canonical) types that we've already handled.
9678     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9679 
9680     for (int Arg = 0; Arg < 2; ++Arg) {
9681       QualType AsymmetricParamTypes[2] = {
9682         S.Context.getPointerDiffType(),
9683         S.Context.getPointerDiffType(),
9684       };
9685       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9686         QualType PointeeTy = PtrTy->getPointeeType();
9687         if (!PointeeTy->isObjectType())
9688           continue;
9689 
9690         AsymmetricParamTypes[Arg] = PtrTy;
9691         if (Arg == 0 || Op == OO_Plus) {
9692           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9693           // T* operator+(ptrdiff_t, T*);
9694           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9695         }
9696         if (Op == OO_Minus) {
9697           // ptrdiff_t operator-(T, T);
9698           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9699             continue;
9700 
9701           QualType ParamTypes[2] = {PtrTy, PtrTy};
9702           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9703         }
9704       }
9705     }
9706   }
9707 
9708   // C++ [over.built]p12:
9709   //
9710   //   For every pair of promoted arithmetic types L and R, there
9711   //   exist candidate operator functions of the form
9712   //
9713   //        LR         operator*(L, R);
9714   //        LR         operator/(L, R);
9715   //        LR         operator+(L, R);
9716   //        LR         operator-(L, R);
9717   //        bool       operator<(L, R);
9718   //        bool       operator>(L, R);
9719   //        bool       operator<=(L, R);
9720   //        bool       operator>=(L, R);
9721   //        bool       operator==(L, R);
9722   //        bool       operator!=(L, R);
9723   //
9724   //   where LR is the result of the usual arithmetic conversions
9725   //   between types L and R.
9726   //
9727   // C++ [over.built]p24:
9728   //
9729   //   For every pair of promoted arithmetic types L and R, there exist
9730   //   candidate operator functions of the form
9731   //
9732   //        LR       operator?(bool, L, R);
9733   //
9734   //   where LR is the result of the usual arithmetic conversions
9735   //   between types L and R.
9736   // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads()9737   void addGenericBinaryArithmeticOverloads() {
9738     if (!HasArithmeticOrEnumeralCandidateType)
9739       return;
9740 
9741     for (unsigned Left = FirstPromotedArithmeticType;
9742          Left < LastPromotedArithmeticType; ++Left) {
9743       for (unsigned Right = FirstPromotedArithmeticType;
9744            Right < LastPromotedArithmeticType; ++Right) {
9745         QualType LandR[2] = { ArithmeticTypes[Left],
9746                               ArithmeticTypes[Right] };
9747         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9748       }
9749     }
9750 
9751     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9752     // conditional operator for vector types.
9753     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9754       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9755         QualType LandR[2] = {Vec1Ty, Vec2Ty};
9756         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9757       }
9758   }
9759 
9760   /// Add binary operator overloads for each candidate matrix type M1, M2:
9761   ///  * (M1, M1) -> M1
9762   ///  * (M1, M1.getElementType()) -> M1
9763   ///  * (M2.getElementType(), M2) -> M2
9764   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
addMatrixBinaryArithmeticOverloads()9765   void addMatrixBinaryArithmeticOverloads() {
9766     if (!HasArithmeticOrEnumeralCandidateType)
9767       return;
9768 
9769     for (QualType M1 : CandidateTypes[0].matrix_types()) {
9770       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9771       AddCandidate(M1, M1);
9772     }
9773 
9774     for (QualType M2 : CandidateTypes[1].matrix_types()) {
9775       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9776       if (!CandidateTypes[0].containsMatrixType(M2))
9777         AddCandidate(M2, M2);
9778     }
9779   }
9780 
9781   // C++2a [over.built]p14:
9782   //
9783   //   For every integral type T there exists a candidate operator function
9784   //   of the form
9785   //
9786   //        std::strong_ordering operator<=>(T, T)
9787   //
9788   // C++2a [over.built]p15:
9789   //
9790   //   For every pair of floating-point types L and R, there exists a candidate
9791   //   operator function of the form
9792   //
9793   //       std::partial_ordering operator<=>(L, R);
9794   //
9795   // FIXME: The current specification for integral types doesn't play nice with
9796   // the direction of p0946r0, which allows mixed integral and unscoped-enum
9797   // comparisons. Under the current spec this can lead to ambiguity during
9798   // overload resolution. For example:
9799   //
9800   //   enum A : int {a};
9801   //   auto x = (a <=> (long)42);
9802   //
9803   //   error: call is ambiguous for arguments 'A' and 'long'.
9804   //   note: candidate operator<=>(int, int)
9805   //   note: candidate operator<=>(long, long)
9806   //
9807   // To avoid this error, this function deviates from the specification and adds
9808   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9809   // arithmetic types (the same as the generic relational overloads).
9810   //
9811   // For now this function acts as a placeholder.
addThreeWayArithmeticOverloads()9812   void addThreeWayArithmeticOverloads() {
9813     addGenericBinaryArithmeticOverloads();
9814   }
9815 
9816   // C++ [over.built]p17:
9817   //
9818   //   For every pair of promoted integral types L and R, there
9819   //   exist candidate operator functions of the form
9820   //
9821   //      LR         operator%(L, R);
9822   //      LR         operator&(L, R);
9823   //      LR         operator^(L, R);
9824   //      LR         operator|(L, R);
9825   //      L          operator<<(L, R);
9826   //      L          operator>>(L, R);
9827   //
9828   //   where LR is the result of the usual arithmetic conversions
9829   //   between types L and R.
addBinaryBitwiseArithmeticOverloads()9830   void addBinaryBitwiseArithmeticOverloads() {
9831     if (!HasArithmeticOrEnumeralCandidateType)
9832       return;
9833 
9834     for (unsigned Left = FirstPromotedIntegralType;
9835          Left < LastPromotedIntegralType; ++Left) {
9836       for (unsigned Right = FirstPromotedIntegralType;
9837            Right < LastPromotedIntegralType; ++Right) {
9838         QualType LandR[2] = { ArithmeticTypes[Left],
9839                               ArithmeticTypes[Right] };
9840         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9841       }
9842     }
9843   }
9844 
9845   // C++ [over.built]p20:
9846   //
9847   //   For every pair (T, VQ), where T is an enumeration or
9848   //   pointer to member type and VQ is either volatile or
9849   //   empty, there exist candidate operator functions of the form
9850   //
9851   //        VQ T&      operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()9852   void addAssignmentMemberPointerOrEnumeralOverloads() {
9853     /// Set of (canonical) types that we've already handled.
9854     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9855 
9856     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9857       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9858         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9859           continue;
9860 
9861         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9862       }
9863 
9864       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9865         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9866           continue;
9867 
9868         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9869       }
9870     }
9871   }
9872 
9873   // C++ [over.built]p19:
9874   //
9875   //   For every pair (T, VQ), where T is any type and VQ is either
9876   //   volatile or empty, there exist candidate operator functions
9877   //   of the form
9878   //
9879   //        T*VQ&      operator=(T*VQ&, T*);
9880   //
9881   // C++ [over.built]p21:
9882   //
9883   //   For every pair (T, VQ), where T is a cv-qualified or
9884   //   cv-unqualified object type and VQ is either volatile or
9885   //   empty, there exist candidate operator functions of the form
9886   //
9887   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
9888   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)9889   void addAssignmentPointerOverloads(bool isEqualOp) {
9890     /// Set of (canonical) types that we've already handled.
9891     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9892 
9893     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9894       // If this is operator=, keep track of the builtin candidates we added.
9895       if (isEqualOp)
9896         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9897       else if (!PtrTy->getPointeeType()->isObjectType())
9898         continue;
9899 
9900       // non-volatile version
9901       QualType ParamTypes[2] = {
9902           S.Context.getLValueReferenceType(PtrTy),
9903           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9904       };
9905       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9906                             /*IsAssignmentOperator=*/ isEqualOp);
9907 
9908       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9909                           VisibleTypeConversionsQuals.hasVolatile();
9910       if (NeedVolatile) {
9911         // volatile version
9912         ParamTypes[0] =
9913             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
9914         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9915                               /*IsAssignmentOperator=*/isEqualOp);
9916       }
9917 
9918       if (!PtrTy.isRestrictQualified() &&
9919           VisibleTypeConversionsQuals.hasRestrict()) {
9920         // restrict version
9921         ParamTypes[0] =
9922             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
9923         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9924                               /*IsAssignmentOperator=*/isEqualOp);
9925 
9926         if (NeedVolatile) {
9927           // volatile restrict version
9928           ParamTypes[0] =
9929               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9930                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9931           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9932                                 /*IsAssignmentOperator=*/isEqualOp);
9933         }
9934       }
9935     }
9936 
9937     if (isEqualOp) {
9938       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9939         // Make sure we don't add the same candidate twice.
9940         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9941           continue;
9942 
9943         QualType ParamTypes[2] = {
9944             S.Context.getLValueReferenceType(PtrTy),
9945             PtrTy,
9946         };
9947 
9948         // non-volatile version
9949         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9950                               /*IsAssignmentOperator=*/true);
9951 
9952         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9953                             VisibleTypeConversionsQuals.hasVolatile();
9954         if (NeedVolatile) {
9955           // volatile version
9956           ParamTypes[0] = S.Context.getLValueReferenceType(
9957               S.Context.getVolatileType(PtrTy));
9958           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9959                                 /*IsAssignmentOperator=*/true);
9960         }
9961 
9962         if (!PtrTy.isRestrictQualified() &&
9963             VisibleTypeConversionsQuals.hasRestrict()) {
9964           // restrict version
9965           ParamTypes[0] = S.Context.getLValueReferenceType(
9966               S.Context.getRestrictType(PtrTy));
9967           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9968                                 /*IsAssignmentOperator=*/true);
9969 
9970           if (NeedVolatile) {
9971             // volatile restrict version
9972             ParamTypes[0] =
9973                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9974                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9975             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9976                                   /*IsAssignmentOperator=*/true);
9977           }
9978         }
9979       }
9980     }
9981   }
9982 
9983   // C++ [over.built]p18:
9984   //
9985   //   For every triple (L, VQ, R), where L is an arithmetic type,
9986   //   VQ is either volatile or empty, and R is a promoted
9987   //   arithmetic type, there exist candidate operator functions of
9988   //   the form
9989   //
9990   //        VQ L&      operator=(VQ L&, R);
9991   //        VQ L&      operator*=(VQ L&, R);
9992   //        VQ L&      operator/=(VQ L&, R);
9993   //        VQ L&      operator+=(VQ L&, R);
9994   //        VQ L&      operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)9995   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9996     if (!HasArithmeticOrEnumeralCandidateType)
9997       return;
9998 
9999     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10000       for (unsigned Right = FirstPromotedArithmeticType;
10001            Right < LastPromotedArithmeticType; ++Right) {
10002         QualType ParamTypes[2];
10003         ParamTypes[1] = ArithmeticTypes[Right];
10004         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10005             S, ArithmeticTypes[Left], Args[0]);
10006 
10007         forAllQualifierCombinations(
10008             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10009               ParamTypes[0] =
10010                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10011               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10012                                     /*IsAssignmentOperator=*/isEqualOp);
10013             });
10014       }
10015     }
10016 
10017     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10018     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10019       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10020         QualType ParamTypes[2];
10021         ParamTypes[1] = Vec2Ty;
10022         // Add this built-in operator as a candidate (VQ is empty).
10023         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10024         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10025                               /*IsAssignmentOperator=*/isEqualOp);
10026 
10027         // Add this built-in operator as a candidate (VQ is 'volatile').
10028         if (VisibleTypeConversionsQuals.hasVolatile()) {
10029           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10030           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10031           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10032                                 /*IsAssignmentOperator=*/isEqualOp);
10033         }
10034       }
10035   }
10036 
10037   // C++ [over.built]p22:
10038   //
10039   //   For every triple (L, VQ, R), where L is an integral type, VQ
10040   //   is either volatile or empty, and R is a promoted integral
10041   //   type, there exist candidate operator functions of the form
10042   //
10043   //        VQ L&       operator%=(VQ L&, R);
10044   //        VQ L&       operator<<=(VQ L&, R);
10045   //        VQ L&       operator>>=(VQ L&, R);
10046   //        VQ L&       operator&=(VQ L&, R);
10047   //        VQ L&       operator^=(VQ L&, R);
10048   //        VQ L&       operator|=(VQ L&, R);
addAssignmentIntegralOverloads()10049   void addAssignmentIntegralOverloads() {
10050     if (!HasArithmeticOrEnumeralCandidateType)
10051       return;
10052 
10053     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10054       for (unsigned Right = FirstPromotedIntegralType;
10055            Right < LastPromotedIntegralType; ++Right) {
10056         QualType ParamTypes[2];
10057         ParamTypes[1] = ArithmeticTypes[Right];
10058         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10059             S, ArithmeticTypes[Left], Args[0]);
10060 
10061         forAllQualifierCombinations(
10062             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10063               ParamTypes[0] =
10064                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10065               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10066             });
10067       }
10068     }
10069   }
10070 
10071   // C++ [over.operator]p23:
10072   //
10073   //   There also exist candidate operator functions of the form
10074   //
10075   //        bool        operator!(bool);
10076   //        bool        operator&&(bool, bool);
10077   //        bool        operator||(bool, bool);
addExclaimOverload()10078   void addExclaimOverload() {
10079     QualType ParamTy = S.Context.BoolTy;
10080     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10081                           /*IsAssignmentOperator=*/false,
10082                           /*NumContextualBoolArguments=*/1);
10083   }
addAmpAmpOrPipePipeOverload()10084   void addAmpAmpOrPipePipeOverload() {
10085     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10086     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10087                           /*IsAssignmentOperator=*/false,
10088                           /*NumContextualBoolArguments=*/2);
10089   }
10090 
10091   // C++ [over.built]p13:
10092   //
10093   //   For every cv-qualified or cv-unqualified object type T there
10094   //   exist candidate operator functions of the form
10095   //
10096   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
10097   //        T&         operator[](T*, ptrdiff_t);
10098   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
10099   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
10100   //        T&         operator[](ptrdiff_t, T*);
addSubscriptOverloads()10101   void addSubscriptOverloads() {
10102     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10103       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10104       QualType PointeeType = PtrTy->getPointeeType();
10105       if (!PointeeType->isObjectType())
10106         continue;
10107 
10108       // T& operator[](T*, ptrdiff_t)
10109       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10110     }
10111 
10112     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10113       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10114       QualType PointeeType = PtrTy->getPointeeType();
10115       if (!PointeeType->isObjectType())
10116         continue;
10117 
10118       // T& operator[](ptrdiff_t, T*)
10119       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10120     }
10121   }
10122 
10123   // C++ [over.built]p11:
10124   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10125   //    C1 is the same type as C2 or is a derived class of C2, T is an object
10126   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10127   //    there exist candidate operator functions of the form
10128   //
10129   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10130   //
10131   //    where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()10132   void addArrowStarOverloads() {
10133     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10134       QualType C1Ty = PtrTy;
10135       QualType C1;
10136       QualifierCollector Q1;
10137       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10138       if (!isa<RecordType>(C1))
10139         continue;
10140       // heuristic to reduce number of builtin candidates in the set.
10141       // Add volatile/restrict version only if there are conversions to a
10142       // volatile/restrict type.
10143       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10144         continue;
10145       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10146         continue;
10147       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10148         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10149         CXXRecordDecl *D1 = C1->getAsCXXRecordDecl(),
10150                       *D2 = mptr->getMostRecentCXXRecordDecl();
10151         if (!declaresSameEntity(D1, D2) &&
10152             !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10153           break;
10154         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10155         // build CV12 T&
10156         QualType T = mptr->getPointeeType();
10157         if (!VisibleTypeConversionsQuals.hasVolatile() &&
10158             T.isVolatileQualified())
10159           continue;
10160         if (!VisibleTypeConversionsQuals.hasRestrict() &&
10161             T.isRestrictQualified())
10162           continue;
10163         T = Q1.apply(S.Context, T);
10164         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10165       }
10166     }
10167   }
10168 
10169   // Note that we don't consider the first argument, since it has been
10170   // contextually converted to bool long ago. The candidates below are
10171   // therefore added as binary.
10172   //
10173   // C++ [over.built]p25:
10174   //   For every type T, where T is a pointer, pointer-to-member, or scoped
10175   //   enumeration type, there exist candidate operator functions of the form
10176   //
10177   //        T        operator?(bool, T, T);
10178   //
addConditionalOperatorOverloads()10179   void addConditionalOperatorOverloads() {
10180     /// Set of (canonical) types that we've already handled.
10181     llvm::SmallPtrSet<QualType, 8> AddedTypes;
10182 
10183     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10184       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10185         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10186           continue;
10187 
10188         QualType ParamTypes[2] = {PtrTy, PtrTy};
10189         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10190       }
10191 
10192       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10193         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10194           continue;
10195 
10196         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10197         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10198       }
10199 
10200       if (S.getLangOpts().CPlusPlus11) {
10201         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10202           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
10203             continue;
10204 
10205           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10206             continue;
10207 
10208           QualType ParamTypes[2] = {EnumTy, EnumTy};
10209           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10210         }
10211       }
10212     }
10213   }
10214 };
10215 
10216 } // end anonymous namespace
10217 
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)10218 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10219                                         SourceLocation OpLoc,
10220                                         ArrayRef<Expr *> Args,
10221                                         OverloadCandidateSet &CandidateSet) {
10222   // Find all of the types that the arguments can convert to, but only
10223   // if the operator we're looking at has built-in operator candidates
10224   // that make use of these types. Also record whether we encounter non-record
10225   // candidate types or either arithmetic or enumeral candidate types.
10226   QualifiersAndAtomic VisibleTypeConversionsQuals;
10227   VisibleTypeConversionsQuals.addConst();
10228   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10229     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10230     if (Args[ArgIdx]->getType()->isAtomicType())
10231       VisibleTypeConversionsQuals.addAtomic();
10232   }
10233 
10234   bool HasNonRecordCandidateType = false;
10235   bool HasArithmeticOrEnumeralCandidateType = false;
10236   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10237   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10238     CandidateTypes.emplace_back(*this);
10239     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10240                                                  OpLoc,
10241                                                  true,
10242                                                  (Op == OO_Exclaim ||
10243                                                   Op == OO_AmpAmp ||
10244                                                   Op == OO_PipePipe),
10245                                                  VisibleTypeConversionsQuals);
10246     HasNonRecordCandidateType = HasNonRecordCandidateType ||
10247         CandidateTypes[ArgIdx].hasNonRecordTypes();
10248     HasArithmeticOrEnumeralCandidateType =
10249         HasArithmeticOrEnumeralCandidateType ||
10250         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10251   }
10252 
10253   // Exit early when no non-record types have been added to the candidate set
10254   // for any of the arguments to the operator.
10255   //
10256   // We can't exit early for !, ||, or &&, since there we have always have
10257   // 'bool' overloads.
10258   if (!HasNonRecordCandidateType &&
10259       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10260     return;
10261 
10262   // Setup an object to manage the common state for building overloads.
10263   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10264                                            VisibleTypeConversionsQuals,
10265                                            HasArithmeticOrEnumeralCandidateType,
10266                                            CandidateTypes, CandidateSet);
10267 
10268   // Dispatch over the operation to add in only those overloads which apply.
10269   switch (Op) {
10270   case OO_None:
10271   case NUM_OVERLOADED_OPERATORS:
10272     llvm_unreachable("Expected an overloaded operator");
10273 
10274   case OO_New:
10275   case OO_Delete:
10276   case OO_Array_New:
10277   case OO_Array_Delete:
10278   case OO_Call:
10279     llvm_unreachable(
10280                     "Special operators don't use AddBuiltinOperatorCandidates");
10281 
10282   case OO_Comma:
10283   case OO_Arrow:
10284   case OO_Coawait:
10285     // C++ [over.match.oper]p3:
10286     //   -- For the operator ',', the unary operator '&', the
10287     //      operator '->', or the operator 'co_await', the
10288     //      built-in candidates set is empty.
10289     break;
10290 
10291   case OO_Plus: // '+' is either unary or binary
10292     if (Args.size() == 1)
10293       OpBuilder.addUnaryPlusPointerOverloads();
10294     [[fallthrough]];
10295 
10296   case OO_Minus: // '-' is either unary or binary
10297     if (Args.size() == 1) {
10298       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10299     } else {
10300       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10301       OpBuilder.addGenericBinaryArithmeticOverloads();
10302       OpBuilder.addMatrixBinaryArithmeticOverloads();
10303     }
10304     break;
10305 
10306   case OO_Star: // '*' is either unary or binary
10307     if (Args.size() == 1)
10308       OpBuilder.addUnaryStarPointerOverloads();
10309     else {
10310       OpBuilder.addGenericBinaryArithmeticOverloads();
10311       OpBuilder.addMatrixBinaryArithmeticOverloads();
10312     }
10313     break;
10314 
10315   case OO_Slash:
10316     OpBuilder.addGenericBinaryArithmeticOverloads();
10317     break;
10318 
10319   case OO_PlusPlus:
10320   case OO_MinusMinus:
10321     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10322     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10323     break;
10324 
10325   case OO_EqualEqual:
10326   case OO_ExclaimEqual:
10327     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10328     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10329     OpBuilder.addGenericBinaryArithmeticOverloads();
10330     break;
10331 
10332   case OO_Less:
10333   case OO_Greater:
10334   case OO_LessEqual:
10335   case OO_GreaterEqual:
10336     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10337     OpBuilder.addGenericBinaryArithmeticOverloads();
10338     break;
10339 
10340   case OO_Spaceship:
10341     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10342     OpBuilder.addThreeWayArithmeticOverloads();
10343     break;
10344 
10345   case OO_Percent:
10346   case OO_Caret:
10347   case OO_Pipe:
10348   case OO_LessLess:
10349   case OO_GreaterGreater:
10350     OpBuilder.addBinaryBitwiseArithmeticOverloads();
10351     break;
10352 
10353   case OO_Amp: // '&' is either unary or binary
10354     if (Args.size() == 1)
10355       // C++ [over.match.oper]p3:
10356       //   -- For the operator ',', the unary operator '&', or the
10357       //      operator '->', the built-in candidates set is empty.
10358       break;
10359 
10360     OpBuilder.addBinaryBitwiseArithmeticOverloads();
10361     break;
10362 
10363   case OO_Tilde:
10364     OpBuilder.addUnaryTildePromotedIntegralOverloads();
10365     break;
10366 
10367   case OO_Equal:
10368     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10369     [[fallthrough]];
10370 
10371   case OO_PlusEqual:
10372   case OO_MinusEqual:
10373     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10374     [[fallthrough]];
10375 
10376   case OO_StarEqual:
10377   case OO_SlashEqual:
10378     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10379     break;
10380 
10381   case OO_PercentEqual:
10382   case OO_LessLessEqual:
10383   case OO_GreaterGreaterEqual:
10384   case OO_AmpEqual:
10385   case OO_CaretEqual:
10386   case OO_PipeEqual:
10387     OpBuilder.addAssignmentIntegralOverloads();
10388     break;
10389 
10390   case OO_Exclaim:
10391     OpBuilder.addExclaimOverload();
10392     break;
10393 
10394   case OO_AmpAmp:
10395   case OO_PipePipe:
10396     OpBuilder.addAmpAmpOrPipePipeOverload();
10397     break;
10398 
10399   case OO_Subscript:
10400     if (Args.size() == 2)
10401       OpBuilder.addSubscriptOverloads();
10402     break;
10403 
10404   case OO_ArrowStar:
10405     OpBuilder.addArrowStarOverloads();
10406     break;
10407 
10408   case OO_Conditional:
10409     OpBuilder.addConditionalOperatorOverloads();
10410     OpBuilder.addGenericBinaryArithmeticOverloads();
10411     break;
10412   }
10413 }
10414 
10415 void
AddArgumentDependentLookupCandidates(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading)10416 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10417                                            SourceLocation Loc,
10418                                            ArrayRef<Expr *> Args,
10419                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
10420                                            OverloadCandidateSet& CandidateSet,
10421                                            bool PartialOverloading) {
10422   ADLResult Fns;
10423 
10424   // FIXME: This approach for uniquing ADL results (and removing
10425   // redundant candidates from the set) relies on pointer-equality,
10426   // which means we need to key off the canonical decl.  However,
10427   // always going back to the canonical decl might not get us the
10428   // right set of default arguments.  What default arguments are
10429   // we supposed to consider on ADL candidates, anyway?
10430 
10431   // FIXME: Pass in the explicit template arguments?
10432   ArgumentDependentLookup(Name, Loc, Args, Fns);
10433 
10434   ArrayRef<Expr *> ReversedArgs;
10435 
10436   // Erase all of the candidates we already knew about.
10437   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10438                                    CandEnd = CandidateSet.end();
10439        Cand != CandEnd; ++Cand)
10440     if (Cand->Function) {
10441       FunctionDecl *Fn = Cand->Function;
10442       Fns.erase(Fn);
10443       if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10444         Fns.erase(FunTmpl);
10445     }
10446 
10447   // For each of the ADL candidates we found, add it to the overload
10448   // set.
10449   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10450     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
10451 
10452     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10453       if (ExplicitTemplateArgs)
10454         continue;
10455 
10456       AddOverloadCandidate(
10457           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10458           PartialOverloading, /*AllowExplicit=*/true,
10459           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10460       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10461         AddOverloadCandidate(
10462             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10463             /*SuppressUserConversions=*/false, PartialOverloading,
10464             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10465             ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10466       }
10467     } else {
10468       auto *FTD = cast<FunctionTemplateDecl>(*I);
10469       AddTemplateOverloadCandidate(
10470           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10471           /*SuppressUserConversions=*/false, PartialOverloading,
10472           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10473       if (CandidateSet.getRewriteInfo().shouldAddReversed(
10474               *this, Args, FTD->getTemplatedDecl())) {
10475 
10476         // As template candidates are not deduced immediately,
10477         // persist the array in the overload set.
10478         if (ReversedArgs.empty())
10479           ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10480 
10481         AddTemplateOverloadCandidate(
10482             FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10483             /*SuppressUserConversions=*/false, PartialOverloading,
10484             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10485             OverloadCandidateParamOrder::Reversed);
10486       }
10487     }
10488   }
10489 }
10490 
10491 namespace {
10492 enum class Comparison { Equal, Better, Worse };
10493 }
10494 
10495 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10496 /// overload resolution.
10497 ///
10498 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10499 /// Cand1's first N enable_if attributes have precisely the same conditions as
10500 /// Cand2's first N enable_if attributes (where N = the number of enable_if
10501 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10502 ///
10503 /// Note that you can have a pair of candidates such that Cand1's enable_if
10504 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10505 /// worse than Cand1's.
compareEnableIfAttrs(const Sema & S,const FunctionDecl * Cand1,const FunctionDecl * Cand2)10506 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10507                                        const FunctionDecl *Cand2) {
10508   // Common case: One (or both) decls don't have enable_if attrs.
10509   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10510   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10511   if (!Cand1Attr || !Cand2Attr) {
10512     if (Cand1Attr == Cand2Attr)
10513       return Comparison::Equal;
10514     return Cand1Attr ? Comparison::Better : Comparison::Worse;
10515   }
10516 
10517   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10518   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10519 
10520   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10521   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10522     std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10523     std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10524 
10525     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10526     // has fewer enable_if attributes than Cand2, and vice versa.
10527     if (!Cand1A)
10528       return Comparison::Worse;
10529     if (!Cand2A)
10530       return Comparison::Better;
10531 
10532     Cand1ID.clear();
10533     Cand2ID.clear();
10534 
10535     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10536     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10537     if (Cand1ID != Cand2ID)
10538       return Comparison::Worse;
10539   }
10540 
10541   return Comparison::Equal;
10542 }
10543 
10544 static Comparison
isBetterMultiversionCandidate(const OverloadCandidate & Cand1,const OverloadCandidate & Cand2)10545 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10546                               const OverloadCandidate &Cand2) {
10547   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10548       !Cand2.Function->isMultiVersion())
10549     return Comparison::Equal;
10550 
10551   // If both are invalid, they are equal. If one of them is invalid, the other
10552   // is better.
10553   if (Cand1.Function->isInvalidDecl()) {
10554     if (Cand2.Function->isInvalidDecl())
10555       return Comparison::Equal;
10556     return Comparison::Worse;
10557   }
10558   if (Cand2.Function->isInvalidDecl())
10559     return Comparison::Better;
10560 
10561   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10562   // cpu_dispatch, else arbitrarily based on the identifiers.
10563   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10564   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10565   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10566   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10567 
10568   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10569     return Comparison::Equal;
10570 
10571   if (Cand1CPUDisp && !Cand2CPUDisp)
10572     return Comparison::Better;
10573   if (Cand2CPUDisp && !Cand1CPUDisp)
10574     return Comparison::Worse;
10575 
10576   if (Cand1CPUSpec && Cand2CPUSpec) {
10577     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10578       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10579                  ? Comparison::Better
10580                  : Comparison::Worse;
10581 
10582     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10583         FirstDiff = std::mismatch(
10584             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10585             Cand2CPUSpec->cpus_begin(),
10586             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10587               return LHS->getName() == RHS->getName();
10588             });
10589 
10590     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10591            "Two different cpu-specific versions should not have the same "
10592            "identifier list, otherwise they'd be the same decl!");
10593     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10594                ? Comparison::Better
10595                : Comparison::Worse;
10596   }
10597   llvm_unreachable("No way to get here unless both had cpu_dispatch");
10598 }
10599 
10600 /// Compute the type of the implicit object parameter for the given function,
10601 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10602 /// null QualType if there is a 'matches anything' implicit object parameter.
10603 static std::optional<QualType>
getImplicitObjectParamType(ASTContext & Context,const FunctionDecl * F)10604 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10605   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10606     return std::nullopt;
10607 
10608   auto *M = cast<CXXMethodDecl>(F);
10609   // Static member functions' object parameters match all types.
10610   if (M->isStatic())
10611     return QualType();
10612   return M->getFunctionObjectParameterReferenceType();
10613 }
10614 
10615 // As a Clang extension, allow ambiguity among F1 and F2 if they represent
10616 // represent the same entity.
allowAmbiguity(ASTContext & Context,const FunctionDecl * F1,const FunctionDecl * F2)10617 static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10618                            const FunctionDecl *F2) {
10619   if (declaresSameEntity(F1, F2))
10620     return true;
10621   auto PT1 = F1->getPrimaryTemplate();
10622   auto PT2 = F2->getPrimaryTemplate();
10623   if (PT1 && PT2) {
10624     if (declaresSameEntity(PT1, PT2) ||
10625         declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10626                            PT2->getInstantiatedFromMemberTemplate()))
10627       return true;
10628   }
10629   // TODO: It is not clear whether comparing parameters is necessary (i.e.
10630   // different functions with same params). Consider removing this (as no test
10631   // fail w/o it).
10632   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10633     if (First) {
10634       if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10635         return *T;
10636     }
10637     assert(I < F->getNumParams());
10638     return F->getParamDecl(I++)->getType();
10639   };
10640 
10641   unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10642   unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10643 
10644   if (F1NumParams != F2NumParams)
10645     return false;
10646 
10647   unsigned I1 = 0, I2 = 0;
10648   for (unsigned I = 0; I != F1NumParams; ++I) {
10649     QualType T1 = NextParam(F1, I1, I == 0);
10650     QualType T2 = NextParam(F2, I2, I == 0);
10651     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10652     if (!Context.hasSameUnqualifiedType(T1, T2))
10653       return false;
10654   }
10655   return true;
10656 }
10657 
10658 /// We're allowed to use constraints partial ordering only if the candidates
10659 /// have the same parameter types:
10660 /// [over.match.best.general]p2.6
10661 /// F1 and F2 are non-template functions with the same
10662 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
sameFunctionParameterTypeLists(Sema & S,FunctionDecl * Fn1,FunctionDecl * Fn2,bool IsFn1Reversed,bool IsFn2Reversed)10663 static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10664                                            FunctionDecl *Fn2,
10665                                            bool IsFn1Reversed,
10666                                            bool IsFn2Reversed) {
10667   assert(Fn1 && Fn2);
10668   if (Fn1->isVariadic() != Fn2->isVariadic())
10669     return false;
10670 
10671   if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10672                                              IsFn1Reversed ^ IsFn2Reversed))
10673     return false;
10674 
10675   auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10676   auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10677   if (Mem1 && Mem2) {
10678     // if they are member functions, both are direct members of the same class,
10679     // and
10680     if (Mem1->getParent() != Mem2->getParent())
10681       return false;
10682     // if both are non-static member functions, they have the same types for
10683     // their object parameters
10684     if (Mem1->isInstance() && Mem2->isInstance() &&
10685         !S.getASTContext().hasSameType(
10686             Mem1->getFunctionObjectParameterReferenceType(),
10687             Mem1->getFunctionObjectParameterReferenceType()))
10688       return false;
10689   }
10690   return true;
10691 }
10692 
10693 static FunctionDecl *
getMorePartialOrderingConstrained(Sema & S,FunctionDecl * Fn1,FunctionDecl * Fn2,bool IsFn1Reversed,bool IsFn2Reversed)10694 getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10695                                   bool IsFn1Reversed, bool IsFn2Reversed) {
10696   if (!Fn1 || !Fn2)
10697     return nullptr;
10698 
10699   // C++ [temp.constr.order]:
10700   //   A non-template function F1 is more partial-ordering-constrained than a
10701   //   non-template function F2 if:
10702   bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10703   bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10704 
10705   if (Cand1IsSpecialization || Cand2IsSpecialization)
10706     return nullptr;
10707 
10708   // - they have the same non-object-parameter-type-lists, and [...]
10709   if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10710                                       IsFn2Reversed))
10711     return nullptr;
10712 
10713   // - the declaration of F1 is more constrained than the declaration of F2.
10714   return S.getMoreConstrainedFunction(Fn1, Fn2);
10715 }
10716 
10717 /// isBetterOverloadCandidate - Determines whether the first overload
10718 /// 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,bool PartialOverloading)10719 bool clang::isBetterOverloadCandidate(
10720     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10721     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10722     bool PartialOverloading) {
10723   // Define viable functions to be better candidates than non-viable
10724   // functions.
10725   if (!Cand2.Viable)
10726     return Cand1.Viable;
10727   else if (!Cand1.Viable)
10728     return false;
10729 
10730   // [CUDA] A function with 'never' preference is marked not viable, therefore
10731   // is never shown up here. The worst preference shown up here is 'wrong side',
10732   // e.g. an H function called by a HD function in device compilation. This is
10733   // valid AST as long as the HD function is not emitted, e.g. it is an inline
10734   // function which is called only by an H function. A deferred diagnostic will
10735   // be triggered if it is emitted. However a wrong-sided function is still
10736   // a viable candidate here.
10737   //
10738   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10739   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10740   // can be emitted, Cand1 is not better than Cand2. This rule should have
10741   // precedence over other rules.
10742   //
10743   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10744   // other rules should be used to determine which is better. This is because
10745   // host/device based overloading resolution is mostly for determining
10746   // viability of a function. If two functions are both viable, other factors
10747   // should take precedence in preference, e.g. the standard-defined preferences
10748   // like argument conversion ranks or enable_if partial-ordering. The
10749   // preference for pass-object-size parameters is probably most similar to a
10750   // type-based-overloading decision and so should take priority.
10751   //
10752   // If other rules cannot determine which is better, CUDA preference will be
10753   // used again to determine which is better.
10754   //
10755   // TODO: Currently IdentifyPreference does not return correct values
10756   // for functions called in global variable initializers due to missing
10757   // correct context about device/host. Therefore we can only enforce this
10758   // rule when there is a caller. We should enforce this rule for functions
10759   // in global variable initializers once proper context is added.
10760   //
10761   // TODO: We can only enable the hostness based overloading resolution when
10762   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10763   // overloading resolution diagnostics.
10764   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10765       S.getLangOpts().GPUExcludeWrongSideOverloads) {
10766     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10767       bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10768       bool IsCand1ImplicitHD =
10769           SemaCUDA::isImplicitHostDeviceFunction(Cand1.Function);
10770       bool IsCand2ImplicitHD =
10771           SemaCUDA::isImplicitHostDeviceFunction(Cand2.Function);
10772       auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10773       auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10774       assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10775       // The implicit HD function may be a function in a system header which
10776       // is forced by pragma. In device compilation, if we prefer HD candidates
10777       // over wrong-sided candidates, overloading resolution may change, which
10778       // may result in non-deferrable diagnostics. As a workaround, we let
10779       // implicit HD candidates take equal preference as wrong-sided candidates.
10780       // This will preserve the overloading resolution.
10781       // TODO: We still need special handling of implicit HD functions since
10782       // they may incur other diagnostics to be deferred. We should make all
10783       // host/device related diagnostics deferrable and remove special handling
10784       // of implicit HD functions.
10785       auto EmitThreshold =
10786           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10787            (IsCand1ImplicitHD || IsCand2ImplicitHD))
10788               ? SemaCUDA::CFP_Never
10789               : SemaCUDA::CFP_WrongSide;
10790       auto Cand1Emittable = P1 > EmitThreshold;
10791       auto Cand2Emittable = P2 > EmitThreshold;
10792       if (Cand1Emittable && !Cand2Emittable)
10793         return true;
10794       if (!Cand1Emittable && Cand2Emittable)
10795         return false;
10796     }
10797   }
10798 
10799   // C++ [over.match.best]p1: (Changed in C++23)
10800   //
10801   //   -- if F is a static member function, ICS1(F) is defined such
10802   //      that ICS1(F) is neither better nor worse than ICS1(G) for
10803   //      any function G, and, symmetrically, ICS1(G) is neither
10804   //      better nor worse than ICS1(F).
10805   unsigned StartArg = 0;
10806   if (!Cand1.TookAddressOfOverload &&
10807       (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
10808     StartArg = 1;
10809 
10810   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10811     // We don't allow incompatible pointer conversions in C++.
10812     if (!S.getLangOpts().CPlusPlus)
10813       return ICS.isStandard() &&
10814              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10815 
10816     // The only ill-formed conversion we allow in C++ is the string literal to
10817     // char* conversion, which is only considered ill-formed after C++11.
10818     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10819            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10820   };
10821 
10822   // Define functions that don't require ill-formed conversions for a given
10823   // argument to be better candidates than functions that do.
10824   unsigned NumArgs = Cand1.Conversions.size();
10825   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10826   bool HasBetterConversion = false;
10827   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10828     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10829     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10830     if (Cand1Bad != Cand2Bad) {
10831       if (Cand1Bad)
10832         return false;
10833       HasBetterConversion = true;
10834     }
10835   }
10836 
10837   if (HasBetterConversion)
10838     return true;
10839 
10840   // C++ [over.match.best]p1:
10841   //   A viable function F1 is defined to be a better function than another
10842   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
10843   //   conversion sequence than ICSi(F2), and then...
10844   bool HasWorseConversion = false;
10845   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10846     switch (CompareImplicitConversionSequences(S, Loc,
10847                                                Cand1.Conversions[ArgIdx],
10848                                                Cand2.Conversions[ArgIdx])) {
10849     case ImplicitConversionSequence::Better:
10850       // Cand1 has a better conversion sequence.
10851       HasBetterConversion = true;
10852       break;
10853 
10854     case ImplicitConversionSequence::Worse:
10855       if (Cand1.Function && Cand2.Function &&
10856           Cand1.isReversed() != Cand2.isReversed() &&
10857           allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10858         // Work around large-scale breakage caused by considering reversed
10859         // forms of operator== in C++20:
10860         //
10861         // When comparing a function against a reversed function, if we have a
10862         // better conversion for one argument and a worse conversion for the
10863         // other, the implicit conversion sequences are treated as being equally
10864         // good.
10865         //
10866         // This prevents a comparison function from being considered ambiguous
10867         // with a reversed form that is written in the same way.
10868         //
10869         // We diagnose this as an extension from CreateOverloadedBinOp.
10870         HasWorseConversion = true;
10871         break;
10872       }
10873 
10874       // Cand1 can't be better than Cand2.
10875       return false;
10876 
10877     case ImplicitConversionSequence::Indistinguishable:
10878       // Do nothing.
10879       break;
10880     }
10881   }
10882 
10883   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
10884   //       ICSj(F2), or, if not that,
10885   if (HasBetterConversion && !HasWorseConversion)
10886     return true;
10887 
10888   //   -- the context is an initialization by user-defined conversion
10889   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
10890   //      from the return type of F1 to the destination type (i.e.,
10891   //      the type of the entity being initialized) is a better
10892   //      conversion sequence than the standard conversion sequence
10893   //      from the return type of F2 to the destination type.
10894   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10895       Cand1.Function && Cand2.Function &&
10896       isa<CXXConversionDecl>(Cand1.Function) &&
10897       isa<CXXConversionDecl>(Cand2.Function)) {
10898 
10899     assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10900     // First check whether we prefer one of the conversion functions over the
10901     // other. This only distinguishes the results in non-standard, extension
10902     // cases such as the conversion from a lambda closure type to a function
10903     // pointer or block.
10904     ImplicitConversionSequence::CompareKind Result =
10905         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10906     if (Result == ImplicitConversionSequence::Indistinguishable)
10907       Result = CompareStandardConversionSequences(S, Loc,
10908                                                   Cand1.FinalConversion,
10909                                                   Cand2.FinalConversion);
10910 
10911     if (Result != ImplicitConversionSequence::Indistinguishable)
10912       return Result == ImplicitConversionSequence::Better;
10913 
10914     // FIXME: Compare kind of reference binding if conversion functions
10915     // convert to a reference type used in direct reference binding, per
10916     // C++14 [over.match.best]p1 section 2 bullet 3.
10917   }
10918 
10919   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10920   // as combined with the resolution to CWG issue 243.
10921   //
10922   // When the context is initialization by constructor ([over.match.ctor] or
10923   // either phase of [over.match.list]), a constructor is preferred over
10924   // a conversion function.
10925   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10926       Cand1.Function && Cand2.Function &&
10927       isa<CXXConstructorDecl>(Cand1.Function) !=
10928           isa<CXXConstructorDecl>(Cand2.Function))
10929     return isa<CXXConstructorDecl>(Cand1.Function);
10930 
10931   if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10932     return Cand2.StrictPackMatch;
10933 
10934   //    -- F1 is a non-template function and F2 is a function template
10935   //       specialization, or, if not that,
10936   bool Cand1IsSpecialization = Cand1.Function &&
10937                                Cand1.Function->getPrimaryTemplate();
10938   bool Cand2IsSpecialization = Cand2.Function &&
10939                                Cand2.Function->getPrimaryTemplate();
10940   if (Cand1IsSpecialization != Cand2IsSpecialization)
10941     return Cand2IsSpecialization;
10942 
10943   //   -- F1 and F2 are function template specializations, and the function
10944   //      template for F1 is more specialized than the template for F2
10945   //      according to the partial ordering rules described in 14.5.5.2, or,
10946   //      if not that,
10947   if (Cand1IsSpecialization && Cand2IsSpecialization) {
10948     const auto *Obj1Context =
10949         dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10950     const auto *Obj2Context =
10951         dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10952     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10953             Cand1.Function->getPrimaryTemplate(),
10954             Cand2.Function->getPrimaryTemplate(), Loc,
10955             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10956                                                    : TPOC_Call,
10957             Cand1.ExplicitCallArguments,
10958             Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10959                         : QualType{},
10960             Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10961                         : QualType{},
10962             Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10963       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10964     }
10965   }
10966 
10967   //   -— F1 and F2 are non-template functions and F1 is more
10968   //      partial-ordering-constrained than F2 [...],
10969   if (FunctionDecl *F = getMorePartialOrderingConstrained(
10970           S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10971           Cand2.isReversed());
10972       F && F == Cand1.Function)
10973     return true;
10974 
10975   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
10976   //      class B of D, and for all arguments the corresponding parameters of
10977   //      F1 and F2 have the same type.
10978   // FIXME: Implement the "all parameters have the same type" check.
10979   bool Cand1IsInherited =
10980       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10981   bool Cand2IsInherited =
10982       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10983   if (Cand1IsInherited != Cand2IsInherited)
10984     return Cand2IsInherited;
10985   else if (Cand1IsInherited) {
10986     assert(Cand2IsInherited);
10987     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10988     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10989     if (Cand1Class->isDerivedFrom(Cand2Class))
10990       return true;
10991     if (Cand2Class->isDerivedFrom(Cand1Class))
10992       return false;
10993     // Inherited from sibling base classes: still ambiguous.
10994   }
10995 
10996   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10997   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10998   //      with reversed order of parameters and F1 is not
10999   //
11000   // We rank reversed + different operator as worse than just reversed, but
11001   // that comparison can never happen, because we only consider reversing for
11002   // the maximally-rewritten operator (== or <=>).
11003   if (Cand1.RewriteKind != Cand2.RewriteKind)
11004     return Cand1.RewriteKind < Cand2.RewriteKind;
11005 
11006   // Check C++17 tie-breakers for deduction guides.
11007   {
11008     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11009     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11010     if (Guide1 && Guide2) {
11011       //  -- F1 is generated from a deduction-guide and F2 is not
11012       if (Guide1->isImplicit() != Guide2->isImplicit())
11013         return Guide2->isImplicit();
11014 
11015       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11016       if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11017         return true;
11018       if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11019         return false;
11020 
11021       //  --F1 is generated from a non-template constructor and F2 is generated
11022       //  from a constructor template
11023       const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11024       const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11025       if (Constructor1 && Constructor2) {
11026         bool isC1Templated = Constructor1->getTemplatedKind() !=
11027                              FunctionDecl::TemplatedKind::TK_NonTemplate;
11028         bool isC2Templated = Constructor2->getTemplatedKind() !=
11029                              FunctionDecl::TemplatedKind::TK_NonTemplate;
11030         if (isC1Templated != isC2Templated)
11031           return isC2Templated;
11032       }
11033     }
11034   }
11035 
11036   // Check for enable_if value-based overload resolution.
11037   if (Cand1.Function && Cand2.Function) {
11038     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11039     if (Cmp != Comparison::Equal)
11040       return Cmp == Comparison::Better;
11041   }
11042 
11043   bool HasPS1 = Cand1.Function != nullptr &&
11044                 functionHasPassObjectSizeParams(Cand1.Function);
11045   bool HasPS2 = Cand2.Function != nullptr &&
11046                 functionHasPassObjectSizeParams(Cand2.Function);
11047   if (HasPS1 != HasPS2 && HasPS1)
11048     return true;
11049 
11050   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11051   if (MV == Comparison::Better)
11052     return true;
11053   if (MV == Comparison::Worse)
11054     return false;
11055 
11056   // If other rules cannot determine which is better, CUDA preference is used
11057   // to determine which is better.
11058   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11059     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11060     return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11061            S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11062   }
11063 
11064   // General member function overloading is handled above, so this only handles
11065   // constructors with address spaces.
11066   // This only handles address spaces since C++ has no other
11067   // qualifier that can be used with constructors.
11068   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11069   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11070   if (CD1 && CD2) {
11071     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11072     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11073     if (AS1 != AS2) {
11074       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1, S.getASTContext()))
11075         return true;
11076       if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2, S.getASTContext()))
11077         return false;
11078     }
11079   }
11080 
11081   return false;
11082 }
11083 
11084 /// Determine whether two declarations are "equivalent" for the purposes of
11085 /// name lookup and overload resolution. This applies when the same internal/no
11086 /// linkage entity is defined by two modules (probably by textually including
11087 /// the same header). In such a case, we don't consider the declarations to
11088 /// declare the same entity, but we also don't want lookups with both
11089 /// declarations visible to be ambiguous in some cases (this happens when using
11090 /// a modularized libstdc++).
isEquivalentInternalLinkageDeclaration(const NamedDecl * A,const NamedDecl * B)11091 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11092                                                   const NamedDecl *B) {
11093   auto *VA = dyn_cast_or_null<ValueDecl>(A);
11094   auto *VB = dyn_cast_or_null<ValueDecl>(B);
11095   if (!VA || !VB)
11096     return false;
11097 
11098   // The declarations must be declaring the same name as an internal linkage
11099   // entity in different modules.
11100   if (!VA->getDeclContext()->getRedeclContext()->Equals(
11101           VB->getDeclContext()->getRedeclContext()) ||
11102       getOwningModule(VA) == getOwningModule(VB) ||
11103       VA->isExternallyVisible() || VB->isExternallyVisible())
11104     return false;
11105 
11106   // Check that the declarations appear to be equivalent.
11107   //
11108   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11109   // For constants and functions, we should check the initializer or body is
11110   // the same. For non-constant variables, we shouldn't allow it at all.
11111   if (Context.hasSameType(VA->getType(), VB->getType()))
11112     return true;
11113 
11114   // Enum constants within unnamed enumerations will have different types, but
11115   // may still be similar enough to be interchangeable for our purposes.
11116   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11117     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11118       // Only handle anonymous enums. If the enumerations were named and
11119       // equivalent, they would have been merged to the same type.
11120       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11121       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11122       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11123           !Context.hasSameType(EnumA->getIntegerType(),
11124                                EnumB->getIntegerType()))
11125         return false;
11126       // Allow this only if the value is the same for both enumerators.
11127       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11128     }
11129   }
11130 
11131   // Nothing else is sufficiently similar.
11132   return false;
11133 }
11134 
diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc,const NamedDecl * D,ArrayRef<const NamedDecl * > Equiv)11135 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11136     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11137   assert(D && "Unknown declaration");
11138   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11139 
11140   Module *M = getOwningModule(D);
11141   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11142       << !M << (M ? M->getFullModuleName() : "");
11143 
11144   for (auto *E : Equiv) {
11145     Module *M = getOwningModule(E);
11146     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11147         << !M << (M ? M->getFullModuleName() : "");
11148   }
11149 }
11150 
NotValidBecauseConstraintExprHasError() const11151 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11152   return FailureKind == ovl_fail_bad_deduction &&
11153          static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11154              TemplateDeductionResult::ConstraintsNotSatisfied &&
11155          static_cast<CNSInfo *>(DeductionFailure.Data)
11156              ->Satisfaction.ContainsErrors;
11157 }
11158 
AddDeferredTemplateCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,ArrayRef<Expr * > Args,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit,CallExpr::ADLCallKind IsADLCandidate,OverloadCandidateParamOrder PO,bool AggregateCandidateDeduction)11159 void OverloadCandidateSet::AddDeferredTemplateCandidate(
11160     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11161     ArrayRef<Expr *> Args, bool SuppressUserConversions,
11162     bool PartialOverloading, bool AllowExplicit,
11163     CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11164     bool AggregateCandidateDeduction) {
11165 
11166   auto *C =
11167       allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11168 
11169   C = new (C) DeferredFunctionTemplateOverloadCandidate{
11170       {nullptr, DeferredFunctionTemplateOverloadCandidate::Function,
11171        /*AllowObjCConversionOnExplicit=*/false,
11172        /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11173        PartialOverloading, AggregateCandidateDeduction},
11174       FunctionTemplate,
11175       FoundDecl,
11176       Args,
11177       IsADLCandidate,
11178       PO};
11179 
11180   HasDeferredTemplateConstructors |=
11181       isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11182 }
11183 
AddDeferredMethodTemplateCandidate(FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,bool SuppressUserConversions,bool PartialOverloading,OverloadCandidateParamOrder PO)11184 void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11185     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11186     CXXRecordDecl *ActingContext, QualType ObjectType,
11187     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11188     bool SuppressUserConversions, bool PartialOverloading,
11189     OverloadCandidateParamOrder PO) {
11190 
11191   assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11192 
11193   auto *C =
11194       allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11195 
11196   C = new (C) DeferredMethodTemplateOverloadCandidate{
11197       {nullptr, DeferredFunctionTemplateOverloadCandidate::Method,
11198        /*AllowObjCConversionOnExplicit=*/false,
11199        /*AllowResultConversion=*/false,
11200        /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11201        /*AggregateCandidateDeduction=*/false},
11202       MethodTmpl,
11203       FoundDecl,
11204       Args,
11205       ActingContext,
11206       ObjectClassification,
11207       ObjectType,
11208       PO};
11209 }
11210 
AddDeferredConversionTemplateCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,bool AllowObjCConversionOnExplicit,bool AllowExplicit,bool AllowResultConversion)11211 void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11212     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11213     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11214     bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11215     bool AllowResultConversion) {
11216 
11217   auto *C =
11218       allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11219 
11220   C = new (C) DeferredConversionTemplateOverloadCandidate{
11221       {nullptr, DeferredFunctionTemplateOverloadCandidate::Conversion,
11222        AllowObjCConversionOnExplicit, AllowResultConversion,
11223        /*AllowExplicit=*/false,
11224        /*SuppressUserConversions=*/false,
11225        /*PartialOverloading*/ false,
11226        /*AggregateCandidateDeduction=*/false},
11227       FunctionTemplate,
11228       FoundDecl,
11229       ActingContext,
11230       From,
11231       ToType};
11232 }
11233 
11234 static void
AddTemplateOverloadCandidate(Sema & S,OverloadCandidateSet & CandidateSet,DeferredMethodTemplateOverloadCandidate & C)11235 AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11236                              DeferredMethodTemplateOverloadCandidate &C) {
11237 
11238   AddMethodTemplateCandidateImmediately(
11239       S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11240       /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11241       C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11242 }
11243 
11244 static void
AddTemplateOverloadCandidate(Sema & S,OverloadCandidateSet & CandidateSet,DeferredFunctionTemplateOverloadCandidate & C)11245 AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11246                              DeferredFunctionTemplateOverloadCandidate &C) {
11247   AddTemplateOverloadCandidateImmediately(
11248       S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11249       /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11250       C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11251       C.AggregateCandidateDeduction);
11252 }
11253 
11254 static void
AddTemplateOverloadCandidate(Sema & S,OverloadCandidateSet & CandidateSet,DeferredConversionTemplateOverloadCandidate & C)11255 AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11256                              DeferredConversionTemplateOverloadCandidate &C) {
11257   return AddTemplateConversionCandidateImmediately(
11258       S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11259       C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11260       C.AllowResultConversion);
11261 }
11262 
InjectNonDeducedTemplateCandidates(Sema & S)11263 void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11264   Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11265   DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11266   while (Cand) {
11267     switch (Cand->Kind) {
11268     case DeferredTemplateOverloadCandidate::Function:
11269       AddTemplateOverloadCandidate(
11270           S, *this,
11271           *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11272       break;
11273     case DeferredTemplateOverloadCandidate::Method:
11274       AddTemplateOverloadCandidate(
11275           S, *this,
11276           *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11277       break;
11278     case DeferredTemplateOverloadCandidate::Conversion:
11279       AddTemplateOverloadCandidate(
11280           S, *this,
11281           *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11282       break;
11283     }
11284     Cand = Cand->Next;
11285   }
11286   FirstDeferredCandidate = nullptr;
11287   DeferredCandidatesCount = 0;
11288 }
11289 
11290 OverloadingResult
ResultForBestCandidate(const iterator & Best)11291 OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11292   Best->Best = true;
11293   if (Best->Function && Best->Function->isDeleted())
11294     return OR_Deleted;
11295   return OR_Success;
11296 }
11297 
CudaExcludeWrongSideCandidates(Sema & S,SmallVectorImpl<OverloadCandidate * > & Candidates)11298 void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11299     Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11300   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11301   // are accepted by both clang and NVCC. However, during a particular
11302   // compilation mode only one call variant is viable. We need to
11303   // exclude non-viable overload candidates from consideration based
11304   // only on their host/device attributes. Specifically, if one
11305   // candidate call is WrongSide and the other is SameSide, we ignore
11306   // the WrongSide candidate.
11307   // We only need to remove wrong-sided candidates here if
11308   // -fgpu-exclude-wrong-side-overloads is off. When
11309   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11310   // uniformly in isBetterOverloadCandidate.
11311   if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11312     return;
11313   const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11314 
11315   bool ContainsSameSideCandidate =
11316       llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11317         // Check viable function only.
11318         return Cand->Viable && Cand->Function &&
11319                S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11320                    SemaCUDA::CFP_SameSide;
11321       });
11322 
11323   if (!ContainsSameSideCandidate)
11324     return;
11325 
11326   auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11327     // Check viable function only to avoid unnecessary data copying/moving.
11328     return Cand->Viable && Cand->Function &&
11329            S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11330                SemaCUDA::CFP_WrongSide;
11331   };
11332   llvm::erase_if(Candidates, IsWrongSideCandidate);
11333 }
11334 
11335 /// Computes the best viable function (C++ 13.3.3)
11336 /// within an overload candidate set.
11337 ///
11338 /// \param Loc The location of the function name (or operator symbol) for
11339 /// which overload resolution occurs.
11340 ///
11341 /// \param Best If overload resolution was successful or found a deleted
11342 /// function, \p Best points to the candidate function found.
11343 ///
11344 /// \returns The result of overload resolution.
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best)11345 OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11346                                                            SourceLocation Loc,
11347                                                            iterator &Best) {
11348 
11349   assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11350           DeferredCandidatesCount == 0) &&
11351          "Unexpected deferred template candidates");
11352 
11353   bool TwoPhaseResolution =
11354       DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11355 
11356   if (TwoPhaseResolution) {
11357 
11358     PerfectViableFunction(S, Loc, Best);
11359     if (Best != end())
11360       return ResultForBestCandidate(Best);
11361   }
11362 
11363   InjectNonDeducedTemplateCandidates(S);
11364   return BestViableFunctionImpl(S, Loc, Best);
11365 }
11366 
PerfectViableFunction(Sema & S,SourceLocation Loc,OverloadCandidateSet::iterator & Best)11367 void OverloadCandidateSet::PerfectViableFunction(
11368     Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11369 
11370   Best = end();
11371   for (auto It = Candidates.begin(); It != Candidates.end(); ++It) {
11372 
11373     if (!It->isPerfectMatch(S.getASTContext()))
11374       continue;
11375 
11376     // We found a suitable conversion function
11377     // but if there is a template constructor in the target class
11378     // we might prefer that instead.
11379     if (HasDeferredTemplateConstructors &&
11380         isa_and_nonnull<CXXConversionDecl>(It->Function)) {
11381       Best = end();
11382       break;
11383     }
11384 
11385     if (Best == end()) {
11386       Best = It;
11387       continue;
11388     }
11389     if (Best->Function && It->Function) {
11390       FunctionDecl *D =
11391           S.getMoreConstrainedFunction(Best->Function, It->Function);
11392       if (D == nullptr) {
11393         Best = end();
11394         break;
11395       }
11396       if (D == It->Function)
11397         Best = It;
11398       continue;
11399     }
11400     // ambiguous
11401     Best = end();
11402     break;
11403   }
11404 }
11405 
BestViableFunctionImpl(Sema & S,SourceLocation Loc,OverloadCandidateSet::iterator & Best)11406 OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11407     Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11408 
11409   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11410   Candidates.reserve(this->Candidates.size());
11411   std::transform(this->Candidates.begin(), this->Candidates.end(),
11412                  std::back_inserter(Candidates),
11413                  [](OverloadCandidate &Cand) { return &Cand; });
11414 
11415   if (S.getLangOpts().CUDA)
11416     CudaExcludeWrongSideCandidates(S, Candidates);
11417 
11418   Best = end();
11419   for (auto *Cand : Candidates) {
11420     Cand->Best = false;
11421     if (Cand->Viable) {
11422       if (Best == end() ||
11423           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11424         Best = Cand;
11425     } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11426       // This candidate has constraint that we were unable to evaluate because
11427       // it referenced an expression that contained an error. Rather than fall
11428       // back onto a potentially unintended candidate (made worse by
11429       // subsuming constraints), treat this as 'no viable candidate'.
11430       Best = end();
11431       return OR_No_Viable_Function;
11432     }
11433   }
11434 
11435   // If we didn't find any viable functions, abort.
11436   if (Best == end())
11437     return OR_No_Viable_Function;
11438 
11439   llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11440   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11441   PendingBest.push_back(&*Best);
11442   Best->Best = true;
11443 
11444   // Make sure that this function is better than every other viable
11445   // function. If not, we have an ambiguity.
11446   while (!PendingBest.empty()) {
11447     auto *Curr = PendingBest.pop_back_val();
11448     for (auto *Cand : Candidates) {
11449       if (Cand->Viable && !Cand->Best &&
11450           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11451         PendingBest.push_back(Cand);
11452         Cand->Best = true;
11453 
11454         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
11455                                                      Curr->Function))
11456           EquivalentCands.push_back(Cand->Function);
11457         else
11458           Best = end();
11459       }
11460     }
11461   }
11462 
11463   if (Best == end())
11464     return OR_Ambiguous;
11465 
11466   OverloadingResult R = ResultForBestCandidate(Best);
11467 
11468   if (!EquivalentCands.empty())
11469     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
11470                                                     EquivalentCands);
11471   return R;
11472 }
11473 
11474 namespace {
11475 
11476 enum OverloadCandidateKind {
11477   oc_function,
11478   oc_method,
11479   oc_reversed_binary_operator,
11480   oc_constructor,
11481   oc_implicit_default_constructor,
11482   oc_implicit_copy_constructor,
11483   oc_implicit_move_constructor,
11484   oc_implicit_copy_assignment,
11485   oc_implicit_move_assignment,
11486   oc_implicit_equality_comparison,
11487   oc_inherited_constructor
11488 };
11489 
11490 enum OverloadCandidateSelect {
11491   ocs_non_template,
11492   ocs_template,
11493   ocs_described_template,
11494 };
11495 
11496 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
ClassifyOverloadCandidate(Sema & S,const NamedDecl * Found,const FunctionDecl * Fn,OverloadCandidateRewriteKind CRK,std::string & Description)11497 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11498                           const FunctionDecl *Fn,
11499                           OverloadCandidateRewriteKind CRK,
11500                           std::string &Description) {
11501 
11502   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11503   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11504     isTemplate = true;
11505     Description = S.getTemplateArgumentBindingsText(
11506         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11507   }
11508 
11509   OverloadCandidateSelect Select = [&]() {
11510     if (!Description.empty())
11511       return ocs_described_template;
11512     return isTemplate ? ocs_template : ocs_non_template;
11513   }();
11514 
11515   OverloadCandidateKind Kind = [&]() {
11516     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11517       return oc_implicit_equality_comparison;
11518 
11519     if (CRK & CRK_Reversed)
11520       return oc_reversed_binary_operator;
11521 
11522     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11523       if (!Ctor->isImplicit()) {
11524         if (isa<ConstructorUsingShadowDecl>(Found))
11525           return oc_inherited_constructor;
11526         else
11527           return oc_constructor;
11528       }
11529 
11530       if (Ctor->isDefaultConstructor())
11531         return oc_implicit_default_constructor;
11532 
11533       if (Ctor->isMoveConstructor())
11534         return oc_implicit_move_constructor;
11535 
11536       assert(Ctor->isCopyConstructor() &&
11537              "unexpected sort of implicit constructor");
11538       return oc_implicit_copy_constructor;
11539     }
11540 
11541     if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11542       // This actually gets spelled 'candidate function' for now, but
11543       // it doesn't hurt to split it out.
11544       if (!Meth->isImplicit())
11545         return oc_method;
11546 
11547       if (Meth->isMoveAssignmentOperator())
11548         return oc_implicit_move_assignment;
11549 
11550       if (Meth->isCopyAssignmentOperator())
11551         return oc_implicit_copy_assignment;
11552 
11553       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11554       return oc_method;
11555     }
11556 
11557     return oc_function;
11558   }();
11559 
11560   return std::make_pair(Kind, Select);
11561 }
11562 
MaybeEmitInheritedConstructorNote(Sema & S,const Decl * FoundDecl)11563 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11564   // FIXME: It'd be nice to only emit a note once per using-decl per overload
11565   // set.
11566   if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11567     S.Diag(FoundDecl->getLocation(),
11568            diag::note_ovl_candidate_inherited_constructor)
11569       << Shadow->getNominatedBaseClass();
11570 }
11571 
11572 } // end anonymous namespace
11573 
isFunctionAlwaysEnabled(const ASTContext & Ctx,const FunctionDecl * FD)11574 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11575                                     const FunctionDecl *FD) {
11576   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11577     bool AlwaysTrue;
11578     if (EnableIf->getCond()->isValueDependent() ||
11579         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11580       return false;
11581     if (!AlwaysTrue)
11582       return false;
11583   }
11584   return true;
11585 }
11586 
11587 /// Returns true if we can take the address of the function.
11588 ///
11589 /// \param Complain - If true, we'll emit a diagnostic
11590 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11591 ///   we in overload resolution?
11592 /// \param Loc - The location of the statement we're complaining about. Ignored
11593 ///   if we're not complaining, or if we're in overload resolution.
checkAddressOfFunctionIsAvailable(Sema & S,const FunctionDecl * FD,bool Complain,bool InOverloadResolution,SourceLocation Loc)11594 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11595                                               bool Complain,
11596                                               bool InOverloadResolution,
11597                                               SourceLocation Loc) {
11598   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11599     if (Complain) {
11600       if (InOverloadResolution)
11601         S.Diag(FD->getBeginLoc(),
11602                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11603       else
11604         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11605     }
11606     return false;
11607   }
11608 
11609   if (FD->getTrailingRequiresClause()) {
11610     ConstraintSatisfaction Satisfaction;
11611     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11612       return false;
11613     if (!Satisfaction.IsSatisfied) {
11614       if (Complain) {
11615         if (InOverloadResolution) {
11616           SmallString<128> TemplateArgString;
11617           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11618             TemplateArgString += " ";
11619             TemplateArgString += S.getTemplateArgumentBindingsText(
11620                 FunTmpl->getTemplateParameters(),
11621                 *FD->getTemplateSpecializationArgs());
11622           }
11623 
11624           S.Diag(FD->getBeginLoc(),
11625                  diag::note_ovl_candidate_unsatisfied_constraints)
11626               << TemplateArgString;
11627         } else
11628           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11629               << FD;
11630         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11631       }
11632       return false;
11633     }
11634   }
11635 
11636   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11637     return P->hasAttr<PassObjectSizeAttr>();
11638   });
11639   if (I == FD->param_end())
11640     return true;
11641 
11642   if (Complain) {
11643     // Add one to ParamNo because it's user-facing
11644     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11645     if (InOverloadResolution)
11646       S.Diag(FD->getLocation(),
11647              diag::note_ovl_candidate_has_pass_object_size_params)
11648           << ParamNo;
11649     else
11650       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11651           << FD << ParamNo;
11652   }
11653   return false;
11654 }
11655 
checkAddressOfCandidateIsAvailable(Sema & S,const FunctionDecl * FD)11656 static bool checkAddressOfCandidateIsAvailable(Sema &S,
11657                                                const FunctionDecl *FD) {
11658   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11659                                            /*InOverloadResolution=*/true,
11660                                            /*Loc=*/SourceLocation());
11661 }
11662 
checkAddressOfFunctionIsAvailable(const FunctionDecl * Function,bool Complain,SourceLocation Loc)11663 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11664                                              bool Complain,
11665                                              SourceLocation Loc) {
11666   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11667                                              /*InOverloadResolution=*/false,
11668                                              Loc);
11669 }
11670 
11671 // Don't print candidates other than the one that matches the calling
11672 // convention of the call operator, since that is guaranteed to exist.
shouldSkipNotingLambdaConversionDecl(const FunctionDecl * Fn)11673 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11674   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11675 
11676   if (!ConvD)
11677     return false;
11678   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11679   if (!RD->isLambda())
11680     return false;
11681 
11682   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11683   CallingConv CallOpCC =
11684       CallOp->getType()->castAs<FunctionType>()->getCallConv();
11685   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11686   CallingConv ConvToCC =
11687       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11688 
11689   return ConvToCC != CallOpCC;
11690 }
11691 
11692 // Notes the location of an overload candidate.
NoteOverloadCandidate(const NamedDecl * Found,const FunctionDecl * Fn,OverloadCandidateRewriteKind RewriteKind,QualType DestType,bool TakingAddress)11693 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11694                                  OverloadCandidateRewriteKind RewriteKind,
11695                                  QualType DestType, bool TakingAddress) {
11696   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11697     return;
11698   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11699       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11700     return;
11701   if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11702       !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11703     return;
11704   if (shouldSkipNotingLambdaConversionDecl(Fn))
11705     return;
11706 
11707   std::string FnDesc;
11708   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11709       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11710   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11711                          << (unsigned)KSPair.first << (unsigned)KSPair.second
11712                          << Fn << FnDesc;
11713 
11714   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11715   Diag(Fn->getLocation(), PD);
11716   MaybeEmitInheritedConstructorNote(*this, Found);
11717 }
11718 
11719 static void
MaybeDiagnoseAmbiguousConstraints(Sema & S,ArrayRef<OverloadCandidate> Cands)11720 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11721   // Perhaps the ambiguity was caused by two atomic constraints that are
11722   // 'identical' but not equivalent:
11723   //
11724   // void foo() requires (sizeof(T) > 4) { } // #1
11725   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11726   //
11727   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11728   // #2 to subsume #1, but these constraint are not considered equivalent
11729   // according to the subsumption rules because they are not the same
11730   // source-level construct. This behavior is quite confusing and we should try
11731   // to help the user figure out what happened.
11732 
11733   SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11734   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11735   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11736     if (!I->Function)
11737       continue;
11738     SmallVector<AssociatedConstraint, 3> AC;
11739     if (auto *Template = I->Function->getPrimaryTemplate())
11740       Template->getAssociatedConstraints(AC);
11741     else
11742       I->Function->getAssociatedConstraints(AC);
11743     if (AC.empty())
11744       continue;
11745     if (FirstCand == nullptr) {
11746       FirstCand = I->Function;
11747       FirstAC = AC;
11748     } else if (SecondCand == nullptr) {
11749       SecondCand = I->Function;
11750       SecondAC = AC;
11751     } else {
11752       // We have more than one pair of constrained functions - this check is
11753       // expensive and we'd rather not try to diagnose it.
11754       return;
11755     }
11756   }
11757   if (!SecondCand)
11758     return;
11759   // The diagnostic can only happen if there are associated constraints on
11760   // both sides (there needs to be some identical atomic constraint).
11761   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11762                                                       SecondCand, SecondAC))
11763     // Just show the user one diagnostic, they'll probably figure it out
11764     // from here.
11765     return;
11766 }
11767 
11768 // Notes the location of all overload candidates designated through
11769 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType,bool TakingAddress)11770 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11771                                      bool TakingAddress) {
11772   assert(OverloadedExpr->getType() == Context.OverloadTy);
11773 
11774   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11775   OverloadExpr *OvlExpr = Ovl.Expression;
11776 
11777   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11778                             IEnd = OvlExpr->decls_end();
11779        I != IEnd; ++I) {
11780     if (FunctionTemplateDecl *FunTmpl =
11781                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11782       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11783                             TakingAddress);
11784     } else if (FunctionDecl *Fun
11785                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11786       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11787     }
11788   }
11789 }
11790 
11791 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
11792 /// "lead" diagnostic; it will be given two arguments, the source and
11793 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const11794 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11795                                  Sema &S,
11796                                  SourceLocation CaretLoc,
11797                                  const PartialDiagnostic &PDiag) const {
11798   S.Diag(CaretLoc, PDiag)
11799     << Ambiguous.getFromType() << Ambiguous.getToType();
11800   unsigned CandsShown = 0;
11801   AmbiguousConversionSequence::const_iterator I, E;
11802   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11803     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11804       break;
11805     ++CandsShown;
11806     S.NoteOverloadCandidate(I->first, I->second);
11807   }
11808   S.Diags.overloadCandidatesShown(CandsShown);
11809   if (I != E)
11810     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11811 }
11812 
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I,bool TakingCandidateAddress)11813 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11814                                   unsigned I, bool TakingCandidateAddress) {
11815   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11816   assert(Conv.isBad());
11817   assert(Cand->Function && "for now, candidate must be a function");
11818   FunctionDecl *Fn = Cand->Function;
11819 
11820   // There's a conversion slot for the object argument if this is a
11821   // non-constructor method.  Note that 'I' corresponds the
11822   // conversion-slot index.
11823   bool isObjectArgument = false;
11824   if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11825       !isa<CXXConstructorDecl>(Fn)) {
11826     if (I == 0)
11827       isObjectArgument = true;
11828     else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11829       I--;
11830   }
11831 
11832   std::string FnDesc;
11833   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11834       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11835                                 FnDesc);
11836 
11837   Expr *FromExpr = Conv.Bad.FromExpr;
11838   QualType FromTy = Conv.Bad.getFromType();
11839   QualType ToTy = Conv.Bad.getToType();
11840   SourceRange ToParamRange;
11841 
11842   // FIXME: In presence of parameter packs we can't determine parameter range
11843   // reliably, as we don't have access to instantiation.
11844   bool HasParamPack =
11845       llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11846         return Parm->isParameterPack();
11847       });
11848   if (!isObjectArgument && !HasParamPack)
11849     ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11850 
11851   if (FromTy == S.Context.OverloadTy) {
11852     assert(FromExpr && "overload set argument came from implicit argument?");
11853     Expr *E = FromExpr->IgnoreParens();
11854     if (isa<UnaryOperator>(E))
11855       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11856     DeclarationName Name = cast<OverloadExpr>(E)->getName();
11857 
11858     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11859         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11860         << ToParamRange << ToTy << Name << I + 1;
11861     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11862     return;
11863   }
11864 
11865   // Do some hand-waving analysis to see if the non-viability is due
11866   // to a qualifier mismatch.
11867   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11868   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11869   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11870     CToTy = RT->getPointeeType();
11871   else {
11872     // TODO: detect and diagnose the full richness of const mismatches.
11873     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11874       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11875         CFromTy = FromPT->getPointeeType();
11876         CToTy = ToPT->getPointeeType();
11877       }
11878   }
11879 
11880   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11881       !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11882     Qualifiers FromQs = CFromTy.getQualifiers();
11883     Qualifiers ToQs = CToTy.getQualifiers();
11884 
11885     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11886       if (isObjectArgument)
11887         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11888             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11889             << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11890       else
11891         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11892             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11893             << FnDesc << ToParamRange << FromQs.getAddressSpace()
11894             << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11895       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11896       return;
11897     }
11898 
11899     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11900       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11901           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11902           << ToParamRange << FromTy << FromQs.getObjCLifetime()
11903           << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11904       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11905       return;
11906     }
11907 
11908     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11909       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11910           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11911           << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11912           << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11913       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11914       return;
11915     }
11916 
11917     if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11918       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11919           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11920           << FromTy << !!FromQs.getPointerAuth()
11921           << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11922           << ToQs.getPointerAuth().getAsString() << I + 1
11923           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11924       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11925       return;
11926     }
11927 
11928     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11929     assert(CVR && "expected qualifiers mismatch");
11930 
11931     if (isObjectArgument) {
11932       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11933           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11934           << FromTy << (CVR - 1);
11935     } else {
11936       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11937           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11938           << ToParamRange << FromTy << (CVR - 1) << I + 1;
11939     }
11940     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11941     return;
11942   }
11943 
11944   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11945       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11946     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11947         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11948         << (unsigned)isObjectArgument << I + 1
11949         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11950         << ToParamRange;
11951     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11952     return;
11953   }
11954 
11955   // Special diagnostic for failure to convert an initializer list, since
11956   // telling the user that it has type void is not useful.
11957   if (FromExpr && isa<InitListExpr>(FromExpr)) {
11958     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11959         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11960         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11961         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11962             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11963                 ? 2
11964                 : 0);
11965     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11966     return;
11967   }
11968 
11969   // Diagnose references or pointers to incomplete types differently,
11970   // since it's far from impossible that the incompleteness triggered
11971   // the failure.
11972   QualType TempFromTy = FromTy.getNonReferenceType();
11973   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11974     TempFromTy = PTy->getPointeeType();
11975   if (TempFromTy->isIncompleteType()) {
11976     // Emit the generic diagnostic and, optionally, add the hints to it.
11977     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11978         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11979         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11980         << (unsigned)(Cand->Fix.Kind);
11981 
11982     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11983     return;
11984   }
11985 
11986   // Diagnose base -> derived pointer conversions.
11987   unsigned BaseToDerivedConversion = 0;
11988   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11989     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11990       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11991               FromPtrTy->getPointeeType(), S.getASTContext()) &&
11992           !FromPtrTy->getPointeeType()->isIncompleteType() &&
11993           !ToPtrTy->getPointeeType()->isIncompleteType() &&
11994           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11995                           FromPtrTy->getPointeeType()))
11996         BaseToDerivedConversion = 1;
11997     }
11998   } else if (const ObjCObjectPointerType *FromPtrTy
11999                                     = FromTy->getAs<ObjCObjectPointerType>()) {
12000     if (const ObjCObjectPointerType *ToPtrTy
12001                                         = ToTy->getAs<ObjCObjectPointerType>())
12002       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12003         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12004           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12005                   FromPtrTy->getPointeeType(), S.getASTContext()) &&
12006               FromIface->isSuperClassOf(ToIface))
12007             BaseToDerivedConversion = 2;
12008   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12009     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12010                                                          S.getASTContext()) &&
12011         !FromTy->isIncompleteType() &&
12012         !ToRefTy->getPointeeType()->isIncompleteType() &&
12013         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12014       BaseToDerivedConversion = 3;
12015     }
12016   }
12017 
12018   if (BaseToDerivedConversion) {
12019     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12020         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12021         << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12022         << I + 1;
12023     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12024     return;
12025   }
12026 
12027   if (isa<ObjCObjectPointerType>(CFromTy) &&
12028       isa<PointerType>(CToTy)) {
12029     Qualifiers FromQs = CFromTy.getQualifiers();
12030     Qualifiers ToQs = CToTy.getQualifiers();
12031     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12032       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12033           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12034           << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12035           << I + 1;
12036       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12037       return;
12038     }
12039   }
12040 
12041   if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12042     return;
12043 
12044   // Emit the generic diagnostic and, optionally, add the hints to it.
12045   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12046   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12047         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12048         << (unsigned)(Cand->Fix.Kind);
12049 
12050   // Check that location of Fn is not in system header.
12051   if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12052     // If we can fix the conversion, suggest the FixIts.
12053     for (const FixItHint &HI : Cand->Fix.Hints)
12054         FDiag << HI;
12055   }
12056 
12057   S.Diag(Fn->getLocation(), FDiag);
12058 
12059   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12060 }
12061 
12062 /// Additional arity mismatch diagnosis specific to a function overload
12063 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
12064 /// over a candidate in any candidate set.
CheckArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool IsAddressOf=false)12065 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12066                                unsigned NumArgs, bool IsAddressOf = false) {
12067   assert(Cand->Function && "Candidate is required to be a function.");
12068   FunctionDecl *Fn = Cand->Function;
12069   unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12070                        ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12071 
12072   // With invalid overloaded operators, it's possible that we think we
12073   // have an arity mismatch when in fact it looks like we have the
12074   // right number of arguments, because only overloaded operators have
12075   // the weird behavior of overloading member and non-member functions.
12076   // Just don't report anything.
12077   if (Fn->isInvalidDecl() &&
12078       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12079     return true;
12080 
12081   if (NumArgs < MinParams) {
12082     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12083            (Cand->FailureKind == ovl_fail_bad_deduction &&
12084             Cand->DeductionFailure.getResult() ==
12085                 TemplateDeductionResult::TooFewArguments));
12086   } else {
12087     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12088            (Cand->FailureKind == ovl_fail_bad_deduction &&
12089             Cand->DeductionFailure.getResult() ==
12090                 TemplateDeductionResult::TooManyArguments));
12091   }
12092 
12093   return false;
12094 }
12095 
12096 /// General arity mismatch diagnosis over a candidate in a candidate set.
DiagnoseArityMismatch(Sema & S,NamedDecl * Found,Decl * D,unsigned NumFormalArgs,bool IsAddressOf=false)12097 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12098                                   unsigned NumFormalArgs,
12099                                   bool IsAddressOf = false) {
12100   assert(isa<FunctionDecl>(D) &&
12101       "The templated declaration should at least be a function"
12102       " when diagnosing bad template argument deduction due to too many"
12103       " or too few arguments");
12104 
12105   FunctionDecl *Fn = cast<FunctionDecl>(D);
12106 
12107   // TODO: treat calls to a missing default constructor as a special case
12108   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12109   unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12110                        ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12111 
12112   // at least / at most / exactly
12113   bool HasExplicitObjectParam =
12114       !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12115 
12116   unsigned ParamCount =
12117       Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12118   unsigned mode, modeCount;
12119 
12120   if (NumFormalArgs < MinParams) {
12121     if (MinParams != ParamCount || FnTy->isVariadic() ||
12122         FnTy->isTemplateVariadic())
12123       mode = 0; // "at least"
12124     else
12125       mode = 2; // "exactly"
12126     modeCount = MinParams;
12127   } else {
12128     if (MinParams != ParamCount)
12129       mode = 1; // "at most"
12130     else
12131       mode = 2; // "exactly"
12132     modeCount = ParamCount;
12133   }
12134 
12135   std::string Description;
12136   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12137       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12138 
12139   if (modeCount == 1 && !IsAddressOf &&
12140       Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12141     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12142         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12143         << Description << mode
12144         << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12145         << HasExplicitObjectParam << Fn->getParametersSourceRange();
12146   else
12147     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12148         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12149         << Description << mode << modeCount << NumFormalArgs
12150         << HasExplicitObjectParam << Fn->getParametersSourceRange();
12151 
12152   MaybeEmitInheritedConstructorNote(S, Found);
12153 }
12154 
12155 /// Arity mismatch diagnosis specific to a function overload candidate.
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)12156 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12157                                   unsigned NumFormalArgs) {
12158   assert(Cand->Function && "Candidate must be a function");
12159   FunctionDecl *Fn = Cand->Function;
12160   if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12161     DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12162                           Cand->TookAddressOfOverload);
12163 }
12164 
getDescribedTemplate(Decl * Templated)12165 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12166   if (TemplateDecl *TD = Templated->getDescribedTemplate())
12167     return TD;
12168   llvm_unreachable("Unsupported: Getting the described template declaration"
12169                    " for bad deduction diagnosis");
12170 }
12171 
12172 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,NamedDecl * Found,Decl * Templated,DeductionFailureInfo & DeductionFailure,unsigned NumArgs,bool TakingCandidateAddress)12173 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12174                                  DeductionFailureInfo &DeductionFailure,
12175                                  unsigned NumArgs,
12176                                  bool TakingCandidateAddress) {
12177   TemplateParameter Param = DeductionFailure.getTemplateParameter();
12178   NamedDecl *ParamD;
12179   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12180   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12181   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12182   switch (DeductionFailure.getResult()) {
12183   case TemplateDeductionResult::Success:
12184     llvm_unreachable(
12185         "TemplateDeductionResult::Success while diagnosing bad deduction");
12186   case TemplateDeductionResult::NonDependentConversionFailure:
12187     llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12188                      "while diagnosing bad deduction");
12189   case TemplateDeductionResult::Invalid:
12190   case TemplateDeductionResult::AlreadyDiagnosed:
12191     return;
12192 
12193   case TemplateDeductionResult::Incomplete: {
12194     assert(ParamD && "no parameter found for incomplete deduction result");
12195     S.Diag(Templated->getLocation(),
12196            diag::note_ovl_candidate_incomplete_deduction)
12197         << ParamD->getDeclName();
12198     MaybeEmitInheritedConstructorNote(S, Found);
12199     return;
12200   }
12201 
12202   case TemplateDeductionResult::IncompletePack: {
12203     assert(ParamD && "no parameter found for incomplete deduction result");
12204     S.Diag(Templated->getLocation(),
12205            diag::note_ovl_candidate_incomplete_deduction_pack)
12206         << ParamD->getDeclName()
12207         << (DeductionFailure.getFirstArg()->pack_size() + 1)
12208         << *DeductionFailure.getFirstArg();
12209     MaybeEmitInheritedConstructorNote(S, Found);
12210     return;
12211   }
12212 
12213   case TemplateDeductionResult::Underqualified: {
12214     assert(ParamD && "no parameter found for bad qualifiers deduction result");
12215     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
12216 
12217     QualType Param = DeductionFailure.getFirstArg()->getAsType();
12218 
12219     // Param will have been canonicalized, but it should just be a
12220     // qualified version of ParamD, so move the qualifiers to that.
12221     QualifierCollector Qs;
12222     Qs.strip(Param);
12223     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12224     assert(S.Context.hasSameType(Param, NonCanonParam));
12225 
12226     // Arg has also been canonicalized, but there's nothing we can do
12227     // about that.  It also doesn't matter as much, because it won't
12228     // have any template parameters in it (because deduction isn't
12229     // done on dependent types).
12230     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12231 
12232     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12233         << ParamD->getDeclName() << Arg << NonCanonParam;
12234     MaybeEmitInheritedConstructorNote(S, Found);
12235     return;
12236   }
12237 
12238   case TemplateDeductionResult::Inconsistent: {
12239     assert(ParamD && "no parameter found for inconsistent deduction result");
12240     int which = 0;
12241     if (isa<TemplateTypeParmDecl>(ParamD))
12242       which = 0;
12243     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12244       // Deduction might have failed because we deduced arguments of two
12245       // different types for a non-type template parameter.
12246       // FIXME: Use a different TDK value for this.
12247       QualType T1 =
12248           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12249       QualType T2 =
12250           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12251       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12252         S.Diag(Templated->getLocation(),
12253                diag::note_ovl_candidate_inconsistent_deduction_types)
12254           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12255           << *DeductionFailure.getSecondArg() << T2;
12256         MaybeEmitInheritedConstructorNote(S, Found);
12257         return;
12258       }
12259 
12260       which = 1;
12261     } else {
12262       which = 2;
12263     }
12264 
12265     // Tweak the diagnostic if the problem is that we deduced packs of
12266     // different arities. We'll print the actual packs anyway in case that
12267     // includes additional useful information.
12268     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12269         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12270         DeductionFailure.getFirstArg()->pack_size() !=
12271             DeductionFailure.getSecondArg()->pack_size()) {
12272       which = 3;
12273     }
12274 
12275     S.Diag(Templated->getLocation(),
12276            diag::note_ovl_candidate_inconsistent_deduction)
12277         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12278         << *DeductionFailure.getSecondArg();
12279     MaybeEmitInheritedConstructorNote(S, Found);
12280     return;
12281   }
12282 
12283   case TemplateDeductionResult::InvalidExplicitArguments:
12284     assert(ParamD && "no parameter found for invalid explicit arguments");
12285     if (ParamD->getDeclName())
12286       S.Diag(Templated->getLocation(),
12287              diag::note_ovl_candidate_explicit_arg_mismatch_named)
12288           << ParamD->getDeclName();
12289     else {
12290       int index = 0;
12291       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12292         index = TTP->getIndex();
12293       else if (NonTypeTemplateParmDecl *NTTP
12294                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12295         index = NTTP->getIndex();
12296       else
12297         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12298       S.Diag(Templated->getLocation(),
12299              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12300           << (index + 1);
12301     }
12302     MaybeEmitInheritedConstructorNote(S, Found);
12303     return;
12304 
12305   case TemplateDeductionResult::ConstraintsNotSatisfied: {
12306     // Format the template argument list into the argument string.
12307     SmallString<128> TemplateArgString;
12308     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12309     TemplateArgString = " ";
12310     TemplateArgString += S.getTemplateArgumentBindingsText(
12311         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12312     if (TemplateArgString.size() == 1)
12313       TemplateArgString.clear();
12314     S.Diag(Templated->getLocation(),
12315            diag::note_ovl_candidate_unsatisfied_constraints)
12316         << TemplateArgString;
12317 
12318     S.DiagnoseUnsatisfiedConstraint(
12319         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12320     return;
12321   }
12322   case TemplateDeductionResult::TooManyArguments:
12323   case TemplateDeductionResult::TooFewArguments:
12324     DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12325     return;
12326 
12327   case TemplateDeductionResult::InstantiationDepth:
12328     S.Diag(Templated->getLocation(),
12329            diag::note_ovl_candidate_instantiation_depth);
12330     MaybeEmitInheritedConstructorNote(S, Found);
12331     return;
12332 
12333   case TemplateDeductionResult::SubstitutionFailure: {
12334     // Format the template argument list into the argument string.
12335     SmallString<128> TemplateArgString;
12336     if (TemplateArgumentList *Args =
12337             DeductionFailure.getTemplateArgumentList()) {
12338       TemplateArgString = " ";
12339       TemplateArgString += S.getTemplateArgumentBindingsText(
12340           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12341       if (TemplateArgString.size() == 1)
12342         TemplateArgString.clear();
12343     }
12344 
12345     // If this candidate was disabled by enable_if, say so.
12346     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12347     if (PDiag && PDiag->second.getDiagID() ==
12348           diag::err_typename_nested_not_found_enable_if) {
12349       // FIXME: Use the source range of the condition, and the fully-qualified
12350       //        name of the enable_if template. These are both present in PDiag.
12351       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12352         << "'enable_if'" << TemplateArgString;
12353       return;
12354     }
12355 
12356     // We found a specific requirement that disabled the enable_if.
12357     if (PDiag && PDiag->second.getDiagID() ==
12358         diag::err_typename_nested_not_found_requirement) {
12359       S.Diag(Templated->getLocation(),
12360              diag::note_ovl_candidate_disabled_by_requirement)
12361         << PDiag->second.getStringArg(0) << TemplateArgString;
12362       return;
12363     }
12364 
12365     // Format the SFINAE diagnostic into the argument string.
12366     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12367     //        formatted message in another diagnostic.
12368     SmallString<128> SFINAEArgString;
12369     SourceRange R;
12370     if (PDiag) {
12371       SFINAEArgString = ": ";
12372       R = SourceRange(PDiag->first, PDiag->first);
12373       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12374     }
12375 
12376     S.Diag(Templated->getLocation(),
12377            diag::note_ovl_candidate_substitution_failure)
12378         << TemplateArgString << SFINAEArgString << R;
12379     MaybeEmitInheritedConstructorNote(S, Found);
12380     return;
12381   }
12382 
12383   case TemplateDeductionResult::DeducedMismatch:
12384   case TemplateDeductionResult::DeducedMismatchNested: {
12385     // Format the template argument list into the argument string.
12386     SmallString<128> TemplateArgString;
12387     if (TemplateArgumentList *Args =
12388             DeductionFailure.getTemplateArgumentList()) {
12389       TemplateArgString = " ";
12390       TemplateArgString += S.getTemplateArgumentBindingsText(
12391           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12392       if (TemplateArgString.size() == 1)
12393         TemplateArgString.clear();
12394     }
12395 
12396     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12397         << (*DeductionFailure.getCallArgIndex() + 1)
12398         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12399         << TemplateArgString
12400         << (DeductionFailure.getResult() ==
12401             TemplateDeductionResult::DeducedMismatchNested);
12402     break;
12403   }
12404 
12405   case TemplateDeductionResult::NonDeducedMismatch: {
12406     // FIXME: Provide a source location to indicate what we couldn't match.
12407     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12408     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12409     if (FirstTA.getKind() == TemplateArgument::Template &&
12410         SecondTA.getKind() == TemplateArgument::Template) {
12411       TemplateName FirstTN = FirstTA.getAsTemplate();
12412       TemplateName SecondTN = SecondTA.getAsTemplate();
12413       if (FirstTN.getKind() == TemplateName::Template &&
12414           SecondTN.getKind() == TemplateName::Template) {
12415         if (FirstTN.getAsTemplateDecl()->getName() ==
12416             SecondTN.getAsTemplateDecl()->getName()) {
12417           // FIXME: This fixes a bad diagnostic where both templates are named
12418           // the same.  This particular case is a bit difficult since:
12419           // 1) It is passed as a string to the diagnostic printer.
12420           // 2) The diagnostic printer only attempts to find a better
12421           //    name for types, not decls.
12422           // Ideally, this should folded into the diagnostic printer.
12423           S.Diag(Templated->getLocation(),
12424                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12425               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12426           return;
12427         }
12428       }
12429     }
12430 
12431     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12432         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
12433       return;
12434 
12435     // FIXME: For generic lambda parameters, check if the function is a lambda
12436     // call operator, and if so, emit a prettier and more informative
12437     // diagnostic that mentions 'auto' and lambda in addition to
12438     // (or instead of?) the canonical template type parameters.
12439     S.Diag(Templated->getLocation(),
12440            diag::note_ovl_candidate_non_deduced_mismatch)
12441         << FirstTA << SecondTA;
12442     return;
12443   }
12444   // TODO: diagnose these individually, then kill off
12445   // note_ovl_candidate_bad_deduction, which is uselessly vague.
12446   case TemplateDeductionResult::MiscellaneousDeductionFailure:
12447     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12448     MaybeEmitInheritedConstructorNote(S, Found);
12449     return;
12450   case TemplateDeductionResult::CUDATargetMismatch:
12451     S.Diag(Templated->getLocation(),
12452            diag::note_cuda_ovl_candidate_target_mismatch);
12453     return;
12454   }
12455 }
12456 
12457 /// Diagnose a failed template-argument deduction, for function calls.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress)12458 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12459                                  unsigned NumArgs,
12460                                  bool TakingCandidateAddress) {
12461   assert(Cand->Function && "Candidate must be a function");
12462   FunctionDecl *Fn = Cand->Function;
12463   TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12464   if (TDK == TemplateDeductionResult::TooFewArguments ||
12465       TDK == TemplateDeductionResult::TooManyArguments) {
12466     if (CheckArityMismatch(S, Cand, NumArgs))
12467       return;
12468   }
12469   DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12470                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12471 }
12472 
12473 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)12474 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12475   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12476   assert(Cand->Function && "Candidate must be a Function.");
12477   FunctionDecl *Callee = Cand->Function;
12478 
12479   CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12480                      CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12481 
12482   std::string FnDesc;
12483   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12484       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12485                                 Cand->getRewriteKind(), FnDesc);
12486 
12487   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12488       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12489       << FnDesc /* Ignored */
12490       << CalleeTarget << CallerTarget;
12491 
12492   // This could be an implicit constructor for which we could not infer the
12493   // target due to a collsion. Diagnose that case.
12494   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12495   if (Meth != nullptr && Meth->isImplicit()) {
12496     CXXRecordDecl *ParentClass = Meth->getParent();
12497     CXXSpecialMemberKind CSM;
12498 
12499     switch (FnKindPair.first) {
12500     default:
12501       return;
12502     case oc_implicit_default_constructor:
12503       CSM = CXXSpecialMemberKind::DefaultConstructor;
12504       break;
12505     case oc_implicit_copy_constructor:
12506       CSM = CXXSpecialMemberKind::CopyConstructor;
12507       break;
12508     case oc_implicit_move_constructor:
12509       CSM = CXXSpecialMemberKind::MoveConstructor;
12510       break;
12511     case oc_implicit_copy_assignment:
12512       CSM = CXXSpecialMemberKind::CopyAssignment;
12513       break;
12514     case oc_implicit_move_assignment:
12515       CSM = CXXSpecialMemberKind::MoveAssignment;
12516       break;
12517     };
12518 
12519     bool ConstRHS = false;
12520     if (Meth->getNumParams()) {
12521       if (const ReferenceType *RT =
12522               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12523         ConstRHS = RT->getPointeeType().isConstQualified();
12524       }
12525     }
12526 
12527     S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12528                                                  /* ConstRHS */ ConstRHS,
12529                                                  /* Diagnose */ true);
12530   }
12531 }
12532 
DiagnoseFailedEnableIfAttr(Sema & S,OverloadCandidate * Cand)12533 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12534   assert(Cand->Function && "Candidate must be a function");
12535   FunctionDecl *Callee = Cand->Function;
12536   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12537 
12538   S.Diag(Callee->getLocation(),
12539          diag::note_ovl_candidate_disabled_by_function_cond_attr)
12540       << Attr->getCond()->getSourceRange() << Attr->getMessage();
12541 }
12542 
DiagnoseFailedExplicitSpec(Sema & S,OverloadCandidate * Cand)12543 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12544   assert(Cand->Function && "Candidate must be a function");
12545   FunctionDecl *Fn = Cand->Function;
12546   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Fn);
12547   assert(ES.isExplicit() && "not an explicit candidate");
12548 
12549   unsigned Kind;
12550   switch (Fn->getDeclKind()) {
12551   case Decl::Kind::CXXConstructor:
12552     Kind = 0;
12553     break;
12554   case Decl::Kind::CXXConversion:
12555     Kind = 1;
12556     break;
12557   case Decl::Kind::CXXDeductionGuide:
12558     Kind = Fn->isImplicit() ? 0 : 2;
12559     break;
12560   default:
12561     llvm_unreachable("invalid Decl");
12562   }
12563 
12564   // Note the location of the first (in-class) declaration; a redeclaration
12565   // (particularly an out-of-class definition) will typically lack the
12566   // 'explicit' specifier.
12567   // FIXME: This is probably a good thing to do for all 'candidate' notes.
12568   FunctionDecl *First = Fn->getFirstDecl();
12569   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12570     First = Pattern->getFirstDecl();
12571 
12572   S.Diag(First->getLocation(),
12573          diag::note_ovl_candidate_explicit)
12574       << Kind << (ES.getExpr() ? 1 : 0)
12575       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12576 }
12577 
NoteImplicitDeductionGuide(Sema & S,FunctionDecl * Fn)12578 static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12579   auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12580   if (!DG)
12581     return;
12582   TemplateDecl *OriginTemplate =
12583       DG->getDeclName().getCXXDeductionGuideTemplate();
12584   // We want to always print synthesized deduction guides for type aliases.
12585   // They would retain the explicit bit of the corresponding constructor.
12586   if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12587     return;
12588   std::string FunctionProto;
12589   llvm::raw_string_ostream OS(FunctionProto);
12590   FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12591   if (!Template) {
12592     // This also could be an instantiation. Find out the primary template.
12593     FunctionDecl *Pattern =
12594         DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12595     if (!Pattern) {
12596       // The implicit deduction guide is built on an explicit non-template
12597       // deduction guide. Currently, this might be the case only for type
12598       // aliases.
12599       // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12600       // gets merged.
12601       assert(OriginTemplate->isTypeAlias() &&
12602              "Non-template implicit deduction guides are only possible for "
12603              "type aliases");
12604       DG->print(OS);
12605       S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12606           << FunctionProto;
12607       return;
12608     }
12609     Template = Pattern->getDescribedFunctionTemplate();
12610     assert(Template && "Cannot find the associated function template of "
12611                        "CXXDeductionGuideDecl?");
12612   }
12613   Template->print(OS);
12614   S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12615       << FunctionProto;
12616 }
12617 
12618 /// Generates a 'note' diagnostic for an overload candidate.  We've
12619 /// already generated a primary error at the call site.
12620 ///
12621 /// It really does need to be a single diagnostic with its caret
12622 /// pointed at the candidate declaration.  Yes, this creates some
12623 /// major challenges of technical writing.  Yes, this makes pointing
12624 /// out problems with specific arguments quite awkward.  It's still
12625 /// better than generating twenty screens of text for every failed
12626 /// overload.
12627 ///
12628 /// It would be great to be able to express per-candidate problems
12629 /// more richly for those diagnostic clients that cared, but we'd
12630 /// still have to be just as careful with the default diagnostics.
12631 /// \param CtorDestAS Addr space of object being constructed (for ctor
12632 /// candidates only).
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress,LangAS CtorDestAS=LangAS::Default)12633 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12634                                   unsigned NumArgs,
12635                                   bool TakingCandidateAddress,
12636                                   LangAS CtorDestAS = LangAS::Default) {
12637   assert(Cand->Function && "Candidate must be a function");
12638   FunctionDecl *Fn = Cand->Function;
12639   if (shouldSkipNotingLambdaConversionDecl(Fn))
12640     return;
12641 
12642   // There is no physical candidate declaration to point to for OpenCL builtins.
12643   // Except for failed conversions, the notes are identical for each candidate,
12644   // so do not generate such notes.
12645   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12646       Cand->FailureKind != ovl_fail_bad_conversion)
12647     return;
12648 
12649   // Skip implicit member functions when trying to resolve
12650   // the address of a an overload set for a function pointer.
12651   if (Cand->TookAddressOfOverload &&
12652       !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12653     return;
12654 
12655   // Note deleted candidates, but only if they're viable.
12656   if (Cand->Viable) {
12657     if (Fn->isDeleted()) {
12658       std::string FnDesc;
12659       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12660           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12661                                     Cand->getRewriteKind(), FnDesc);
12662 
12663       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12664           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12665           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12666       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12667       return;
12668     }
12669 
12670     // We don't really have anything else to say about viable candidates.
12671     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12672     return;
12673   }
12674 
12675   // If this is a synthesized deduction guide we're deducing against, add a note
12676   // for it. These deduction guides are not explicitly spelled in the source
12677   // code, so simply printing a deduction failure note mentioning synthesized
12678   // template parameters or pointing to the header of the surrounding RecordDecl
12679   // would be confusing.
12680   //
12681   // We prefer adding such notes at the end of the deduction failure because
12682   // duplicate code snippets appearing in the diagnostic would likely become
12683   // noisy.
12684   auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12685 
12686   switch (Cand->FailureKind) {
12687   case ovl_fail_too_many_arguments:
12688   case ovl_fail_too_few_arguments:
12689     return DiagnoseArityMismatch(S, Cand, NumArgs);
12690 
12691   case ovl_fail_bad_deduction:
12692     return DiagnoseBadDeduction(S, Cand, NumArgs,
12693                                 TakingCandidateAddress);
12694 
12695   case ovl_fail_illegal_constructor: {
12696     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12697       << (Fn->getPrimaryTemplate() ? 1 : 0);
12698     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12699     return;
12700   }
12701 
12702   case ovl_fail_object_addrspace_mismatch: {
12703     Qualifiers QualsForPrinting;
12704     QualsForPrinting.setAddressSpace(CtorDestAS);
12705     S.Diag(Fn->getLocation(),
12706            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12707         << QualsForPrinting;
12708     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12709     return;
12710   }
12711 
12712   case ovl_fail_trivial_conversion:
12713   case ovl_fail_bad_final_conversion:
12714   case ovl_fail_final_conversion_not_exact:
12715     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12716 
12717   case ovl_fail_bad_conversion: {
12718     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12719     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12720       if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12721         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12722 
12723     // FIXME: this currently happens when we're called from SemaInit
12724     // when user-conversion overload fails.  Figure out how to handle
12725     // those conditions and diagnose them well.
12726     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12727   }
12728 
12729   case ovl_fail_bad_target:
12730     return DiagnoseBadTarget(S, Cand);
12731 
12732   case ovl_fail_enable_if:
12733     return DiagnoseFailedEnableIfAttr(S, Cand);
12734 
12735   case ovl_fail_explicit:
12736     return DiagnoseFailedExplicitSpec(S, Cand);
12737 
12738   case ovl_fail_inhctor_slice:
12739     // It's generally not interesting to note copy/move constructors here.
12740     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12741       return;
12742     S.Diag(Fn->getLocation(),
12743            diag::note_ovl_candidate_inherited_constructor_slice)
12744       << (Fn->getPrimaryTemplate() ? 1 : 0)
12745       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12746     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12747     return;
12748 
12749   case ovl_fail_addr_not_available: {
12750     bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12751     (void)Available;
12752     assert(!Available);
12753     break;
12754   }
12755   case ovl_non_default_multiversion_function:
12756     // Do nothing, these should simply be ignored.
12757     break;
12758 
12759   case ovl_fail_constraints_not_satisfied: {
12760     std::string FnDesc;
12761     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12762         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12763                                   Cand->getRewriteKind(), FnDesc);
12764 
12765     S.Diag(Fn->getLocation(),
12766            diag::note_ovl_candidate_constraints_not_satisfied)
12767         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12768         << FnDesc /* Ignored */;
12769     ConstraintSatisfaction Satisfaction;
12770     if (S.CheckFunctionConstraints(Fn, Satisfaction))
12771       break;
12772     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12773   }
12774   }
12775 }
12776 
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)12777 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12778   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
12779     return;
12780 
12781   // Desugar the type of the surrogate down to a function type,
12782   // retaining as many typedefs as possible while still showing
12783   // the function type (and, therefore, its parameter types).
12784   QualType FnType = Cand->Surrogate->getConversionType();
12785   bool isLValueReference = false;
12786   bool isRValueReference = false;
12787   bool isPointer = false;
12788   if (const LValueReferenceType *FnTypeRef =
12789         FnType->getAs<LValueReferenceType>()) {
12790     FnType = FnTypeRef->getPointeeType();
12791     isLValueReference = true;
12792   } else if (const RValueReferenceType *FnTypeRef =
12793                FnType->getAs<RValueReferenceType>()) {
12794     FnType = FnTypeRef->getPointeeType();
12795     isRValueReference = true;
12796   }
12797   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12798     FnType = FnTypePtr->getPointeeType();
12799     isPointer = true;
12800   }
12801   // Desugar down to a function type.
12802   FnType = QualType(FnType->getAs<FunctionType>(), 0);
12803   // Reconstruct the pointer/reference as appropriate.
12804   if (isPointer) FnType = S.Context.getPointerType(FnType);
12805   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12806   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12807 
12808   if (!Cand->Viable &&
12809       Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12810     S.Diag(Cand->Surrogate->getLocation(),
12811            diag::note_ovl_surrogate_constraints_not_satisfied)
12812         << Cand->Surrogate;
12813     ConstraintSatisfaction Satisfaction;
12814     if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12815       S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12816   } else {
12817     S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12818         << FnType;
12819   }
12820 }
12821 
NoteBuiltinOperatorCandidate(Sema & S,StringRef Opc,SourceLocation OpLoc,OverloadCandidate * Cand)12822 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12823                                          SourceLocation OpLoc,
12824                                          OverloadCandidate *Cand) {
12825   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12826   std::string TypeStr("operator");
12827   TypeStr += Opc;
12828   TypeStr += "(";
12829   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12830   if (Cand->Conversions.size() == 1) {
12831     TypeStr += ")";
12832     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12833   } else {
12834     TypeStr += ", ";
12835     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12836     TypeStr += ")";
12837     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12838   }
12839 }
12840 
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)12841 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12842                                          OverloadCandidate *Cand) {
12843   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12844     if (ICS.isBad()) break; // all meaningless after first invalid
12845     if (!ICS.isAmbiguous()) continue;
12846 
12847     ICS.DiagnoseAmbiguousConversion(
12848         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12849   }
12850 }
12851 
GetLocationForCandidate(const OverloadCandidate * Cand)12852 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12853   if (Cand->Function)
12854     return Cand->Function->getLocation();
12855   if (Cand->IsSurrogate)
12856     return Cand->Surrogate->getLocation();
12857   return SourceLocation();
12858 }
12859 
RankDeductionFailure(const DeductionFailureInfo & DFI)12860 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12861   switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12862   case TemplateDeductionResult::Success:
12863   case TemplateDeductionResult::NonDependentConversionFailure:
12864   case TemplateDeductionResult::AlreadyDiagnosed:
12865     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12866 
12867   case TemplateDeductionResult::Invalid:
12868   case TemplateDeductionResult::Incomplete:
12869   case TemplateDeductionResult::IncompletePack:
12870     return 1;
12871 
12872   case TemplateDeductionResult::Underqualified:
12873   case TemplateDeductionResult::Inconsistent:
12874     return 2;
12875 
12876   case TemplateDeductionResult::SubstitutionFailure:
12877   case TemplateDeductionResult::DeducedMismatch:
12878   case TemplateDeductionResult::ConstraintsNotSatisfied:
12879   case TemplateDeductionResult::DeducedMismatchNested:
12880   case TemplateDeductionResult::NonDeducedMismatch:
12881   case TemplateDeductionResult::MiscellaneousDeductionFailure:
12882   case TemplateDeductionResult::CUDATargetMismatch:
12883     return 3;
12884 
12885   case TemplateDeductionResult::InstantiationDepth:
12886     return 4;
12887 
12888   case TemplateDeductionResult::InvalidExplicitArguments:
12889     return 5;
12890 
12891   case TemplateDeductionResult::TooManyArguments:
12892   case TemplateDeductionResult::TooFewArguments:
12893     return 6;
12894   }
12895   llvm_unreachable("Unhandled deduction result");
12896 }
12897 
12898 namespace {
12899 
12900 struct CompareOverloadCandidatesForDisplay {
12901   Sema &S;
12902   SourceLocation Loc;
12903   size_t NumArgs;
12904   OverloadCandidateSet::CandidateSetKind CSK;
12905 
CompareOverloadCandidatesForDisplay__anon2e1ecc912b11::CompareOverloadCandidatesForDisplay12906   CompareOverloadCandidatesForDisplay(
12907       Sema &S, SourceLocation Loc, size_t NArgs,
12908       OverloadCandidateSet::CandidateSetKind CSK)
12909       : S(S), NumArgs(NArgs), CSK(CSK) {}
12910 
EffectiveFailureKind__anon2e1ecc912b11::CompareOverloadCandidatesForDisplay12911   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12912     // If there are too many or too few arguments, that's the high-order bit we
12913     // want to sort by, even if the immediate failure kind was something else.
12914     if (C->FailureKind == ovl_fail_too_many_arguments ||
12915         C->FailureKind == ovl_fail_too_few_arguments)
12916       return static_cast<OverloadFailureKind>(C->FailureKind);
12917 
12918     if (C->Function) {
12919       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12920         return ovl_fail_too_many_arguments;
12921       if (NumArgs < C->Function->getMinRequiredArguments())
12922         return ovl_fail_too_few_arguments;
12923     }
12924 
12925     return static_cast<OverloadFailureKind>(C->FailureKind);
12926   }
12927 
operator ()__anon2e1ecc912b11::CompareOverloadCandidatesForDisplay12928   bool operator()(const OverloadCandidate *L,
12929                   const OverloadCandidate *R) {
12930     // Fast-path this check.
12931     if (L == R) return false;
12932 
12933     // Order first by viability.
12934     if (L->Viable) {
12935       if (!R->Viable) return true;
12936 
12937       if (int Ord = CompareConversions(*L, *R))
12938         return Ord < 0;
12939       // Use other tie breakers.
12940     } else if (R->Viable)
12941       return false;
12942 
12943     assert(L->Viable == R->Viable);
12944 
12945     // Criteria by which we can sort non-viable candidates:
12946     if (!L->Viable) {
12947       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12948       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12949 
12950       // 1. Arity mismatches come after other candidates.
12951       if (LFailureKind == ovl_fail_too_many_arguments ||
12952           LFailureKind == ovl_fail_too_few_arguments) {
12953         if (RFailureKind == ovl_fail_too_many_arguments ||
12954             RFailureKind == ovl_fail_too_few_arguments) {
12955           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12956           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12957           if (LDist == RDist) {
12958             if (LFailureKind == RFailureKind)
12959               // Sort non-surrogates before surrogates.
12960               return !L->IsSurrogate && R->IsSurrogate;
12961             // Sort candidates requiring fewer parameters than there were
12962             // arguments given after candidates requiring more parameters
12963             // than there were arguments given.
12964             return LFailureKind == ovl_fail_too_many_arguments;
12965           }
12966           return LDist < RDist;
12967         }
12968         return false;
12969       }
12970       if (RFailureKind == ovl_fail_too_many_arguments ||
12971           RFailureKind == ovl_fail_too_few_arguments)
12972         return true;
12973 
12974       // 2. Bad conversions come first and are ordered by the number
12975       // of bad conversions and quality of good conversions.
12976       if (LFailureKind == ovl_fail_bad_conversion) {
12977         if (RFailureKind != ovl_fail_bad_conversion)
12978           return true;
12979 
12980         // The conversion that can be fixed with a smaller number of changes,
12981         // comes first.
12982         unsigned numLFixes = L->Fix.NumConversionsFixed;
12983         unsigned numRFixes = R->Fix.NumConversionsFixed;
12984         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12985         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12986         if (numLFixes != numRFixes) {
12987           return numLFixes < numRFixes;
12988         }
12989 
12990         // If there's any ordering between the defined conversions...
12991         if (int Ord = CompareConversions(*L, *R))
12992           return Ord < 0;
12993       } else if (RFailureKind == ovl_fail_bad_conversion)
12994         return false;
12995 
12996       if (LFailureKind == ovl_fail_bad_deduction) {
12997         if (RFailureKind != ovl_fail_bad_deduction)
12998           return true;
12999 
13000         if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13001           unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13002           unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13003           if (LRank != RRank)
13004             return LRank < RRank;
13005         }
13006       } else if (RFailureKind == ovl_fail_bad_deduction)
13007         return false;
13008 
13009       // TODO: others?
13010     }
13011 
13012     // Sort everything else by location.
13013     SourceLocation LLoc = GetLocationForCandidate(L);
13014     SourceLocation RLoc = GetLocationForCandidate(R);
13015 
13016     // Put candidates without locations (e.g. builtins) at the end.
13017     if (LLoc.isValid() && RLoc.isValid())
13018       return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13019     if (LLoc.isValid() && !RLoc.isValid())
13020       return true;
13021     if (RLoc.isValid() && !LLoc.isValid())
13022       return false;
13023     assert(!LLoc.isValid() && !RLoc.isValid());
13024     // For builtins and other functions without locations, fallback to the order
13025     // in which they were added into the candidate set.
13026     return L < R;
13027   }
13028 
13029 private:
13030   struct ConversionSignals {
13031     unsigned KindRank = 0;
13032     ImplicitConversionRank Rank = ICR_Exact_Match;
13033 
ForSequence__anon2e1ecc912b11::CompareOverloadCandidatesForDisplay::ConversionSignals13034     static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13035       ConversionSignals Sig;
13036       Sig.KindRank = Seq.getKindRank();
13037       if (Seq.isStandard())
13038         Sig.Rank = Seq.Standard.getRank();
13039       else if (Seq.isUserDefined())
13040         Sig.Rank = Seq.UserDefined.After.getRank();
13041       // We intend StaticObjectArgumentConversion to compare the same as
13042       // StandardConversion with ICR_ExactMatch rank.
13043       return Sig;
13044     }
13045 
ForObjectArgument__anon2e1ecc912b11::CompareOverloadCandidatesForDisplay::ConversionSignals13046     static ConversionSignals ForObjectArgument() {
13047       // We intend StaticObjectArgumentConversion to compare the same as
13048       // StandardConversion with ICR_ExactMatch rank. Default give us that.
13049       return {};
13050     }
13051   };
13052 
13053   // Returns -1 if conversions in L are considered better.
13054   //          0 if they are considered indistinguishable.
13055   //          1 if conversions in R are better.
CompareConversions__anon2e1ecc912b11::CompareOverloadCandidatesForDisplay13056   int CompareConversions(const OverloadCandidate &L,
13057                          const OverloadCandidate &R) {
13058     // We cannot use `isBetterOverloadCandidate` because it is defined
13059     // according to the C++ standard and provides a partial order, but we need
13060     // a total order as this function is used in sort.
13061     assert(L.Conversions.size() == R.Conversions.size());
13062     for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13063       auto LS = L.IgnoreObjectArgument && I == 0
13064                     ? ConversionSignals::ForObjectArgument()
13065                     : ConversionSignals::ForSequence(L.Conversions[I]);
13066       auto RS = R.IgnoreObjectArgument
13067                     ? ConversionSignals::ForObjectArgument()
13068                     : ConversionSignals::ForSequence(R.Conversions[I]);
13069       if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13070         return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13071                    ? -1
13072                    : 1;
13073     }
13074     // FIXME: find a way to compare templates for being more or less
13075     // specialized that provides a strict weak ordering.
13076     return 0;
13077   }
13078 };
13079 }
13080 
13081 /// CompleteNonViableCandidate - Normally, overload resolution only
13082 /// computes up to the first bad conversion. Produces the FixIt set if
13083 /// possible.
13084 static void
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,ArrayRef<Expr * > Args,OverloadCandidateSet::CandidateSetKind CSK)13085 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13086                            ArrayRef<Expr *> Args,
13087                            OverloadCandidateSet::CandidateSetKind CSK) {
13088   assert(!Cand->Viable);
13089 
13090   // Don't do anything on failures other than bad conversion.
13091   if (Cand->FailureKind != ovl_fail_bad_conversion)
13092     return;
13093 
13094   // We only want the FixIts if all the arguments can be corrected.
13095   bool Unfixable = false;
13096   // Use a implicit copy initialization to check conversion fixes.
13097   Cand->Fix.setConversionChecker(TryCopyInitialization);
13098 
13099   // Attempt to fix the bad conversion.
13100   unsigned ConvCount = Cand->Conversions.size();
13101   for (unsigned ConvIdx =
13102            ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13103                                                                          : 0);
13104        /**/; ++ConvIdx) {
13105     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13106     if (Cand->Conversions[ConvIdx].isInitialized() &&
13107         Cand->Conversions[ConvIdx].isBad()) {
13108       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13109       break;
13110     }
13111   }
13112 
13113   // FIXME: this should probably be preserved from the overload
13114   // operation somehow.
13115   bool SuppressUserConversions = false;
13116 
13117   unsigned ConvIdx = 0;
13118   unsigned ArgIdx = 0;
13119   ArrayRef<QualType> ParamTypes;
13120   bool Reversed = Cand->isReversed();
13121 
13122   if (Cand->IsSurrogate) {
13123     QualType ConvType
13124       = Cand->Surrogate->getConversionType().getNonReferenceType();
13125     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13126       ConvType = ConvPtrType->getPointeeType();
13127     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13128     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13129     ConvIdx = 1;
13130   } else if (Cand->Function) {
13131     ParamTypes =
13132         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13133     if (isa<CXXMethodDecl>(Cand->Function) &&
13134         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed &&
13135         !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13136       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13137       ConvIdx = 1;
13138       if (CSK == OverloadCandidateSet::CSK_Operator &&
13139           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13140           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13141               OO_Subscript)
13142         // Argument 0 is 'this', which doesn't have a corresponding parameter.
13143         ArgIdx = 1;
13144     }
13145   } else {
13146     // Builtin operator.
13147     assert(ConvCount <= 3);
13148     ParamTypes = Cand->BuiltinParamTypes;
13149   }
13150 
13151   // Fill in the rest of the conversions.
13152   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13153        ConvIdx != ConvCount && ArgIdx < Args.size();
13154        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13155     if (Cand->Conversions[ConvIdx].isInitialized()) {
13156       // We've already checked this conversion.
13157     } else if (ParamIdx < ParamTypes.size()) {
13158       if (ParamTypes[ParamIdx]->isDependentType())
13159         Cand->Conversions[ConvIdx].setAsIdentityConversion(
13160             Args[ArgIdx]->getType());
13161       else {
13162         Cand->Conversions[ConvIdx] =
13163             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13164                                   SuppressUserConversions,
13165                                   /*InOverloadResolution=*/true,
13166                                   /*AllowObjCWritebackConversion=*/
13167                                   S.getLangOpts().ObjCAutoRefCount);
13168         // Store the FixIt in the candidate if it exists.
13169         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13170           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13171       }
13172     } else
13173       Cand->Conversions[ConvIdx].setEllipsis();
13174   }
13175 }
13176 
CompleteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,SourceLocation OpLoc,llvm::function_ref<bool (OverloadCandidate &)> Filter)13177 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13178     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13179     SourceLocation OpLoc,
13180     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13181 
13182   InjectNonDeducedTemplateCandidates(S);
13183 
13184   // Sort the candidates by viability and position.  Sorting directly would
13185   // be prohibitive, so we make a set of pointers and sort those.
13186   SmallVector<OverloadCandidate*, 32> Cands;
13187   if (OCD == OCD_AllCandidates) Cands.reserve(size());
13188   for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13189        Cand != LastCand; ++Cand) {
13190     if (!Filter(*Cand))
13191       continue;
13192     switch (OCD) {
13193     case OCD_AllCandidates:
13194       if (!Cand->Viable) {
13195         if (!Cand->Function && !Cand->IsSurrogate) {
13196           // This a non-viable builtin candidate.  We do not, in general,
13197           // want to list every possible builtin candidate.
13198           continue;
13199         }
13200         CompleteNonViableCandidate(S, Cand, Args, Kind);
13201       }
13202       break;
13203 
13204     case OCD_ViableCandidates:
13205       if (!Cand->Viable)
13206         continue;
13207       break;
13208 
13209     case OCD_AmbiguousCandidates:
13210       if (!Cand->Best)
13211         continue;
13212       break;
13213     }
13214 
13215     Cands.push_back(Cand);
13216   }
13217 
13218   llvm::stable_sort(
13219       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13220 
13221   return Cands;
13222 }
13223 
shouldDeferDiags(Sema & S,ArrayRef<Expr * > Args,SourceLocation OpLoc)13224 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13225                                             SourceLocation OpLoc) {
13226   bool DeferHint = false;
13227   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13228     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13229     // host device candidates.
13230     auto WrongSidedCands =
13231         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13232           return (Cand.Viable == false &&
13233                   Cand.FailureKind == ovl_fail_bad_target) ||
13234                  (Cand.Function &&
13235                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
13236                   Cand.Function->template hasAttr<CUDADeviceAttr>());
13237         });
13238     DeferHint = !WrongSidedCands.empty();
13239   }
13240   return DeferHint;
13241 }
13242 
13243 /// When overload resolution fails, prints diagnostic messages containing the
13244 /// 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)13245 void OverloadCandidateSet::NoteCandidates(
13246     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13247     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13248     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13249 
13250   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13251 
13252   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
13253 
13254   // In WebAssembly we don't want to emit further diagnostics if a table is
13255   // passed as an argument to a function.
13256   bool NoteCands = true;
13257   for (const Expr *Arg : Args) {
13258     if (Arg->getType()->isWebAssemblyTableType())
13259       NoteCands = false;
13260   }
13261 
13262   if (NoteCands)
13263     NoteCandidates(S, Args, Cands, Opc, OpLoc);
13264 
13265   if (OCD == OCD_AmbiguousCandidates)
13266     MaybeDiagnoseAmbiguousConstraints(S,
13267                                       {Candidates.begin(), Candidates.end()});
13268 }
13269 
NoteCandidates(Sema & S,ArrayRef<Expr * > Args,ArrayRef<OverloadCandidate * > Cands,StringRef Opc,SourceLocation OpLoc)13270 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13271                                           ArrayRef<OverloadCandidate *> Cands,
13272                                           StringRef Opc, SourceLocation OpLoc) {
13273   bool ReportedAmbiguousConversions = false;
13274 
13275   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13276   unsigned CandsShown = 0;
13277   auto I = Cands.begin(), E = Cands.end();
13278   for (; I != E; ++I) {
13279     OverloadCandidate *Cand = *I;
13280 
13281     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13282         ShowOverloads == Ovl_Best) {
13283       break;
13284     }
13285     ++CandsShown;
13286 
13287     if (Cand->Function)
13288       NoteFunctionCandidate(S, Cand, Args.size(),
13289                             Kind == CSK_AddressOfOverloadSet, DestAS);
13290     else if (Cand->IsSurrogate)
13291       NoteSurrogateCandidate(S, Cand);
13292     else {
13293       assert(Cand->Viable &&
13294              "Non-viable built-in candidates are not added to Cands.");
13295       // Generally we only see ambiguities including viable builtin
13296       // operators if overload resolution got screwed up by an
13297       // ambiguous user-defined conversion.
13298       //
13299       // FIXME: It's quite possible for different conversions to see
13300       // different ambiguities, though.
13301       if (!ReportedAmbiguousConversions) {
13302         NoteAmbiguousUserConversions(S, OpLoc, Cand);
13303         ReportedAmbiguousConversions = true;
13304       }
13305 
13306       // If this is a viable builtin, print it.
13307       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13308     }
13309   }
13310 
13311   // Inform S.Diags that we've shown an overload set with N elements.  This may
13312   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13313   S.Diags.overloadCandidatesShown(CandsShown);
13314 
13315   if (I != E)
13316     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
13317            shouldDeferDiags(S, Args, OpLoc))
13318         << int(E - I);
13319 }
13320 
13321 static SourceLocation
GetLocationForCandidate(const TemplateSpecCandidate * Cand)13322 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13323   return Cand->Specialization ? Cand->Specialization->getLocation()
13324                               : SourceLocation();
13325 }
13326 
13327 namespace {
13328 struct CompareTemplateSpecCandidatesForDisplay {
13329   Sema &S;
CompareTemplateSpecCandidatesForDisplay__anon2e1ecc912d11::CompareTemplateSpecCandidatesForDisplay13330   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13331 
operator ()__anon2e1ecc912d11::CompareTemplateSpecCandidatesForDisplay13332   bool operator()(const TemplateSpecCandidate *L,
13333                   const TemplateSpecCandidate *R) {
13334     // Fast-path this check.
13335     if (L == R)
13336       return false;
13337 
13338     // Assuming that both candidates are not matches...
13339 
13340     // Sort by the ranking of deduction failures.
13341     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13342       return RankDeductionFailure(L->DeductionFailure) <
13343              RankDeductionFailure(R->DeductionFailure);
13344 
13345     // Sort everything else by location.
13346     SourceLocation LLoc = GetLocationForCandidate(L);
13347     SourceLocation RLoc = GetLocationForCandidate(R);
13348 
13349     // Put candidates without locations (e.g. builtins) at the end.
13350     if (LLoc.isInvalid())
13351       return false;
13352     if (RLoc.isInvalid())
13353       return true;
13354 
13355     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13356   }
13357 };
13358 }
13359 
13360 /// Diagnose a template argument deduction failure.
13361 /// We are treating these failures as overload failures due to bad
13362 /// deductions.
NoteDeductionFailure(Sema & S,bool ForTakingAddress)13363 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13364                                                  bool ForTakingAddress) {
13365   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
13366                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13367 }
13368 
destroyCandidates()13369 void TemplateSpecCandidateSet::destroyCandidates() {
13370   for (iterator i = begin(), e = end(); i != e; ++i) {
13371     i->DeductionFailure.Destroy();
13372   }
13373 }
13374 
clear()13375 void TemplateSpecCandidateSet::clear() {
13376   destroyCandidates();
13377   Candidates.clear();
13378 }
13379 
13380 /// NoteCandidates - When no template specialization match is found, prints
13381 /// diagnostic messages containing the non-matching specializations that form
13382 /// the candidate set.
13383 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13384 /// OCD == OCD_AllCandidates and Cand->Viable == false.
NoteCandidates(Sema & S,SourceLocation Loc)13385 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13386   // Sort the candidates by position (assuming no candidate is a match).
13387   // Sorting directly would be prohibitive, so we make a set of pointers
13388   // and sort those.
13389   SmallVector<TemplateSpecCandidate *, 32> Cands;
13390   Cands.reserve(size());
13391   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13392     if (Cand->Specialization)
13393       Cands.push_back(Cand);
13394     // Otherwise, this is a non-matching builtin candidate.  We do not,
13395     // in general, want to list every possible builtin candidate.
13396   }
13397 
13398   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13399 
13400   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13401   // for generalization purposes (?).
13402   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13403 
13404   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13405   unsigned CandsShown = 0;
13406   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13407     TemplateSpecCandidate *Cand = *I;
13408 
13409     // Set an arbitrary limit on the number of candidates we'll spam
13410     // the user with.  FIXME: This limit should depend on details of the
13411     // candidate list.
13412     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13413       break;
13414     ++CandsShown;
13415 
13416     assert(Cand->Specialization &&
13417            "Non-matching built-in candidates are not added to Cands.");
13418     Cand->NoteDeductionFailure(S, ForTakingAddress);
13419   }
13420 
13421   if (I != E)
13422     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13423 }
13424 
13425 // [PossiblyAFunctionType]  -->   [Return]
13426 // NonFunctionType --> NonFunctionType
13427 // R (A) --> R(A)
13428 // R (*)(A) --> R (A)
13429 // R (&)(A) --> R (A)
13430 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)13431 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13432   QualType Ret = PossiblyAFunctionType;
13433   if (const PointerType *ToTypePtr =
13434     PossiblyAFunctionType->getAs<PointerType>())
13435     Ret = ToTypePtr->getPointeeType();
13436   else if (const ReferenceType *ToTypeRef =
13437     PossiblyAFunctionType->getAs<ReferenceType>())
13438     Ret = ToTypeRef->getPointeeType();
13439   else if (const MemberPointerType *MemTypePtr =
13440     PossiblyAFunctionType->getAs<MemberPointerType>())
13441     Ret = MemTypePtr->getPointeeType();
13442   Ret =
13443     Context.getCanonicalType(Ret).getUnqualifiedType();
13444   return Ret;
13445 }
13446 
completeFunctionType(Sema & S,FunctionDecl * FD,SourceLocation Loc,bool Complain=true)13447 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13448                                  bool Complain = true) {
13449   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13450       S.DeduceReturnType(FD, Loc, Complain))
13451     return true;
13452 
13453   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13454   if (S.getLangOpts().CPlusPlus17 &&
13455       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13456       !S.ResolveExceptionSpec(Loc, FPT))
13457     return true;
13458 
13459   return false;
13460 }
13461 
13462 namespace {
13463 // A helper class to help with address of function resolution
13464 // - allows us to avoid passing around all those ugly parameters
13465 class AddressOfFunctionResolver {
13466   Sema& S;
13467   Expr* SourceExpr;
13468   const QualType& TargetType;
13469   QualType TargetFunctionType; // Extracted function type from target type
13470 
13471   bool Complain;
13472   //DeclAccessPair& ResultFunctionAccessPair;
13473   ASTContext& Context;
13474 
13475   bool TargetTypeIsNonStaticMemberFunction;
13476   bool FoundNonTemplateFunction;
13477   bool StaticMemberFunctionFromBoundPointer;
13478   bool HasComplained;
13479 
13480   OverloadExpr::FindResult OvlExprInfo;
13481   OverloadExpr *OvlExpr;
13482   TemplateArgumentListInfo OvlExplicitTemplateArgs;
13483   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13484   TemplateSpecCandidateSet FailedCandidates;
13485 
13486 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)13487   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13488                             const QualType &TargetType, bool Complain)
13489       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13490         Complain(Complain), Context(S.getASTContext()),
13491         TargetTypeIsNonStaticMemberFunction(
13492             !!TargetType->getAs<MemberPointerType>()),
13493         FoundNonTemplateFunction(false),
13494         StaticMemberFunctionFromBoundPointer(false),
13495         HasComplained(false),
13496         OvlExprInfo(OverloadExpr::find(SourceExpr)),
13497         OvlExpr(OvlExprInfo.Expression),
13498         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13499     ExtractUnqualifiedFunctionTypeFromTargetType();
13500 
13501     if (TargetFunctionType->isFunctionType()) {
13502       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13503         if (!UME->isImplicitAccess() &&
13504             !S.ResolveSingleFunctionTemplateSpecialization(UME))
13505           StaticMemberFunctionFromBoundPointer = true;
13506     } else if (OvlExpr->hasExplicitTemplateArgs()) {
13507       DeclAccessPair dap;
13508       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13509               OvlExpr, false, &dap)) {
13510         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13511           if (!Method->isStatic()) {
13512             // If the target type is a non-function type and the function found
13513             // is a non-static member function, pretend as if that was the
13514             // target, it's the only possible type to end up with.
13515             TargetTypeIsNonStaticMemberFunction = true;
13516 
13517             // And skip adding the function if its not in the proper form.
13518             // We'll diagnose this due to an empty set of functions.
13519             if (!OvlExprInfo.HasFormOfMemberPointer)
13520               return;
13521           }
13522 
13523         Matches.push_back(std::make_pair(dap, Fn));
13524       }
13525       return;
13526     }
13527 
13528     if (OvlExpr->hasExplicitTemplateArgs())
13529       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13530 
13531     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13532       // C++ [over.over]p4:
13533       //   If more than one function is selected, [...]
13534       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13535         if (FoundNonTemplateFunction) {
13536           EliminateAllTemplateMatches();
13537           EliminateLessPartialOrderingConstrainedMatches();
13538         } else
13539           EliminateAllExceptMostSpecializedTemplate();
13540       }
13541     }
13542 
13543     if (S.getLangOpts().CUDA && Matches.size() > 1)
13544       EliminateSuboptimalCudaMatches();
13545   }
13546 
hasComplained() const13547   bool hasComplained() const { return HasComplained; }
13548 
13549 private:
candidateHasExactlyCorrectType(const FunctionDecl * FD)13550   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13551     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13552            S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13553   }
13554 
13555   /// \return true if A is considered a better overload candidate for the
13556   /// desired type than B.
isBetterCandidate(const FunctionDecl * A,const FunctionDecl * B)13557   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13558     // If A doesn't have exactly the correct type, we don't want to classify it
13559     // as "better" than anything else. This way, the user is required to
13560     // disambiguate for us if there are multiple candidates and no exact match.
13561     return candidateHasExactlyCorrectType(A) &&
13562            (!candidateHasExactlyCorrectType(B) ||
13563             compareEnableIfAttrs(S, A, B) == Comparison::Better);
13564   }
13565 
13566   /// \return true if we were able to eliminate all but one overload candidate,
13567   /// false otherwise.
eliminiateSuboptimalOverloadCandidates()13568   bool eliminiateSuboptimalOverloadCandidates() {
13569     // Same algorithm as overload resolution -- one pass to pick the "best",
13570     // another pass to be sure that nothing is better than the best.
13571     auto Best = Matches.begin();
13572     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13573       if (isBetterCandidate(I->second, Best->second))
13574         Best = I;
13575 
13576     const FunctionDecl *BestFn = Best->second;
13577     auto IsBestOrInferiorToBest = [this, BestFn](
13578         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13579       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13580     };
13581 
13582     // Note: We explicitly leave Matches unmodified if there isn't a clear best
13583     // option, so we can potentially give the user a better error
13584     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13585       return false;
13586     Matches[0] = *Best;
13587     Matches.resize(1);
13588     return true;
13589   }
13590 
isTargetTypeAFunction() const13591   bool isTargetTypeAFunction() const {
13592     return TargetFunctionType->isFunctionType();
13593   }
13594 
13595   // [ToType]     [Return]
13596 
13597   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13598   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13599   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()13600   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13601     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13602   }
13603 
13604   // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)13605   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13606                                    const DeclAccessPair& CurAccessFunPair) {
13607     if (CXXMethodDecl *Method
13608               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13609       // Skip non-static function templates when converting to pointer, and
13610       // static when converting to member pointer.
13611       bool CanConvertToFunctionPointer =
13612           Method->isStatic() || Method->isExplicitObjectMemberFunction();
13613       if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13614         return false;
13615     }
13616     else if (TargetTypeIsNonStaticMemberFunction)
13617       return false;
13618 
13619     // C++ [over.over]p2:
13620     //   If the name is a function template, template argument deduction is
13621     //   done (14.8.2.2), and if the argument deduction succeeds, the
13622     //   resulting template argument list is used to generate a single
13623     //   function template specialization, which is added to the set of
13624     //   overloaded functions considered.
13625     FunctionDecl *Specialization = nullptr;
13626     TemplateDeductionInfo Info(FailedCandidates.getLocation());
13627     if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13628             FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13629             Specialization, Info, /*IsAddressOfFunction*/ true);
13630         Result != TemplateDeductionResult::Success) {
13631       // Make a note of the failed deduction for diagnostics.
13632       FailedCandidates.addCandidate()
13633           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13634                MakeDeductionFailureInfo(Context, Result, Info));
13635       return false;
13636     }
13637 
13638     // Template argument deduction ensures that we have an exact match or
13639     // compatible pointer-to-function arguments that would be adjusted by ICS.
13640     // This function template specicalization works.
13641     assert(S.isSameOrCompatibleFunctionType(
13642               Context.getCanonicalType(Specialization->getType()),
13643               Context.getCanonicalType(TargetFunctionType)));
13644 
13645     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
13646       return false;
13647 
13648     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13649     return true;
13650   }
13651 
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)13652   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13653                                       const DeclAccessPair& CurAccessFunPair) {
13654     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13655       // Skip non-static functions when converting to pointer, and static
13656       // when converting to member pointer.
13657       bool CanConvertToFunctionPointer =
13658           Method->isStatic() || Method->isExplicitObjectMemberFunction();
13659       if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13660         return false;
13661     }
13662     else if (TargetTypeIsNonStaticMemberFunction)
13663       return false;
13664 
13665     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13666       if (S.getLangOpts().CUDA) {
13667         FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13668         if (!(Caller && Caller->isImplicit()) &&
13669             !S.CUDA().IsAllowedCall(Caller, FunDecl))
13670           return false;
13671       }
13672       if (FunDecl->isMultiVersion()) {
13673         const auto *TA = FunDecl->getAttr<TargetAttr>();
13674         if (TA && !TA->isDefaultVersion())
13675           return false;
13676         const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13677         if (TVA && !TVA->isDefaultVersion())
13678           return false;
13679       }
13680 
13681       // If any candidate has a placeholder return type, trigger its deduction
13682       // now.
13683       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13684                                Complain)) {
13685         HasComplained |= Complain;
13686         return false;
13687       }
13688 
13689       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13690         return false;
13691 
13692       // If we're in C, we need to support types that aren't exactly identical.
13693       if (!S.getLangOpts().CPlusPlus ||
13694           candidateHasExactlyCorrectType(FunDecl)) {
13695         Matches.push_back(std::make_pair(
13696             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13697         FoundNonTemplateFunction = true;
13698         return true;
13699       }
13700     }
13701 
13702     return false;
13703   }
13704 
FindAllFunctionsThatMatchTargetTypeExactly()13705   bool FindAllFunctionsThatMatchTargetTypeExactly() {
13706     bool Ret = false;
13707 
13708     // If the overload expression doesn't have the form of a pointer to
13709     // member, don't try to convert it to a pointer-to-member type.
13710     if (IsInvalidFormOfPointerToMemberFunction())
13711       return false;
13712 
13713     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13714                                E = OvlExpr->decls_end();
13715          I != E; ++I) {
13716       // Look through any using declarations to find the underlying function.
13717       NamedDecl *Fn = (*I)->getUnderlyingDecl();
13718 
13719       // C++ [over.over]p3:
13720       //   Non-member functions and static member functions match
13721       //   targets of type "pointer-to-function" or "reference-to-function."
13722       //   Nonstatic member functions match targets of
13723       //   type "pointer-to-member-function."
13724       // Note that according to DR 247, the containing class does not matter.
13725       if (FunctionTemplateDecl *FunctionTemplate
13726                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
13727         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13728           Ret = true;
13729       }
13730       // If we have explicit template arguments supplied, skip non-templates.
13731       else if (!OvlExpr->hasExplicitTemplateArgs() &&
13732                AddMatchingNonTemplateFunction(Fn, I.getPair()))
13733         Ret = true;
13734     }
13735     assert(Ret || Matches.empty());
13736     return Ret;
13737   }
13738 
EliminateAllExceptMostSpecializedTemplate()13739   void EliminateAllExceptMostSpecializedTemplate() {
13740     //   [...] and any given function template specialization F1 is
13741     //   eliminated if the set contains a second function template
13742     //   specialization whose function template is more specialized
13743     //   than the function template of F1 according to the partial
13744     //   ordering rules of 14.5.5.2.
13745 
13746     // The algorithm specified above is quadratic. We instead use a
13747     // two-pass algorithm (similar to the one used to identify the
13748     // best viable function in an overload set) that identifies the
13749     // best function template (if it exists).
13750 
13751     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13752     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13753       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13754 
13755     // TODO: It looks like FailedCandidates does not serve much purpose
13756     // here, since the no_viable diagnostic has index 0.
13757     UnresolvedSetIterator Result = S.getMostSpecialized(
13758         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13759         SourceExpr->getBeginLoc(), S.PDiag(),
13760         S.PDiag(diag::err_addr_ovl_ambiguous)
13761             << Matches[0].second->getDeclName(),
13762         S.PDiag(diag::note_ovl_candidate)
13763             << (unsigned)oc_function << (unsigned)ocs_described_template,
13764         Complain, TargetFunctionType);
13765 
13766     if (Result != MatchesCopy.end()) {
13767       // Make it the first and only element
13768       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13769       Matches[0].second = cast<FunctionDecl>(*Result);
13770       Matches.resize(1);
13771     } else
13772       HasComplained |= Complain;
13773   }
13774 
EliminateAllTemplateMatches()13775   void EliminateAllTemplateMatches() {
13776     //   [...] any function template specializations in the set are
13777     //   eliminated if the set also contains a non-template function, [...]
13778     for (unsigned I = 0, N = Matches.size(); I != N; ) {
13779       if (Matches[I].second->getPrimaryTemplate() == nullptr)
13780         ++I;
13781       else {
13782         Matches[I] = Matches[--N];
13783         Matches.resize(N);
13784       }
13785     }
13786   }
13787 
EliminateLessPartialOrderingConstrainedMatches()13788   void EliminateLessPartialOrderingConstrainedMatches() {
13789     // C++ [over.over]p5:
13790     //   [...] Any given non-template function F0 is eliminated if the set
13791     //   contains a second non-template function that is more
13792     //   partial-ordering-constrained than F0. [...]
13793     assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13794            "Call EliminateAllTemplateMatches() first");
13795     SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13796     Results.push_back(Matches[0]);
13797     for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13798       assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13799       FunctionDecl *F = getMorePartialOrderingConstrained(
13800           S, Matches[I].second, Results[0].second,
13801           /*IsFn1Reversed=*/false,
13802           /*IsFn2Reversed=*/false);
13803       if (!F) {
13804         Results.push_back(Matches[I]);
13805         continue;
13806       }
13807       if (F == Matches[I].second) {
13808         Results.clear();
13809         Results.push_back(Matches[I]);
13810       }
13811     }
13812     std::swap(Matches, Results);
13813   }
13814 
EliminateSuboptimalCudaMatches()13815   void EliminateSuboptimalCudaMatches() {
13816     S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13817                                   Matches);
13818   }
13819 
13820 public:
ComplainNoMatchesFound() const13821   void ComplainNoMatchesFound() const {
13822     assert(Matches.empty());
13823     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13824         << OvlExpr->getName() << TargetFunctionType
13825         << OvlExpr->getSourceRange();
13826     if (FailedCandidates.empty())
13827       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13828                                   /*TakingAddress=*/true);
13829     else {
13830       // We have some deduction failure messages. Use them to diagnose
13831       // the function templates, and diagnose the non-template candidates
13832       // normally.
13833       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13834                                  IEnd = OvlExpr->decls_end();
13835            I != IEnd; ++I)
13836         if (FunctionDecl *Fun =
13837                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13838           if (!functionHasPassObjectSizeParams(Fun))
13839             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13840                                     /*TakingAddress=*/true);
13841       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13842     }
13843   }
13844 
IsInvalidFormOfPointerToMemberFunction() const13845   bool IsInvalidFormOfPointerToMemberFunction() const {
13846     return TargetTypeIsNonStaticMemberFunction &&
13847       !OvlExprInfo.HasFormOfMemberPointer;
13848   }
13849 
ComplainIsInvalidFormOfPointerToMemberFunction() const13850   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13851       // TODO: Should we condition this on whether any functions might
13852       // have matched, or is it more appropriate to do that in callers?
13853       // TODO: a fixit wouldn't hurt.
13854       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13855         << TargetType << OvlExpr->getSourceRange();
13856   }
13857 
IsStaticMemberFunctionFromBoundPointer() const13858   bool IsStaticMemberFunctionFromBoundPointer() const {
13859     return StaticMemberFunctionFromBoundPointer;
13860   }
13861 
ComplainIsStaticMemberFunctionFromBoundPointer() const13862   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13863     S.Diag(OvlExpr->getBeginLoc(),
13864            diag::err_invalid_form_pointer_member_function)
13865         << OvlExpr->getSourceRange();
13866   }
13867 
ComplainOfInvalidConversion() const13868   void ComplainOfInvalidConversion() const {
13869     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13870         << OvlExpr->getName() << TargetType;
13871   }
13872 
ComplainMultipleMatchesFound() const13873   void ComplainMultipleMatchesFound() const {
13874     assert(Matches.size() > 1);
13875     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13876         << OvlExpr->getName() << OvlExpr->getSourceRange();
13877     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13878                                 /*TakingAddress=*/true);
13879   }
13880 
hadMultipleCandidates() const13881   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13882 
getNumMatches() const13883   int getNumMatches() const { return Matches.size(); }
13884 
getMatchingFunctionDecl() const13885   FunctionDecl* getMatchingFunctionDecl() const {
13886     if (Matches.size() != 1) return nullptr;
13887     return Matches[0].second;
13888   }
13889 
getMatchingFunctionAccessPair() const13890   const DeclAccessPair* getMatchingFunctionAccessPair() const {
13891     if (Matches.size() != 1) return nullptr;
13892     return &Matches[0].first;
13893   }
13894 };
13895 }
13896 
13897 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)13898 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13899                                          QualType TargetType,
13900                                          bool Complain,
13901                                          DeclAccessPair &FoundResult,
13902                                          bool *pHadMultipleCandidates) {
13903   assert(AddressOfExpr->getType() == Context.OverloadTy);
13904 
13905   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13906                                      Complain);
13907   int NumMatches = Resolver.getNumMatches();
13908   FunctionDecl *Fn = nullptr;
13909   bool ShouldComplain = Complain && !Resolver.hasComplained();
13910   if (NumMatches == 0 && ShouldComplain) {
13911     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13912       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13913     else
13914       Resolver.ComplainNoMatchesFound();
13915   }
13916   else if (NumMatches > 1 && ShouldComplain)
13917     Resolver.ComplainMultipleMatchesFound();
13918   else if (NumMatches == 1) {
13919     Fn = Resolver.getMatchingFunctionDecl();
13920     assert(Fn);
13921     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13922       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13923     FoundResult = *Resolver.getMatchingFunctionAccessPair();
13924     if (Complain) {
13925       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13926         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13927       else
13928         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13929     }
13930   }
13931 
13932   if (pHadMultipleCandidates)
13933     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13934   return Fn;
13935 }
13936 
13937 FunctionDecl *
resolveAddressOfSingleOverloadCandidate(Expr * E,DeclAccessPair & Pair)13938 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13939   OverloadExpr::FindResult R = OverloadExpr::find(E);
13940   OverloadExpr *Ovl = R.Expression;
13941   bool IsResultAmbiguous = false;
13942   FunctionDecl *Result = nullptr;
13943   DeclAccessPair DAP;
13944   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13945 
13946   // Return positive for better, negative for worse, 0 for equal preference.
13947   auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13948     FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13949     return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13950            static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13951   };
13952 
13953   // Don't use the AddressOfResolver because we're specifically looking for
13954   // cases where we have one overload candidate that lacks
13955   // enable_if/pass_object_size/...
13956   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13957     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13958     if (!FD)
13959       return nullptr;
13960 
13961     if (!checkAddressOfFunctionIsAvailable(FD))
13962       continue;
13963 
13964     // If we found a better result, update Result.
13965     auto FoundBetter = [&]() {
13966       IsResultAmbiguous = false;
13967       DAP = I.getPair();
13968       Result = FD;
13969     };
13970 
13971     // We have more than one result - see if it is more
13972     // partial-ordering-constrained than the previous one.
13973     if (Result) {
13974       // Check CUDA preference first. If the candidates have differennt CUDA
13975       // preference, choose the one with higher CUDA preference. Otherwise,
13976       // choose the one with more constraints.
13977       if (getLangOpts().CUDA) {
13978         int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13979         // FD has different preference than Result.
13980         if (PreferenceByCUDA != 0) {
13981           // FD is more preferable than Result.
13982           if (PreferenceByCUDA > 0)
13983             FoundBetter();
13984           continue;
13985         }
13986       }
13987       // FD has the same CUDA preference than Result. Continue to check
13988       // constraints.
13989 
13990       // C++ [over.over]p5:
13991       //    [...] Any given non-template function F0 is eliminated if the set
13992       //    contains a second non-template function that is more
13993       //    partial-ordering-constrained than F0 [...]
13994       FunctionDecl *MoreConstrained =
13995           getMorePartialOrderingConstrained(*this, FD, Result,
13996                                             /*IsFn1Reversed=*/false,
13997                                             /*IsFn2Reversed=*/false);
13998       if (MoreConstrained != FD) {
13999         if (!MoreConstrained) {
14000           IsResultAmbiguous = true;
14001           AmbiguousDecls.push_back(FD);
14002         }
14003         continue;
14004       }
14005       // FD is more constrained - replace Result with it.
14006     }
14007     FoundBetter();
14008   }
14009 
14010   if (IsResultAmbiguous)
14011     return nullptr;
14012 
14013   if (Result) {
14014     // We skipped over some ambiguous declarations which might be ambiguous with
14015     // the selected result.
14016     for (FunctionDecl *Skipped : AmbiguousDecls) {
14017       // If skipped candidate has different CUDA preference than the result,
14018       // there is no ambiguity. Otherwise check whether they have different
14019       // constraints.
14020       if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14021         continue;
14022       if (!getMoreConstrainedFunction(Skipped, Result))
14023         return nullptr;
14024     }
14025     Pair = DAP;
14026   }
14027   return Result;
14028 }
14029 
resolveAndFixAddressOfSingleOverloadCandidate(ExprResult & SrcExpr,bool DoFunctionPointerConversion)14030 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14031     ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14032   Expr *E = SrcExpr.get();
14033   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14034 
14035   DeclAccessPair DAP;
14036   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
14037   if (!Found || Found->isCPUDispatchMultiVersion() ||
14038       Found->isCPUSpecificMultiVersion())
14039     return false;
14040 
14041   // Emitting multiple diagnostics for a function that is both inaccessible and
14042   // unavailable is consistent with our behavior elsewhere. So, always check
14043   // for both.
14044   DiagnoseUseOfDecl(Found, E->getExprLoc());
14045   CheckAddressOfMemberAccess(E, DAP);
14046   ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
14047   if (Res.isInvalid())
14048     return false;
14049   Expr *Fixed = Res.get();
14050   if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14051     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14052   else
14053     SrcExpr = Fixed;
14054   return true;
14055 }
14056 
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult,TemplateSpecCandidateSet * FailedTSC,bool ForTypeDeduction)14057 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14058     OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14059     TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14060   // C++ [over.over]p1:
14061   //   [...] [Note: any redundant set of parentheses surrounding the
14062   //   overloaded function name is ignored (5.1). ]
14063   // C++ [over.over]p1:
14064   //   [...] The overloaded function name can be preceded by the &
14065   //   operator.
14066 
14067   // If we didn't actually find any template-ids, we're done.
14068   if (!ovl->hasExplicitTemplateArgs())
14069     return nullptr;
14070 
14071   TemplateArgumentListInfo ExplicitTemplateArgs;
14072   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14073 
14074   // Look through all of the overloaded functions, searching for one
14075   // whose type matches exactly.
14076   FunctionDecl *Matched = nullptr;
14077   for (UnresolvedSetIterator I = ovl->decls_begin(),
14078          E = ovl->decls_end(); I != E; ++I) {
14079     // C++0x [temp.arg.explicit]p3:
14080     //   [...] In contexts where deduction is done and fails, or in contexts
14081     //   where deduction is not done, if a template argument list is
14082     //   specified and it, along with any default template arguments,
14083     //   identifies a single function template specialization, then the
14084     //   template-id is an lvalue for the function template specialization.
14085     FunctionTemplateDecl *FunctionTemplate =
14086         dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14087     if (!FunctionTemplate)
14088       continue;
14089 
14090     // C++ [over.over]p2:
14091     //   If the name is a function template, template argument deduction is
14092     //   done (14.8.2.2), and if the argument deduction succeeds, the
14093     //   resulting template argument list is used to generate a single
14094     //   function template specialization, which is added to the set of
14095     //   overloaded functions considered.
14096     FunctionDecl *Specialization = nullptr;
14097     TemplateDeductionInfo Info(ovl->getNameLoc());
14098     if (TemplateDeductionResult Result = DeduceTemplateArguments(
14099             FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14100             /*IsAddressOfFunction*/ true);
14101         Result != TemplateDeductionResult::Success) {
14102       // Make a note of the failed deduction for diagnostics.
14103       if (FailedTSC)
14104         FailedTSC->addCandidate().set(
14105             I.getPair(), FunctionTemplate->getTemplatedDecl(),
14106             MakeDeductionFailureInfo(Context, Result, Info));
14107       continue;
14108     }
14109 
14110     assert(Specialization && "no specialization and no error?");
14111 
14112     // C++ [temp.deduct.call]p6:
14113     //    [...] If all successful deductions yield the same deduced A, that
14114     //    deduced A is the result of deduction; otherwise, the parameter is
14115     //    treated as a non-deduced context.
14116     if (Matched) {
14117       if (ForTypeDeduction &&
14118           isSameOrCompatibleFunctionType(Matched->getType(),
14119                                          Specialization->getType()))
14120         continue;
14121       // Multiple matches; we can't resolve to a single declaration.
14122       if (Complain) {
14123         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14124           << ovl->getName();
14125         NoteAllOverloadCandidates(ovl);
14126       }
14127       return nullptr;
14128     }
14129 
14130     Matched = Specialization;
14131     if (FoundResult) *FoundResult = I.getPair();
14132   }
14133 
14134   if (Matched &&
14135       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14136     return nullptr;
14137 
14138   return Matched;
14139 }
14140 
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConversion,bool complain,SourceRange OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)14141 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14142     ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14143     SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14144     unsigned DiagIDForComplaining) {
14145   assert(SrcExpr.get()->getType() == Context.OverloadTy);
14146 
14147   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
14148 
14149   DeclAccessPair found;
14150   ExprResult SingleFunctionExpression;
14151   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14152                            ovl.Expression, /*complain*/ false, &found)) {
14153     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14154       SrcExpr = ExprError();
14155       return true;
14156     }
14157 
14158     // It is only correct to resolve to an instance method if we're
14159     // resolving a form that's permitted to be a pointer to member.
14160     // Otherwise we'll end up making a bound member expression, which
14161     // is illegal in all the contexts we resolve like this.
14162     if (!ovl.HasFormOfMemberPointer &&
14163         isa<CXXMethodDecl>(fn) &&
14164         cast<CXXMethodDecl>(fn)->isInstance()) {
14165       if (!complain) return false;
14166 
14167       Diag(ovl.Expression->getExprLoc(),
14168            diag::err_bound_member_function)
14169         << 0 << ovl.Expression->getSourceRange();
14170 
14171       // TODO: I believe we only end up here if there's a mix of
14172       // static and non-static candidates (otherwise the expression
14173       // would have 'bound member' type, not 'overload' type).
14174       // Ideally we would note which candidate was chosen and why
14175       // the static candidates were rejected.
14176       SrcExpr = ExprError();
14177       return true;
14178     }
14179 
14180     // Fix the expression to refer to 'fn'.
14181     SingleFunctionExpression =
14182         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14183 
14184     // If desired, do function-to-pointer decay.
14185     if (doFunctionPointerConversion) {
14186       SingleFunctionExpression =
14187         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14188       if (SingleFunctionExpression.isInvalid()) {
14189         SrcExpr = ExprError();
14190         return true;
14191       }
14192     }
14193   }
14194 
14195   if (!SingleFunctionExpression.isUsable()) {
14196     if (complain) {
14197       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14198         << ovl.Expression->getName()
14199         << DestTypeForComplaining
14200         << OpRangeForComplaining
14201         << ovl.Expression->getQualifierLoc().getSourceRange();
14202       NoteAllOverloadCandidates(SrcExpr.get());
14203 
14204       SrcExpr = ExprError();
14205       return true;
14206     }
14207 
14208     return false;
14209   }
14210 
14211   SrcExpr = SingleFunctionExpression;
14212   return true;
14213 }
14214 
14215 /// Add a single candidate to the overload set.
AddOverloadedCallCandidate(Sema & S,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool KnownValid)14216 static void AddOverloadedCallCandidate(Sema &S,
14217                                        DeclAccessPair FoundDecl,
14218                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
14219                                        ArrayRef<Expr *> Args,
14220                                        OverloadCandidateSet &CandidateSet,
14221                                        bool PartialOverloading,
14222                                        bool KnownValid) {
14223   NamedDecl *Callee = FoundDecl.getDecl();
14224   if (isa<UsingShadowDecl>(Callee))
14225     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14226 
14227   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14228     if (ExplicitTemplateArgs) {
14229       assert(!KnownValid && "Explicit template arguments?");
14230       return;
14231     }
14232     // Prevent ill-formed function decls to be added as overload candidates.
14233     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14234       return;
14235 
14236     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14237                            /*SuppressUserConversions=*/false,
14238                            PartialOverloading);
14239     return;
14240   }
14241 
14242   if (FunctionTemplateDecl *FuncTemplate
14243       = dyn_cast<FunctionTemplateDecl>(Callee)) {
14244     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14245                                    ExplicitTemplateArgs, Args, CandidateSet,
14246                                    /*SuppressUserConversions=*/false,
14247                                    PartialOverloading);
14248     return;
14249   }
14250 
14251   assert(!KnownValid && "unhandled case in overloaded call candidate");
14252 }
14253 
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)14254 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14255                                        ArrayRef<Expr *> Args,
14256                                        OverloadCandidateSet &CandidateSet,
14257                                        bool PartialOverloading) {
14258 
14259 #ifndef NDEBUG
14260   // Verify that ArgumentDependentLookup is consistent with the rules
14261   // in C++0x [basic.lookup.argdep]p3:
14262   //
14263   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
14264   //   and let Y be the lookup set produced by argument dependent
14265   //   lookup (defined as follows). If X contains
14266   //
14267   //     -- a declaration of a class member, or
14268   //
14269   //     -- a block-scope function declaration that is not a
14270   //        using-declaration, or
14271   //
14272   //     -- a declaration that is neither a function or a function
14273   //        template
14274   //
14275   //   then Y is empty.
14276 
14277   if (ULE->requiresADL()) {
14278     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14279            E = ULE->decls_end(); I != E; ++I) {
14280       assert(!(*I)->getDeclContext()->isRecord());
14281       assert(isa<UsingShadowDecl>(*I) ||
14282              !(*I)->getDeclContext()->isFunctionOrMethod());
14283       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14284     }
14285   }
14286 #endif
14287 
14288   // It would be nice to avoid this copy.
14289   TemplateArgumentListInfo TABuffer;
14290   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14291   if (ULE->hasExplicitTemplateArgs()) {
14292     ULE->copyTemplateArgumentsInto(TABuffer);
14293     ExplicitTemplateArgs = &TABuffer;
14294   }
14295 
14296   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14297          E = ULE->decls_end(); I != E; ++I)
14298     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14299                                CandidateSet, PartialOverloading,
14300                                /*KnownValid*/ true);
14301 
14302   if (ULE->requiresADL())
14303     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
14304                                          Args, ExplicitTemplateArgs,
14305                                          CandidateSet, PartialOverloading);
14306 }
14307 
AddOverloadedCallCandidates(LookupResult & R,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)14308 void Sema::AddOverloadedCallCandidates(
14309     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14310     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14311   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14312     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14313                                CandidateSet, false, /*KnownValid*/ false);
14314 }
14315 
14316 /// Determine whether a declaration with the specified name could be moved into
14317 /// a different namespace.
canBeDeclaredInNamespace(const DeclarationName & Name)14318 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14319   switch (Name.getCXXOverloadedOperator()) {
14320   case OO_New: case OO_Array_New:
14321   case OO_Delete: case OO_Array_Delete:
14322     return false;
14323 
14324   default:
14325     return true;
14326   }
14327 }
14328 
14329 /// Attempt to recover from an ill-formed use of a non-dependent name in a
14330 /// template, where the non-dependent name was declared after the template
14331 /// was defined. This is common in code written for a compilers which do not
14332 /// correctly implement two-stage name lookup.
14333 ///
14334 /// 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)14335 static bool DiagnoseTwoPhaseLookup(
14336     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14337     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14338     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14339     CXXRecordDecl **FoundInClass = nullptr) {
14340   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14341     return false;
14342 
14343   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14344     if (DC->isTransparentContext())
14345       continue;
14346 
14347     SemaRef.LookupQualifiedName(R, DC);
14348 
14349     if (!R.empty()) {
14350       R.suppressDiagnostics();
14351 
14352       OverloadCandidateSet Candidates(FnLoc, CSK);
14353       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14354                                           Candidates);
14355 
14356       OverloadCandidateSet::iterator Best;
14357       OverloadingResult OR =
14358           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14359 
14360       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14361         // We either found non-function declarations or a best viable function
14362         // at class scope. A class-scope lookup result disables ADL. Don't
14363         // look past this, but let the caller know that we found something that
14364         // either is, or might be, usable in this class.
14365         if (FoundInClass) {
14366           *FoundInClass = RD;
14367           if (OR == OR_Success) {
14368             R.clear();
14369             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14370             R.resolveKind();
14371           }
14372         }
14373         return false;
14374       }
14375 
14376       if (OR != OR_Success) {
14377         // There wasn't a unique best function or function template.
14378         return false;
14379       }
14380 
14381       // Find the namespaces where ADL would have looked, and suggest
14382       // declaring the function there instead.
14383       Sema::AssociatedNamespaceSet AssociatedNamespaces;
14384       Sema::AssociatedClassSet AssociatedClasses;
14385       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14386                                                  AssociatedNamespaces,
14387                                                  AssociatedClasses);
14388       Sema::AssociatedNamespaceSet SuggestedNamespaces;
14389       if (canBeDeclaredInNamespace(R.getLookupName())) {
14390         DeclContext *Std = SemaRef.getStdNamespace();
14391         for (Sema::AssociatedNamespaceSet::iterator
14392                it = AssociatedNamespaces.begin(),
14393                end = AssociatedNamespaces.end(); it != end; ++it) {
14394           // Never suggest declaring a function within namespace 'std'.
14395           if (Std && Std->Encloses(*it))
14396             continue;
14397 
14398           // Never suggest declaring a function within a namespace with a
14399           // reserved name, like __gnu_cxx.
14400           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14401           if (NS &&
14402               NS->getQualifiedNameAsString().find("__") != std::string::npos)
14403             continue;
14404 
14405           SuggestedNamespaces.insert(*it);
14406         }
14407       }
14408 
14409       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14410         << R.getLookupName();
14411       if (SuggestedNamespaces.empty()) {
14412         SemaRef.Diag(Best->Function->getLocation(),
14413                      diag::note_not_found_by_two_phase_lookup)
14414           << R.getLookupName() << 0;
14415       } else if (SuggestedNamespaces.size() == 1) {
14416         SemaRef.Diag(Best->Function->getLocation(),
14417                      diag::note_not_found_by_two_phase_lookup)
14418           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14419       } else {
14420         // FIXME: It would be useful to list the associated namespaces here,
14421         // but the diagnostics infrastructure doesn't provide a way to produce
14422         // a localized representation of a list of items.
14423         SemaRef.Diag(Best->Function->getLocation(),
14424                      diag::note_not_found_by_two_phase_lookup)
14425           << R.getLookupName() << 2;
14426       }
14427 
14428       // Try to recover by calling this function.
14429       return true;
14430     }
14431 
14432     R.clear();
14433   }
14434 
14435   return false;
14436 }
14437 
14438 /// Attempt to recover from ill-formed use of a non-dependent operator in a
14439 /// template, where the non-dependent operator was declared after the template
14440 /// was defined.
14441 ///
14442 /// Returns true if a viable candidate was found and a diagnostic was issued.
14443 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args)14444 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14445                                SourceLocation OpLoc,
14446                                ArrayRef<Expr *> Args) {
14447   DeclarationName OpName =
14448     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14449   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14450   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14451                                 OverloadCandidateSet::CSK_Operator,
14452                                 /*ExplicitTemplateArgs=*/nullptr, Args);
14453 }
14454 
14455 namespace {
14456 class BuildRecoveryCallExprRAII {
14457   Sema &SemaRef;
14458   Sema::SatisfactionStackResetRAII SatStack;
14459 
14460 public:
BuildRecoveryCallExprRAII(Sema & S)14461   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14462     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14463     SemaRef.IsBuildingRecoveryCallExpr = true;
14464   }
14465 
~BuildRecoveryCallExprRAII()14466   ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14467 };
14468 }
14469 
14470 /// Attempts to recover from a call where no functions were found.
14471 ///
14472 /// This function will do one of three things:
14473 ///  * Diagnose, recover, and return a recovery expression.
14474 ///  * Diagnose, fail to recover, and return ExprError().
14475 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
14476 ///    expected to diagnose as appropriate.
14477 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)14478 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14479                       UnresolvedLookupExpr *ULE,
14480                       SourceLocation LParenLoc,
14481                       MutableArrayRef<Expr *> Args,
14482                       SourceLocation RParenLoc,
14483                       bool EmptyLookup, bool AllowTypoCorrection) {
14484   // Do not try to recover if it is already building a recovery call.
14485   // This stops infinite loops for template instantiations like
14486   //
14487   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14488   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14489   if (SemaRef.IsBuildingRecoveryCallExpr)
14490     return ExprResult();
14491   BuildRecoveryCallExprRAII RCE(SemaRef);
14492 
14493   CXXScopeSpec SS;
14494   SS.Adopt(ULE->getQualifierLoc());
14495   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14496 
14497   TemplateArgumentListInfo TABuffer;
14498   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14499   if (ULE->hasExplicitTemplateArgs()) {
14500     ULE->copyTemplateArgumentsInto(TABuffer);
14501     ExplicitTemplateArgs = &TABuffer;
14502   }
14503 
14504   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14505                  Sema::LookupOrdinaryName);
14506   CXXRecordDecl *FoundInClass = nullptr;
14507   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14508                              OverloadCandidateSet::CSK_Normal,
14509                              ExplicitTemplateArgs, Args, &FoundInClass)) {
14510     // OK, diagnosed a two-phase lookup issue.
14511   } else if (EmptyLookup) {
14512     // Try to recover from an empty lookup with typo correction.
14513     R.clear();
14514     NoTypoCorrectionCCC NoTypoValidator{};
14515     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14516                                                 ExplicitTemplateArgs != nullptr,
14517                                                 dyn_cast<MemberExpr>(Fn));
14518     CorrectionCandidateCallback &Validator =
14519         AllowTypoCorrection
14520             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14521             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14522     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14523                                     Args))
14524       return ExprError();
14525   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14526     // We found a usable declaration of the name in a dependent base of some
14527     // enclosing class.
14528     // FIXME: We should also explain why the candidates found by name lookup
14529     // were not viable.
14530     if (SemaRef.DiagnoseDependentMemberLookup(R))
14531       return ExprError();
14532   } else {
14533     // We had viable candidates and couldn't recover; let the caller diagnose
14534     // this.
14535     return ExprResult();
14536   }
14537 
14538   // If we get here, we should have issued a diagnostic and formed a recovery
14539   // lookup result.
14540   assert(!R.empty() && "lookup results empty despite recovery");
14541 
14542   // If recovery created an ambiguity, just bail out.
14543   if (R.isAmbiguous()) {
14544     R.suppressDiagnostics();
14545     return ExprError();
14546   }
14547 
14548   // Build an implicit member call if appropriate.  Just drop the
14549   // casts and such from the call, we don't really care.
14550   ExprResult NewFn = ExprError();
14551   if ((*R.begin())->isCXXClassMember())
14552     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14553                                                     ExplicitTemplateArgs, S);
14554   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14555     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14556                                         ExplicitTemplateArgs);
14557   else
14558     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14559 
14560   if (NewFn.isInvalid())
14561     return ExprError();
14562 
14563   // This shouldn't cause an infinite loop because we're giving it
14564   // an expression with viable lookup results, which should never
14565   // end up here.
14566   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14567                                MultiExprArg(Args.data(), Args.size()),
14568                                RParenLoc);
14569 }
14570 
buildOverloadedCallSet(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,MultiExprArg Args,SourceLocation RParenLoc,OverloadCandidateSet * CandidateSet,ExprResult * Result)14571 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14572                                   UnresolvedLookupExpr *ULE,
14573                                   MultiExprArg Args,
14574                                   SourceLocation RParenLoc,
14575                                   OverloadCandidateSet *CandidateSet,
14576                                   ExprResult *Result) {
14577 #ifndef NDEBUG
14578   if (ULE->requiresADL()) {
14579     // To do ADL, we must have found an unqualified name.
14580     assert(!ULE->getQualifier() && "qualified name with ADL");
14581 
14582     // We don't perform ADL for implicit declarations of builtins.
14583     // Verify that this was correctly set up.
14584     FunctionDecl *F;
14585     if (ULE->decls_begin() != ULE->decls_end() &&
14586         ULE->decls_begin() + 1 == ULE->decls_end() &&
14587         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14588         F->getBuiltinID() && F->isImplicit())
14589       llvm_unreachable("performing ADL for builtin");
14590 
14591     // We don't perform ADL in C.
14592     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14593   }
14594 #endif
14595 
14596   UnbridgedCastsSet UnbridgedCasts;
14597   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14598     *Result = ExprError();
14599     return true;
14600   }
14601 
14602   // Add the functions denoted by the callee to the set of candidate
14603   // functions, including those from argument-dependent lookup.
14604   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14605 
14606   if (getLangOpts().MSVCCompat &&
14607       CurContext->isDependentContext() && !isSFINAEContext() &&
14608       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14609 
14610     OverloadCandidateSet::iterator Best;
14611     if (CandidateSet->empty() ||
14612         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14613             OR_No_Viable_Function) {
14614       // In Microsoft mode, if we are inside a template class member function
14615       // then create a type dependent CallExpr. The goal is to postpone name
14616       // lookup to instantiation time to be able to search into type dependent
14617       // base classes.
14618       CallExpr *CE =
14619           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14620                            RParenLoc, CurFPFeatureOverrides());
14621       CE->markDependentForPostponedNameLookup();
14622       *Result = CE;
14623       return true;
14624     }
14625   }
14626 
14627   if (CandidateSet->empty())
14628     return false;
14629 
14630   UnbridgedCasts.restore();
14631   return false;
14632 }
14633 
14634 // Guess at what the return type for an unresolvable overload should be.
chooseRecoveryType(OverloadCandidateSet & CS,OverloadCandidateSet::iterator * Best)14635 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14636                                    OverloadCandidateSet::iterator *Best) {
14637   std::optional<QualType> Result;
14638   // Adjust Type after seeing a candidate.
14639   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14640     if (!Candidate.Function)
14641       return;
14642     if (Candidate.Function->isInvalidDecl())
14643       return;
14644     QualType T = Candidate.Function->getReturnType();
14645     if (T.isNull())
14646       return;
14647     if (!Result)
14648       Result = T;
14649     else if (Result != T)
14650       Result = QualType();
14651   };
14652 
14653   // Look for an unambiguous type from a progressively larger subset.
14654   // e.g. if types disagree, but all *viable* overloads return int, choose int.
14655   //
14656   // First, consider only the best candidate.
14657   if (Best && *Best != CS.end())
14658     ConsiderCandidate(**Best);
14659   // Next, consider only viable candidates.
14660   if (!Result)
14661     for (const auto &C : CS)
14662       if (C.Viable)
14663         ConsiderCandidate(C);
14664   // Finally, consider all candidates.
14665   if (!Result)
14666     for (const auto &C : CS)
14667       ConsiderCandidate(C);
14668 
14669   if (!Result)
14670     return QualType();
14671   auto Value = *Result;
14672   if (Value.isNull() || Value->isUndeducedType())
14673     return QualType();
14674   return Value;
14675 }
14676 
14677 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14678 /// the completed call expression. If overload resolution fails, emits
14679 /// 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)14680 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14681                                            UnresolvedLookupExpr *ULE,
14682                                            SourceLocation LParenLoc,
14683                                            MultiExprArg Args,
14684                                            SourceLocation RParenLoc,
14685                                            Expr *ExecConfig,
14686                                            OverloadCandidateSet *CandidateSet,
14687                                            OverloadCandidateSet::iterator *Best,
14688                                            OverloadingResult OverloadResult,
14689                                            bool AllowTypoCorrection) {
14690   switch (OverloadResult) {
14691   case OR_Success: {
14692     FunctionDecl *FDecl = (*Best)->Function;
14693     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14694     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14695       return ExprError();
14696     ExprResult Res =
14697         SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14698     if (Res.isInvalid())
14699       return ExprError();
14700     return SemaRef.BuildResolvedCallExpr(
14701         Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14702         /*IsExecConfig=*/false,
14703         static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14704   }
14705 
14706   case OR_No_Viable_Function: {
14707     if (*Best != CandidateSet->end() &&
14708         CandidateSet->getKind() ==
14709             clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14710       if (CXXMethodDecl *M =
14711               dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14712           M && M->isImplicitObjectMemberFunction()) {
14713         CandidateSet->NoteCandidates(
14714             PartialDiagnosticAt(
14715                 Fn->getBeginLoc(),
14716                 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14717             SemaRef, OCD_AmbiguousCandidates, Args);
14718         return ExprError();
14719       }
14720     }
14721 
14722     // Try to recover by looking for viable functions which the user might
14723     // have meant to call.
14724     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14725                                                 Args, RParenLoc,
14726                                                 CandidateSet->empty(),
14727                                                 AllowTypoCorrection);
14728     if (Recovery.isInvalid() || Recovery.isUsable())
14729       return Recovery;
14730 
14731     // If the user passes in a function that we can't take the address of, we
14732     // generally end up emitting really bad error messages. Here, we attempt to
14733     // emit better ones.
14734     for (const Expr *Arg : Args) {
14735       if (!Arg->getType()->isFunctionType())
14736         continue;
14737       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14738         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14739         if (FD &&
14740             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14741                                                        Arg->getExprLoc()))
14742           return ExprError();
14743       }
14744     }
14745 
14746     CandidateSet->NoteCandidates(
14747         PartialDiagnosticAt(
14748             Fn->getBeginLoc(),
14749             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14750                 << ULE->getName() << Fn->getSourceRange()),
14751         SemaRef, OCD_AllCandidates, Args);
14752     break;
14753   }
14754 
14755   case OR_Ambiguous:
14756     CandidateSet->NoteCandidates(
14757         PartialDiagnosticAt(Fn->getBeginLoc(),
14758                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14759                                 << ULE->getName() << Fn->getSourceRange()),
14760         SemaRef, OCD_AmbiguousCandidates, Args);
14761     break;
14762 
14763   case OR_Deleted: {
14764     FunctionDecl *FDecl = (*Best)->Function;
14765     SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14766                                          Fn->getSourceRange(), ULE->getName(),
14767                                          *CandidateSet, FDecl, Args);
14768 
14769     // We emitted an error for the unavailable/deleted function call but keep
14770     // the call in the AST.
14771     ExprResult Res =
14772         SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14773     if (Res.isInvalid())
14774       return ExprError();
14775     return SemaRef.BuildResolvedCallExpr(
14776         Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14777         /*IsExecConfig=*/false,
14778         static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14779   }
14780   }
14781 
14782   // Overload resolution failed, try to recover.
14783   SmallVector<Expr *, 8> SubExprs = {Fn};
14784   SubExprs.append(Args.begin(), Args.end());
14785   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14786                                     chooseRecoveryType(*CandidateSet, Best));
14787 }
14788 
markUnaddressableCandidatesUnviable(Sema & S,OverloadCandidateSet & CS)14789 static void markUnaddressableCandidatesUnviable(Sema &S,
14790                                                 OverloadCandidateSet &CS) {
14791   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14792     if (I->Viable &&
14793         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14794       I->Viable = false;
14795       I->FailureKind = ovl_fail_addr_not_available;
14796     }
14797   }
14798 }
14799 
BuildOverloadedCallExpr(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,bool AllowTypoCorrection,bool CalleesAddressIsTaken)14800 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14801                                          UnresolvedLookupExpr *ULE,
14802                                          SourceLocation LParenLoc,
14803                                          MultiExprArg Args,
14804                                          SourceLocation RParenLoc,
14805                                          Expr *ExecConfig,
14806                                          bool AllowTypoCorrection,
14807                                          bool CalleesAddressIsTaken) {
14808 
14809   OverloadCandidateSet::CandidateSetKind CSK =
14810       CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14811                             : OverloadCandidateSet::CSK_Normal;
14812 
14813   OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14814   ExprResult result;
14815 
14816   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14817                              &result))
14818     return result;
14819 
14820   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14821   // functions that aren't addressible are considered unviable.
14822   if (CalleesAddressIsTaken)
14823     markUnaddressableCandidatesUnviable(*this, CandidateSet);
14824 
14825   OverloadCandidateSet::iterator Best;
14826   OverloadingResult OverloadResult =
14827       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14828 
14829   // [C++23][over.call.func]
14830   // if overload resolution selects a non-static member function,
14831   // the call is ill-formed;
14832   if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
14833       Best != CandidateSet.end()) {
14834     if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14835         M && M->isImplicitObjectMemberFunction()) {
14836       OverloadResult = OR_No_Viable_Function;
14837     }
14838   }
14839 
14840   // Model the case with a call to a templated function whose definition
14841   // encloses the call and whose return type contains a placeholder type as if
14842   // the UnresolvedLookupExpr was type-dependent.
14843   if (OverloadResult == OR_Success) {
14844     const FunctionDecl *FDecl = Best->Function;
14845     if (LangOpts.CUDA)
14846       CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14847     if (FDecl && FDecl->isTemplateInstantiation() &&
14848         FDecl->getReturnType()->isUndeducedType()) {
14849 
14850       // Creating dependent CallExpr is not okay if the enclosing context itself
14851       // is not dependent. This situation notably arises if a non-dependent
14852       // member function calls the later-defined overloaded static function.
14853       //
14854       // For example, in
14855       // class A {
14856       //    void c() { callee(1); }
14857       //    static auto callee(auto x) { }
14858       // };
14859       //
14860       // Here callee(1) is unresolved at the call site, but is not inside a
14861       // dependent context. There will be no further attempt to resolve this
14862       // call if it is made dependent.
14863 
14864       if (const auto *TP =
14865               FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14866           TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14867         return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14868                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14869       }
14870     }
14871   }
14872 
14873   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14874                                   ExecConfig, &CandidateSet, &Best,
14875                                   OverloadResult, AllowTypoCorrection);
14876 }
14877 
CreateUnresolvedLookupExpr(CXXRecordDecl * NamingClass,NestedNameSpecifierLoc NNSLoc,DeclarationNameInfo DNI,const UnresolvedSetImpl & Fns,bool PerformADL)14878 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14879                                             NestedNameSpecifierLoc NNSLoc,
14880                                             DeclarationNameInfo DNI,
14881                                             const UnresolvedSetImpl &Fns,
14882                                             bool PerformADL) {
14883   return UnresolvedLookupExpr::Create(
14884       Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14885       /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14886 }
14887 
BuildCXXMemberCallExpr(Expr * E,NamedDecl * FoundDecl,CXXConversionDecl * Method,bool HadMultipleCandidates)14888 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14889                                         CXXConversionDecl *Method,
14890                                         bool HadMultipleCandidates) {
14891   // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14892   // the FoundDecl as it impedes TransformMemberExpr.
14893   // We go a bit further here: if there's no difference in UnderlyingDecl,
14894   // then using FoundDecl vs Method shouldn't make a difference either.
14895   if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14896     FoundDecl = Method;
14897   // Convert the expression to match the conversion function's implicit object
14898   // parameter.
14899   ExprResult Exp;
14900   if (Method->isExplicitObjectMemberFunction())
14901     Exp = InitializeExplicitObjectArgument(*this, E, Method);
14902   else
14903     Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14904                                                       FoundDecl, Method);
14905   if (Exp.isInvalid())
14906     return true;
14907 
14908   if (Method->getParent()->isLambda() &&
14909       Method->getConversionType()->isBlockPointerType()) {
14910     // This is a lambda conversion to block pointer; check if the argument
14911     // was a LambdaExpr.
14912     Expr *SubE = E;
14913     auto *CE = dyn_cast<CastExpr>(SubE);
14914     if (CE && CE->getCastKind() == CK_NoOp)
14915       SubE = CE->getSubExpr();
14916     SubE = SubE->IgnoreParens();
14917     if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14918       SubE = BE->getSubExpr();
14919     if (isa<LambdaExpr>(SubE)) {
14920       // For the conversion to block pointer on a lambda expression, we
14921       // construct a special BlockLiteral instead; this doesn't really make
14922       // a difference in ARC, but outside of ARC the resulting block literal
14923       // follows the normal lifetime rules for block literals instead of being
14924       // autoreleased.
14925       PushExpressionEvaluationContext(
14926           ExpressionEvaluationContext::PotentiallyEvaluated);
14927       ExprResult BlockExp = BuildBlockForLambdaConversion(
14928           Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14929       PopExpressionEvaluationContext();
14930 
14931       // FIXME: This note should be produced by a CodeSynthesisContext.
14932       if (BlockExp.isInvalid())
14933         Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14934       return BlockExp;
14935     }
14936   }
14937   CallExpr *CE;
14938   QualType ResultType = Method->getReturnType();
14939   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14940   ResultType = ResultType.getNonLValueExprType(Context);
14941   if (Method->isExplicitObjectMemberFunction()) {
14942     ExprResult FnExpr =
14943         CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14944                               HadMultipleCandidates, E->getBeginLoc());
14945     if (FnExpr.isInvalid())
14946       return ExprError();
14947     Expr *ObjectParam = Exp.get();
14948     CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14949                           ResultType, VK, Exp.get()->getEndLoc(),
14950                           CurFPFeatureOverrides());
14951     CE->setUsesMemberSyntax(true);
14952   } else {
14953     MemberExpr *ME =
14954         BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14955                         NestedNameSpecifierLoc(), SourceLocation(), Method,
14956                         DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14957                         HadMultipleCandidates, DeclarationNameInfo(),
14958                         Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14959 
14960     CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14961                                    Exp.get()->getEndLoc(),
14962                                    CurFPFeatureOverrides());
14963   }
14964 
14965   if (CheckFunctionCall(Method, CE,
14966                         Method->getType()->castAs<FunctionProtoType>()))
14967     return ExprError();
14968 
14969   return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14970 }
14971 
14972 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * Input,bool PerformADL)14973 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14974                               const UnresolvedSetImpl &Fns,
14975                               Expr *Input, bool PerformADL) {
14976   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14977   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14978   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14979   // TODO: provide better source location info.
14980   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14981 
14982   if (checkPlaceholderForOverload(*this, Input))
14983     return ExprError();
14984 
14985   Expr *Args[2] = { Input, nullptr };
14986   unsigned NumArgs = 1;
14987 
14988   // For post-increment and post-decrement, add the implicit '0' as
14989   // the second argument, so that we know this is a post-increment or
14990   // post-decrement.
14991   if (Opc == UO_PostInc || Opc == UO_PostDec) {
14992     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14993     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14994                                      SourceLocation());
14995     NumArgs = 2;
14996   }
14997 
14998   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14999 
15000   if (Input->isTypeDependent()) {
15001     ExprValueKind VK = ExprValueKind::VK_PRValue;
15002     // [C++26][expr.unary.op][expr.pre.incr]
15003     // The * operator yields an lvalue of type
15004     // The pre/post increment operators yied an lvalue.
15005     if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15006       VK = VK_LValue;
15007 
15008     if (Fns.empty())
15009       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15010                                    OK_Ordinary, OpLoc, false,
15011                                    CurFPFeatureOverrides());
15012 
15013     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15014     ExprResult Fn = CreateUnresolvedLookupExpr(
15015         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15016     if (Fn.isInvalid())
15017       return ExprError();
15018     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15019                                        Context.DependentTy, VK_PRValue, OpLoc,
15020                                        CurFPFeatureOverrides());
15021   }
15022 
15023   // Build an empty overload set.
15024   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15025 
15026   // Add the candidates from the given function set.
15027   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15028 
15029   // Add operator candidates that are member functions.
15030   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15031 
15032   // Add candidates from ADL.
15033   if (PerformADL) {
15034     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15035                                          /*ExplicitTemplateArgs*/nullptr,
15036                                          CandidateSet);
15037   }
15038 
15039   // Add builtin operator candidates.
15040   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15041 
15042   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15043 
15044   // Perform overload resolution.
15045   OverloadCandidateSet::iterator Best;
15046   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15047   case OR_Success: {
15048     // We found a built-in operator or an overloaded operator.
15049     FunctionDecl *FnDecl = Best->Function;
15050 
15051     if (FnDecl) {
15052       Expr *Base = nullptr;
15053       // We matched an overloaded operator. Build a call to that
15054       // operator.
15055 
15056       // Convert the arguments.
15057       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15058         CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15059 
15060         ExprResult InputInit;
15061         if (Method->isExplicitObjectMemberFunction())
15062           InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15063         else
15064           InputInit = PerformImplicitObjectArgumentInitialization(
15065               Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15066         if (InputInit.isInvalid())
15067           return ExprError();
15068         Base = Input = InputInit.get();
15069       } else {
15070         // Convert the arguments.
15071         ExprResult InputInit
15072           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
15073                                                       Context,
15074                                                       FnDecl->getParamDecl(0)),
15075                                       SourceLocation(),
15076                                       Input);
15077         if (InputInit.isInvalid())
15078           return ExprError();
15079         Input = InputInit.get();
15080       }
15081 
15082       // Build the actual expression node.
15083       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15084                                                 Base, HadMultipleCandidates,
15085                                                 OpLoc);
15086       if (FnExpr.isInvalid())
15087         return ExprError();
15088 
15089       // Determine the result type.
15090       QualType ResultTy = FnDecl->getReturnType();
15091       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15092       ResultTy = ResultTy.getNonLValueExprType(Context);
15093 
15094       Args[0] = Input;
15095       CallExpr *TheCall = CXXOperatorCallExpr::Create(
15096           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15097           CurFPFeatureOverrides(),
15098           static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15099 
15100       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15101         return ExprError();
15102 
15103       if (CheckFunctionCall(FnDecl, TheCall,
15104                             FnDecl->getType()->castAs<FunctionProtoType>()))
15105         return ExprError();
15106       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15107     } else {
15108       // We matched a built-in operator. Convert the arguments, then
15109       // break out so that we will build the appropriate built-in
15110       // operator node.
15111       ExprResult InputRes = PerformImplicitConversion(
15112           Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15113           AssignmentAction::Passing,
15114           CheckedConversionKind::ForBuiltinOverloadedOp);
15115       if (InputRes.isInvalid())
15116         return ExprError();
15117       Input = InputRes.get();
15118       break;
15119     }
15120   }
15121 
15122   case OR_No_Viable_Function:
15123     // This is an erroneous use of an operator which can be overloaded by
15124     // a non-member function. Check for non-member operators which were
15125     // defined too late to be candidates.
15126     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15127       // FIXME: Recover by calling the found function.
15128       return ExprError();
15129 
15130     // No viable function; fall through to handling this as a
15131     // built-in operator, which will produce an error message for us.
15132     break;
15133 
15134   case OR_Ambiguous:
15135     CandidateSet.NoteCandidates(
15136         PartialDiagnosticAt(OpLoc,
15137                             PDiag(diag::err_ovl_ambiguous_oper_unary)
15138                                 << UnaryOperator::getOpcodeStr(Opc)
15139                                 << Input->getType() << Input->getSourceRange()),
15140         *this, OCD_AmbiguousCandidates, ArgsArray,
15141         UnaryOperator::getOpcodeStr(Opc), OpLoc);
15142     return ExprError();
15143 
15144   case OR_Deleted: {
15145     // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15146     // object whose method was called. Later in NoteCandidates size of ArgsArray
15147     // is passed further and it eventually ends up compared to number of
15148     // function candidate parameters which never includes the object parameter,
15149     // so slice ArgsArray to make sure apples are compared to apples.
15150     StringLiteral *Msg = Best->Function->getDeletedMessage();
15151     CandidateSet.NoteCandidates(
15152         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15153                                        << UnaryOperator::getOpcodeStr(Opc)
15154                                        << (Msg != nullptr)
15155                                        << (Msg ? Msg->getString() : StringRef())
15156                                        << Input->getSourceRange()),
15157         *this, OCD_AllCandidates, ArgsArray.drop_front(),
15158         UnaryOperator::getOpcodeStr(Opc), OpLoc);
15159     return ExprError();
15160   }
15161   }
15162 
15163   // Either we found no viable overloaded operator or we matched a
15164   // built-in operator. In either case, fall through to trying to
15165   // build a built-in operation.
15166   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15167 }
15168 
LookupOverloadedBinOp(OverloadCandidateSet & CandidateSet,OverloadedOperatorKind Op,const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,bool PerformADL)15169 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15170                                  OverloadedOperatorKind Op,
15171                                  const UnresolvedSetImpl &Fns,
15172                                  ArrayRef<Expr *> Args, bool PerformADL) {
15173   SourceLocation OpLoc = CandidateSet.getLocation();
15174 
15175   OverloadedOperatorKind ExtraOp =
15176       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15177           ? getRewrittenOverloadedOperator(Op)
15178           : OO_None;
15179 
15180   // Add the candidates from the given function set. This also adds the
15181   // rewritten candidates using these functions if necessary.
15182   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15183 
15184   // As template candidates are not deduced immediately,
15185   // persist the array in the overload set.
15186   ArrayRef<Expr *> ReversedArgs;
15187   if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15188       CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15189     ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15190 
15191   // Add operator candidates that are member functions.
15192   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15193   if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15194     AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15195                                 OverloadCandidateParamOrder::Reversed);
15196 
15197   // In C++20, also add any rewritten member candidates.
15198   if (ExtraOp) {
15199     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15200     if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15201       AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15202                                   OverloadCandidateParamOrder::Reversed);
15203   }
15204 
15205   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15206   // performed for an assignment operator (nor for operator[] nor operator->,
15207   // which don't get here).
15208   if (Op != OO_Equal && PerformADL) {
15209     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15210     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15211                                          /*ExplicitTemplateArgs*/ nullptr,
15212                                          CandidateSet);
15213     if (ExtraOp) {
15214       DeclarationName ExtraOpName =
15215           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15216       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15217                                            /*ExplicitTemplateArgs*/ nullptr,
15218                                            CandidateSet);
15219     }
15220   }
15221 
15222   // Add builtin operator candidates.
15223   //
15224   // FIXME: We don't add any rewritten candidates here. This is strictly
15225   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15226   // resulting in our selecting a rewritten builtin candidate. For example:
15227   //
15228   //   enum class E { e };
15229   //   bool operator!=(E, E) requires false;
15230   //   bool k = E::e != E::e;
15231   //
15232   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15233   // it seems unreasonable to consider rewritten builtin candidates. A core
15234   // issue has been filed proposing to removed this requirement.
15235   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15236 }
15237 
CreateOverloadedBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS,bool PerformADL,bool AllowRewrittenCandidates,FunctionDecl * DefaultedFn)15238 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15239                                        BinaryOperatorKind Opc,
15240                                        const UnresolvedSetImpl &Fns, Expr *LHS,
15241                                        Expr *RHS, bool PerformADL,
15242                                        bool AllowRewrittenCandidates,
15243                                        FunctionDecl *DefaultedFn) {
15244   Expr *Args[2] = { LHS, RHS };
15245   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15246 
15247   if (!getLangOpts().CPlusPlus20)
15248     AllowRewrittenCandidates = false;
15249 
15250   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15251 
15252   // If either side is type-dependent, create an appropriate dependent
15253   // expression.
15254   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15255     if (Fns.empty()) {
15256       // If there are no functions to store, just build a dependent
15257       // BinaryOperator or CompoundAssignment.
15258       if (BinaryOperator::isCompoundAssignmentOp(Opc))
15259         return CompoundAssignOperator::Create(
15260             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15261             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15262             Context.DependentTy);
15263       return BinaryOperator::Create(
15264           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15265           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
15266     }
15267 
15268     // FIXME: save results of ADL from here?
15269     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15270     // TODO: provide better source location info in DNLoc component.
15271     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15272     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15273     ExprResult Fn = CreateUnresolvedLookupExpr(
15274         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15275     if (Fn.isInvalid())
15276       return ExprError();
15277     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15278                                        Context.DependentTy, VK_PRValue, OpLoc,
15279                                        CurFPFeatureOverrides());
15280   }
15281 
15282   // If this is the .* operator, which is not overloadable, just
15283   // create a built-in binary operator.
15284   if (Opc == BO_PtrMemD) {
15285     auto CheckPlaceholder = [&](Expr *&Arg) {
15286       ExprResult Res = CheckPlaceholderExpr(Arg);
15287       if (Res.isUsable())
15288         Arg = Res.get();
15289       return !Res.isUsable();
15290     };
15291 
15292     // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15293     // expression that contains placeholders (in either the LHS or RHS).
15294     if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15295       return ExprError();
15296     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15297   }
15298 
15299   // Always do placeholder-like conversions on the RHS.
15300   if (checkPlaceholderForOverload(*this, Args[1]))
15301     return ExprError();
15302 
15303   // Do placeholder-like conversion on the LHS; note that we should
15304   // not get here with a PseudoObject LHS.
15305   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15306   if (checkPlaceholderForOverload(*this, Args[0]))
15307     return ExprError();
15308 
15309   // If this is the assignment operator, we only perform overload resolution
15310   // if the left-hand side is a class or enumeration type. This is actually
15311   // a hack. The standard requires that we do overload resolution between the
15312   // various built-in candidates, but as DR507 points out, this can lead to
15313   // problems. So we do it this way, which pretty much follows what GCC does.
15314   // Note that we go the traditional code path for compound assignment forms.
15315   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15316     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15317 
15318   // Build the overload set.
15319   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15320                                     OverloadCandidateSet::OperatorRewriteInfo(
15321                                         Op, OpLoc, AllowRewrittenCandidates));
15322   if (DefaultedFn)
15323     CandidateSet.exclude(DefaultedFn);
15324   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15325 
15326   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15327 
15328   // Perform overload resolution.
15329   OverloadCandidateSet::iterator Best;
15330   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15331     case OR_Success: {
15332       // We found a built-in operator or an overloaded operator.
15333       FunctionDecl *FnDecl = Best->Function;
15334 
15335       bool IsReversed = Best->isReversed();
15336       if (IsReversed)
15337         std::swap(Args[0], Args[1]);
15338 
15339       if (FnDecl) {
15340 
15341         if (FnDecl->isInvalidDecl())
15342           return ExprError();
15343 
15344         Expr *Base = nullptr;
15345         // We matched an overloaded operator. Build a call to that
15346         // operator.
15347 
15348         OverloadedOperatorKind ChosenOp =
15349             FnDecl->getDeclName().getCXXOverloadedOperator();
15350 
15351         // C++2a [over.match.oper]p9:
15352         //   If a rewritten operator== candidate is selected by overload
15353         //   resolution for an operator@, its return type shall be cv bool
15354         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15355             !FnDecl->getReturnType()->isBooleanType()) {
15356           bool IsExtension =
15357               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15358           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15359                                   : diag::err_ovl_rewrite_equalequal_not_bool)
15360               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15361               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15362           Diag(FnDecl->getLocation(), diag::note_declared_at);
15363           if (!IsExtension)
15364             return ExprError();
15365         }
15366 
15367         if (AllowRewrittenCandidates && !IsReversed &&
15368             CandidateSet.getRewriteInfo().isReversible()) {
15369           // We could have reversed this operator, but didn't. Check if some
15370           // reversed form was a viable candidate, and if so, if it had a
15371           // better conversion for either parameter. If so, this call is
15372           // formally ambiguous, and allowing it is an extension.
15373           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15374           for (OverloadCandidate &Cand : CandidateSet) {
15375             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15376                 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15377               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15378                 if (CompareImplicitConversionSequences(
15379                         *this, OpLoc, Cand.Conversions[ArgIdx],
15380                         Best->Conversions[ArgIdx]) ==
15381                     ImplicitConversionSequence::Better) {
15382                   AmbiguousWith.push_back(Cand.Function);
15383                   break;
15384                 }
15385               }
15386             }
15387           }
15388 
15389           if (!AmbiguousWith.empty()) {
15390             bool AmbiguousWithSelf =
15391                 AmbiguousWith.size() == 1 &&
15392                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15393             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15394                 << BinaryOperator::getOpcodeStr(Opc)
15395                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15396                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15397             if (AmbiguousWithSelf) {
15398               Diag(FnDecl->getLocation(),
15399                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
15400               // Mark member== const or provide matching != to disallow reversed
15401               // args. Eg.
15402               // struct S { bool operator==(const S&); };
15403               // S()==S();
15404               if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15405                 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15406                     !MD->isConst() &&
15407                     !MD->hasCXXExplicitFunctionObjectParameter() &&
15408                     Context.hasSameUnqualifiedType(
15409                         MD->getFunctionObjectParameterType(),
15410                         MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15411                     Context.hasSameUnqualifiedType(
15412                         MD->getFunctionObjectParameterType(),
15413                         Args[0]->getType()) &&
15414                     Context.hasSameUnqualifiedType(
15415                         MD->getFunctionObjectParameterType(),
15416                         Args[1]->getType()))
15417                   Diag(FnDecl->getLocation(),
15418                        diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15419             } else {
15420               Diag(FnDecl->getLocation(),
15421                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15422               for (auto *F : AmbiguousWith)
15423                 Diag(F->getLocation(),
15424                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15425             }
15426           }
15427         }
15428 
15429         // Check for nonnull = nullable.
15430         // This won't be caught in the arg's initialization: the parameter to
15431         // the assignment operator is not marked nonnull.
15432         if (Op == OO_Equal)
15433           diagnoseNullableToNonnullConversion(Args[0]->getType(),
15434                                               Args[1]->getType(), OpLoc);
15435 
15436         // Convert the arguments.
15437         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15438           // Best->Access is only meaningful for class members.
15439           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15440 
15441           ExprResult Arg0, Arg1;
15442           unsigned ParamIdx = 0;
15443           if (Method->isExplicitObjectMemberFunction()) {
15444             Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15445             ParamIdx = 1;
15446           } else {
15447             Arg0 = PerformImplicitObjectArgumentInitialization(
15448                 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15449           }
15450           Arg1 = PerformCopyInitialization(
15451               InitializedEntity::InitializeParameter(
15452                   Context, FnDecl->getParamDecl(ParamIdx)),
15453               SourceLocation(), Args[1]);
15454           if (Arg0.isInvalid() || Arg1.isInvalid())
15455             return ExprError();
15456 
15457           Base = Args[0] = Arg0.getAs<Expr>();
15458           Args[1] = RHS = Arg1.getAs<Expr>();
15459         } else {
15460           // Convert the arguments.
15461           ExprResult Arg0 = PerformCopyInitialization(
15462             InitializedEntity::InitializeParameter(Context,
15463                                                    FnDecl->getParamDecl(0)),
15464             SourceLocation(), Args[0]);
15465           if (Arg0.isInvalid())
15466             return ExprError();
15467 
15468           ExprResult Arg1 =
15469             PerformCopyInitialization(
15470               InitializedEntity::InitializeParameter(Context,
15471                                                      FnDecl->getParamDecl(1)),
15472               SourceLocation(), Args[1]);
15473           if (Arg1.isInvalid())
15474             return ExprError();
15475           Args[0] = LHS = Arg0.getAs<Expr>();
15476           Args[1] = RHS = Arg1.getAs<Expr>();
15477         }
15478 
15479         // Build the actual expression node.
15480         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15481                                                   Best->FoundDecl, Base,
15482                                                   HadMultipleCandidates, OpLoc);
15483         if (FnExpr.isInvalid())
15484           return ExprError();
15485 
15486         // Determine the result type.
15487         QualType ResultTy = FnDecl->getReturnType();
15488         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15489         ResultTy = ResultTy.getNonLValueExprType(Context);
15490 
15491         CallExpr *TheCall;
15492         ArrayRef<const Expr *> ArgsArray(Args, 2);
15493         const Expr *ImplicitThis = nullptr;
15494 
15495         // We always create a CXXOperatorCallExpr, even for explicit object
15496         // members; CodeGen should take care not to emit the this pointer.
15497         TheCall = CXXOperatorCallExpr::Create(
15498             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15499             CurFPFeatureOverrides(),
15500             static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15501 
15502         if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15503             Method && Method->isImplicitObjectMemberFunction()) {
15504           // Cut off the implicit 'this'.
15505           ImplicitThis = ArgsArray[0];
15506           ArgsArray = ArgsArray.slice(1);
15507         }
15508 
15509         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15510                                 FnDecl))
15511           return ExprError();
15512 
15513         if (Op == OO_Equal) {
15514           // Check for a self move.
15515           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15516           // lifetime check.
15517           checkAssignmentLifetime(
15518               *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15519               Args[1]);
15520         }
15521         if (ImplicitThis) {
15522           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15523           QualType ThisTypeFromDecl = Context.getPointerType(
15524               cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15525 
15526           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15527                             ThisTypeFromDecl);
15528         }
15529 
15530         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15531                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15532                   VariadicCallType::DoesNotApply);
15533 
15534         ExprResult R = MaybeBindToTemporary(TheCall);
15535         if (R.isInvalid())
15536           return ExprError();
15537 
15538         R = CheckForImmediateInvocation(R, FnDecl);
15539         if (R.isInvalid())
15540           return ExprError();
15541 
15542         // For a rewritten candidate, we've already reversed the arguments
15543         // if needed. Perform the rest of the rewrite now.
15544         if ((Best->RewriteKind & CRK_DifferentOperator) ||
15545             (Op == OO_Spaceship && IsReversed)) {
15546           if (Op == OO_ExclaimEqual) {
15547             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15548             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15549           } else {
15550             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15551             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15552             Expr *ZeroLiteral =
15553                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
15554 
15555             Sema::CodeSynthesisContext Ctx;
15556             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15557             Ctx.Entity = FnDecl;
15558             pushCodeSynthesisContext(Ctx);
15559 
15560             R = CreateOverloadedBinOp(
15561                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15562                 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15563                 /*AllowRewrittenCandidates=*/false);
15564 
15565             popCodeSynthesisContext();
15566           }
15567           if (R.isInvalid())
15568             return ExprError();
15569         } else {
15570           assert(ChosenOp == Op && "unexpected operator name");
15571         }
15572 
15573         // Make a note in the AST if we did any rewriting.
15574         if (Best->RewriteKind != CRK_None)
15575           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15576 
15577         return R;
15578       } else {
15579         // We matched a built-in operator. Convert the arguments, then
15580         // break out so that we will build the appropriate built-in
15581         // operator node.
15582         ExprResult ArgsRes0 = PerformImplicitConversion(
15583             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15584             AssignmentAction::Passing,
15585             CheckedConversionKind::ForBuiltinOverloadedOp);
15586         if (ArgsRes0.isInvalid())
15587           return ExprError();
15588         Args[0] = ArgsRes0.get();
15589 
15590         ExprResult ArgsRes1 = PerformImplicitConversion(
15591             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15592             AssignmentAction::Passing,
15593             CheckedConversionKind::ForBuiltinOverloadedOp);
15594         if (ArgsRes1.isInvalid())
15595           return ExprError();
15596         Args[1] = ArgsRes1.get();
15597         break;
15598       }
15599     }
15600 
15601     case OR_No_Viable_Function: {
15602       // C++ [over.match.oper]p9:
15603       //   If the operator is the operator , [...] and there are no
15604       //   viable functions, then the operator is assumed to be the
15605       //   built-in operator and interpreted according to clause 5.
15606       if (Opc == BO_Comma)
15607         break;
15608 
15609       // When defaulting an 'operator<=>', we can try to synthesize a three-way
15610       // compare result using '==' and '<'.
15611       if (DefaultedFn && Opc == BO_Cmp) {
15612         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15613                                                           Args[1], DefaultedFn);
15614         if (E.isInvalid() || E.isUsable())
15615           return E;
15616       }
15617 
15618       // For class as left operand for assignment or compound assignment
15619       // operator do not fall through to handling in built-in, but report that
15620       // no overloaded assignment operator found
15621       ExprResult Result = ExprError();
15622       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15623       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15624                                                    Args, OpLoc);
15625       DeferDiagsRAII DDR(*this,
15626                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15627       if (Args[0]->getType()->isRecordType() &&
15628           Opc >= BO_Assign && Opc <= BO_OrAssign) {
15629         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
15630              << BinaryOperator::getOpcodeStr(Opc)
15631              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15632         if (Args[0]->getType()->isIncompleteType()) {
15633           Diag(OpLoc, diag::note_assign_lhs_incomplete)
15634             << Args[0]->getType()
15635             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15636         }
15637       } else {
15638         // This is an erroneous use of an operator which can be overloaded by
15639         // a non-member function. Check for non-member operators which were
15640         // defined too late to be candidates.
15641         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15642           // FIXME: Recover by calling the found function.
15643           return ExprError();
15644 
15645         // No viable function; try to create a built-in operation, which will
15646         // produce an error. Then, show the non-viable candidates.
15647         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15648       }
15649       assert(Result.isInvalid() &&
15650              "C++ binary operator overloading is missing candidates!");
15651       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15652       return Result;
15653     }
15654 
15655     case OR_Ambiguous:
15656       CandidateSet.NoteCandidates(
15657           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15658                                          << BinaryOperator::getOpcodeStr(Opc)
15659                                          << Args[0]->getType()
15660                                          << Args[1]->getType()
15661                                          << Args[0]->getSourceRange()
15662                                          << Args[1]->getSourceRange()),
15663           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15664           OpLoc);
15665       return ExprError();
15666 
15667     case OR_Deleted: {
15668       if (isImplicitlyDeleted(Best->Function)) {
15669         FunctionDecl *DeletedFD = Best->Function;
15670         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15671         if (DFK.isSpecialMember()) {
15672           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15673               << Args[0]->getType() << DFK.asSpecialMember();
15674         } else {
15675           assert(DFK.isComparison());
15676           Diag(OpLoc, diag::err_ovl_deleted_comparison)
15677             << Args[0]->getType() << DeletedFD;
15678         }
15679 
15680         // The user probably meant to call this special member. Just
15681         // explain why it's deleted.
15682         NoteDeletedFunction(DeletedFD);
15683         return ExprError();
15684       }
15685 
15686       StringLiteral *Msg = Best->Function->getDeletedMessage();
15687       CandidateSet.NoteCandidates(
15688           PartialDiagnosticAt(
15689               OpLoc,
15690               PDiag(diag::err_ovl_deleted_oper)
15691                   << getOperatorSpelling(Best->Function->getDeclName()
15692                                              .getCXXOverloadedOperator())
15693                   << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15694                   << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15695           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15696           OpLoc);
15697       return ExprError();
15698     }
15699   }
15700 
15701   // We matched a built-in operator; build it.
15702   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15703 }
15704 
BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS,FunctionDecl * DefaultedFn)15705 ExprResult Sema::BuildSynthesizedThreeWayComparison(
15706     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15707     FunctionDecl *DefaultedFn) {
15708   const ComparisonCategoryInfo *Info =
15709       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15710   // If we're not producing a known comparison category type, we can't
15711   // synthesize a three-way comparison. Let the caller diagnose this.
15712   if (!Info)
15713     return ExprResult((Expr*)nullptr);
15714 
15715   // If we ever want to perform this synthesis more generally, we will need to
15716   // apply the temporary materialization conversion to the operands.
15717   assert(LHS->isGLValue() && RHS->isGLValue() &&
15718          "cannot use prvalue expressions more than once");
15719   Expr *OrigLHS = LHS;
15720   Expr *OrigRHS = RHS;
15721 
15722   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15723   // each of them multiple times below.
15724   LHS = new (Context)
15725       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15726                       LHS->getObjectKind(), LHS);
15727   RHS = new (Context)
15728       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15729                       RHS->getObjectKind(), RHS);
15730 
15731   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15732                                         DefaultedFn);
15733   if (Eq.isInvalid())
15734     return ExprError();
15735 
15736   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15737                                           true, DefaultedFn);
15738   if (Less.isInvalid())
15739     return ExprError();
15740 
15741   ExprResult Greater;
15742   if (Info->isPartial()) {
15743     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15744                                     DefaultedFn);
15745     if (Greater.isInvalid())
15746       return ExprError();
15747   }
15748 
15749   // Form the list of comparisons we're going to perform.
15750   struct Comparison {
15751     ExprResult Cmp;
15752     ComparisonCategoryResult Result;
15753   } Comparisons[4] =
15754   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
15755                           : ComparisonCategoryResult::Equivalent},
15756     {Less, ComparisonCategoryResult::Less},
15757     {Greater, ComparisonCategoryResult::Greater},
15758     {ExprResult(), ComparisonCategoryResult::Unordered},
15759   };
15760 
15761   int I = Info->isPartial() ? 3 : 2;
15762 
15763   // Combine the comparisons with suitable conditional expressions.
15764   ExprResult Result;
15765   for (; I >= 0; --I) {
15766     // Build a reference to the comparison category constant.
15767     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15768     // FIXME: Missing a constant for a comparison category. Diagnose this?
15769     if (!VI)
15770       return ExprResult((Expr*)nullptr);
15771     ExprResult ThisResult =
15772         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15773     if (ThisResult.isInvalid())
15774       return ExprError();
15775 
15776     // Build a conditional unless this is the final case.
15777     if (Result.get()) {
15778       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15779                                   ThisResult.get(), Result.get());
15780       if (Result.isInvalid())
15781         return ExprError();
15782     } else {
15783       Result = ThisResult;
15784     }
15785   }
15786 
15787   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15788   // bind the OpaqueValueExprs before they're (repeatedly) used.
15789   Expr *SyntacticForm = BinaryOperator::Create(
15790       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15791       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15792       CurFPFeatureOverrides());
15793   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15794   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15795 }
15796 
PrepareArgumentsForCallToObjectOfClassType(Sema & S,SmallVectorImpl<Expr * > & MethodArgs,CXXMethodDecl * Method,MultiExprArg Args,SourceLocation LParenLoc)15797 static bool PrepareArgumentsForCallToObjectOfClassType(
15798     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15799     MultiExprArg Args, SourceLocation LParenLoc) {
15800 
15801   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15802   unsigned NumParams = Proto->getNumParams();
15803   unsigned NumArgsSlots =
15804       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15805   // Build the full argument list for the method call (the implicit object
15806   // parameter is placed at the beginning of the list).
15807   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15808   bool IsError = false;
15809   // Initialize the implicit object parameter.
15810   // Check the argument types.
15811   for (unsigned i = 0; i != NumParams; i++) {
15812     Expr *Arg;
15813     if (i < Args.size()) {
15814       Arg = Args[i];
15815       ExprResult InputInit =
15816           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
15817                                           S.Context, Method->getParamDecl(i)),
15818                                       SourceLocation(), Arg);
15819       IsError |= InputInit.isInvalid();
15820       Arg = InputInit.getAs<Expr>();
15821     } else {
15822       ExprResult DefArg =
15823           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15824       if (DefArg.isInvalid()) {
15825         IsError = true;
15826         break;
15827       }
15828       Arg = DefArg.getAs<Expr>();
15829     }
15830 
15831     MethodArgs.push_back(Arg);
15832   }
15833   return IsError;
15834 }
15835 
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,MultiExprArg ArgExpr)15836 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15837                                                     SourceLocation RLoc,
15838                                                     Expr *Base,
15839                                                     MultiExprArg ArgExpr) {
15840   SmallVector<Expr *, 2> Args;
15841   Args.push_back(Base);
15842   for (auto *e : ArgExpr) {
15843     Args.push_back(e);
15844   }
15845   DeclarationName OpName =
15846       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15847 
15848   SourceRange Range = ArgExpr.empty()
15849                           ? SourceRange{}
15850                           : SourceRange(ArgExpr.front()->getBeginLoc(),
15851                                         ArgExpr.back()->getEndLoc());
15852 
15853   // If either side is type-dependent, create an appropriate dependent
15854   // expression.
15855   if (Expr::hasAnyTypeDependentArguments(Args)) {
15856 
15857     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15858     // CHECKME: no 'operator' keyword?
15859     DeclarationNameInfo OpNameInfo(OpName, LLoc);
15860     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15861     ExprResult Fn = CreateUnresolvedLookupExpr(
15862         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15863     if (Fn.isInvalid())
15864       return ExprError();
15865     // Can't add any actual overloads yet
15866 
15867     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15868                                        Context.DependentTy, VK_PRValue, RLoc,
15869                                        CurFPFeatureOverrides());
15870   }
15871 
15872   // Handle placeholders
15873   UnbridgedCastsSet UnbridgedCasts;
15874   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15875     return ExprError();
15876   }
15877   // Build an empty overload set.
15878   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15879 
15880   // Subscript can only be overloaded as a member function.
15881 
15882   // Add operator candidates that are member functions.
15883   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15884 
15885   // Add builtin operator candidates.
15886   if (Args.size() == 2)
15887     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15888 
15889   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15890 
15891   // Perform overload resolution.
15892   OverloadCandidateSet::iterator Best;
15893   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15894     case OR_Success: {
15895       // We found a built-in operator or an overloaded operator.
15896       FunctionDecl *FnDecl = Best->Function;
15897 
15898       if (FnDecl) {
15899         // We matched an overloaded operator. Build a call to that
15900         // operator.
15901 
15902         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15903 
15904         // Convert the arguments.
15905         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15906         SmallVector<Expr *, 2> MethodArgs;
15907 
15908         // Initialize the object parameter.
15909         if (Method->isExplicitObjectMemberFunction()) {
15910           ExprResult Res =
15911               InitializeExplicitObjectArgument(*this, Args[0], Method);
15912           if (Res.isInvalid())
15913             return ExprError();
15914           Args[0] = Res.get();
15915           ArgExpr = Args;
15916         } else {
15917           ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15918               Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15919           if (Arg0.isInvalid())
15920             return ExprError();
15921 
15922           MethodArgs.push_back(Arg0.get());
15923         }
15924 
15925         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15926             *this, MethodArgs, Method, ArgExpr, LLoc);
15927         if (IsError)
15928           return ExprError();
15929 
15930         // Build the actual expression node.
15931         DeclarationNameInfo OpLocInfo(OpName, LLoc);
15932         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15933         ExprResult FnExpr = CreateFunctionRefExpr(
15934             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15935             OpLocInfo.getLoc(), OpLocInfo.getInfo());
15936         if (FnExpr.isInvalid())
15937           return ExprError();
15938 
15939         // Determine the result type
15940         QualType ResultTy = FnDecl->getReturnType();
15941         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15942         ResultTy = ResultTy.getNonLValueExprType(Context);
15943 
15944         CallExpr *TheCall = CXXOperatorCallExpr::Create(
15945             Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15946             CurFPFeatureOverrides());
15947 
15948         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15949           return ExprError();
15950 
15951         if (CheckFunctionCall(Method, TheCall,
15952                               Method->getType()->castAs<FunctionProtoType>()))
15953           return ExprError();
15954 
15955         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15956                                            FnDecl);
15957       } else {
15958         // We matched a built-in operator. Convert the arguments, then
15959         // break out so that we will build the appropriate built-in
15960         // operator node.
15961         ExprResult ArgsRes0 = PerformImplicitConversion(
15962             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15963             AssignmentAction::Passing,
15964             CheckedConversionKind::ForBuiltinOverloadedOp);
15965         if (ArgsRes0.isInvalid())
15966           return ExprError();
15967         Args[0] = ArgsRes0.get();
15968 
15969         ExprResult ArgsRes1 = PerformImplicitConversion(
15970             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15971             AssignmentAction::Passing,
15972             CheckedConversionKind::ForBuiltinOverloadedOp);
15973         if (ArgsRes1.isInvalid())
15974           return ExprError();
15975         Args[1] = ArgsRes1.get();
15976 
15977         break;
15978       }
15979     }
15980 
15981     case OR_No_Viable_Function: {
15982       PartialDiagnostic PD =
15983           CandidateSet.empty()
15984               ? (PDiag(diag::err_ovl_no_oper)
15985                  << Args[0]->getType() << /*subscript*/ 0
15986                  << Args[0]->getSourceRange() << Range)
15987               : (PDiag(diag::err_ovl_no_viable_subscript)
15988                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15989       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15990                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
15991       return ExprError();
15992     }
15993 
15994     case OR_Ambiguous:
15995       if (Args.size() == 2) {
15996         CandidateSet.NoteCandidates(
15997             PartialDiagnosticAt(
15998                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15999                           << "[]" << Args[0]->getType() << Args[1]->getType()
16000                           << Args[0]->getSourceRange() << Range),
16001             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16002       } else {
16003         CandidateSet.NoteCandidates(
16004             PartialDiagnosticAt(LLoc,
16005                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
16006                                     << Args[0]->getType()
16007                                     << Args[0]->getSourceRange() << Range),
16008             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16009       }
16010       return ExprError();
16011 
16012     case OR_Deleted: {
16013       StringLiteral *Msg = Best->Function->getDeletedMessage();
16014       CandidateSet.NoteCandidates(
16015           PartialDiagnosticAt(LLoc,
16016                               PDiag(diag::err_ovl_deleted_oper)
16017                                   << "[]" << (Msg != nullptr)
16018                                   << (Msg ? Msg->getString() : StringRef())
16019                                   << Args[0]->getSourceRange() << Range),
16020           *this, OCD_AllCandidates, Args, "[]", LLoc);
16021       return ExprError();
16022     }
16023     }
16024 
16025   // We matched a built-in operator; build it.
16026   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16027 }
16028 
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig,bool AllowRecovery)16029 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16030                                            SourceLocation LParenLoc,
16031                                            MultiExprArg Args,
16032                                            SourceLocation RParenLoc,
16033                                            Expr *ExecConfig, bool IsExecConfig,
16034                                            bool AllowRecovery) {
16035   assert(MemExprE->getType() == Context.BoundMemberTy ||
16036          MemExprE->getType() == Context.OverloadTy);
16037 
16038   // Dig out the member expression. This holds both the object
16039   // argument and the member function we're referring to.
16040   Expr *NakedMemExpr = MemExprE->IgnoreParens();
16041 
16042   // Determine whether this is a call to a pointer-to-member function.
16043   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16044     assert(op->getType() == Context.BoundMemberTy);
16045     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16046 
16047     QualType fnType =
16048       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16049 
16050     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16051     QualType resultType = proto->getCallResultType(Context);
16052     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
16053 
16054     // Check that the object type isn't more qualified than the
16055     // member function we're calling.
16056     Qualifiers funcQuals = proto->getMethodQuals();
16057 
16058     QualType objectType = op->getLHS()->getType();
16059     if (op->getOpcode() == BO_PtrMemI)
16060       objectType = objectType->castAs<PointerType>()->getPointeeType();
16061     Qualifiers objectQuals = objectType.getQualifiers();
16062 
16063     Qualifiers difference = objectQuals - funcQuals;
16064     difference.removeObjCGCAttr();
16065     difference.removeAddressSpace();
16066     if (difference) {
16067       std::string qualsString = difference.getAsString();
16068       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16069         << fnType.getUnqualifiedType()
16070         << qualsString
16071         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16072     }
16073 
16074     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16075         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16076         CurFPFeatureOverrides(), proto->getNumParams());
16077 
16078     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16079                             call, nullptr))
16080       return ExprError();
16081 
16082     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16083       return ExprError();
16084 
16085     if (CheckOtherCall(call, proto))
16086       return ExprError();
16087 
16088     return MaybeBindToTemporary(call);
16089   }
16090 
16091   // We only try to build a recovery expr at this level if we can preserve
16092   // the return type, otherwise we return ExprError() and let the caller
16093   // recover.
16094   auto BuildRecoveryExpr = [&](QualType Type) {
16095     if (!AllowRecovery)
16096       return ExprError();
16097     std::vector<Expr *> SubExprs = {MemExprE};
16098     llvm::append_range(SubExprs, Args);
16099     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16100                               Type);
16101   };
16102   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16103     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16104                             RParenLoc, CurFPFeatureOverrides());
16105 
16106   UnbridgedCastsSet UnbridgedCasts;
16107   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16108     return ExprError();
16109 
16110   MemberExpr *MemExpr;
16111   CXXMethodDecl *Method = nullptr;
16112   bool HadMultipleCandidates = false;
16113   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16114   NestedNameSpecifier *Qualifier = nullptr;
16115   if (isa<MemberExpr>(NakedMemExpr)) {
16116     MemExpr = cast<MemberExpr>(NakedMemExpr);
16117     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
16118     FoundDecl = MemExpr->getFoundDecl();
16119     Qualifier = MemExpr->getQualifier();
16120     UnbridgedCasts.restore();
16121   } else {
16122     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16123     Qualifier = UnresExpr->getQualifier();
16124 
16125     QualType ObjectType = UnresExpr->getBaseType();
16126     Expr::Classification ObjectClassification
16127       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16128                             : UnresExpr->getBase()->Classify(Context);
16129 
16130     // Add overload candidates
16131     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16132                                       OverloadCandidateSet::CSK_Normal);
16133 
16134     // FIXME: avoid copy.
16135     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16136     if (UnresExpr->hasExplicitTemplateArgs()) {
16137       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16138       TemplateArgs = &TemplateArgsBuffer;
16139     }
16140 
16141     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16142            E = UnresExpr->decls_end(); I != E; ++I) {
16143 
16144       QualType ExplicitObjectType = ObjectType;
16145 
16146       NamedDecl *Func = *I;
16147       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16148       if (isa<UsingShadowDecl>(Func))
16149         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16150 
16151       bool HasExplicitParameter = false;
16152       if (const auto *M = dyn_cast<FunctionDecl>(Func);
16153           M && M->hasCXXExplicitFunctionObjectParameter())
16154         HasExplicitParameter = true;
16155       else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16156                M &&
16157                M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16158         HasExplicitParameter = true;
16159 
16160       if (HasExplicitParameter)
16161         ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16162 
16163       // Microsoft supports direct constructor calls.
16164       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16165         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
16166                              CandidateSet,
16167                              /*SuppressUserConversions*/ false);
16168       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16169         // If explicit template arguments were provided, we can't call a
16170         // non-template member function.
16171         if (TemplateArgs)
16172           continue;
16173 
16174         AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16175                            ObjectClassification, Args, CandidateSet,
16176                            /*SuppressUserConversions=*/false);
16177       } else {
16178         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
16179                                    I.getPair(), ActingDC, TemplateArgs,
16180                                    ExplicitObjectType, ObjectClassification,
16181                                    Args, CandidateSet,
16182                                    /*SuppressUserConversions=*/false);
16183       }
16184     }
16185 
16186     HadMultipleCandidates = (CandidateSet.size() > 1);
16187 
16188     DeclarationName DeclName = UnresExpr->getMemberName();
16189 
16190     UnbridgedCasts.restore();
16191 
16192     OverloadCandidateSet::iterator Best;
16193     bool Succeeded = false;
16194     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16195                                             Best)) {
16196     case OR_Success:
16197       Method = cast<CXXMethodDecl>(Best->Function);
16198       FoundDecl = Best->FoundDecl;
16199       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16200       if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16201         break;
16202       // If FoundDecl is different from Method (such as if one is a template
16203       // and the other a specialization), make sure DiagnoseUseOfDecl is
16204       // called on both.
16205       // FIXME: This would be more comprehensively addressed by modifying
16206       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16207       // being used.
16208       if (Method != FoundDecl.getDecl() &&
16209           DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
16210         break;
16211       Succeeded = true;
16212       break;
16213 
16214     case OR_No_Viable_Function:
16215       CandidateSet.NoteCandidates(
16216           PartialDiagnosticAt(
16217               UnresExpr->getMemberLoc(),
16218               PDiag(diag::err_ovl_no_viable_member_function_in_call)
16219                   << DeclName << MemExprE->getSourceRange()),
16220           *this, OCD_AllCandidates, Args);
16221       break;
16222     case OR_Ambiguous:
16223       CandidateSet.NoteCandidates(
16224           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16225                               PDiag(diag::err_ovl_ambiguous_member_call)
16226                                   << DeclName << MemExprE->getSourceRange()),
16227           *this, OCD_AmbiguousCandidates, Args);
16228       break;
16229     case OR_Deleted:
16230       DiagnoseUseOfDeletedFunction(
16231           UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16232           CandidateSet, Best->Function, Args, /*IsMember=*/true);
16233       break;
16234     }
16235     // Overload resolution fails, try to recover.
16236     if (!Succeeded)
16237       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16238 
16239     ExprResult Res =
16240         FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16241     if (Res.isInvalid())
16242       return ExprError();
16243     MemExprE = Res.get();
16244 
16245     // If overload resolution picked a static member
16246     // build a non-member call based on that function.
16247     if (Method->isStatic()) {
16248       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16249                                    ExecConfig, IsExecConfig);
16250     }
16251 
16252     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16253   }
16254 
16255   QualType ResultType = Method->getReturnType();
16256   ExprValueKind VK = Expr::getValueKindForType(ResultType);
16257   ResultType = ResultType.getNonLValueExprType(Context);
16258 
16259   assert(Method && "Member call to something that isn't a method?");
16260   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16261 
16262   CallExpr *TheCall = nullptr;
16263   llvm::SmallVector<Expr *, 8> NewArgs;
16264   if (Method->isExplicitObjectMemberFunction()) {
16265     if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16266                                       NewArgs))
16267       return ExprError();
16268 
16269     // Build the actual expression node.
16270     ExprResult FnExpr =
16271         CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16272                               HadMultipleCandidates, MemExpr->getExprLoc());
16273     if (FnExpr.isInvalid())
16274       return ExprError();
16275 
16276     TheCall =
16277         CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16278                          CurFPFeatureOverrides(), Proto->getNumParams());
16279     TheCall->setUsesMemberSyntax(true);
16280   } else {
16281     // Convert the object argument (for a non-static member function call).
16282     ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16283         MemExpr->getBase(), Qualifier, FoundDecl, Method);
16284     if (ObjectArg.isInvalid())
16285       return ExprError();
16286     MemExpr->setBase(ObjectArg.get());
16287     TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16288                                         RParenLoc, CurFPFeatureOverrides(),
16289                                         Proto->getNumParams());
16290   }
16291 
16292   // Check for a valid return type.
16293   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16294                           TheCall, Method))
16295     return BuildRecoveryExpr(ResultType);
16296 
16297   // Convert the rest of the arguments
16298   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16299                               RParenLoc))
16300     return BuildRecoveryExpr(ResultType);
16301 
16302   DiagnoseSentinelCalls(Method, LParenLoc, Args);
16303 
16304   if (CheckFunctionCall(Method, TheCall, Proto))
16305     return ExprError();
16306 
16307   // In the case the method to call was not selected by the overloading
16308   // resolution process, we still need to handle the enable_if attribute. Do
16309   // that here, so it will not hide previous -- and more relevant -- errors.
16310   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16311     if (const EnableIfAttr *Attr =
16312             CheckEnableIf(Method, LParenLoc, Args, true)) {
16313       Diag(MemE->getMemberLoc(),
16314            diag::err_ovl_no_viable_member_function_in_call)
16315           << Method << Method->getSourceRange();
16316       Diag(Method->getLocation(),
16317            diag::note_ovl_candidate_disabled_by_function_cond_attr)
16318           << Attr->getCond()->getSourceRange() << Attr->getMessage();
16319       return ExprError();
16320     }
16321   }
16322 
16323   if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
16324       TheCall->getDirectCallee()->isPureVirtual()) {
16325     const FunctionDecl *MD = TheCall->getDirectCallee();
16326 
16327     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16328         MemExpr->performsVirtualDispatch(getLangOpts())) {
16329       Diag(MemExpr->getBeginLoc(),
16330            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16331           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
16332           << MD->getParent();
16333 
16334       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16335       if (getLangOpts().AppleKext)
16336         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16337             << MD->getParent() << MD->getDeclName();
16338     }
16339   }
16340 
16341   if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16342     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16343     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16344     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16345                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16346                          MemExpr->getMemberLoc());
16347   }
16348 
16349   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
16350                                      TheCall->getDirectCallee());
16351 }
16352 
16353 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)16354 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16355                                    SourceLocation LParenLoc,
16356                                    MultiExprArg Args,
16357                                    SourceLocation RParenLoc) {
16358   if (checkPlaceholderForOverload(*this, Obj))
16359     return ExprError();
16360   ExprResult Object = Obj;
16361 
16362   UnbridgedCastsSet UnbridgedCasts;
16363   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16364     return ExprError();
16365 
16366   assert(Object.get()->getType()->isRecordType() &&
16367          "Requires object type argument");
16368 
16369   // C++ [over.call.object]p1:
16370   //  If the primary-expression E in the function call syntax
16371   //  evaluates to a class object of type "cv T", then the set of
16372   //  candidate functions includes at least the function call
16373   //  operators of T. The function call operators of T are obtained by
16374   //  ordinary lookup of the name operator() in the context of
16375   //  (E).operator().
16376   OverloadCandidateSet CandidateSet(LParenLoc,
16377                                     OverloadCandidateSet::CSK_Operator);
16378   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16379 
16380   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16381                           diag::err_incomplete_object_call, Object.get()))
16382     return true;
16383 
16384   const auto *Record = Object.get()->getType()->castAs<RecordType>();
16385   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16386   LookupQualifiedName(R, Record->getDecl());
16387   R.suppressAccessDiagnostics();
16388 
16389   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16390        Oper != OperEnd; ++Oper) {
16391     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16392                        Object.get()->Classify(Context), Args, CandidateSet,
16393                        /*SuppressUserConversion=*/false);
16394   }
16395 
16396   // When calling a lambda, both the call operator, and
16397   // the conversion operator to function pointer
16398   // are considered. But when constraint checking
16399   // on the call operator fails, it will also fail on the
16400   // conversion operator as the constraints are always the same.
16401   // As the user probably does not intend to perform a surrogate call,
16402   // we filter them out to produce better error diagnostics, ie to avoid
16403   // showing 2 failed overloads instead of one.
16404   bool IgnoreSurrogateFunctions = false;
16405   if (CandidateSet.nonDeferredCandidatesCount() == 1 &&
16406       Record->getAsCXXRecordDecl()->isLambda()) {
16407     const OverloadCandidate &Candidate = *CandidateSet.begin();
16408     if (!Candidate.Viable &&
16409         Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16410       IgnoreSurrogateFunctions = true;
16411   }
16412 
16413   // C++ [over.call.object]p2:
16414   //   In addition, for each (non-explicit in C++0x) conversion function
16415   //   declared in T of the form
16416   //
16417   //        operator conversion-type-id () cv-qualifier;
16418   //
16419   //   where cv-qualifier is the same cv-qualification as, or a
16420   //   greater cv-qualification than, cv, and where conversion-type-id
16421   //   denotes the type "pointer to function of (P1,...,Pn) returning
16422   //   R", or the type "reference to pointer to function of
16423   //   (P1,...,Pn) returning R", or the type "reference to function
16424   //   of (P1,...,Pn) returning R", a surrogate call function [...]
16425   //   is also considered as a candidate function. Similarly,
16426   //   surrogate call functions are added to the set of candidate
16427   //   functions for each conversion function declared in an
16428   //   accessible base class provided the function is not hidden
16429   //   within T by another intervening declaration.
16430   const auto &Conversions =
16431       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
16432   for (auto I = Conversions.begin(), E = Conversions.end();
16433        !IgnoreSurrogateFunctions && I != E; ++I) {
16434     NamedDecl *D = *I;
16435     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16436     if (isa<UsingShadowDecl>(D))
16437       D = cast<UsingShadowDecl>(D)->getTargetDecl();
16438 
16439     // Skip over templated conversion functions; they aren't
16440     // surrogates.
16441     if (isa<FunctionTemplateDecl>(D))
16442       continue;
16443 
16444     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
16445     if (!Conv->isExplicit()) {
16446       // Strip the reference type (if any) and then the pointer type (if
16447       // any) to get down to what might be a function type.
16448       QualType ConvType = Conv->getConversionType().getNonReferenceType();
16449       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16450         ConvType = ConvPtrType->getPointeeType();
16451 
16452       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16453       {
16454         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16455                               Object.get(), Args, CandidateSet);
16456       }
16457     }
16458   }
16459 
16460   bool HadMultipleCandidates = (CandidateSet.size() > 1);
16461 
16462   // Perform overload resolution.
16463   OverloadCandidateSet::iterator Best;
16464   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16465                                           Best)) {
16466   case OR_Success:
16467     // Overload resolution succeeded; we'll build the appropriate call
16468     // below.
16469     break;
16470 
16471   case OR_No_Viable_Function: {
16472     PartialDiagnostic PD =
16473         CandidateSet.empty()
16474             ? (PDiag(diag::err_ovl_no_oper)
16475                << Object.get()->getType() << /*call*/ 1
16476                << Object.get()->getSourceRange())
16477             : (PDiag(diag::err_ovl_no_viable_object_call)
16478                << Object.get()->getType() << Object.get()->getSourceRange());
16479     CandidateSet.NoteCandidates(
16480         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16481         OCD_AllCandidates, Args);
16482     break;
16483   }
16484   case OR_Ambiguous:
16485     if (!R.isAmbiguous())
16486       CandidateSet.NoteCandidates(
16487           PartialDiagnosticAt(Object.get()->getBeginLoc(),
16488                               PDiag(diag::err_ovl_ambiguous_object_call)
16489                                   << Object.get()->getType()
16490                                   << Object.get()->getSourceRange()),
16491           *this, OCD_AmbiguousCandidates, Args);
16492     break;
16493 
16494   case OR_Deleted: {
16495     // FIXME: Is this diagnostic here really necessary? It seems that
16496     //   1. we don't have any tests for this diagnostic, and
16497     //   2. we already issue err_deleted_function_use for this later on anyway.
16498     StringLiteral *Msg = Best->Function->getDeletedMessage();
16499     CandidateSet.NoteCandidates(
16500         PartialDiagnosticAt(Object.get()->getBeginLoc(),
16501                             PDiag(diag::err_ovl_deleted_object_call)
16502                                 << Object.get()->getType() << (Msg != nullptr)
16503                                 << (Msg ? Msg->getString() : StringRef())
16504                                 << Object.get()->getSourceRange()),
16505         *this, OCD_AllCandidates, Args);
16506     break;
16507   }
16508   }
16509 
16510   if (Best == CandidateSet.end())
16511     return true;
16512 
16513   UnbridgedCasts.restore();
16514 
16515   if (Best->Function == nullptr) {
16516     // Since there is no function declaration, this is one of the
16517     // surrogate candidates. Dig out the conversion function.
16518     CXXConversionDecl *Conv
16519       = cast<CXXConversionDecl>(
16520                          Best->Conversions[0].UserDefined.ConversionFunction);
16521 
16522     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16523                               Best->FoundDecl);
16524     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16525       return ExprError();
16526     assert(Conv == Best->FoundDecl.getDecl() &&
16527              "Found Decl & conversion-to-functionptr should be same, right?!");
16528     // We selected one of the surrogate functions that converts the
16529     // object parameter to a function pointer. Perform the conversion
16530     // on the object argument, then let BuildCallExpr finish the job.
16531 
16532     // Create an implicit member expr to refer to the conversion operator.
16533     // and then call it.
16534     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16535                                              Conv, HadMultipleCandidates);
16536     if (Call.isInvalid())
16537       return ExprError();
16538     // Record usage of conversion in an implicit cast.
16539     Call = ImplicitCastExpr::Create(
16540         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16541         nullptr, VK_PRValue, CurFPFeatureOverrides());
16542 
16543     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16544   }
16545 
16546   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16547 
16548   // We found an overloaded operator(). Build a CXXOperatorCallExpr
16549   // that calls this method, using Object for the implicit object
16550   // parameter and passing along the remaining arguments.
16551   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16552 
16553   // An error diagnostic has already been printed when parsing the declaration.
16554   if (Method->isInvalidDecl())
16555     return ExprError();
16556 
16557   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16558   unsigned NumParams = Proto->getNumParams();
16559 
16560   DeclarationNameInfo OpLocInfo(
16561                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16562   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16563   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16564                                            Obj, HadMultipleCandidates,
16565                                            OpLocInfo.getLoc(),
16566                                            OpLocInfo.getInfo());
16567   if (NewFn.isInvalid())
16568     return true;
16569 
16570   SmallVector<Expr *, 8> MethodArgs;
16571   MethodArgs.reserve(NumParams + 1);
16572 
16573   bool IsError = false;
16574 
16575   // Initialize the object parameter.
16576   llvm::SmallVector<Expr *, 8> NewArgs;
16577   if (Method->isExplicitObjectMemberFunction()) {
16578     IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16579   } else {
16580     ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16581         Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16582     if (ObjRes.isInvalid())
16583       IsError = true;
16584     else
16585       Object = ObjRes;
16586     MethodArgs.push_back(Object.get());
16587   }
16588 
16589   IsError |= PrepareArgumentsForCallToObjectOfClassType(
16590       *this, MethodArgs, Method, Args, LParenLoc);
16591 
16592   // If this is a variadic call, handle args passed through "...".
16593   if (Proto->isVariadic()) {
16594     // Promote the arguments (C99 6.5.2.2p7).
16595     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16596       ExprResult Arg = DefaultVariadicArgumentPromotion(
16597           Args[i], VariadicCallType::Method, nullptr);
16598       IsError |= Arg.isInvalid();
16599       MethodArgs.push_back(Arg.get());
16600     }
16601   }
16602 
16603   if (IsError)
16604     return true;
16605 
16606   DiagnoseSentinelCalls(Method, LParenLoc, Args);
16607 
16608   // Once we've built TheCall, all of the expressions are properly owned.
16609   QualType ResultTy = Method->getReturnType();
16610   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16611   ResultTy = ResultTy.getNonLValueExprType(Context);
16612 
16613   CallExpr *TheCall = CXXOperatorCallExpr::Create(
16614       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16615       CurFPFeatureOverrides());
16616 
16617   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16618     return true;
16619 
16620   if (CheckFunctionCall(Method, TheCall, Proto))
16621     return true;
16622 
16623   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16624 }
16625 
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc,bool * NoArrowOperatorFound)16626 ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16627                                           SourceLocation OpLoc,
16628                                           bool *NoArrowOperatorFound) {
16629   assert(Base->getType()->isRecordType() &&
16630          "left-hand side must have class type");
16631 
16632   if (checkPlaceholderForOverload(*this, Base))
16633     return ExprError();
16634 
16635   SourceLocation Loc = Base->getExprLoc();
16636 
16637   // C++ [over.ref]p1:
16638   //
16639   //   [...] An expression x->m is interpreted as (x.operator->())->m
16640   //   for a class object x of type T if T::operator->() exists and if
16641   //   the operator is selected as the best match function by the
16642   //   overload resolution mechanism (13.3).
16643   DeclarationName OpName =
16644     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16645   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16646 
16647   if (RequireCompleteType(Loc, Base->getType(),
16648                           diag::err_typecheck_incomplete_tag, Base))
16649     return ExprError();
16650 
16651   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16652   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16653   R.suppressAccessDiagnostics();
16654 
16655   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16656        Oper != OperEnd; ++Oper) {
16657     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16658                        {}, CandidateSet,
16659                        /*SuppressUserConversion=*/false);
16660   }
16661 
16662   bool HadMultipleCandidates = (CandidateSet.size() > 1);
16663 
16664   // Perform overload resolution.
16665   OverloadCandidateSet::iterator Best;
16666   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16667   case OR_Success:
16668     // Overload resolution succeeded; we'll build the call below.
16669     break;
16670 
16671   case OR_No_Viable_Function: {
16672     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16673     if (CandidateSet.empty()) {
16674       QualType BaseType = Base->getType();
16675       if (NoArrowOperatorFound) {
16676         // Report this specific error to the caller instead of emitting a
16677         // diagnostic, as requested.
16678         *NoArrowOperatorFound = true;
16679         return ExprError();
16680       }
16681       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16682         << BaseType << Base->getSourceRange();
16683       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16684         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16685           << FixItHint::CreateReplacement(OpLoc, ".");
16686       }
16687     } else
16688       Diag(OpLoc, diag::err_ovl_no_viable_oper)
16689         << "operator->" << Base->getSourceRange();
16690     CandidateSet.NoteCandidates(*this, Base, Cands);
16691     return ExprError();
16692   }
16693   case OR_Ambiguous:
16694     if (!R.isAmbiguous())
16695       CandidateSet.NoteCandidates(
16696           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16697                                          << "->" << Base->getType()
16698                                          << Base->getSourceRange()),
16699           *this, OCD_AmbiguousCandidates, Base);
16700     return ExprError();
16701 
16702   case OR_Deleted: {
16703     StringLiteral *Msg = Best->Function->getDeletedMessage();
16704     CandidateSet.NoteCandidates(
16705         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16706                                        << "->" << (Msg != nullptr)
16707                                        << (Msg ? Msg->getString() : StringRef())
16708                                        << Base->getSourceRange()),
16709         *this, OCD_AllCandidates, Base);
16710     return ExprError();
16711   }
16712   }
16713 
16714   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16715 
16716   // Convert the object parameter.
16717   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16718 
16719   if (Method->isExplicitObjectMemberFunction()) {
16720     ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16721     if (R.isInvalid())
16722       return ExprError();
16723     Base = R.get();
16724   } else {
16725     ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16726         Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16727     if (BaseResult.isInvalid())
16728       return ExprError();
16729     Base = BaseResult.get();
16730   }
16731 
16732   // Build the operator call.
16733   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16734                                             Base, HadMultipleCandidates, OpLoc);
16735   if (FnExpr.isInvalid())
16736     return ExprError();
16737 
16738   QualType ResultTy = Method->getReturnType();
16739   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16740   ResultTy = ResultTy.getNonLValueExprType(Context);
16741 
16742   CallExpr *TheCall =
16743       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16744                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16745 
16746   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16747     return ExprError();
16748 
16749   if (CheckFunctionCall(Method, TheCall,
16750                         Method->getType()->castAs<FunctionProtoType>()))
16751     return ExprError();
16752 
16753   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16754 }
16755 
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)16756 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16757                                           DeclarationNameInfo &SuffixInfo,
16758                                           ArrayRef<Expr*> Args,
16759                                           SourceLocation LitEndLoc,
16760                                        TemplateArgumentListInfo *TemplateArgs) {
16761   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16762 
16763   OverloadCandidateSet CandidateSet(UDSuffixLoc,
16764                                     OverloadCandidateSet::CSK_Normal);
16765   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16766                                  TemplateArgs);
16767 
16768   bool HadMultipleCandidates = (CandidateSet.size() > 1);
16769 
16770   // Perform overload resolution. This will usually be trivial, but might need
16771   // to perform substitutions for a literal operator template.
16772   OverloadCandidateSet::iterator Best;
16773   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16774   case OR_Success:
16775   case OR_Deleted:
16776     break;
16777 
16778   case OR_No_Viable_Function:
16779     CandidateSet.NoteCandidates(
16780         PartialDiagnosticAt(UDSuffixLoc,
16781                             PDiag(diag::err_ovl_no_viable_function_in_call)
16782                                 << R.getLookupName()),
16783         *this, OCD_AllCandidates, Args);
16784     return ExprError();
16785 
16786   case OR_Ambiguous:
16787     CandidateSet.NoteCandidates(
16788         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16789                                                 << R.getLookupName()),
16790         *this, OCD_AmbiguousCandidates, Args);
16791     return ExprError();
16792   }
16793 
16794   FunctionDecl *FD = Best->Function;
16795   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16796                                         nullptr, HadMultipleCandidates,
16797                                         SuffixInfo.getLoc(),
16798                                         SuffixInfo.getInfo());
16799   if (Fn.isInvalid())
16800     return true;
16801 
16802   // Check the argument types. This should almost always be a no-op, except
16803   // that array-to-pointer decay is applied to string literals.
16804   Expr *ConvArgs[2];
16805   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16806     ExprResult InputInit = PerformCopyInitialization(
16807       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
16808       SourceLocation(), Args[ArgIdx]);
16809     if (InputInit.isInvalid())
16810       return true;
16811     ConvArgs[ArgIdx] = InputInit.get();
16812   }
16813 
16814   QualType ResultTy = FD->getReturnType();
16815   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16816   ResultTy = ResultTy.getNonLValueExprType(Context);
16817 
16818   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16819       Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16820       LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16821 
16822   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16823     return ExprError();
16824 
16825   if (CheckFunctionCall(FD, UDL, nullptr))
16826     return ExprError();
16827 
16828   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16829 }
16830 
16831 Sema::ForRangeStatus
BuildForRangeBeginEndCall(SourceLocation Loc,SourceLocation RangeLoc,const DeclarationNameInfo & NameInfo,LookupResult & MemberLookup,OverloadCandidateSet * CandidateSet,Expr * Range,ExprResult * CallExpr)16832 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16833                                 SourceLocation RangeLoc,
16834                                 const DeclarationNameInfo &NameInfo,
16835                                 LookupResult &MemberLookup,
16836                                 OverloadCandidateSet *CandidateSet,
16837                                 Expr *Range, ExprResult *CallExpr) {
16838   Scope *S = nullptr;
16839 
16840   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
16841   if (!MemberLookup.empty()) {
16842     ExprResult MemberRef =
16843         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16844                                  /*IsPtr=*/false, CXXScopeSpec(),
16845                                  /*TemplateKWLoc=*/SourceLocation(),
16846                                  /*FirstQualifierInScope=*/nullptr,
16847                                  MemberLookup,
16848                                  /*TemplateArgs=*/nullptr, S);
16849     if (MemberRef.isInvalid()) {
16850       *CallExpr = ExprError();
16851       return FRS_DiagnosticIssued;
16852     }
16853     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16854     if (CallExpr->isInvalid()) {
16855       *CallExpr = ExprError();
16856       return FRS_DiagnosticIssued;
16857     }
16858   } else {
16859     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16860                                                 NestedNameSpecifierLoc(),
16861                                                 NameInfo, UnresolvedSet<0>());
16862     if (FnR.isInvalid())
16863       return FRS_DiagnosticIssued;
16864     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16865 
16866     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16867                                                     CandidateSet, CallExpr);
16868     if (CandidateSet->empty() || CandidateSetError) {
16869       *CallExpr = ExprError();
16870       return FRS_NoViableFunction;
16871     }
16872     OverloadCandidateSet::iterator Best;
16873     OverloadingResult OverloadResult =
16874         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16875 
16876     if (OverloadResult == OR_No_Viable_Function) {
16877       *CallExpr = ExprError();
16878       return FRS_NoViableFunction;
16879     }
16880     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16881                                          Loc, nullptr, CandidateSet, &Best,
16882                                          OverloadResult,
16883                                          /*AllowTypoCorrection=*/false);
16884     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16885       *CallExpr = ExprError();
16886       return FRS_DiagnosticIssued;
16887     }
16888   }
16889   return FRS_Success;
16890 }
16891 
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)16892 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16893                                                 FunctionDecl *Fn) {
16894   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16895     ExprResult SubExpr =
16896         FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16897     if (SubExpr.isInvalid())
16898       return ExprError();
16899     if (SubExpr.get() == PE->getSubExpr())
16900       return PE;
16901 
16902     return new (Context)
16903         ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16904   }
16905 
16906   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16907     ExprResult SubExpr =
16908         FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16909     if (SubExpr.isInvalid())
16910       return ExprError();
16911     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16912                                SubExpr.get()->getType()) &&
16913            "Implicit cast type cannot be determined from overload");
16914     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16915     if (SubExpr.get() == ICE->getSubExpr())
16916       return ICE;
16917 
16918     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16919                                     SubExpr.get(), nullptr, ICE->getValueKind(),
16920                                     CurFPFeatureOverrides());
16921   }
16922 
16923   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16924     if (!GSE->isResultDependent()) {
16925       ExprResult SubExpr =
16926           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16927       if (SubExpr.isInvalid())
16928         return ExprError();
16929       if (SubExpr.get() == GSE->getResultExpr())
16930         return GSE;
16931 
16932       // Replace the resulting type information before rebuilding the generic
16933       // selection expression.
16934       ArrayRef<Expr *> A = GSE->getAssocExprs();
16935       SmallVector<Expr *, 4> AssocExprs(A);
16936       unsigned ResultIdx = GSE->getResultIndex();
16937       AssocExprs[ResultIdx] = SubExpr.get();
16938 
16939       if (GSE->isExprPredicate())
16940         return GenericSelectionExpr::Create(
16941             Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16942             GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16943             GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16944             ResultIdx);
16945       return GenericSelectionExpr::Create(
16946           Context, GSE->getGenericLoc(), GSE->getControllingType(),
16947           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16948           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16949           ResultIdx);
16950     }
16951     // Rather than fall through to the unreachable, return the original generic
16952     // selection expression.
16953     return GSE;
16954   }
16955 
16956   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16957     assert(UnOp->getOpcode() == UO_AddrOf &&
16958            "Can only take the address of an overloaded function");
16959     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16960       if (!Method->isImplicitObjectMemberFunction()) {
16961         // Do nothing: the address of static and
16962         // explicit object member functions is a (non-member) function pointer.
16963       } else {
16964         // Fix the subexpression, which really has to be an
16965         // UnresolvedLookupExpr holding an overloaded member function
16966         // or template.
16967         ExprResult SubExpr =
16968             FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16969         if (SubExpr.isInvalid())
16970           return ExprError();
16971         if (SubExpr.get() == UnOp->getSubExpr())
16972           return UnOp;
16973 
16974         if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16975                                                   SubExpr.get(), Method))
16976           return ExprError();
16977 
16978         assert(isa<DeclRefExpr>(SubExpr.get()) &&
16979                "fixed to something other than a decl ref");
16980         NestedNameSpecifier *Qualifier =
16981             cast<DeclRefExpr>(SubExpr.get())->getQualifier();
16982         assert(Qualifier &&
16983                "fixed to a member ref with no nested name qualifier");
16984 
16985         // We have taken the address of a pointer to member
16986         // function. Perform the computation here so that we get the
16987         // appropriate pointer to member type.
16988         QualType MemPtrType = Context.getMemberPointerType(
16989             Fn->getType(), Qualifier,
16990             cast<CXXRecordDecl>(Method->getDeclContext()));
16991         // Under the MS ABI, lock down the inheritance model now.
16992         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16993           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16994 
16995         return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16996                                      MemPtrType, VK_PRValue, OK_Ordinary,
16997                                      UnOp->getOperatorLoc(), false,
16998                                      CurFPFeatureOverrides());
16999       }
17000     }
17001     ExprResult SubExpr =
17002         FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17003     if (SubExpr.isInvalid())
17004       return ExprError();
17005     if (SubExpr.get() == UnOp->getSubExpr())
17006       return UnOp;
17007 
17008     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17009                                 SubExpr.get());
17010   }
17011 
17012   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17013     if (Found.getAccess() == AS_none) {
17014       CheckUnresolvedLookupAccess(ULE, Found);
17015     }
17016     // FIXME: avoid copy.
17017     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17018     if (ULE->hasExplicitTemplateArgs()) {
17019       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17020       TemplateArgs = &TemplateArgsBuffer;
17021     }
17022 
17023     QualType Type = Fn->getType();
17024     ExprValueKind ValueKind =
17025         getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17026             ? VK_LValue
17027             : VK_PRValue;
17028 
17029     // FIXME: Duplicated from BuildDeclarationNameExpr.
17030     if (unsigned BID = Fn->getBuiltinID()) {
17031       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17032         Type = Context.BuiltinFnTy;
17033         ValueKind = VK_PRValue;
17034       }
17035     }
17036 
17037     DeclRefExpr *DRE = BuildDeclRefExpr(
17038         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17039         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17040     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17041     return DRE;
17042   }
17043 
17044   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17045     // FIXME: avoid copy.
17046     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17047     if (MemExpr->hasExplicitTemplateArgs()) {
17048       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17049       TemplateArgs = &TemplateArgsBuffer;
17050     }
17051 
17052     Expr *Base;
17053 
17054     // If we're filling in a static method where we used to have an
17055     // implicit member access, rewrite to a simple decl ref.
17056     if (MemExpr->isImplicitAccess()) {
17057       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17058         DeclRefExpr *DRE = BuildDeclRefExpr(
17059             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17060             MemExpr->getQualifierLoc(), Found.getDecl(),
17061             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17062         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17063         return DRE;
17064       } else {
17065         SourceLocation Loc = MemExpr->getMemberLoc();
17066         if (MemExpr->getQualifier())
17067           Loc = MemExpr->getQualifierLoc().getBeginLoc();
17068         Base =
17069             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17070       }
17071     } else
17072       Base = MemExpr->getBase();
17073 
17074     ExprValueKind valueKind;
17075     QualType type;
17076     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17077       valueKind = VK_LValue;
17078       type = Fn->getType();
17079     } else {
17080       valueKind = VK_PRValue;
17081       type = Context.BoundMemberTy;
17082     }
17083 
17084     return BuildMemberExpr(
17085         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17086         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17087         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17088         type, valueKind, OK_Ordinary, TemplateArgs);
17089   }
17090 
17091   llvm_unreachable("Invalid reference to overloaded function");
17092 }
17093 
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)17094 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17095                                                 DeclAccessPair Found,
17096                                                 FunctionDecl *Fn) {
17097   return FixOverloadedFunctionReference(E.get(), Found, Fn);
17098 }
17099 
shouldEnforceArgLimit(bool PartialOverloading,FunctionDecl * Function)17100 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17101                                   FunctionDecl *Function) {
17102   if (!PartialOverloading || !Function)
17103     return true;
17104   if (Function->isVariadic())
17105     return false;
17106   if (const auto *Proto =
17107           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17108     if (Proto->isTemplateVariadic())
17109       return false;
17110   if (auto *Pattern = Function->getTemplateInstantiationPattern())
17111     if (const auto *Proto =
17112             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17113       if (Proto->isTemplateVariadic())
17114         return false;
17115   return true;
17116 }
17117 
DiagnoseUseOfDeletedFunction(SourceLocation Loc,SourceRange Range,DeclarationName Name,OverloadCandidateSet & CandidateSet,FunctionDecl * Fn,MultiExprArg Args,bool IsMember)17118 void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17119                                         DeclarationName Name,
17120                                         OverloadCandidateSet &CandidateSet,
17121                                         FunctionDecl *Fn, MultiExprArg Args,
17122                                         bool IsMember) {
17123   StringLiteral *Msg = Fn->getDeletedMessage();
17124   CandidateSet.NoteCandidates(
17125       PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17126                                    << IsMember << Name << (Msg != nullptr)
17127                                    << (Msg ? Msg->getString() : StringRef())
17128                                    << Range),
17129       *this, OCD_AllCandidates, Args);
17130 }
17131