clang 19.0.0git
SemaOverload.cpp
Go to the documentation of this file.
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
14#include "clang/AST/ASTLambda.h"
16#include "clang/AST/DeclCXX.h"
17#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"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/SemaObjC.h"
37#include "clang/Sema/Template.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/STLForwardCompat.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/SmallVector.h"
45#include "llvm/Support/Casting.h"
46#include <algorithm>
47#include <cstddef>
48#include <cstdlib>
49#include <optional>
50
51using namespace clang;
52using namespace sema;
53
55
57 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
58 return P->hasAttr<PassObjectSizeAttr>();
59 });
60}
61
62/// A convenience routine for creating a decayed reference to a function.
64 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
65 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
66 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
67 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
68 return ExprError();
69 // If FoundDecl is different from Fn (such as if one is a template
70 // and the other a specialization), make sure DiagnoseUseOfDecl is
71 // called on both.
72 // FIXME: This would be more comprehensively addressed by modifying
73 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
74 // being used.
75 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
76 return ExprError();
77 DeclRefExpr *DRE = new (S.Context)
78 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
79 if (HadMultipleCandidates)
80 DRE->setHadMultipleCandidates(true);
81
83 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
84 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
86 DRE->setType(Fn->getType());
87 }
88 }
89 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
90 CK_FunctionToPointerDecay);
91}
92
93static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
94 bool InOverloadResolution,
96 bool CStyle,
97 bool AllowObjCWritebackConversion);
98
100 QualType &ToType,
101 bool InOverloadResolution,
103 bool CStyle);
105IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
107 OverloadCandidateSet& Conversions,
108 AllowedExplicit AllowExplicit,
109 bool AllowObjCConversionOnExplicit);
110
113 const StandardConversionSequence& SCS1,
114 const StandardConversionSequence& SCS2);
115
118 const StandardConversionSequence& SCS1,
119 const StandardConversionSequence& SCS2);
120
123 const StandardConversionSequence& SCS1,
124 const StandardConversionSequence& SCS2);
125
126/// GetConversionRank - Retrieve the implicit conversion rank
127/// corresponding to the given implicit conversion kind.
129 static const ImplicitConversionRank Rank[] = {
156 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
157 // it was omitted by the patch that added
158 // ICK_Zero_Event_Conversion
159 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
160 // it was omitted by the patch that added
161 // ICK_Zero_Queue_Conversion
167 };
168 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
169 return Rank[(int)Kind];
170}
171
172/// GetImplicitConversionName - Return the name of this kind of
173/// implicit conversion.
175 static const char *const Name[] = {
176 "No conversion",
177 "Lvalue-to-rvalue",
178 "Array-to-pointer",
179 "Function-to-pointer",
180 "Function pointer conversion",
181 "Qualification",
182 "Integral promotion",
183 "Floating point promotion",
184 "Complex promotion",
185 "Integral conversion",
186 "Floating conversion",
187 "Complex conversion",
188 "Floating-integral conversion",
189 "Pointer conversion",
190 "Pointer-to-member conversion",
191 "Boolean conversion",
192 "Compatible-types conversion",
193 "Derived-to-base conversion",
194 "Vector conversion",
195 "SVE Vector conversion",
196 "RVV Vector conversion",
197 "Vector splat",
198 "Complex-real conversion",
199 "Block Pointer conversion",
200 "Transparent Union Conversion",
201 "Writeback conversion",
202 "OpenCL Zero Event Conversion",
203 "OpenCL Zero Queue Conversion",
204 "C specific type conversion",
205 "Incompatible pointer conversion",
206 "Fixed point conversion",
207 "HLSL vector truncation",
208 "Non-decaying array conversion",
209 };
210 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
211 return Name[Kind];
212}
213
214/// StandardConversionSequence - Set the standard conversion
215/// sequence to the identity conversion.
223 ReferenceBinding = false;
224 DirectBinding = false;
225 IsLvalueReference = true;
226 BindsToFunctionLvalue = false;
227 BindsToRvalue = false;
230 CopyConstructor = nullptr;
231}
232
233/// getRank - Retrieve the rank of this standard conversion sequence
234/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
235/// implicit conversions.
238 if (GetConversionRank(First) > Rank)
239 Rank = GetConversionRank(First);
240 if (GetConversionRank(Second) > Rank)
242 if (GetConversionRank(Element) > Rank)
244 if (GetConversionRank(Third) > Rank)
245 Rank = GetConversionRank(Third);
246 return Rank;
247}
248
249/// isPointerConversionToBool - Determines whether this conversion is
250/// a conversion of a pointer or pointer-to-member to bool. This is
251/// used as part of the ranking of standard conversion sequences
252/// (C++ 13.3.3.2p4).
254 // Note that FromType has not necessarily been transformed by the
255 // array-to-pointer or function-to-pointer implicit conversions, so
256 // check for their presence as well as checking whether FromType is
257 // a pointer.
258 if (getToType(1)->isBooleanType() &&
259 (getFromType()->isPointerType() ||
260 getFromType()->isMemberPointerType() ||
261 getFromType()->isObjCObjectPointerType() ||
262 getFromType()->isBlockPointerType() ||
264 return true;
265
266 return false;
267}
268
269/// isPointerConversionToVoidPointer - Determines whether this
270/// conversion is a conversion of a pointer to a void pointer. This is
271/// used as part of the ranking of standard conversion sequences (C++
272/// 13.3.3.2p4).
273bool
276 QualType FromType = getFromType();
277 QualType ToType = getToType(1);
278
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer implicit conversion, so check for its presence
281 // and redo the conversion to get a pointer.
283 FromType = Context.getArrayDecayedType(FromType);
284
285 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
286 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
287 return ToPtrType->getPointeeType()->isVoidType();
288
289 return false;
290}
291
292/// Skip any implicit casts which could be either part of a narrowing conversion
293/// or after one in an implicit conversion.
295 const Expr *Converted) {
296 // We can have cleanups wrapping the converted expression; these need to be
297 // preserved so that destructors run if necessary.
298 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
299 Expr *Inner =
300 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
301 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
302 EWC->getObjects());
303 }
304
305 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
306 switch (ICE->getCastKind()) {
307 case CK_NoOp:
308 case CK_IntegralCast:
309 case CK_IntegralToBoolean:
310 case CK_IntegralToFloating:
311 case CK_BooleanToSignedIntegral:
312 case CK_FloatingToIntegral:
313 case CK_FloatingToBoolean:
314 case CK_FloatingCast:
315 Converted = ICE->getSubExpr();
316 continue;
317
318 default:
319 return Converted;
320 }
321 }
322
323 return Converted;
324}
325
326/// Check if this standard conversion sequence represents a narrowing
327/// conversion, according to C++11 [dcl.init.list]p7.
328///
329/// \param Ctx The AST context.
330/// \param Converted The result of applying this standard conversion sequence.
331/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
332/// value of the expression prior to the narrowing conversion.
333/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
334/// type of the expression prior to the narrowing conversion.
335/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
336/// from floating point types to integral types should be ignored.
338 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
339 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
340 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
341 "narrowing check outside C++");
342
343 // C++11 [dcl.init.list]p7:
344 // A narrowing conversion is an implicit conversion ...
345 QualType FromType = getToType(0);
346 QualType ToType = getToType(1);
347
348 // A conversion to an enumeration type is narrowing if the conversion to
349 // the underlying type is narrowing. This only arises for expressions of
350 // the form 'Enum{init}'.
351 if (auto *ET = ToType->getAs<EnumType>())
352 ToType = ET->getDecl()->getIntegerType();
353
354 switch (Second) {
355 // 'bool' is an integral type; dispatch to the right place to handle it.
357 if (FromType->isRealFloatingType())
358 goto FloatingIntegralConversion;
360 goto IntegralConversion;
361 // -- from a pointer type or pointer-to-member type to bool, or
362 return NK_Type_Narrowing;
363
364 // -- from a floating-point type to an integer type, or
365 //
366 // -- from an integer type or unscoped enumeration type to a floating-point
367 // type, except where the source is a constant expression and the actual
368 // value after conversion will fit into the target type and will produce
369 // the original value when converted back to the original type, or
371 FloatingIntegralConversion:
372 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
373 return NK_Type_Narrowing;
374 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
375 ToType->isRealFloatingType()) {
376 if (IgnoreFloatToIntegralConversion)
377 return NK_Not_Narrowing;
378 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
379 assert(Initializer && "Unknown conversion expression");
380
381 // If it's value-dependent, we can't tell whether it's narrowing.
382 if (Initializer->isValueDependent())
384
385 if (std::optional<llvm::APSInt> IntConstantValue =
386 Initializer->getIntegerConstantExpr(Ctx)) {
387 // Convert the integer to the floating type.
388 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
389 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
390 llvm::APFloat::rmNearestTiesToEven);
391 // And back.
392 llvm::APSInt ConvertedValue = *IntConstantValue;
393 bool ignored;
394 Result.convertToInteger(ConvertedValue,
395 llvm::APFloat::rmTowardZero, &ignored);
396 // If the resulting value is different, this was a narrowing conversion.
397 if (*IntConstantValue != ConvertedValue) {
398 ConstantValue = APValue(*IntConstantValue);
399 ConstantType = Initializer->getType();
401 }
402 } else {
403 // Variables are always narrowings.
405 }
406 }
407 return NK_Not_Narrowing;
408
409 // -- from long double to double or float, or from double to float, except
410 // where the source is a constant expression and the actual value after
411 // conversion is within the range of values that can be represented (even
412 // if it cannot be represented exactly), or
414 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
415 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
416 // FromType is larger than ToType.
417 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
418
419 // If it's value-dependent, we can't tell whether it's narrowing.
420 if (Initializer->isValueDependent())
422
424 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
425 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
426 // Constant!
427 if (Ctx.getLangOpts().C23)
428 ConstantValue = R.Val;
429 assert(ConstantValue.isFloat());
430 llvm::APFloat FloatVal = ConstantValue.getFloat();
431 // Convert the source value into the target type.
432 bool ignored;
433 llvm::APFloat Converted = FloatVal;
434 llvm::APFloat::opStatus ConvertStatus =
435 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
436 llvm::APFloat::rmNearestTiesToEven, &ignored);
437 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
438 llvm::APFloat::rmNearestTiesToEven, &ignored);
439 if (Ctx.getLangOpts().C23) {
440 if (FloatVal.isNaN() && Converted.isNaN() &&
441 !FloatVal.isSignaling() && !Converted.isSignaling()) {
442 // Quiet NaNs are considered the same value, regardless of
443 // payloads.
444 return NK_Not_Narrowing;
445 }
446 // For normal values, check exact equality.
447 if (!Converted.bitwiseIsEqual(FloatVal)) {
448 ConstantType = Initializer->getType();
450 }
451 } else {
452 // If there was no overflow, the source value is within the range of
453 // values that can be represented.
454 if (ConvertStatus & llvm::APFloat::opOverflow) {
455 ConstantType = Initializer->getType();
457 }
458 }
459 } else {
461 }
462 }
463 return NK_Not_Narrowing;
464
465 // -- from an integer type or unscoped enumeration type to an integer type
466 // that cannot represent all the values of the original type, except where
467 // the source is a constant expression and the actual value after
468 // conversion will fit into the target type and will produce the original
469 // value when converted back to the original type.
471 IntegralConversion: {
472 assert(FromType->isIntegralOrUnscopedEnumerationType());
473 assert(ToType->isIntegralOrUnscopedEnumerationType());
474 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
475 const unsigned FromWidth = Ctx.getIntWidth(FromType);
476 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
477 const unsigned ToWidth = Ctx.getIntWidth(ToType);
478
479 if (FromWidth > ToWidth ||
480 (FromWidth == ToWidth && FromSigned != ToSigned) ||
481 (FromSigned && !ToSigned)) {
482 // Not all values of FromType can be represented in ToType.
483 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
484
485 // If it's value-dependent, we can't tell whether it's narrowing.
486 if (Initializer->isValueDependent())
488
489 std::optional<llvm::APSInt> OptInitializerValue;
490 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
491 // Such conversions on variables are always narrowing.
493 }
494 llvm::APSInt &InitializerValue = *OptInitializerValue;
495 bool Narrowing = false;
496 if (FromWidth < ToWidth) {
497 // Negative -> unsigned is narrowing. Otherwise, more bits is never
498 // narrowing.
499 if (InitializerValue.isSigned() && InitializerValue.isNegative())
500 Narrowing = true;
501 } else {
502 // Add a bit to the InitializerValue so we don't have to worry about
503 // signed vs. unsigned comparisons.
504 InitializerValue = InitializerValue.extend(
505 InitializerValue.getBitWidth() + 1);
506 // Convert the initializer to and from the target width and signed-ness.
507 llvm::APSInt ConvertedValue = InitializerValue;
508 ConvertedValue = ConvertedValue.trunc(ToWidth);
509 ConvertedValue.setIsSigned(ToSigned);
510 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
511 ConvertedValue.setIsSigned(InitializerValue.isSigned());
512 // If the result is different, this was a narrowing conversion.
513 if (ConvertedValue != InitializerValue)
514 Narrowing = true;
515 }
516 if (Narrowing) {
517 ConstantType = Initializer->getType();
518 ConstantValue = APValue(InitializerValue);
520 }
521 }
522 return NK_Not_Narrowing;
523 }
524 case ICK_Complex_Real:
525 if (FromType->isComplexType() && !ToType->isComplexType())
526 return NK_Type_Narrowing;
527 return NK_Not_Narrowing;
528
530 if (Ctx.getLangOpts().C23) {
531 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
533 if (Initializer->EvaluateAsRValue(R, Ctx)) {
534 ConstantValue = R.Val;
535 assert(ConstantValue.isFloat());
536 llvm::APFloat FloatVal = ConstantValue.getFloat();
537 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
538 // value, the unqualified versions of the type of the initializer and
539 // the corresponding real type of the object declared shall be
540 // compatible.
541 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
542 ConstantType = Initializer->getType();
544 }
545 }
546 }
547 return NK_Not_Narrowing;
548 default:
549 // Other kinds of conversions are not narrowings.
550 return NK_Not_Narrowing;
551 }
552}
553
554/// dump - Print this standard conversion sequence to standard
555/// error. Useful for debugging overloading issues.
556LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
557 raw_ostream &OS = llvm::errs();
558 bool PrintedSomething = false;
559 if (First != ICK_Identity) {
561 PrintedSomething = true;
562 }
563
564 if (Second != ICK_Identity) {
565 if (PrintedSomething) {
566 OS << " -> ";
567 }
569
570 if (CopyConstructor) {
571 OS << " (by copy constructor)";
572 } else if (DirectBinding) {
573 OS << " (direct reference binding)";
574 } else if (ReferenceBinding) {
575 OS << " (reference binding)";
576 }
577 PrintedSomething = true;
578 }
579
580 if (Third != ICK_Identity) {
581 if (PrintedSomething) {
582 OS << " -> ";
583 }
585 PrintedSomething = true;
586 }
587
588 if (!PrintedSomething) {
589 OS << "No conversions required";
590 }
591}
592
593/// dump - Print this user-defined conversion sequence to standard
594/// error. Useful for debugging overloading issues.
596 raw_ostream &OS = llvm::errs();
597 if (Before.First || Before.Second || Before.Third) {
598 Before.dump();
599 OS << " -> ";
600 }
602 OS << '\'' << *ConversionFunction << '\'';
603 else
604 OS << "aggregate initialization";
605 if (After.First || After.Second || After.Third) {
606 OS << " -> ";
607 After.dump();
608 }
609}
610
611/// dump - Print this implicit conversion sequence to standard
612/// error. Useful for debugging overloading issues.
614 raw_ostream &OS = llvm::errs();
616 OS << "Worst list element conversion: ";
617 switch (ConversionKind) {
619 OS << "Standard conversion: ";
620 Standard.dump();
621 break;
623 OS << "User-defined conversion: ";
625 break;
627 OS << "Ellipsis conversion";
628 break;
630 OS << "Ambiguous conversion";
631 break;
632 case BadConversion:
633 OS << "Bad conversion";
634 break;
635 }
636
637 OS << "\n";
638}
639
641 new (&conversions()) ConversionSet();
642}
643
645 conversions().~ConversionSet();
646}
647
648void
653}
654
655namespace {
656 // Structure used by DeductionFailureInfo to store
657 // template argument information.
658 struct DFIArguments {
659 TemplateArgument FirstArg;
660 TemplateArgument SecondArg;
661 };
662 // Structure used by DeductionFailureInfo to store
663 // template parameter and template argument information.
664 struct DFIParamWithArguments : DFIArguments {
665 TemplateParameter Param;
666 };
667 // Structure used by DeductionFailureInfo to store template argument
668 // information and the index of the problematic call argument.
669 struct DFIDeducedMismatchArgs : DFIArguments {
670 TemplateArgumentList *TemplateArgs;
671 unsigned CallArgIndex;
672 };
673 // Structure used by DeductionFailureInfo to store information about
674 // unsatisfied constraints.
675 struct CNSInfo {
676 TemplateArgumentList *TemplateArgs;
677 ConstraintSatisfaction Satisfaction;
678 };
679}
680
681/// Convert from Sema's representation of template deduction information
682/// to the form used in overload-candidate information.
686 TemplateDeductionInfo &Info) {
688 Result.Result = static_cast<unsigned>(TDK);
689 Result.HasDiagnostic = false;
690 switch (TDK) {
697 Result.Data = nullptr;
698 break;
699
702 Result.Data = Info.Param.getOpaqueValue();
703 break;
704
707 // FIXME: Should allocate from normal heap so that we can free this later.
708 auto *Saved = new (Context) DFIDeducedMismatchArgs;
709 Saved->FirstArg = Info.FirstArg;
710 Saved->SecondArg = Info.SecondArg;
711 Saved->TemplateArgs = Info.takeSugared();
712 Saved->CallArgIndex = Info.CallArgIndex;
713 Result.Data = Saved;
714 break;
715 }
716
718 // FIXME: Should allocate from normal heap so that we can free this later.
719 DFIArguments *Saved = new (Context) DFIArguments;
720 Saved->FirstArg = Info.FirstArg;
721 Saved->SecondArg = Info.SecondArg;
722 Result.Data = Saved;
723 break;
724 }
725
727 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
730 // FIXME: Should allocate from normal heap so that we can free this later.
731 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
732 Saved->Param = Info.Param;
733 Saved->FirstArg = Info.FirstArg;
734 Saved->SecondArg = Info.SecondArg;
735 Result.Data = Saved;
736 break;
737 }
738
740 Result.Data = Info.takeSugared();
741 if (Info.hasSFINAEDiagnostic()) {
745 Result.HasDiagnostic = true;
746 }
747 break;
748
750 CNSInfo *Saved = new (Context) CNSInfo;
751 Saved->TemplateArgs = Info.takeSugared();
752 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
753 Result.Data = Saved;
754 break;
755 }
756
760 llvm_unreachable("not a deduction failure");
761 }
762
763 return Result;
764}
765
767 switch (static_cast<TemplateDeductionResult>(Result)) {
777 break;
778
785 // FIXME: Destroy the data?
786 Data = nullptr;
787 break;
788
790 // FIXME: Destroy the template argument list?
791 Data = nullptr;
793 Diag->~PartialDiagnosticAt();
794 HasDiagnostic = false;
795 }
796 break;
797
799 // FIXME: Destroy the template argument list?
800 Data = nullptr;
802 Diag->~PartialDiagnosticAt();
803 HasDiagnostic = false;
804 }
805 break;
806
807 // Unhandled
810 break;
811 }
812}
813
815 if (HasDiagnostic)
816 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
817 return nullptr;
818}
819
821 switch (static_cast<TemplateDeductionResult>(Result)) {
834 return TemplateParameter();
835
838 return TemplateParameter::getFromOpaqueValue(Data);
839
843 return static_cast<DFIParamWithArguments*>(Data)->Param;
844
845 // Unhandled
848 break;
849 }
850
851 return TemplateParameter();
852}
853
855 switch (static_cast<TemplateDeductionResult>(Result)) {
869 return nullptr;
870
873 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
874
876 return static_cast<TemplateArgumentList*>(Data);
877
879 return static_cast<CNSInfo*>(Data)->TemplateArgs;
880
881 // Unhandled
884 break;
885 }
886
887 return nullptr;
888}
889
891 switch (static_cast<TemplateDeductionResult>(Result)) {
903 return nullptr;
904
911 return &static_cast<DFIArguments*>(Data)->FirstArg;
912
913 // Unhandled
916 break;
917 }
918
919 return nullptr;
920}
921
923 switch (static_cast<TemplateDeductionResult>(Result)) {
936 return nullptr;
937
943 return &static_cast<DFIArguments*>(Data)->SecondArg;
944
945 // Unhandled
948 break;
949 }
950
951 return nullptr;
952}
953
954std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
955 switch (static_cast<TemplateDeductionResult>(Result)) {
958 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
959
960 default:
961 return std::nullopt;
962 }
963}
964
966 const FunctionDecl *Y) {
967 if (!X || !Y)
968 return false;
969 if (X->getNumParams() != Y->getNumParams())
970 return false;
971 // FIXME: when do rewritten comparison operators
972 // with explicit object parameters correspond?
973 // https://cplusplus.github.io/CWG/issues/2797.html
974 for (unsigned I = 0; I < X->getNumParams(); ++I)
975 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
976 Y->getParamDecl(I)->getType()))
977 return false;
978 if (auto *FTX = X->getDescribedFunctionTemplate()) {
979 auto *FTY = Y->getDescribedFunctionTemplate();
980 if (!FTY)
981 return false;
982 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
983 FTY->getTemplateParameters()))
984 return false;
985 }
986 return true;
987}
988
990 Expr *FirstOperand, FunctionDecl *EqFD) {
991 assert(EqFD->getOverloadedOperator() ==
992 OverloadedOperatorKind::OO_EqualEqual);
993 // C++2a [over.match.oper]p4:
994 // A non-template function or function template F named operator== is a
995 // rewrite target with first operand o unless a search for the name operator!=
996 // in the scope S from the instantiation context of the operator expression
997 // finds a function or function template that would correspond
998 // ([basic.scope.scope]) to F if its name were operator==, where S is the
999 // scope of the class type of o if F is a class member, and the namespace
1000 // scope of which F is a member otherwise. A function template specialization
1001 // named operator== is a rewrite target if its function template is a rewrite
1002 // target.
1004 OverloadedOperatorKind::OO_ExclaimEqual);
1005 if (isa<CXXMethodDecl>(EqFD)) {
1006 // If F is a class member, search scope is class type of first operand.
1007 QualType RHS = FirstOperand->getType();
1008 auto *RHSRec = RHS->getAs<RecordType>();
1009 if (!RHSRec)
1010 return true;
1011 LookupResult Members(S, NotEqOp, OpLoc,
1013 S.LookupQualifiedName(Members, RHSRec->getDecl());
1014 Members.suppressAccessDiagnostics();
1015 for (NamedDecl *Op : Members)
1016 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1017 return false;
1018 return true;
1019 }
1020 // Otherwise the search scope is the namespace scope of which F is a member.
1021 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1022 auto *NotEqFD = Op->getAsFunction();
1023 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1024 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1025 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1027 cast<Decl>(Op->getLexicalDeclContext())))
1028 return false;
1029 }
1030 return true;
1031}
1032
1036 return false;
1037 return Op == OO_EqualEqual || Op == OO_Spaceship;
1038}
1039
1041 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1042 auto Op = FD->getOverloadedOperator();
1043 if (!allowsReversed(Op))
1044 return false;
1045 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1046 assert(OriginalArgs.size() == 2);
1048 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1049 return false;
1050 }
1051 // Don't bother adding a reversed candidate that can never be a better
1052 // match than the non-reversed version.
1053 return FD->getNumNonObjectParams() != 2 ||
1055 FD->getParamDecl(1)->getType()) ||
1056 FD->hasAttr<EnableIfAttr>();
1057}
1058
1059void OverloadCandidateSet::destroyCandidates() {
1060 for (iterator i = begin(), e = end(); i != e; ++i) {
1061 for (auto &C : i->Conversions)
1062 C.~ImplicitConversionSequence();
1063 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1064 i->DeductionFailure.Destroy();
1065 }
1066}
1067
1069 destroyCandidates();
1070 SlabAllocator.Reset();
1071 NumInlineBytesUsed = 0;
1072 Candidates.clear();
1073 Functions.clear();
1074 Kind = CSK;
1075}
1076
1077namespace {
1078 class UnbridgedCastsSet {
1079 struct Entry {
1080 Expr **Addr;
1081 Expr *Saved;
1082 };
1083 SmallVector<Entry, 2> Entries;
1084
1085 public:
1086 void save(Sema &S, Expr *&E) {
1087 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1088 Entry entry = { &E, E };
1089 Entries.push_back(entry);
1090 E = S.ObjC().stripARCUnbridgedCast(E);
1091 }
1092
1093 void restore() {
1095 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1096 *i->Addr = i->Saved;
1097 }
1098 };
1099}
1100
1101/// checkPlaceholderForOverload - Do any interesting placeholder-like
1102/// preprocessing on the given expression.
1103///
1104/// \param unbridgedCasts a collection to which to add unbridged casts;
1105/// without this, they will be immediately diagnosed as errors
1106///
1107/// Return true on unrecoverable error.
1108static bool
1110 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1111 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1112 // We can't handle overloaded expressions here because overload
1113 // resolution might reasonably tweak them.
1114 if (placeholder->getKind() == BuiltinType::Overload) return false;
1115
1116 // If the context potentially accepts unbridged ARC casts, strip
1117 // the unbridged cast and add it to the collection for later restoration.
1118 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1119 unbridgedCasts) {
1120 unbridgedCasts->save(S, E);
1121 return false;
1122 }
1123
1124 // Go ahead and check everything else.
1125 ExprResult result = S.CheckPlaceholderExpr(E);
1126 if (result.isInvalid())
1127 return true;
1128
1129 E = result.get();
1130 return false;
1131 }
1132
1133 // Nothing to do.
1134 return false;
1135}
1136
1137/// checkArgPlaceholdersForOverload - Check a set of call operands for
1138/// placeholders.
1140 UnbridgedCastsSet &unbridged) {
1141 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1142 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1143 return true;
1144
1145 return false;
1146}
1147
1148/// Determine whether the given New declaration is an overload of the
1149/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1150/// New and Old cannot be overloaded, e.g., if New has the same signature as
1151/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1152/// functions (or function templates) at all. When it does return Ovl_Match or
1153/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1154/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1155/// declaration.
1156///
1157/// Example: Given the following input:
1158///
1159/// void f(int, float); // #1
1160/// void f(int, int); // #2
1161/// int f(int, int); // #3
1162///
1163/// When we process #1, there is no previous declaration of "f", so IsOverload
1164/// will not be used.
1165///
1166/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1167/// the parameter types, we see that #1 and #2 are overloaded (since they have
1168/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1169/// unchanged.
1170///
1171/// When we process #3, Old is an overload set containing #1 and #2. We compare
1172/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1173/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1174/// functions are not part of the signature), IsOverload returns Ovl_Match and
1175/// MatchedDecl will be set to point to the FunctionDecl for #2.
1176///
1177/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1178/// by a using declaration. The rules for whether to hide shadow declarations
1179/// ignore some properties which otherwise figure into a function template's
1180/// signature.
1183 NamedDecl *&Match, bool NewIsUsingDecl) {
1184 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1185 I != E; ++I) {
1186 NamedDecl *OldD = *I;
1187
1188 bool OldIsUsingDecl = false;
1189 if (isa<UsingShadowDecl>(OldD)) {
1190 OldIsUsingDecl = true;
1191
1192 // We can always introduce two using declarations into the same
1193 // context, even if they have identical signatures.
1194 if (NewIsUsingDecl) continue;
1195
1196 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1197 }
1198
1199 // A using-declaration does not conflict with another declaration
1200 // if one of them is hidden.
1201 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1202 continue;
1203
1204 // If either declaration was introduced by a using declaration,
1205 // we'll need to use slightly different rules for matching.
1206 // Essentially, these rules are the normal rules, except that
1207 // function templates hide function templates with different
1208 // return types or template parameter lists.
1209 bool UseMemberUsingDeclRules =
1210 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1211 !New->getFriendObjectKind();
1212
1213 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1214 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1215 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1216 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1217 continue;
1218 }
1219
1220 if (!isa<FunctionTemplateDecl>(OldD) &&
1221 !shouldLinkPossiblyHiddenDecl(*I, New))
1222 continue;
1223
1224 Match = *I;
1225 return Ovl_Match;
1226 }
1227
1228 // Builtins that have custom typechecking or have a reference should
1229 // not be overloadable or redeclarable.
1230 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1231 Match = *I;
1232 return Ovl_NonFunction;
1233 }
1234 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1235 // We can overload with these, which can show up when doing
1236 // redeclaration checks for UsingDecls.
1237 assert(Old.getLookupKind() == LookupUsingDeclName);
1238 } else if (isa<TagDecl>(OldD)) {
1239 // We can always overload with tags by hiding them.
1240 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1241 // Optimistically assume that an unresolved using decl will
1242 // overload; if it doesn't, we'll have to diagnose during
1243 // template instantiation.
1244 //
1245 // Exception: if the scope is dependent and this is not a class
1246 // member, the using declaration can only introduce an enumerator.
1247 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1248 Match = *I;
1249 return Ovl_NonFunction;
1250 }
1251 } else {
1252 // (C++ 13p1):
1253 // Only function declarations can be overloaded; object and type
1254 // declarations cannot be overloaded.
1255 Match = *I;
1256 return Ovl_NonFunction;
1257 }
1258 }
1259
1260 // C++ [temp.friend]p1:
1261 // For a friend function declaration that is not a template declaration:
1262 // -- if the name of the friend is a qualified or unqualified template-id,
1263 // [...], otherwise
1264 // -- if the name of the friend is a qualified-id and a matching
1265 // non-template function is found in the specified class or namespace,
1266 // the friend declaration refers to that function, otherwise,
1267 // -- if the name of the friend is a qualified-id and a matching function
1268 // template is found in the specified class or namespace, the friend
1269 // declaration refers to the deduced specialization of that function
1270 // template, otherwise
1271 // -- the name shall be an unqualified-id [...]
1272 // If we get here for a qualified friend declaration, we've just reached the
1273 // third bullet. If the type of the friend is dependent, skip this lookup
1274 // until instantiation.
1275 if (New->getFriendObjectKind() && New->getQualifier() &&
1278 !New->getType()->isDependentType()) {
1279 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1280 TemplateSpecResult.addAllDecls(Old);
1281 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1282 /*QualifiedFriend*/true)) {
1283 New->setInvalidDecl();
1284 return Ovl_Overload;
1285 }
1286
1287 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1288 return Ovl_Match;
1289 }
1290
1291 return Ovl_Overload;
1292}
1293
1294static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1295 FunctionDecl *Old,
1296 bool UseMemberUsingDeclRules,
1297 bool ConsiderCudaAttrs,
1298 bool UseOverrideRules = false) {
1299 // C++ [basic.start.main]p2: This function shall not be overloaded.
1300 if (New->isMain())
1301 return false;
1302
1303 // MSVCRT user defined entry points cannot be overloaded.
1304 if (New->isMSVCRTEntryPoint())
1305 return false;
1306
1307 NamedDecl *OldDecl = Old;
1308 NamedDecl *NewDecl = New;
1311
1312 // C++ [temp.fct]p2:
1313 // A function template can be overloaded with other function templates
1314 // and with normal (non-template) functions.
1315 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1316 return true;
1317
1318 // Is the function New an overload of the function Old?
1319 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1320 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1321
1322 // Compare the signatures (C++ 1.3.10) of the two functions to
1323 // determine whether they are overloads. If we find any mismatch
1324 // in the signature, they are overloads.
1325
1326 // If either of these functions is a K&R-style function (no
1327 // prototype), then we consider them to have matching signatures.
1328 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1329 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1330 return false;
1331
1332 const auto *OldType = cast<FunctionProtoType>(OldQType);
1333 const auto *NewType = cast<FunctionProtoType>(NewQType);
1334
1335 // The signature of a function includes the types of its
1336 // parameters (C++ 1.3.10), which includes the presence or absence
1337 // of the ellipsis; see C++ DR 357).
1338 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1339 return true;
1340
1341 // For member-like friends, the enclosing class is part of the signature.
1342 if ((New->isMemberLikeConstrainedFriend() ||
1345 return true;
1346
1347 // Compare the parameter lists.
1348 // This can only be done once we have establish that friend functions
1349 // inhabit the same context, otherwise we might tried to instantiate
1350 // references to non-instantiated entities during constraint substitution.
1351 // GH78101.
1352 if (NewTemplate) {
1353 OldDecl = OldTemplate;
1354 NewDecl = NewTemplate;
1355 // C++ [temp.over.link]p4:
1356 // The signature of a function template consists of its function
1357 // signature, its return type and its template parameter list. The names
1358 // of the template parameters are significant only for establishing the
1359 // relationship between the template parameters and the rest of the
1360 // signature.
1361 //
1362 // We check the return type and template parameter lists for function
1363 // templates first; the remaining checks follow.
1364 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1365 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1366 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1367 bool SameReturnType = SemaRef.Context.hasSameType(
1369 // FIXME(GH58571): Match template parameter list even for non-constrained
1370 // template heads. This currently ensures that the code prior to C++20 is
1371 // not newly broken.
1372 bool ConstraintsInTemplateHead =
1375 // C++ [namespace.udecl]p11:
1376 // The set of declarations named by a using-declarator that inhabits a
1377 // class C does not include member functions and member function
1378 // templates of a base class that "correspond" to (and thus would
1379 // conflict with) a declaration of a function or function template in
1380 // C.
1381 // Comparing return types is not required for the "correspond" check to
1382 // decide whether a member introduced by a shadow declaration is hidden.
1383 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1384 !SameTemplateParameterList)
1385 return true;
1386 if (!UseMemberUsingDeclRules &&
1387 (!SameTemplateParameterList || !SameReturnType))
1388 return true;
1389 }
1390
1391 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1392 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1393
1394 int OldParamsOffset = 0;
1395 int NewParamsOffset = 0;
1396
1397 // When determining if a method is an overload from a base class, act as if
1398 // the implicit object parameter are of the same type.
1399
1400 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1402 return Q;
1403
1404 // We do not allow overloading based off of '__restrict'.
1405 Q.removeRestrict();
1406
1407 // We may not have applied the implicit const for a constexpr member
1408 // function yet (because we haven't yet resolved whether this is a static
1409 // or non-static member function). Add it now, on the assumption that this
1410 // is a redeclaration of OldMethod.
1411 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1412 (M->isConstexpr() || M->isConsteval()) &&
1413 !isa<CXXConstructorDecl>(NewMethod))
1414 Q.addConst();
1415 return Q;
1416 };
1417
1418 auto CompareType = [&](QualType Base, QualType D) {
1419 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1420 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1421
1422 auto DS = D.getNonReferenceType().getCanonicalType().split();
1423 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1424
1425 if (BS.Quals != DS.Quals)
1426 return false;
1427
1428 if (OldMethod->isImplicitObjectMemberFunction() &&
1429 OldMethod->getParent() != NewMethod->getParent()) {
1430 QualType ParentType =
1431 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1433 if (ParentType.getTypePtr() != BS.Ty)
1434 return false;
1435 BS.Ty = DS.Ty;
1436 }
1437
1438 // FIXME: should we ignore some type attributes here?
1439 if (BS.Ty != DS.Ty)
1440 return false;
1441
1442 if (Base->isLValueReferenceType())
1443 return D->isLValueReferenceType();
1444 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1445 };
1446
1447 // If the function is a class member, its signature includes the
1448 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1449 auto DiagnoseInconsistentRefQualifiers = [&]() {
1450 if (SemaRef.LangOpts.CPlusPlus23)
1451 return false;
1452 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1453 return false;
1454 if (OldMethod->isExplicitObjectMemberFunction() ||
1455 NewMethod->isExplicitObjectMemberFunction())
1456 return false;
1457 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1458 NewMethod->getRefQualifier() == RQ_None)) {
1459 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1460 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1461 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1462 return true;
1463 }
1464 return false;
1465 };
1466
1467 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1468 OldParamsOffset++;
1469 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1470 NewParamsOffset++;
1471
1472 if (OldType->getNumParams() - OldParamsOffset !=
1473 NewType->getNumParams() - NewParamsOffset ||
1475 {OldType->param_type_begin() + OldParamsOffset,
1476 OldType->param_type_end()},
1477 {NewType->param_type_begin() + NewParamsOffset,
1478 NewType->param_type_end()},
1479 nullptr)) {
1480 return true;
1481 }
1482
1483 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1484 !OldMethod->isStatic()) {
1485 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1486 const CXXMethodDecl *New) {
1487 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1488 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1489
1490 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1491 return F->getRefQualifier() == RQ_None &&
1492 !F->isExplicitObjectMemberFunction();
1493 };
1494
1495 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1496 CompareType(OldObjectType.getNonReferenceType(),
1497 NewObjectType.getNonReferenceType()))
1498 return true;
1499 return CompareType(OldObjectType, NewObjectType);
1500 }(OldMethod, NewMethod);
1501
1502 if (!HaveCorrespondingObjectParameters) {
1503 if (DiagnoseInconsistentRefQualifiers())
1504 return true;
1505 // CWG2554
1506 // and, if at least one is an explicit object member function, ignoring
1507 // object parameters
1508 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1509 !OldMethod->isExplicitObjectMemberFunction()))
1510 return true;
1511 }
1512 }
1513
1514 if (!UseOverrideRules &&
1516 Expr *NewRC = New->getTrailingRequiresClause(),
1517 *OldRC = Old->getTrailingRequiresClause();
1518 if ((NewRC != nullptr) != (OldRC != nullptr))
1519 return true;
1520 if (NewRC &&
1521 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1522 return true;
1523 }
1524
1525 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1526 NewMethod->isImplicitObjectMemberFunction()) {
1527 if (DiagnoseInconsistentRefQualifiers())
1528 return true;
1529 }
1530
1531 // Though pass_object_size is placed on parameters and takes an argument, we
1532 // consider it to be a function-level modifier for the sake of function
1533 // identity. Either the function has one or more parameters with
1534 // pass_object_size or it doesn't.
1537 return true;
1538
1539 // enable_if attributes are an order-sensitive part of the signature.
1541 NewI = New->specific_attr_begin<EnableIfAttr>(),
1542 NewE = New->specific_attr_end<EnableIfAttr>(),
1543 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1544 OldE = Old->specific_attr_end<EnableIfAttr>();
1545 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1546 if (NewI == NewE || OldI == OldE)
1547 return true;
1548 llvm::FoldingSetNodeID NewID, OldID;
1549 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1550 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1551 if (NewID != OldID)
1552 return true;
1553 }
1554
1555 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1556 // Don't allow overloading of destructors. (In theory we could, but it
1557 // would be a giant change to clang.)
1558 if (!isa<CXXDestructorDecl>(New)) {
1559 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1560 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1561 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1562 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1563 "Unexpected invalid target.");
1564
1565 // Allow overloading of functions with same signature and different CUDA
1566 // target attributes.
1567 if (NewTarget != OldTarget)
1568 return true;
1569 }
1570 }
1571 }
1572
1573 // The signatures match; this is not an overload.
1574 return false;
1575}
1576
1578 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1579 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1580 ConsiderCudaAttrs);
1581}
1582
1584 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1585 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1586 /*UseMemberUsingDeclRules=*/false,
1587 /*ConsiderCudaAttrs=*/true,
1588 /*UseOverrideRules=*/true);
1589}
1590
1591/// Tries a user-defined conversion from From to ToType.
1592///
1593/// Produces an implicit conversion sequence for when a standard conversion
1594/// is not an option. See TryImplicitConversion for more information.
1597 bool SuppressUserConversions,
1598 AllowedExplicit AllowExplicit,
1599 bool InOverloadResolution,
1600 bool CStyle,
1601 bool AllowObjCWritebackConversion,
1602 bool AllowObjCConversionOnExplicit) {
1604
1605 if (SuppressUserConversions) {
1606 // We're not in the case above, so there is no conversion that
1607 // we can perform.
1609 return ICS;
1610 }
1611
1612 // Attempt user-defined conversion.
1613 OverloadCandidateSet Conversions(From->getExprLoc(),
1615 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1616 Conversions, AllowExplicit,
1617 AllowObjCConversionOnExplicit)) {
1618 case OR_Success:
1619 case OR_Deleted:
1620 ICS.setUserDefined();
1621 // C++ [over.ics.user]p4:
1622 // A conversion of an expression of class type to the same class
1623 // type is given Exact Match rank, and a conversion of an
1624 // expression of class type to a base class of that type is
1625 // given Conversion rank, in spite of the fact that a copy
1626 // constructor (i.e., a user-defined conversion function) is
1627 // called for those cases.
1628 if (CXXConstructorDecl *Constructor
1629 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1630 QualType FromCanon
1632 QualType ToCanon
1634 if (Constructor->isCopyConstructor() &&
1635 (FromCanon == ToCanon ||
1636 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1637 // Turn this into a "standard" conversion sequence, so that it
1638 // gets ranked with standard conversion sequences.
1640 ICS.setStandard();
1642 ICS.Standard.setFromType(From->getType());
1643 ICS.Standard.setAllToTypes(ToType);
1644 ICS.Standard.CopyConstructor = Constructor;
1645 ICS.Standard.FoundCopyConstructor = Found;
1646 if (ToCanon != FromCanon)
1648 }
1649 }
1650 break;
1651
1652 case OR_Ambiguous:
1653 ICS.setAmbiguous();
1654 ICS.Ambiguous.setFromType(From->getType());
1655 ICS.Ambiguous.setToType(ToType);
1656 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1657 Cand != Conversions.end(); ++Cand)
1658 if (Cand->Best)
1659 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1660 break;
1661
1662 // Fall through.
1665 break;
1666 }
1667
1668 return ICS;
1669}
1670
1671/// TryImplicitConversion - Attempt to perform an implicit conversion
1672/// from the given expression (Expr) to the given type (ToType). This
1673/// function returns an implicit conversion sequence that can be used
1674/// to perform the initialization. Given
1675///
1676/// void f(float f);
1677/// void g(int i) { f(i); }
1678///
1679/// this routine would produce an implicit conversion sequence to
1680/// describe the initialization of f from i, which will be a standard
1681/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1682/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1683//
1684/// Note that this routine only determines how the conversion can be
1685/// performed; it does not actually perform the conversion. As such,
1686/// it will not produce any diagnostics if no conversion is available,
1687/// but will instead return an implicit conversion sequence of kind
1688/// "BadConversion".
1689///
1690/// If @p SuppressUserConversions, then user-defined conversions are
1691/// not permitted.
1692/// If @p AllowExplicit, then explicit user-defined conversions are
1693/// permitted.
1694///
1695/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1696/// writeback conversion, which allows __autoreleasing id* parameters to
1697/// be initialized with __strong id* or __weak id* arguments.
1700 bool SuppressUserConversions,
1701 AllowedExplicit AllowExplicit,
1702 bool InOverloadResolution,
1703 bool CStyle,
1704 bool AllowObjCWritebackConversion,
1705 bool AllowObjCConversionOnExplicit) {
1707 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1708 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1709 ICS.setStandard();
1710 return ICS;
1711 }
1712
1713 if (!S.getLangOpts().CPlusPlus) {
1715 return ICS;
1716 }
1717
1718 // C++ [over.ics.user]p4:
1719 // A conversion of an expression of class type to the same class
1720 // type is given Exact Match rank, and a conversion of an
1721 // expression of class type to a base class of that type is
1722 // given Conversion rank, in spite of the fact that a copy/move
1723 // constructor (i.e., a user-defined conversion function) is
1724 // called for those cases.
1725 QualType FromType = From->getType();
1726 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1727 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1728 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1729 ICS.setStandard();
1731 ICS.Standard.setFromType(FromType);
1732 ICS.Standard.setAllToTypes(ToType);
1733
1734 // We don't actually check at this point whether there is a valid
1735 // copy/move constructor, since overloading just assumes that it
1736 // exists. When we actually perform initialization, we'll find the
1737 // appropriate constructor to copy the returned object, if needed.
1738 ICS.Standard.CopyConstructor = nullptr;
1739
1740 // Determine whether this is considered a derived-to-base conversion.
1741 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1743
1744 return ICS;
1745 }
1746
1747 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1748 AllowExplicit, InOverloadResolution, CStyle,
1749 AllowObjCWritebackConversion,
1750 AllowObjCConversionOnExplicit);
1751}
1752
1755 bool SuppressUserConversions,
1756 AllowedExplicit AllowExplicit,
1757 bool InOverloadResolution,
1758 bool CStyle,
1759 bool AllowObjCWritebackConversion) {
1760 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1761 AllowExplicit, InOverloadResolution, CStyle,
1762 AllowObjCWritebackConversion,
1763 /*AllowObjCConversionOnExplicit=*/false);
1764}
1765
1766/// PerformImplicitConversion - Perform an implicit conversion of the
1767/// expression From to the type ToType. Returns the
1768/// converted expression. Flavor is the kind of conversion we're
1769/// performing, used in the error message. If @p AllowExplicit,
1770/// explicit user-defined conversions are permitted.
1772 AssignmentAction Action,
1773 bool AllowExplicit) {
1774 if (checkPlaceholderForOverload(*this, From))
1775 return ExprError();
1776
1777 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1778 bool AllowObjCWritebackConversion
1779 = getLangOpts().ObjCAutoRefCount &&
1780 (Action == AA_Passing || Action == AA_Sending);
1781 if (getLangOpts().ObjC)
1782 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1783 From->getType(), From);
1785 *this, From, ToType,
1786 /*SuppressUserConversions=*/false,
1787 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1788 /*InOverloadResolution=*/false,
1789 /*CStyle=*/false, AllowObjCWritebackConversion,
1790 /*AllowObjCConversionOnExplicit=*/false);
1791 return PerformImplicitConversion(From, ToType, ICS, Action);
1792}
1793
1794/// Determine whether the conversion from FromType to ToType is a valid
1795/// conversion that strips "noexcept" or "noreturn" off the nested function
1796/// type.
1798 QualType &ResultTy) {
1799 if (Context.hasSameUnqualifiedType(FromType, ToType))
1800 return false;
1801
1802 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1803 // or F(t noexcept) -> F(t)
1804 // where F adds one of the following at most once:
1805 // - a pointer
1806 // - a member pointer
1807 // - a block pointer
1808 // Changes here need matching changes in FindCompositePointerType.
1809 CanQualType CanTo = Context.getCanonicalType(ToType);
1810 CanQualType CanFrom = Context.getCanonicalType(FromType);
1811 Type::TypeClass TyClass = CanTo->getTypeClass();
1812 if (TyClass != CanFrom->getTypeClass()) return false;
1813 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1814 if (TyClass == Type::Pointer) {
1815 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1816 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1817 } else if (TyClass == Type::BlockPointer) {
1818 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1819 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1820 } else if (TyClass == Type::MemberPointer) {
1821 auto ToMPT = CanTo.castAs<MemberPointerType>();
1822 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1823 // A function pointer conversion cannot change the class of the function.
1824 if (ToMPT->getClass() != FromMPT->getClass())
1825 return false;
1826 CanTo = ToMPT->getPointeeType();
1827 CanFrom = FromMPT->getPointeeType();
1828 } else {
1829 return false;
1830 }
1831
1832 TyClass = CanTo->getTypeClass();
1833 if (TyClass != CanFrom->getTypeClass()) return false;
1834 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1835 return false;
1836 }
1837
1838 const auto *FromFn = cast<FunctionType>(CanFrom);
1839 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1840
1841 const auto *ToFn = cast<FunctionType>(CanTo);
1842 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1843
1844 bool Changed = false;
1845
1846 // Drop 'noreturn' if not present in target type.
1847 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1848 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1849 Changed = true;
1850 }
1851
1852 // Drop 'noexcept' if not present in target type.
1853 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1854 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1855 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1856 FromFn = cast<FunctionType>(
1857 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1858 EST_None)
1859 .getTypePtr());
1860 Changed = true;
1861 }
1862
1863 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1864 // only if the ExtParameterInfo lists of the two function prototypes can be
1865 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1867 bool CanUseToFPT, CanUseFromFPT;
1868 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1869 CanUseFromFPT, NewParamInfos) &&
1870 CanUseToFPT && !CanUseFromFPT) {
1871 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1872 ExtInfo.ExtParameterInfos =
1873 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1874 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1875 FromFPT->getParamTypes(), ExtInfo);
1876 FromFn = QT->getAs<FunctionType>();
1877 Changed = true;
1878 }
1879 }
1880
1881 if (!Changed)
1882 return false;
1883
1884 assert(QualType(FromFn, 0).isCanonical());
1885 if (QualType(FromFn, 0) != CanTo) return false;
1886
1887 ResultTy = ToType;
1888 return true;
1889}
1890
1891/// Determine whether the conversion from FromType to ToType is a valid
1892/// floating point conversion.
1893///
1894static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1895 QualType ToType) {
1896 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1897 return false;
1898 // FIXME: disable conversions between long double, __ibm128 and __float128
1899 // if their representation is different until there is back end support
1900 // We of course allow this conversion if long double is really double.
1901
1902 // Conversions between bfloat16 and float16 are currently not supported.
1903 if ((FromType->isBFloat16Type() &&
1904 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1905 (ToType->isBFloat16Type() &&
1906 (FromType->isFloat16Type() || FromType->isHalfType())))
1907 return false;
1908
1909 // Conversions between IEEE-quad and IBM-extended semantics are not
1910 // permitted.
1911 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1912 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1913 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1914 &ToSem == &llvm::APFloat::IEEEquad()) ||
1915 (&FromSem == &llvm::APFloat::IEEEquad() &&
1916 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1917 return false;
1918 return true;
1919}
1920
1921static bool IsVectorElementConversion(Sema &S, QualType FromType,
1922 QualType ToType,
1923 ImplicitConversionKind &ICK, Expr *From) {
1924 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1925 return true;
1926
1927 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1929 return true;
1930 }
1931
1932 if (IsFloatingPointConversion(S, FromType, ToType)) {
1934 return true;
1935 }
1936
1937 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1939 return true;
1940 }
1941
1942 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1944 ToType->isRealFloatingType())) {
1946 return true;
1947 }
1948
1949 if (S.IsIntegralPromotion(From, FromType, ToType)) {
1951 return true;
1952 }
1953
1954 if (FromType->isIntegralOrUnscopedEnumerationType() &&
1955 ToType->isIntegralType(S.Context)) {
1957 return true;
1958 }
1959
1960 return false;
1961}
1962
1963/// Determine whether the conversion from FromType to ToType is a valid
1964/// vector conversion.
1965///
1966/// \param ICK Will be set to the vector conversion kind, if this is a vector
1967/// conversion.
1968static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1970 ImplicitConversionKind &ElConv, Expr *From,
1971 bool InOverloadResolution, bool CStyle) {
1972 // We need at least one of these types to be a vector type to have a vector
1973 // conversion.
1974 if (!ToType->isVectorType() && !FromType->isVectorType())
1975 return false;
1976
1977 // Identical types require no conversions.
1978 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1979 return false;
1980
1981 // There are no conversions between extended vector types, only identity.
1982 if (ToType->isExtVectorType()) {
1983 if (FromType->isExtVectorType()) {
1984 // HLSL allows implicit truncation of vector types.
1985 if (S.getLangOpts().HLSL) {
1986 unsigned FromElts = FromType->getAs<VectorType>()->getNumElements();
1987 unsigned ToElts = ToType->getAs<VectorType>()->getNumElements();
1988 if (FromElts < ToElts)
1989 return false;
1990 if (FromElts == ToElts)
1991 ICK = ICK_Identity;
1992 else
1994
1995 QualType FromElTy = FromType->getAs<VectorType>()->getElementType();
1996 QualType ToElTy = ToType->getAs<VectorType>()->getElementType();
1997 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
1998 return true;
1999 return IsVectorElementConversion(S, FromElTy, ToElTy, ElConv, From);
2000 }
2001 // There are no conversions between extended vector types other than the
2002 // identity conversion.
2003 return false;
2004 }
2005
2006 // Vector splat from any arithmetic type to a vector.
2007 if (FromType->isArithmeticType()) {
2008 ICK = ICK_Vector_Splat;
2009 return true;
2010 }
2011 }
2012
2013 if (ToType->isSVESizelessBuiltinType() ||
2014 FromType->isSVESizelessBuiltinType())
2015 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2016 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2018 return true;
2019 }
2020
2021 if (ToType->isRVVSizelessBuiltinType() ||
2022 FromType->isRVVSizelessBuiltinType())
2023 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2024 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2026 return true;
2027 }
2028
2029 // We can perform the conversion between vector types in the following cases:
2030 // 1)vector types are equivalent AltiVec and GCC vector types
2031 // 2)lax vector conversions are permitted and the vector types are of the
2032 // same size
2033 // 3)the destination type does not have the ARM MVE strict-polymorphism
2034 // attribute, which inhibits lax vector conversion for overload resolution
2035 // only
2036 if (ToType->isVectorType() && FromType->isVectorType()) {
2037 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2038 (S.isLaxVectorConversion(FromType, ToType) &&
2039 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2040 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2041 S.isLaxVectorConversion(FromType, ToType) &&
2042 S.anyAltivecTypes(FromType, ToType) &&
2043 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2044 !InOverloadResolution && !CStyle) {
2045 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2046 << FromType << ToType;
2047 }
2049 return true;
2050 }
2051 }
2052
2053 return false;
2054}
2055
2056static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2057 bool InOverloadResolution,
2059 bool CStyle);
2060
2061/// IsStandardConversion - Determines whether there is a standard
2062/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2063/// expression From to the type ToType. Standard conversion sequences
2064/// only consider non-class types; for conversions that involve class
2065/// types, use TryImplicitConversion. If a conversion exists, SCS will
2066/// contain the standard conversion sequence required to perform this
2067/// conversion and this routine will return true. Otherwise, this
2068/// routine will return false and the value of SCS is unspecified.
2069static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2070 bool InOverloadResolution,
2072 bool CStyle,
2073 bool AllowObjCWritebackConversion) {
2074 QualType FromType = From->getType();
2075
2076 // Standard conversions (C++ [conv])
2078 SCS.IncompatibleObjC = false;
2079 SCS.setFromType(FromType);
2080 SCS.CopyConstructor = nullptr;
2081
2082 // There are no standard conversions for class types in C++, so
2083 // abort early. When overloading in C, however, we do permit them.
2084 if (S.getLangOpts().CPlusPlus &&
2085 (FromType->isRecordType() || ToType->isRecordType()))
2086 return false;
2087
2088 // The first conversion can be an lvalue-to-rvalue conversion,
2089 // array-to-pointer conversion, or function-to-pointer conversion
2090 // (C++ 4p1).
2091
2092 if (FromType == S.Context.OverloadTy) {
2093 DeclAccessPair AccessPair;
2094 if (FunctionDecl *Fn
2095 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2096 AccessPair)) {
2097 // We were able to resolve the address of the overloaded function,
2098 // so we can convert to the type of that function.
2099 FromType = Fn->getType();
2100 SCS.setFromType(FromType);
2101
2102 // we can sometimes resolve &foo<int> regardless of ToType, so check
2103 // if the type matches (identity) or we are converting to bool
2105 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2106 QualType resultTy;
2107 // if the function type matches except for [[noreturn]], it's ok
2108 if (!S.IsFunctionConversion(FromType,
2109 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2110 // otherwise, only a boolean conversion is standard
2111 if (!ToType->isBooleanType())
2112 return false;
2113 }
2114
2115 // Check if the "from" expression is taking the address of an overloaded
2116 // function and recompute the FromType accordingly. Take advantage of the
2117 // fact that non-static member functions *must* have such an address-of
2118 // expression.
2119 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2120 if (Method && !Method->isStatic() &&
2121 !Method->isExplicitObjectMemberFunction()) {
2122 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2123 "Non-unary operator on non-static member address");
2124 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2125 == UO_AddrOf &&
2126 "Non-address-of operator on non-static member address");
2127 const Type *ClassType
2129 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2130 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2131 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2132 UO_AddrOf &&
2133 "Non-address-of operator for overloaded function expression");
2134 FromType = S.Context.getPointerType(FromType);
2135 }
2136 } else {
2137 return false;
2138 }
2139 }
2140 // Lvalue-to-rvalue conversion (C++11 4.1):
2141 // A glvalue (3.10) of a non-function, non-array type T can
2142 // be converted to a prvalue.
2143 bool argIsLValue = From->isGLValue();
2144 if (argIsLValue && !FromType->canDecayToPointerType() &&
2145 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2147
2148 // C11 6.3.2.1p2:
2149 // ... if the lvalue has atomic type, the value has the non-atomic version
2150 // of the type of the lvalue ...
2151 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2152 FromType = Atomic->getValueType();
2153
2154 // If T is a non-class type, the type of the rvalue is the
2155 // cv-unqualified version of T. Otherwise, the type of the rvalue
2156 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2157 // just strip the qualifiers because they don't matter.
2158 FromType = FromType.getUnqualifiedType();
2159 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2160 ToType->isArrayParameterType()) {
2161 // HLSL constant array parameters do not decay, so if the argument is a
2162 // constant array and the parameter is an ArrayParameterType we have special
2163 // handling here.
2164 FromType = S.Context.getArrayParameterType(FromType);
2165 if (S.Context.getCanonicalType(FromType) !=
2166 S.Context.getCanonicalType(ToType))
2167 return false;
2168
2170 SCS.setAllToTypes(ToType);
2171 return true;
2172 } else if (FromType->isArrayType()) {
2173 // Array-to-pointer conversion (C++ 4.2)
2175
2176 // An lvalue or rvalue of type "array of N T" or "array of unknown
2177 // bound of T" can be converted to an rvalue of type "pointer to
2178 // T" (C++ 4.2p1).
2179 FromType = S.Context.getArrayDecayedType(FromType);
2180
2181 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2182 // This conversion is deprecated in C++03 (D.4)
2184
2185 // For the purpose of ranking in overload resolution
2186 // (13.3.3.1.1), this conversion is considered an
2187 // array-to-pointer conversion followed by a qualification
2188 // conversion (4.4). (C++ 4.2p2)
2189 SCS.Second = ICK_Identity;
2192 SCS.setAllToTypes(FromType);
2193 return true;
2194 }
2195 } else if (FromType->isFunctionType() && argIsLValue) {
2196 // Function-to-pointer conversion (C++ 4.3).
2198
2199 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2200 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2202 return false;
2203
2204 // An lvalue of function type T can be converted to an rvalue of
2205 // type "pointer to T." The result is a pointer to the
2206 // function. (C++ 4.3p1).
2207 FromType = S.Context.getPointerType(FromType);
2208 } else {
2209 // We don't require any conversions for the first step.
2210 SCS.First = ICK_Identity;
2211 }
2212 SCS.setToType(0, FromType);
2213
2214 // The second conversion can be an integral promotion, floating
2215 // point promotion, integral conversion, floating point conversion,
2216 // floating-integral conversion, pointer conversion,
2217 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2218 // For overloading in C, this can also be a "compatible-type"
2219 // conversion.
2220 bool IncompatibleObjC = false;
2223 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2224 // The unqualified versions of the types are the same: there's no
2225 // conversion to do.
2226 SCS.Second = ICK_Identity;
2227 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2228 // Integral promotion (C++ 4.5).
2230 FromType = ToType.getUnqualifiedType();
2231 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2232 // Floating point promotion (C++ 4.6).
2234 FromType = ToType.getUnqualifiedType();
2235 } else if (S.IsComplexPromotion(FromType, ToType)) {
2236 // Complex promotion (Clang extension)
2238 FromType = ToType.getUnqualifiedType();
2239 } else if (ToType->isBooleanType() &&
2240 (FromType->isArithmeticType() ||
2241 FromType->isAnyPointerType() ||
2242 FromType->isBlockPointerType() ||
2243 FromType->isMemberPointerType())) {
2244 // Boolean conversions (C++ 4.12).
2246 FromType = S.Context.BoolTy;
2247 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2248 ToType->isIntegralType(S.Context)) {
2249 // Integral conversions (C++ 4.7).
2251 FromType = ToType.getUnqualifiedType();
2252 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2253 // Complex conversions (C99 6.3.1.6)
2255 FromType = ToType.getUnqualifiedType();
2256 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2257 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2258 // Complex-real conversions (C99 6.3.1.7)
2260 FromType = ToType.getUnqualifiedType();
2261 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2262 // Floating point conversions (C++ 4.8).
2264 FromType = ToType.getUnqualifiedType();
2265 } else if ((FromType->isRealFloatingType() &&
2266 ToType->isIntegralType(S.Context)) ||
2268 ToType->isRealFloatingType())) {
2269
2270 // Floating-integral conversions (C++ 4.9).
2272 FromType = ToType.getUnqualifiedType();
2273 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2275 } else if (AllowObjCWritebackConversion &&
2276 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2278 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2279 FromType, IncompatibleObjC)) {
2280 // Pointer conversions (C++ 4.10).
2282 SCS.IncompatibleObjC = IncompatibleObjC;
2283 FromType = FromType.getUnqualifiedType();
2284 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2285 InOverloadResolution, FromType)) {
2286 // Pointer to member conversions (4.11).
2288 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, ElementICK,
2289 From, InOverloadResolution, CStyle)) {
2290 SCS.Second = SecondICK;
2291 SCS.Element = ElementICK;
2292 FromType = ToType.getUnqualifiedType();
2293 } else if (!S.getLangOpts().CPlusPlus &&
2294 S.Context.typesAreCompatible(ToType, FromType)) {
2295 // Compatible conversions (Clang extension for C function overloading)
2297 FromType = ToType.getUnqualifiedType();
2299 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2301 FromType = ToType;
2302 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2303 CStyle)) {
2304 // tryAtomicConversion has updated the standard conversion sequence
2305 // appropriately.
2306 return true;
2307 } else if (ToType->isEventT() &&
2309 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2311 FromType = ToType;
2312 } else if (ToType->isQueueT() &&
2314 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2316 FromType = ToType;
2317 } else if (ToType->isSamplerT() &&
2320 FromType = ToType;
2321 } else if ((ToType->isFixedPointType() &&
2322 FromType->isConvertibleToFixedPointType()) ||
2323 (FromType->isFixedPointType() &&
2324 ToType->isConvertibleToFixedPointType())) {
2326 FromType = ToType;
2327 } else {
2328 // No second conversion required.
2329 SCS.Second = ICK_Identity;
2330 }
2331 SCS.setToType(1, FromType);
2332
2333 // The third conversion can be a function pointer conversion or a
2334 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2335 bool ObjCLifetimeConversion;
2336 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2337 // Function pointer conversions (removing 'noexcept') including removal of
2338 // 'noreturn' (Clang extension).
2340 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2341 ObjCLifetimeConversion)) {
2343 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2344 FromType = ToType;
2345 } else {
2346 // No conversion required
2347 SCS.Third = ICK_Identity;
2348 }
2349
2350 // C++ [over.best.ics]p6:
2351 // [...] Any difference in top-level cv-qualification is
2352 // subsumed by the initialization itself and does not constitute
2353 // a conversion. [...]
2354 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2355 QualType CanonTo = S.Context.getCanonicalType(ToType);
2356 if (CanonFrom.getLocalUnqualifiedType()
2357 == CanonTo.getLocalUnqualifiedType() &&
2358 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2359 FromType = ToType;
2360 CanonFrom = CanonTo;
2361 }
2362
2363 SCS.setToType(2, FromType);
2364
2365 if (CanonFrom == CanonTo)
2366 return true;
2367
2368 // If we have not converted the argument type to the parameter type,
2369 // this is a bad conversion sequence, unless we're resolving an overload in C.
2370 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2371 return false;
2372
2373 ExprResult ER = ExprResult{From};
2376 /*Diagnose=*/false,
2377 /*DiagnoseCFAudited=*/false,
2378 /*ConvertRHS=*/false);
2379 ImplicitConversionKind SecondConv;
2380 switch (Conv) {
2381 case Sema::Compatible:
2382 SecondConv = ICK_C_Only_Conversion;
2383 break;
2384 // For our purposes, discarding qualifiers is just as bad as using an
2385 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2386 // qualifiers, as well.
2391 break;
2392 default:
2393 return false;
2394 }
2395
2396 // First can only be an lvalue conversion, so we pretend that this was the
2397 // second conversion. First should already be valid from earlier in the
2398 // function.
2399 SCS.Second = SecondConv;
2400 SCS.setToType(1, ToType);
2401
2402 // Third is Identity, because Second should rank us worse than any other
2403 // conversion. This could also be ICK_Qualification, but it's simpler to just
2404 // lump everything in with the second conversion, and we don't gain anything
2405 // from making this ICK_Qualification.
2406 SCS.Third = ICK_Identity;
2407 SCS.setToType(2, ToType);
2408 return true;
2409}
2410
2411static bool
2413 QualType &ToType,
2414 bool InOverloadResolution,
2416 bool CStyle) {
2417
2418 const RecordType *UT = ToType->getAsUnionType();
2419 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2420 return false;
2421 // The field to initialize within the transparent union.
2422 RecordDecl *UD = UT->getDecl();
2423 // It's compatible if the expression matches any of the fields.
2424 for (const auto *it : UD->fields()) {
2425 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2426 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2427 ToType = it->getType();
2428 return true;
2429 }
2430 }
2431 return false;
2432}
2433
2434/// IsIntegralPromotion - Determines whether the conversion from the
2435/// expression From (whose potentially-adjusted type is FromType) to
2436/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2437/// sets PromotedType to the promoted type.
2438bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2439 const BuiltinType *To = ToType->getAs<BuiltinType>();
2440 // All integers are built-in.
2441 if (!To) {
2442 return false;
2443 }
2444
2445 // An rvalue of type char, signed char, unsigned char, short int, or
2446 // unsigned short int can be converted to an rvalue of type int if
2447 // int can represent all the values of the source type; otherwise,
2448 // the source rvalue can be converted to an rvalue of type unsigned
2449 // int (C++ 4.5p1).
2450 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2451 !FromType->isEnumeralType()) {
2452 if ( // We can promote any signed, promotable integer type to an int
2453 (FromType->isSignedIntegerType() ||
2454 // We can promote any unsigned integer type whose size is
2455 // less than int to an int.
2456 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2457 return To->getKind() == BuiltinType::Int;
2458 }
2459
2460 return To->getKind() == BuiltinType::UInt;
2461 }
2462
2463 // C++11 [conv.prom]p3:
2464 // A prvalue of an unscoped enumeration type whose underlying type is not
2465 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2466 // following types that can represent all the values of the enumeration
2467 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2468 // unsigned int, long int, unsigned long int, long long int, or unsigned
2469 // long long int. If none of the types in that list can represent all the
2470 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2471 // type can be converted to an rvalue a prvalue of the extended integer type
2472 // with lowest integer conversion rank (4.13) greater than the rank of long
2473 // long in which all the values of the enumeration can be represented. If
2474 // there are two such extended types, the signed one is chosen.
2475 // C++11 [conv.prom]p4:
2476 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2477 // can be converted to a prvalue of its underlying type. Moreover, if
2478 // integral promotion can be applied to its underlying type, a prvalue of an
2479 // unscoped enumeration type whose underlying type is fixed can also be
2480 // converted to a prvalue of the promoted underlying type.
2481 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2482 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2483 // provided for a scoped enumeration.
2484 if (FromEnumType->getDecl()->isScoped())
2485 return false;
2486
2487 // We can perform an integral promotion to the underlying type of the enum,
2488 // even if that's not the promoted type. Note that the check for promoting
2489 // the underlying type is based on the type alone, and does not consider
2490 // the bitfield-ness of the actual source expression.
2491 if (FromEnumType->getDecl()->isFixed()) {
2492 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2493 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2494 IsIntegralPromotion(nullptr, Underlying, ToType);
2495 }
2496
2497 // We have already pre-calculated the promotion type, so this is trivial.
2498 if (ToType->isIntegerType() &&
2499 isCompleteType(From->getBeginLoc(), FromType))
2500 return Context.hasSameUnqualifiedType(
2501 ToType, FromEnumType->getDecl()->getPromotionType());
2502
2503 // C++ [conv.prom]p5:
2504 // If the bit-field has an enumerated type, it is treated as any other
2505 // value of that type for promotion purposes.
2506 //
2507 // ... so do not fall through into the bit-field checks below in C++.
2508 if (getLangOpts().CPlusPlus)
2509 return false;
2510 }
2511
2512 // C++0x [conv.prom]p2:
2513 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2514 // to an rvalue a prvalue of the first of the following types that can
2515 // represent all the values of its underlying type: int, unsigned int,
2516 // long int, unsigned long int, long long int, or unsigned long long int.
2517 // If none of the types in that list can represent all the values of its
2518 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2519 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2520 // type.
2521 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2522 ToType->isIntegerType()) {
2523 // Determine whether the type we're converting from is signed or
2524 // unsigned.
2525 bool FromIsSigned = FromType->isSignedIntegerType();
2526 uint64_t FromSize = Context.getTypeSize(FromType);
2527
2528 // The types we'll try to promote to, in the appropriate
2529 // order. Try each of these types.
2530 QualType PromoteTypes[6] = {
2531 Context.IntTy, Context.UnsignedIntTy,
2532 Context.LongTy, Context.UnsignedLongTy ,
2533 Context.LongLongTy, Context.UnsignedLongLongTy
2534 };
2535 for (int Idx = 0; Idx < 6; ++Idx) {
2536 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2537 if (FromSize < ToSize ||
2538 (FromSize == ToSize &&
2539 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2540 // We found the type that we can promote to. If this is the
2541 // type we wanted, we have a promotion. Otherwise, no
2542 // promotion.
2543 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2544 }
2545 }
2546 }
2547
2548 // An rvalue for an integral bit-field (9.6) can be converted to an
2549 // rvalue of type int if int can represent all the values of the
2550 // bit-field; otherwise, it can be converted to unsigned int if
2551 // unsigned int can represent all the values of the bit-field. If
2552 // the bit-field is larger yet, no integral promotion applies to
2553 // it. If the bit-field has an enumerated type, it is treated as any
2554 // other value of that type for promotion purposes (C++ 4.5p3).
2555 // FIXME: We should delay checking of bit-fields until we actually perform the
2556 // conversion.
2557 //
2558 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2559 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2560 // bit-fields and those whose underlying type is larger than int) for GCC
2561 // compatibility.
2562 if (From) {
2563 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2564 std::optional<llvm::APSInt> BitWidth;
2565 if (FromType->isIntegralType(Context) &&
2566 (BitWidth =
2567 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2568 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2569 ToSize = Context.getTypeSize(ToType);
2570
2571 // Are we promoting to an int from a bitfield that fits in an int?
2572 if (*BitWidth < ToSize ||
2573 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2574 return To->getKind() == BuiltinType::Int;
2575 }
2576
2577 // Are we promoting to an unsigned int from an unsigned bitfield
2578 // that fits into an unsigned int?
2579 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2580 return To->getKind() == BuiltinType::UInt;
2581 }
2582
2583 return false;
2584 }
2585 }
2586 }
2587
2588 // An rvalue of type bool can be converted to an rvalue of type int,
2589 // with false becoming zero and true becoming one (C++ 4.5p4).
2590 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2591 return true;
2592 }
2593
2594 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2595 // integral type.
2596 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2597 ToType->isIntegerType())
2598 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2599
2600 return false;
2601}
2602
2603/// IsFloatingPointPromotion - Determines whether the conversion from
2604/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2605/// returns true and sets PromotedType to the promoted type.
2607 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2608 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2609 /// An rvalue of type float can be converted to an rvalue of type
2610 /// double. (C++ 4.6p1).
2611 if (FromBuiltin->getKind() == BuiltinType::Float &&
2612 ToBuiltin->getKind() == BuiltinType::Double)
2613 return true;
2614
2615 // C99 6.3.1.5p1:
2616 // When a float is promoted to double or long double, or a
2617 // double is promoted to long double [...].
2618 if (!getLangOpts().CPlusPlus &&
2619 (FromBuiltin->getKind() == BuiltinType::Float ||
2620 FromBuiltin->getKind() == BuiltinType::Double) &&
2621 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2622 ToBuiltin->getKind() == BuiltinType::Float128 ||
2623 ToBuiltin->getKind() == BuiltinType::Ibm128))
2624 return true;
2625
2626 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2627 // or not native half types are enabled.
2628 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2629 (ToBuiltin->getKind() == BuiltinType::Float ||
2630 ToBuiltin->getKind() == BuiltinType::Double))
2631 return true;
2632
2633 // Half can be promoted to float.
2634 if (!getLangOpts().NativeHalfType &&
2635 FromBuiltin->getKind() == BuiltinType::Half &&
2636 ToBuiltin->getKind() == BuiltinType::Float)
2637 return true;
2638 }
2639
2640 return false;
2641}
2642
2643/// Determine if a conversion is a complex promotion.
2644///
2645/// A complex promotion is defined as a complex -> complex conversion
2646/// where the conversion between the underlying real types is a
2647/// floating-point or integral promotion.
2649 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2650 if (!FromComplex)
2651 return false;
2652
2653 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2654 if (!ToComplex)
2655 return false;
2656
2657 return IsFloatingPointPromotion(FromComplex->getElementType(),
2658 ToComplex->getElementType()) ||
2659 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2660 ToComplex->getElementType());
2661}
2662
2663/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2664/// the pointer type FromPtr to a pointer to type ToPointee, with the
2665/// same type qualifiers as FromPtr has on its pointee type. ToType,
2666/// if non-empty, will be a pointer to ToType that may or may not have
2667/// the right set of qualifiers on its pointee.
2668///
2669static QualType
2671 QualType ToPointee, QualType ToType,
2672 ASTContext &Context,
2673 bool StripObjCLifetime = false) {
2674 assert((FromPtr->getTypeClass() == Type::Pointer ||
2675 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2676 "Invalid similarly-qualified pointer type");
2677
2678 /// Conversions to 'id' subsume cv-qualifier conversions.
2679 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2680 return ToType.getUnqualifiedType();
2681
2682 QualType CanonFromPointee
2683 = Context.getCanonicalType(FromPtr->getPointeeType());
2684 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2685 Qualifiers Quals = CanonFromPointee.getQualifiers();
2686
2687 if (StripObjCLifetime)
2688 Quals.removeObjCLifetime();
2689
2690 // Exact qualifier match -> return the pointer type we're converting to.
2691 if (CanonToPointee.getLocalQualifiers() == Quals) {
2692 // ToType is exactly what we need. Return it.
2693 if (!ToType.isNull())
2694 return ToType.getUnqualifiedType();
2695
2696 // Build a pointer to ToPointee. It has the right qualifiers
2697 // already.
2698 if (isa<ObjCObjectPointerType>(ToType))
2699 return Context.getObjCObjectPointerType(ToPointee);
2700 return Context.getPointerType(ToPointee);
2701 }
2702
2703 // Just build a canonical type that has the right qualifiers.
2704 QualType QualifiedCanonToPointee
2705 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2706
2707 if (isa<ObjCObjectPointerType>(ToType))
2708 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2709 return Context.getPointerType(QualifiedCanonToPointee);
2710}
2711
2713 bool InOverloadResolution,
2714 ASTContext &Context) {
2715 // Handle value-dependent integral null pointer constants correctly.
2716 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2717 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2719 return !InOverloadResolution;
2720
2721 return Expr->isNullPointerConstant(Context,
2722 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2724}
2725
2726/// IsPointerConversion - Determines whether the conversion of the
2727/// expression From, which has the (possibly adjusted) type FromType,
2728/// can be converted to the type ToType via a pointer conversion (C++
2729/// 4.10). If so, returns true and places the converted type (that
2730/// might differ from ToType in its cv-qualifiers at some level) into
2731/// ConvertedType.
2732///
2733/// This routine also supports conversions to and from block pointers
2734/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2735/// pointers to interfaces. FIXME: Once we've determined the
2736/// appropriate overloading rules for Objective-C, we may want to
2737/// split the Objective-C checks into a different routine; however,
2738/// GCC seems to consider all of these conversions to be pointer
2739/// conversions, so for now they live here. IncompatibleObjC will be
2740/// set if the conversion is an allowed Objective-C conversion that
2741/// should result in a warning.
2743 bool InOverloadResolution,
2744 QualType& ConvertedType,
2745 bool &IncompatibleObjC) {
2746 IncompatibleObjC = false;
2747 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2748 IncompatibleObjC))
2749 return true;
2750
2751 // Conversion from a null pointer constant to any Objective-C pointer type.
2752 if (ToType->isObjCObjectPointerType() &&
2753 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2754 ConvertedType = ToType;
2755 return true;
2756 }
2757
2758 // Blocks: Block pointers can be converted to void*.
2759 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2760 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2761 ConvertedType = ToType;
2762 return true;
2763 }
2764 // Blocks: A null pointer constant can be converted to a block
2765 // pointer type.
2766 if (ToType->isBlockPointerType() &&
2767 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2768 ConvertedType = ToType;
2769 return true;
2770 }
2771
2772 // If the left-hand-side is nullptr_t, the right side can be a null
2773 // pointer constant.
2774 if (ToType->isNullPtrType() &&
2775 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2776 ConvertedType = ToType;
2777 return true;
2778 }
2779
2780 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2781 if (!ToTypePtr)
2782 return false;
2783
2784 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2785 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2786 ConvertedType = ToType;
2787 return true;
2788 }
2789
2790 // Beyond this point, both types need to be pointers
2791 // , including objective-c pointers.
2792 QualType ToPointeeType = ToTypePtr->getPointeeType();
2793 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2794 !getLangOpts().ObjCAutoRefCount) {
2795 ConvertedType = BuildSimilarlyQualifiedPointerType(
2796 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2797 Context);
2798 return true;
2799 }
2800 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2801 if (!FromTypePtr)
2802 return false;
2803
2804 QualType FromPointeeType = FromTypePtr->getPointeeType();
2805
2806 // If the unqualified pointee types are the same, this can't be a
2807 // pointer conversion, so don't do all of the work below.
2808 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2809 return false;
2810
2811 // An rvalue of type "pointer to cv T," where T is an object type,
2812 // can be converted to an rvalue of type "pointer to cv void" (C++
2813 // 4.10p2).
2814 if (FromPointeeType->isIncompleteOrObjectType() &&
2815 ToPointeeType->isVoidType()) {
2816 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2817 ToPointeeType,
2818 ToType, Context,
2819 /*StripObjCLifetime=*/true);
2820 return true;
2821 }
2822
2823 // MSVC allows implicit function to void* type conversion.
2824 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2825 ToPointeeType->isVoidType()) {
2826 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2827 ToPointeeType,
2828 ToType, Context);
2829 return true;
2830 }
2831
2832 // When we're overloading in C, we allow a special kind of pointer
2833 // conversion for compatible-but-not-identical pointee types.
2834 if (!getLangOpts().CPlusPlus &&
2835 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2836 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2837 ToPointeeType,
2838 ToType, Context);
2839 return true;
2840 }
2841
2842 // C++ [conv.ptr]p3:
2843 //
2844 // An rvalue of type "pointer to cv D," where D is a class type,
2845 // can be converted to an rvalue of type "pointer to cv B," where
2846 // B is a base class (clause 10) of D. If B is an inaccessible
2847 // (clause 11) or ambiguous (10.2) base class of D, a program that
2848 // necessitates this conversion is ill-formed. The result of the
2849 // conversion is a pointer to the base class sub-object of the
2850 // derived class object. The null pointer value is converted to
2851 // the null pointer value of the destination type.
2852 //
2853 // Note that we do not check for ambiguity or inaccessibility
2854 // here. That is handled by CheckPointerConversion.
2855 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2856 ToPointeeType->isRecordType() &&
2857 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2858 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2859 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2860 ToPointeeType,
2861 ToType, Context);
2862 return true;
2863 }
2864
2865 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2866 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2867 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2868 ToPointeeType,
2869 ToType, Context);
2870 return true;
2871 }
2872
2873 return false;
2874}
2875
2876/// Adopt the given qualifiers for the given type.
2878 Qualifiers TQs = T.getQualifiers();
2879
2880 // Check whether qualifiers already match.
2881 if (TQs == Qs)
2882 return T;
2883
2884 if (Qs.compatiblyIncludes(TQs))
2885 return Context.getQualifiedType(T, Qs);
2886
2887 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2888}
2889
2890/// isObjCPointerConversion - Determines whether this is an
2891/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2892/// with the same arguments and return values.
2894 QualType& ConvertedType,
2895 bool &IncompatibleObjC) {
2896 if (!getLangOpts().ObjC)
2897 return false;
2898
2899 // The set of qualifiers on the type we're converting from.
2900 Qualifiers FromQualifiers = FromType.getQualifiers();
2901
2902 // First, we handle all conversions on ObjC object pointer types.
2903 const ObjCObjectPointerType* ToObjCPtr =
2904 ToType->getAs<ObjCObjectPointerType>();
2905 const ObjCObjectPointerType *FromObjCPtr =
2906 FromType->getAs<ObjCObjectPointerType>();
2907
2908 if (ToObjCPtr && FromObjCPtr) {
2909 // If the pointee types are the same (ignoring qualifications),
2910 // then this is not a pointer conversion.
2911 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2912 FromObjCPtr->getPointeeType()))
2913 return false;
2914
2915 // Conversion between Objective-C pointers.
2916 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2917 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2918 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2919 if (getLangOpts().CPlusPlus && LHS && RHS &&
2921 FromObjCPtr->getPointeeType()))
2922 return false;
2923 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2924 ToObjCPtr->getPointeeType(),
2925 ToType, Context);
2926 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2927 return true;
2928 }
2929
2930 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2931 // Okay: this is some kind of implicit downcast of Objective-C
2932 // interfaces, which is permitted. However, we're going to
2933 // complain about it.
2934 IncompatibleObjC = true;
2935 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2936 ToObjCPtr->getPointeeType(),
2937 ToType, Context);
2938 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2939 return true;
2940 }
2941 }
2942 // Beyond this point, both types need to be C pointers or block pointers.
2943 QualType ToPointeeType;
2944 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2945 ToPointeeType = ToCPtr->getPointeeType();
2946 else if (const BlockPointerType *ToBlockPtr =
2947 ToType->getAs<BlockPointerType>()) {
2948 // Objective C++: We're able to convert from a pointer to any object
2949 // to a block pointer type.
2950 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2951 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2952 return true;
2953 }
2954 ToPointeeType = ToBlockPtr->getPointeeType();
2955 }
2956 else if (FromType->getAs<BlockPointerType>() &&
2957 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2958 // Objective C++: We're able to convert from a block pointer type to a
2959 // pointer to any object.
2960 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2961 return true;
2962 }
2963 else
2964 return false;
2965
2966 QualType FromPointeeType;
2967 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2968 FromPointeeType = FromCPtr->getPointeeType();
2969 else if (const BlockPointerType *FromBlockPtr =
2970 FromType->getAs<BlockPointerType>())
2971 FromPointeeType = FromBlockPtr->getPointeeType();
2972 else
2973 return false;
2974
2975 // If we have pointers to pointers, recursively check whether this
2976 // is an Objective-C conversion.
2977 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2978 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2979 IncompatibleObjC)) {
2980 // We always complain about this conversion.
2981 IncompatibleObjC = true;
2982 ConvertedType = Context.getPointerType(ConvertedType);
2983 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2984 return true;
2985 }
2986 // Allow conversion of pointee being objective-c pointer to another one;
2987 // as in I* to id.
2988 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2989 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2990 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2991 IncompatibleObjC)) {
2992
2993 ConvertedType = Context.getPointerType(ConvertedType);
2994 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2995 return true;
2996 }
2997
2998 // If we have pointers to functions or blocks, check whether the only
2999 // differences in the argument and result types are in Objective-C
3000 // pointer conversions. If so, we permit the conversion (but
3001 // complain about it).
3002 const FunctionProtoType *FromFunctionType
3003 = FromPointeeType->getAs<FunctionProtoType>();
3004 const FunctionProtoType *ToFunctionType
3005 = ToPointeeType->getAs<FunctionProtoType>();
3006 if (FromFunctionType && ToFunctionType) {
3007 // If the function types are exactly the same, this isn't an
3008 // Objective-C pointer conversion.
3009 if (Context.getCanonicalType(FromPointeeType)
3010 == Context.getCanonicalType(ToPointeeType))
3011 return false;
3012
3013 // Perform the quick checks that will tell us whether these
3014 // function types are obviously different.
3015 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3016 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3017 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3018 return false;
3019
3020 bool HasObjCConversion = false;
3021 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3022 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3023 // Okay, the types match exactly. Nothing to do.
3024 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3025 ToFunctionType->getReturnType(),
3026 ConvertedType, IncompatibleObjC)) {
3027 // Okay, we have an Objective-C pointer conversion.
3028 HasObjCConversion = true;
3029 } else {
3030 // Function types are too different. Abort.
3031 return false;
3032 }
3033
3034 // Check argument types.
3035 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3036 ArgIdx != NumArgs; ++ArgIdx) {
3037 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3038 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3039 if (Context.getCanonicalType(FromArgType)
3040 == Context.getCanonicalType(ToArgType)) {
3041 // Okay, the types match exactly. Nothing to do.
3042 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3043 ConvertedType, IncompatibleObjC)) {
3044 // Okay, we have an Objective-C pointer conversion.
3045 HasObjCConversion = true;
3046 } else {
3047 // Argument types are too different. Abort.
3048 return false;
3049 }
3050 }
3051
3052 if (HasObjCConversion) {
3053 // We had an Objective-C conversion. Allow this pointer
3054 // conversion, but complain about it.
3055 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3056 IncompatibleObjC = true;
3057 return true;
3058 }
3059 }
3060
3061 return false;
3062}
3063
3065 QualType& ConvertedType) {
3066 QualType ToPointeeType;
3067 if (const BlockPointerType *ToBlockPtr =
3068 ToType->getAs<BlockPointerType>())
3069 ToPointeeType = ToBlockPtr->getPointeeType();
3070 else
3071 return false;
3072
3073 QualType FromPointeeType;
3074 if (const BlockPointerType *FromBlockPtr =
3075 FromType->getAs<BlockPointerType>())
3076 FromPointeeType = FromBlockPtr->getPointeeType();
3077 else
3078 return false;
3079 // We have pointer to blocks, check whether the only
3080 // differences in the argument and result types are in Objective-C
3081 // pointer conversions. If so, we permit the conversion.
3082
3083 const FunctionProtoType *FromFunctionType
3084 = FromPointeeType->getAs<FunctionProtoType>();
3085 const FunctionProtoType *ToFunctionType
3086 = ToPointeeType->getAs<FunctionProtoType>();
3087
3088 if (!FromFunctionType || !ToFunctionType)
3089 return false;
3090
3091 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3092 return true;
3093
3094 // Perform the quick checks that will tell us whether these
3095 // function types are obviously different.
3096 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3097 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3098 return false;
3099
3100 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3101 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3102 if (FromEInfo != ToEInfo)
3103 return false;
3104
3105 bool IncompatibleObjC = false;
3106 if (Context.hasSameType(FromFunctionType->getReturnType(),
3107 ToFunctionType->getReturnType())) {
3108 // Okay, the types match exactly. Nothing to do.
3109 } else {
3110 QualType RHS = FromFunctionType->getReturnType();
3111 QualType LHS = ToFunctionType->getReturnType();
3112 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3113 !RHS.hasQualifiers() && LHS.hasQualifiers())
3114 LHS = LHS.getUnqualifiedType();
3115
3116 if (Context.hasSameType(RHS,LHS)) {
3117 // OK exact match.
3118 } else if (isObjCPointerConversion(RHS, LHS,
3119 ConvertedType, IncompatibleObjC)) {
3120 if (IncompatibleObjC)
3121 return false;
3122 // Okay, we have an Objective-C pointer conversion.
3123 }
3124 else
3125 return false;
3126 }
3127
3128 // Check argument types.
3129 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3130 ArgIdx != NumArgs; ++ArgIdx) {
3131 IncompatibleObjC = false;
3132 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3133 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3134 if (Context.hasSameType(FromArgType, ToArgType)) {
3135 // Okay, the types match exactly. Nothing to do.
3136 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3137 ConvertedType, IncompatibleObjC)) {
3138 if (IncompatibleObjC)
3139 return false;
3140 // Okay, we have an Objective-C pointer conversion.
3141 } else
3142 // Argument types are too different. Abort.
3143 return false;
3144 }
3145
3147 bool CanUseToFPT, CanUseFromFPT;
3148 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3149 CanUseToFPT, CanUseFromFPT,
3150 NewParamInfos))
3151 return false;
3152
3153 ConvertedType = ToType;
3154 return true;
3155}
3156
3157enum {
3166
3167/// Attempts to get the FunctionProtoType from a Type. Handles
3168/// MemberFunctionPointers properly.
3170 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3171 return FPT;
3172
3173 if (auto *MPT = FromType->getAs<MemberPointerType>())
3174 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3175
3176 return nullptr;
3177}
3178
3179/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3180/// function types. Catches different number of parameter, mismatch in
3181/// parameter types, and different return types.
3183 QualType FromType, QualType ToType) {
3184 // If either type is not valid, include no extra info.
3185 if (FromType.isNull() || ToType.isNull()) {
3186 PDiag << ft_default;
3187 return;
3188 }
3189
3190 // Get the function type from the pointers.
3191 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3192 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3193 *ToMember = ToType->castAs<MemberPointerType>();
3194 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3195 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3196 << QualType(FromMember->getClass(), 0);
3197 return;
3198 }
3199 FromType = FromMember->getPointeeType();
3200 ToType = ToMember->getPointeeType();
3201 }
3202
3203 if (FromType->isPointerType())
3204 FromType = FromType->getPointeeType();
3205 if (ToType->isPointerType())
3206 ToType = ToType->getPointeeType();
3207
3208 // Remove references.
3209 FromType = FromType.getNonReferenceType();
3210 ToType = ToType.getNonReferenceType();
3211
3212 // Don't print extra info for non-specialized template functions.
3213 if (FromType->isInstantiationDependentType() &&
3214 !FromType->getAs<TemplateSpecializationType>()) {
3215 PDiag << ft_default;
3216 return;
3217 }
3218
3219 // No extra info for same types.
3220 if (Context.hasSameType(FromType, ToType)) {
3221 PDiag << ft_default;
3222 return;
3223 }
3224
3225 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3226 *ToFunction = tryGetFunctionProtoType(ToType);
3227
3228 // Both types need to be function types.
3229 if (!FromFunction || !ToFunction) {
3230 PDiag << ft_default;
3231 return;
3232 }
3233
3234 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3235 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3236 << FromFunction->getNumParams();
3237 return;
3238 }
3239
3240 // Handle different parameter types.
3241 unsigned ArgPos;
3242 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3243 PDiag << ft_parameter_mismatch << ArgPos + 1
3244 << ToFunction->getParamType(ArgPos)
3245 << FromFunction->getParamType(ArgPos);
3246 return;
3247 }
3248
3249 // Handle different return type.
3250 if (!Context.hasSameType(FromFunction->getReturnType(),
3251 ToFunction->getReturnType())) {
3252 PDiag << ft_return_type << ToFunction->getReturnType()
3253 << FromFunction->getReturnType();
3254 return;
3255 }
3256
3257 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3258 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3259 << FromFunction->getMethodQuals();
3260 return;
3261 }
3262
3263 // Handle exception specification differences on canonical type (in C++17
3264 // onwards).
3265 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3266 ->isNothrow() !=
3267 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3268 ->isNothrow()) {
3269 PDiag << ft_noexcept;
3270 return;
3271 }
3272
3273 // Unable to find a difference, so add no extra info.
3274 PDiag << ft_default;
3275}
3276
3277/// FunctionParamTypesAreEqual - This routine checks two function proto types
3278/// for equality of their parameter types. Caller has already checked that
3279/// they have same number of parameters. If the parameters are different,
3280/// ArgPos will have the parameter index of the first different parameter.
3281/// If `Reversed` is true, the parameters of `NewType` will be compared in
3282/// reverse order. That's useful if one of the functions is being used as a C++20
3283/// synthesized operator overload with a reversed parameter order.
3285 ArrayRef<QualType> New, unsigned *ArgPos,
3286 bool Reversed) {
3287 assert(llvm::size(Old) == llvm::size(New) &&
3288 "Can't compare parameters of functions with different number of "
3289 "parameters!");
3290
3291 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3292 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3293 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3294
3295 // Ignore address spaces in pointee type. This is to disallow overloading
3296 // on __ptr32/__ptr64 address spaces.
3297 QualType OldType =
3298 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3299 QualType NewType =
3300 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3301
3302 if (!Context.hasSameType(OldType, NewType)) {
3303 if (ArgPos)
3304 *ArgPos = Idx;
3305 return false;
3306 }
3307 }
3308 return true;
3309}
3310
3312 const FunctionProtoType *NewType,
3313 unsigned *ArgPos, bool Reversed) {
3314 return FunctionParamTypesAreEqual(OldType->param_types(),
3315 NewType->param_types(), ArgPos, Reversed);
3316}
3317
3319 const FunctionDecl *NewFunction,
3320 unsigned *ArgPos,
3321 bool Reversed) {
3322
3323 if (OldFunction->getNumNonObjectParams() !=
3324 NewFunction->getNumNonObjectParams())
3325 return false;
3326
3327 unsigned OldIgnore =
3329 unsigned NewIgnore =
3331
3332 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3333 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3334
3335 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3336 NewPT->param_types().slice(NewIgnore),
3337 ArgPos, Reversed);
3338}
3339
3340/// CheckPointerConversion - Check the pointer conversion from the
3341/// expression From to the type ToType. This routine checks for
3342/// ambiguous or inaccessible derived-to-base pointer
3343/// conversions for which IsPointerConversion has already returned
3344/// true. It returns true and produces a diagnostic if there was an
3345/// error, or returns false otherwise.
3347 CastKind &Kind,
3348 CXXCastPath& BasePath,
3349 bool IgnoreBaseAccess,
3350 bool Diagnose) {
3351 QualType FromType = From->getType();
3352 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3353
3354 Kind = CK_BitCast;
3355
3356 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3359 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3360 DiagRuntimeBehavior(From->getExprLoc(), From,
3361 PDiag(diag::warn_impcast_bool_to_null_pointer)
3362 << ToType << From->getSourceRange());
3363 else if (!isUnevaluatedContext())
3364 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3365 << ToType << From->getSourceRange();
3366 }
3367 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3368 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3369 QualType FromPointeeType = FromPtrType->getPointeeType(),
3370 ToPointeeType = ToPtrType->getPointeeType();
3371
3372 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3373 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3374 // We must have a derived-to-base conversion. Check an
3375 // ambiguous or inaccessible conversion.
3376 unsigned InaccessibleID = 0;
3377 unsigned AmbiguousID = 0;
3378 if (Diagnose) {
3379 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3380 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3381 }
3382 if (CheckDerivedToBaseConversion(
3383 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3384 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3385 &BasePath, IgnoreBaseAccess))
3386 return true;
3387
3388 // The conversion was successful.
3389 Kind = CK_DerivedToBase;
3390 }
3391
3392 if (Diagnose && !IsCStyleOrFunctionalCast &&
3393 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3394 assert(getLangOpts().MSVCCompat &&
3395 "this should only be possible with MSVCCompat!");
3396 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3397 << From->getSourceRange();
3398 }
3399 }
3400 } else if (const ObjCObjectPointerType *ToPtrType =
3401 ToType->getAs<ObjCObjectPointerType>()) {
3402 if (const ObjCObjectPointerType *FromPtrType =
3403 FromType->getAs<ObjCObjectPointerType>()) {
3404 // Objective-C++ conversions are always okay.
3405 // FIXME: We should have a different class of conversions for the
3406 // Objective-C++ implicit conversions.
3407 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3408 return false;
3409 } else if (FromType->isBlockPointerType()) {
3410 Kind = CK_BlockPointerToObjCPointerCast;
3411 } else {
3412 Kind = CK_CPointerToObjCPointerCast;
3413 }
3414 } else if (ToType->isBlockPointerType()) {
3415 if (!FromType->isBlockPointerType())
3416 Kind = CK_AnyPointerToBlockPointerCast;
3417 }
3418
3419 // We shouldn't fall into this case unless it's valid for other
3420 // reasons.
3422 Kind = CK_NullToPointer;
3423
3424 return false;
3425}
3426
3427/// IsMemberPointerConversion - Determines whether the conversion of the
3428/// expression From, which has the (possibly adjusted) type FromType, can be
3429/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3430/// If so, returns true and places the converted type (that might differ from
3431/// ToType in its cv-qualifiers at some level) into ConvertedType.
3433 QualType ToType,
3434 bool InOverloadResolution,
3435 QualType &ConvertedType) {
3436 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3437 if (!ToTypePtr)
3438 return false;
3439
3440 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3441 if (From->isNullPointerConstant(Context,
3442 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3444 ConvertedType = ToType;
3445 return true;
3446 }
3447
3448 // Otherwise, both types have to be member pointers.
3449 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3450 if (!FromTypePtr)
3451 return false;
3452
3453 // A pointer to member of B can be converted to a pointer to member of D,
3454 // where D is derived from B (C++ 4.11p2).
3455 QualType FromClass(FromTypePtr->getClass(), 0);
3456 QualType ToClass(ToTypePtr->getClass(), 0);
3457
3458 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3459 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3460 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3461 ToClass.getTypePtr());
3462 return true;
3463 }
3464
3465 return false;
3466}
3467
3468/// CheckMemberPointerConversion - Check the member pointer conversion from the
3469/// expression From to the type ToType. This routine checks for ambiguous or
3470/// virtual or inaccessible base-to-derived member pointer conversions
3471/// for which IsMemberPointerConversion has already returned true. It returns
3472/// true and produces a diagnostic if there was an error, or returns false
3473/// otherwise.
3475 CastKind &Kind,
3476 CXXCastPath &BasePath,
3477 bool IgnoreBaseAccess) {
3478 QualType FromType = From->getType();
3479 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3480 if (!FromPtrType) {
3481 // This must be a null pointer to member pointer conversion
3482 assert(From->isNullPointerConstant(Context,
3484 "Expr must be null pointer constant!");
3485 Kind = CK_NullToMemberPointer;
3486 return false;
3487 }
3488
3489 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3490 assert(ToPtrType && "No member pointer cast has a target type "
3491 "that is not a member pointer.");
3492
3493 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3494 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3495
3496 // FIXME: What about dependent types?
3497 assert(FromClass->isRecordType() && "Pointer into non-class.");
3498 assert(ToClass->isRecordType() && "Pointer into non-class.");
3499
3500 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3501 /*DetectVirtual=*/true);
3502 bool DerivationOkay =
3503 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3504 assert(DerivationOkay &&
3505 "Should not have been called if derivation isn't OK.");
3506 (void)DerivationOkay;
3507
3508 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3509 getUnqualifiedType())) {
3510 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3511 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3512 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3513 return true;
3514 }
3515
3516 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3517 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3518 << FromClass << ToClass << QualType(VBase, 0)
3519 << From->getSourceRange();
3520 return true;
3521 }
3522
3523 if (!IgnoreBaseAccess)
3524 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3525 Paths.front(),
3526 diag::err_downcast_from_inaccessible_base);
3527
3528 // Must be a base to derived member conversion.
3529 BuildBasePathArray(Paths, BasePath);
3530 Kind = CK_BaseToDerivedMemberPointer;
3531 return false;
3532}
3533
3534/// Determine whether the lifetime conversion between the two given
3535/// qualifiers sets is nontrivial.
3537 Qualifiers ToQuals) {
3538 // Converting anything to const __unsafe_unretained is trivial.
3539 if (ToQuals.hasConst() &&
3541 return false;
3542
3543 return true;
3544}
3545
3546/// Perform a single iteration of the loop for checking if a qualification
3547/// conversion is valid.
3548///
3549/// Specifically, check whether any change between the qualifiers of \p
3550/// FromType and \p ToType is permissible, given knowledge about whether every
3551/// outer layer is const-qualified.
3553 bool CStyle, bool IsTopLevel,
3554 bool &PreviousToQualsIncludeConst,
3555 bool &ObjCLifetimeConversion) {
3556 Qualifiers FromQuals = FromType.getQualifiers();
3557 Qualifiers ToQuals = ToType.getQualifiers();
3558
3559 // Ignore __unaligned qualifier.
3560 FromQuals.removeUnaligned();
3561
3562 // Objective-C ARC:
3563 // Check Objective-C lifetime conversions.
3564 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3565 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3566 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3567 ObjCLifetimeConversion = true;
3568 FromQuals.removeObjCLifetime();
3569 ToQuals.removeObjCLifetime();
3570 } else {
3571 // Qualification conversions cannot cast between different
3572 // Objective-C lifetime qualifiers.
3573 return false;
3574 }
3575 }
3576
3577 // Allow addition/removal of GC attributes but not changing GC attributes.
3578 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3579 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3580 FromQuals.removeObjCGCAttr();
3581 ToQuals.removeObjCGCAttr();
3582 }
3583
3584 // -- for every j > 0, if const is in cv 1,j then const is in cv
3585 // 2,j, and similarly for volatile.
3586 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3587 return false;
3588
3589 // If address spaces mismatch:
3590 // - in top level it is only valid to convert to addr space that is a
3591 // superset in all cases apart from C-style casts where we allow
3592 // conversions between overlapping address spaces.
3593 // - in non-top levels it is not a valid conversion.
3594 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3595 (!IsTopLevel ||
3596 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3597 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3598 return false;
3599
3600 // -- if the cv 1,j and cv 2,j are different, then const is in
3601 // every cv for 0 < k < j.
3602 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3603 !PreviousToQualsIncludeConst)
3604 return false;
3605
3606 // The following wording is from C++20, where the result of the conversion
3607 // is T3, not T2.
3608 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3609 // "array of unknown bound of"
3610 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3611 return false;
3612
3613 // -- if the resulting P3,i is different from P1,i [...], then const is
3614 // added to every cv 3_k for 0 < k < i.
3615 if (!CStyle && FromType->isConstantArrayType() &&
3616 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3617 return false;
3618
3619 // Keep track of whether all prior cv-qualifiers in the "to" type
3620 // include const.
3621 PreviousToQualsIncludeConst =
3622 PreviousToQualsIncludeConst && ToQuals.hasConst();
3623 return true;
3624}
3625
3626/// IsQualificationConversion - Determines whether the conversion from
3627/// an rvalue of type FromType to ToType is a qualification conversion
3628/// (C++ 4.4).
3629///
3630/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3631/// when the qualification conversion involves a change in the Objective-C
3632/// object lifetime.
3633bool
3635 bool CStyle, bool &ObjCLifetimeConversion) {
3636 FromType = Context.getCanonicalType(FromType);
3637 ToType = Context.getCanonicalType(ToType);
3638 ObjCLifetimeConversion = false;
3639
3640 // If FromType and ToType are the same type, this is not a
3641 // qualification conversion.
3642 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3643 return false;
3644
3645 // (C++ 4.4p4):
3646 // A conversion can add cv-qualifiers at levels other than the first
3647 // in multi-level pointers, subject to the following rules: [...]
3648 bool PreviousToQualsIncludeConst = true;
3649 bool UnwrappedAnyPointer = false;
3650 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3652 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3653 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3654 return false;
3655 UnwrappedAnyPointer = true;
3656 }
3657
3658 // We are left with FromType and ToType being the pointee types
3659 // after unwrapping the original FromType and ToType the same number
3660 // of times. If we unwrapped any pointers, and if FromType and
3661 // ToType have the same unqualified type (since we checked
3662 // qualifiers above), then this is a qualification conversion.
3663 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3664}
3665
3666/// - Determine whether this is a conversion from a scalar type to an
3667/// atomic type.
3668///
3669/// If successful, updates \c SCS's second and third steps in the conversion
3670/// sequence to finish the conversion.
3671static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3672 bool InOverloadResolution,
3674 bool CStyle) {
3675 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3676 if (!ToAtomic)
3677 return false;
3678
3680 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3681 InOverloadResolution, InnerSCS,
3682 CStyle, /*AllowObjCWritebackConversion=*/false))
3683 return false;
3684
3685 SCS.Second = InnerSCS.Second;
3686 SCS.setToType(1, InnerSCS.getToType(1));
3687 SCS.Third = InnerSCS.Third;
3690 SCS.setToType(2, InnerSCS.getToType(2));
3691 return true;
3692}
3693
3695 CXXConstructorDecl *Constructor,
3696 QualType Type) {
3697 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3698 if (CtorType->getNumParams() > 0) {
3699 QualType FirstArg = CtorType->getParamType(0);
3700 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3701 return true;
3702 }
3703 return false;
3704}
3705
3706static OverloadingResult
3708 CXXRecordDecl *To,
3710 OverloadCandidateSet &CandidateSet,
3711 bool AllowExplicit) {
3713 for (auto *D : S.LookupConstructors(To)) {
3714 auto Info = getConstructorInfo(D);
3715 if (!Info)
3716 continue;
3717
3718 bool Usable = !Info.Constructor->isInvalidDecl() &&
3719 S.isInitListConstructor(Info.Constructor);
3720 if (Usable) {
3721 bool SuppressUserConversions = false;
3722 if (Info.ConstructorTmpl)
3723 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3724 /*ExplicitArgs*/ nullptr, From,
3725 CandidateSet, SuppressUserConversions,
3726 /*PartialOverloading*/ false,
3727 AllowExplicit);
3728 else
3729 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3730 CandidateSet, SuppressUserConversions,
3731 /*PartialOverloading*/ false, AllowExplicit);
3732 }
3733 }
3734
3735 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3736
3738 switch (auto Result =
3739 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3740 case OR_Deleted:
3741 case OR_Success: {
3742 // Record the standard conversion we used and the conversion function.
3743 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3744 QualType ThisType = Constructor->getFunctionObjectParameterType();
3745 // Initializer lists don't have conversions as such.
3747 User.HadMultipleCandidates = HadMultipleCandidates;
3748 User.ConversionFunction = Constructor;
3749 User.FoundConversionFunction = Best->FoundDecl;
3751 User.After.setFromType(ThisType);
3752 User.After.setAllToTypes(ToType);
3753 return Result;
3754 }
3755
3757 return OR_No_Viable_Function;
3758 case OR_Ambiguous:
3759 return OR_Ambiguous;
3760 }
3761
3762 llvm_unreachable("Invalid OverloadResult!");
3763}
3764
3765/// Determines whether there is a user-defined conversion sequence
3766/// (C++ [over.ics.user]) that converts expression From to the type
3767/// ToType. If such a conversion exists, User will contain the
3768/// user-defined conversion sequence that performs such a conversion
3769/// and this routine will return true. Otherwise, this routine returns
3770/// false and User is unspecified.
3771///
3772/// \param AllowExplicit true if the conversion should consider C++0x
3773/// "explicit" conversion functions as well as non-explicit conversion
3774/// functions (C++0x [class.conv.fct]p2).
3775///
3776/// \param AllowObjCConversionOnExplicit true if the conversion should
3777/// allow an extra Objective-C pointer conversion on uses of explicit
3778/// constructors. Requires \c AllowExplicit to also be set.
3779static OverloadingResult
3782 OverloadCandidateSet &CandidateSet,
3783 AllowedExplicit AllowExplicit,
3784 bool AllowObjCConversionOnExplicit) {
3785 assert(AllowExplicit != AllowedExplicit::None ||
3786 !AllowObjCConversionOnExplicit);
3788
3789 // Whether we will only visit constructors.
3790 bool ConstructorsOnly = false;
3791
3792 // If the type we are conversion to is a class type, enumerate its
3793 // constructors.
3794 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3795 // C++ [over.match.ctor]p1:
3796 // When objects of class type are direct-initialized (8.5), or
3797 // copy-initialized from an expression of the same or a
3798 // derived class type (8.5), overload resolution selects the
3799 // constructor. [...] For copy-initialization, the candidate
3800 // functions are all the converting constructors (12.3.1) of
3801 // that class. The argument list is the expression-list within
3802 // the parentheses of the initializer.
3803 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3804 (From->getType()->getAs<RecordType>() &&
3805 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3806 ConstructorsOnly = true;
3807
3808 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3809 // We're not going to find any constructors.
3810 } else if (CXXRecordDecl *ToRecordDecl
3811 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3812
3813 Expr **Args = &From;
3814 unsigned NumArgs = 1;
3815 bool ListInitializing = false;
3816 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3817 // But first, see if there is an init-list-constructor that will work.
3819 S, From, ToType, ToRecordDecl, User, CandidateSet,
3820 AllowExplicit == AllowedExplicit::All);
3822 return Result;
3823 // Never mind.
3824 CandidateSet.clear(
3826
3827 // If we're list-initializing, we pass the individual elements as
3828 // arguments, not the entire list.
3829 Args = InitList->getInits();
3830 NumArgs = InitList->getNumInits();
3831 ListInitializing = true;
3832 }
3833
3834 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3835 auto Info = getConstructorInfo(D);
3836 if (!Info)
3837 continue;
3838
3839 bool Usable = !Info.Constructor->isInvalidDecl();
3840 if (!ListInitializing)
3841 Usable = Usable && Info.Constructor->isConvertingConstructor(
3842 /*AllowExplicit*/ true);
3843 if (Usable) {
3844 bool SuppressUserConversions = !ConstructorsOnly;
3845 // C++20 [over.best.ics.general]/4.5:
3846 // if the target is the first parameter of a constructor [of class
3847 // X] and the constructor [...] is a candidate by [...] the second
3848 // phase of [over.match.list] when the initializer list has exactly
3849 // one element that is itself an initializer list, [...] and the
3850 // conversion is to X or reference to cv X, user-defined conversion
3851 // sequences are not cnosidered.
3852 if (SuppressUserConversions && ListInitializing) {
3853 SuppressUserConversions =
3854 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3855 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3856 ToType);
3857 }
3858 if (Info.ConstructorTmpl)
3860 Info.ConstructorTmpl, Info.FoundDecl,
3861 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3862 CandidateSet, SuppressUserConversions,
3863 /*PartialOverloading*/ false,
3864 AllowExplicit == AllowedExplicit::All);
3865 else
3866 // Allow one user-defined conversion when user specifies a
3867 // From->ToType conversion via an static cast (c-style, etc).
3868 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3869 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3870 SuppressUserConversions,
3871 /*PartialOverloading*/ false,
3872 AllowExplicit == AllowedExplicit::All);
3873 }
3874 }
3875 }
3876 }
3877
3878 // Enumerate conversion functions, if we're allowed to.
3879 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3880 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3881 // No conversion functions from incomplete types.
3882 } else if (const RecordType *FromRecordType =
3883 From->getType()->getAs<RecordType>()) {
3884 if (CXXRecordDecl *FromRecordDecl
3885 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3886 // Add all of the conversion functions as candidates.
3887 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3888 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3889 DeclAccessPair FoundDecl = I.getPair();
3890 NamedDecl *D = FoundDecl.getDecl();
3891 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3892 if (isa<UsingShadowDecl>(D))
3893 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3894
3895 CXXConversionDecl *Conv;
3896 FunctionTemplateDecl *ConvTemplate;
3897 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3898 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3899 else
3900 Conv = cast<CXXConversionDecl>(D);
3901
3902 if (ConvTemplate)
3904 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3905 CandidateSet, AllowObjCConversionOnExplicit,
3906 AllowExplicit != AllowedExplicit::None);
3907 else
3908 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3909 CandidateSet, AllowObjCConversionOnExplicit,
3910 AllowExplicit != AllowedExplicit::None);
3911 }
3912 }
3913 }
3914
3915 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3916
3918 switch (auto Result =
3919 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3920 case OR_Success:
3921 case OR_Deleted:
3922 // Record the standard conversion we used and the conversion function.
3923 if (CXXConstructorDecl *Constructor
3924 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3925 // C++ [over.ics.user]p1:
3926 // If the user-defined conversion is specified by a
3927 // constructor (12.3.1), the initial standard conversion
3928 // sequence converts the source type to the type required by
3929 // the argument of the constructor.
3930 //
3931 if (isa<InitListExpr>(From)) {
3932 // Initializer lists don't have conversions as such.
3934 } else {
3935 if (Best->Conversions[0].isEllipsis())
3936 User.EllipsisConversion = true;
3937 else {
3938 User.Before = Best->Conversions[0].Standard;
3939 User.EllipsisConversion = false;
3940 }
3941 }
3942 User.HadMultipleCandidates = HadMultipleCandidates;
3943 User.ConversionFunction = Constructor;
3944 User.FoundConversionFunction = Best->FoundDecl;
3946 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3947 User.After.setAllToTypes(ToType);
3948 return Result;
3949 }
3950 if (CXXConversionDecl *Conversion
3951 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3952 // C++ [over.ics.user]p1:
3953 //
3954 // [...] If the user-defined conversion is specified by a
3955 // conversion function (12.3.2), the initial standard
3956 // conversion sequence converts the source type to the
3957 // implicit object parameter of the conversion function.
3958 User.Before = Best->Conversions[0].Standard;
3959 User.HadMultipleCandidates = HadMultipleCandidates;
3960 User.ConversionFunction = Conversion;
3961 User.FoundConversionFunction = Best->FoundDecl;
3962 User.EllipsisConversion = false;
3963
3964 // C++ [over.ics.user]p2:
3965 // The second standard conversion sequence converts the
3966 // result of the user-defined conversion to the target type
3967 // for the sequence. Since an implicit conversion sequence
3968 // is an initialization, the special rules for
3969 // initialization by user-defined conversion apply when
3970 // selecting the best user-defined conversion for a
3971 // user-defined conversion sequence (see 13.3.3 and
3972 // 13.3.3.1).
3973 User.After = Best->FinalConversion;
3974 return Result;
3975 }
3976 llvm_unreachable("Not a constructor or conversion function?");
3977
3979 return OR_No_Viable_Function;
3980
3981 case OR_Ambiguous:
3982 return OR_Ambiguous;
3983 }
3984
3985 llvm_unreachable("Invalid OverloadResult!");
3986}
3987
3988bool
3991 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3993 OverloadingResult OvResult =
3994 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3995 CandidateSet, AllowedExplicit::None, false);
3996
3997 if (!(OvResult == OR_Ambiguous ||
3998 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3999 return false;
4000
4001 auto Cands = CandidateSet.CompleteCandidates(
4002 *this,
4004 From);
4005 if (OvResult == OR_Ambiguous)
4006 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4007 << From->getType() << ToType << From->getSourceRange();
4008 else { // OR_No_Viable_Function && !CandidateSet.empty()
4009 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4010 diag::err_typecheck_nonviable_condition_incomplete,
4011 From->getType(), From->getSourceRange()))
4012 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4013 << false << From->getType() << From->getSourceRange() << ToType;
4014 }
4015
4016 CandidateSet.NoteCandidates(
4017 *this, From, Cands);
4018 return true;
4019}
4020
4021// Helper for compareConversionFunctions that gets the FunctionType that the
4022// conversion-operator return value 'points' to, or nullptr.
4023static const FunctionType *
4025 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4026 const PointerType *RetPtrTy =
4027 ConvFuncTy->getReturnType()->getAs<PointerType>();
4028
4029 if (!RetPtrTy)
4030 return nullptr;
4031
4032 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4033}
4034
4035/// Compare the user-defined conversion functions or constructors
4036/// of two user-defined conversion sequences to determine whether any ordering
4037/// is possible.
4040 FunctionDecl *Function2) {
4041 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4042 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4043 if (!Conv1 || !Conv2)
4045
4046 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4048
4049 // Objective-C++:
4050 // If both conversion functions are implicitly-declared conversions from
4051 // a lambda closure type to a function pointer and a block pointer,
4052 // respectively, always prefer the conversion to a function pointer,
4053 // because the function pointer is more lightweight and is more likely
4054 // to keep code working.
4055 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4056 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4057 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4058 if (Block1 != Block2)
4059 return Block1 ? ImplicitConversionSequence::Worse
4061 }
4062
4063 // In order to support multiple calling conventions for the lambda conversion
4064 // operator (such as when the free and member function calling convention is
4065 // different), prefer the 'free' mechanism, followed by the calling-convention
4066 // of operator(). The latter is in place to support the MSVC-like solution of
4067 // defining ALL of the possible conversions in regards to calling-convention.
4068 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4069 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4070
4071 if (Conv1FuncRet && Conv2FuncRet &&
4072 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4073 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4074 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4075
4076 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4077 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4078
4079 CallingConv CallOpCC =
4080 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4082 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4084 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4085
4086 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4087 for (CallingConv CC : PrefOrder) {
4088 if (Conv1CC == CC)
4090 if (Conv2CC == CC)
4092 }
4093 }
4094
4096}
4097
4099 const ImplicitConversionSequence &ICS) {
4101 (ICS.isUserDefined() &&
4103}
4104
4105/// CompareImplicitConversionSequences - Compare two implicit
4106/// conversion sequences to determine whether one is better than the
4107/// other or if they are indistinguishable (C++ 13.3.3.2).
4110 const ImplicitConversionSequence& ICS1,
4111 const ImplicitConversionSequence& ICS2)
4112{
4113 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4114 // conversion sequences (as defined in 13.3.3.1)
4115 // -- a standard conversion sequence (13.3.3.1.1) is a better
4116 // conversion sequence than a user-defined conversion sequence or
4117 // an ellipsis conversion sequence, and
4118 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4119 // conversion sequence than an ellipsis conversion sequence
4120 // (13.3.3.1.3).
4121 //
4122 // C++0x [over.best.ics]p10:
4123 // For the purpose of ranking implicit conversion sequences as
4124 // described in 13.3.3.2, the ambiguous conversion sequence is
4125 // treated as a user-defined sequence that is indistinguishable
4126 // from any other user-defined conversion sequence.
4127
4128 // String literal to 'char *' conversion has been deprecated in C++03. It has
4129 // been removed from C++11. We still accept this conversion, if it happens at
4130 // the best viable function. Otherwise, this conversion is considered worse
4131 // than ellipsis conversion. Consider this as an extension; this is not in the
4132 // standard. For example:
4133 //
4134 // int &f(...); // #1
4135 // void f(char*); // #2
4136 // void g() { int &r = f("foo"); }
4137 //
4138 // In C++03, we pick #2 as the best viable function.
4139 // In C++11, we pick #1 as the best viable function, because ellipsis
4140 // conversion is better than string-literal to char* conversion (since there
4141 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4142 // convert arguments, #2 would be the best viable function in C++11.
4143 // If the best viable function has this conversion, a warning will be issued
4144 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4145
4146 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4149 // Ill-formedness must not differ
4150 ICS1.isBad() == ICS2.isBad())
4154
4155 if (ICS1.getKindRank() < ICS2.getKindRank())
4157 if (ICS2.getKindRank() < ICS1.getKindRank())
4159
4160 // The following checks require both conversion sequences to be of
4161 // the same kind.
4162 if (ICS1.getKind() != ICS2.getKind())
4164
4167
4168 // Two implicit conversion sequences of the same form are
4169 // indistinguishable conversion sequences unless one of the
4170 // following rules apply: (C++ 13.3.3.2p3):
4171
4172 // List-initialization sequence L1 is a better conversion sequence than
4173 // list-initialization sequence L2 if:
4174 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4175 // if not that,
4176 // — L1 and L2 convert to arrays of the same element type, and either the
4177 // number of elements n_1 initialized by L1 is less than the number of
4178 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4179 // an array of unknown bound and L1 does not,
4180 // even if one of the other rules in this paragraph would otherwise apply.
4181 if (!ICS1.isBad()) {
4182 bool StdInit1 = false, StdInit2 = false;
4185 nullptr);
4188 nullptr);
4189 if (StdInit1 != StdInit2)
4190 return StdInit1 ? ImplicitConversionSequence::Better
4192
4195 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4197 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4199 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4200 CAT2->getElementType())) {
4201 // Both to arrays of the same element type
4202 if (CAT1->getSize() != CAT2->getSize())
4203 // Different sized, the smaller wins
4204 return CAT1->getSize().ult(CAT2->getSize())
4209 // One is incomplete, it loses
4213 }
4214 }
4215 }
4216
4217 if (ICS1.isStandard())
4218 // Standard conversion sequence S1 is a better conversion sequence than
4219 // standard conversion sequence S2 if [...]
4221 ICS1.Standard, ICS2.Standard);
4222 else if (ICS1.isUserDefined()) {
4223 // User-defined conversion sequence U1 is a better conversion
4224 // sequence than another user-defined conversion sequence U2 if
4225 // they contain the same user-defined conversion function or
4226 // constructor and if the second standard conversion sequence of
4227 // U1 is better than the second standard conversion sequence of
4228 // U2 (C++ 13.3.3.2p3).
4232 ICS1.UserDefined.After,
4233 ICS2.UserDefined.After);
4234 else
4238 }
4239
4240 return Result;
4241}
4242
4243// Per 13.3.3.2p3, compare the given standard conversion sequences to
4244// determine if one is a proper subset of the other.
4247 const StandardConversionSequence& SCS1,
4248 const StandardConversionSequence& SCS2) {
4251
4252 // the identity conversion sequence is considered to be a subsequence of
4253 // any non-identity conversion sequence
4254 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4256 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4258
4259 if (SCS1.Second != SCS2.Second) {
4260 if (SCS1.Second == ICK_Identity)
4262 else if (SCS2.Second == ICK_Identity)
4264 else
4266 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4268
4269 if (SCS1.Third == SCS2.Third) {
4270 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4272 }
4273
4274 if (SCS1.Third == ICK_Identity)
4278
4279 if (SCS2.Third == ICK_Identity)
4283
4285}
4286
4287/// Determine whether one of the given reference bindings is better
4288/// than the other based on what kind of bindings they are.
4289static bool
4291 const StandardConversionSequence &SCS2) {
4292 // C++0x [over.ics.rank]p3b4:
4293 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4294 // implicit object parameter of a non-static member function declared
4295 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4296 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4297 // lvalue reference to a function lvalue and S2 binds an rvalue
4298 // reference*.
4299 //
4300 // FIXME: Rvalue references. We're going rogue with the above edits,
4301 // because the semantics in the current C++0x working paper (N3225 at the
4302 // time of this writing) break the standard definition of std::forward
4303 // and std::reference_wrapper when dealing with references to functions.
4304 // Proposed wording changes submitted to CWG for consideration.
4307 return false;
4308
4309 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4310 SCS2.IsLvalueReference) ||
4313}
4314
4316 None,
4319};
4320
4321/// Returns kind of fixed enum promotion the \a SCS uses.
4322static FixedEnumPromotion
4324
4325 if (SCS.Second != ICK_Integral_Promotion)
4326 return FixedEnumPromotion::None;
4327
4328 QualType FromType = SCS.getFromType();
4329 if (!FromType->isEnumeralType())
4330 return FixedEnumPromotion::None;
4331
4332 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4333 if (!Enum->isFixed())
4334 return FixedEnumPromotion::None;
4335
4336 QualType UnderlyingType = Enum->getIntegerType();
4337 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4338 return FixedEnumPromotion::ToUnderlyingType;
4339
4340 return FixedEnumPromotion::ToPromotedUnderlyingType;
4341}
4342
4345 assert(LHS->isVectorType() == RHS->isVectorType() &&
4346 "Either both elements should be vectors or neither should.");
4347 if (const auto *VT = LHS->getAs<VectorType>())
4348 LHS = VT->getElementType();
4349
4350 if (const auto *VT = RHS->getAs<VectorType>())
4351 RHS = VT->getElementType();
4352
4353 const auto L = LHS->getAs<BuiltinType>()->getKind();
4354 const auto R = RHS->getAs<BuiltinType>()->getKind();
4355 if (L == R)
4359}
4360
4361/// CompareStandardConversionSequences - Compare two standard
4362/// conversion sequences to determine whether one is better than the
4363/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4366 const StandardConversionSequence& SCS1,
4367 const StandardConversionSequence& SCS2)
4368{
4369 // Standard conversion sequence S1 is a better conversion sequence
4370 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4371
4372 // -- S1 is a proper subsequence of S2 (comparing the conversion
4373 // sequences in the canonical form defined by 13.3.3.1.1,
4374 // excluding any Lvalue Transformation; the identity conversion
4375 // sequence is considered to be a subsequence of any
4376 // non-identity conversion sequence) or, if not that,
4379 return CK;
4380
4381 // -- the rank of S1 is better than the rank of S2 (by the rules
4382 // defined below), or, if not that,
4383 ImplicitConversionRank Rank1 = SCS1.getRank();
4384 ImplicitConversionRank Rank2 = SCS2.getRank();
4385 if (Rank1 < Rank2)
4387 else if (Rank2 < Rank1)
4389
4390 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4391 // are indistinguishable unless one of the following rules
4392 // applies:
4393
4394 // A conversion that is not a conversion of a pointer, or
4395 // pointer to member, to bool is better than another conversion
4396 // that is such a conversion.
4398 return SCS2.isPointerConversionToBool()
4401
4402 // C++14 [over.ics.rank]p4b2:
4403 // This is retroactively applied to C++11 by CWG 1601.
4404 //
4405 // A conversion that promotes an enumeration whose underlying type is fixed
4406 // to its underlying type is better than one that promotes to the promoted
4407 // underlying type, if the two are different.
4410 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4411 FEP1 != FEP2)
4412 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4415
4416 // C++ [over.ics.rank]p4b2:
4417 //
4418 // If class B is derived directly or indirectly from class A,
4419 // conversion of B* to A* is better than conversion of B* to
4420 // void*, and conversion of A* to void* is better than conversion
4421 // of B* to void*.
4422 bool SCS1ConvertsToVoid
4424 bool SCS2ConvertsToVoid
4426 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4427 // Exactly one of the conversion sequences is a conversion to
4428 // a void pointer; it's the worse conversion.
4429 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4431 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4432 // Neither conversion sequence converts to a void pointer; compare
4433 // their derived-to-base conversions.
4435 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4436 return DerivedCK;
4437 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4438 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4439 // Both conversion sequences are conversions to void
4440 // pointers. Compare the source types to determine if there's an
4441 // inheritance relationship in their sources.
4442 QualType FromType1 = SCS1.getFromType();
4443 QualType FromType2 = SCS2.getFromType();
4444
4445 // Adjust the types we're converting from via the array-to-pointer
4446 // conversion, if we need to.
4447 if (SCS1.First == ICK_Array_To_Pointer)
4448 FromType1 = S.Context.getArrayDecayedType(FromType1);
4449 if (SCS2.First == ICK_Array_To_Pointer)
4450 FromType2 = S.Context.getArrayDecayedType(FromType2);
4451
4452 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4453 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4454
4455 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4457 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4459
4460 // Objective-C++: If one interface is more specific than the
4461 // other, it is the better one.
4462 const ObjCObjectPointerType* FromObjCPtr1
4463 = FromType1->getAs<ObjCObjectPointerType>();
4464 const ObjCObjectPointerType* FromObjCPtr2
4465 = FromType2->getAs<ObjCObjectPointerType>();
4466 if (FromObjCPtr1 && FromObjCPtr2) {
4467 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4468 FromObjCPtr2);
4469 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4470 FromObjCPtr1);
4471 if (AssignLeft != AssignRight) {
4472 return AssignLeft? ImplicitConversionSequence::Better
4474 }
4475 }
4476 }
4477
4478 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4479 // Check for a better reference binding based on the kind of bindings.
4480 if (isBetterReferenceBindingKind(SCS1, SCS2))
4482 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4484 }
4485
4486 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4487 // bullet 3).
4489 = CompareQualificationConversions(S, SCS1, SCS2))
4490 return QualCK;
4491
4492 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4493 // C++ [over.ics.rank]p3b4:
4494 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4495 // which the references refer are the same type except for
4496 // top-level cv-qualifiers, and the type to which the reference
4497 // initialized by S2 refers is more cv-qualified than the type
4498 // to which the reference initialized by S1 refers.
4499 QualType T1 = SCS1.getToType(2);
4500 QualType T2 = SCS2.getToType(2);
4501 T1 = S.Context.getCanonicalType(T1);
4502 T2 = S.Context.getCanonicalType(T2);
4503 Qualifiers T1Quals, T2Quals;
4504 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4505 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4506 if (UnqualT1 == UnqualT2) {
4507 // Objective-C++ ARC: If the references refer to objects with different
4508 // lifetimes, prefer bindings that don't change lifetime.
4514 }
4515
4516 // If the type is an array type, promote the element qualifiers to the
4517 // type for comparison.
4518 if (isa<ArrayType>(T1) && T1Quals)
4519 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4520 if (isa<ArrayType>(T2) && T2Quals)
4521 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4522 if (T2.isMoreQualifiedThan(T1))
4524 if (T1.isMoreQualifiedThan(T2))
4526 }
4527 }
4528
4529 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4530 // floating-to-integral conversion if the integral conversion
4531 // is between types of the same size.
4532 // For example:
4533 // void f(float);
4534 // void f(int);
4535 // int main {
4536 // long a;
4537 // f(a);
4538 // }
4539 // Here, MSVC will call f(int) instead of generating a compile error
4540 // as clang will do in standard mode.
4541 if (S.getLangOpts().MSVCCompat &&
4544 SCS2.Second == ICK_Floating_Integral &&
4545 S.Context.getTypeSize(SCS1.getFromType()) ==
4546 S.Context.getTypeSize(SCS1.getToType(2)))
4548
4549 // Prefer a compatible vector conversion over a lax vector conversion
4550 // For example:
4551 //
4552 // typedef float __v4sf __attribute__((__vector_size__(16)));
4553 // void f(vector float);
4554 // void f(vector signed int);
4555 // int main() {
4556 // __v4sf a;
4557 // f(a);
4558 // }
4559 // Here, we'd like to choose f(vector float) and not
4560 // report an ambiguous call error
4561 if (SCS1.Second == ICK_Vector_Conversion &&
4562 SCS2.Second == ICK_Vector_Conversion) {
4563 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4564 SCS1.getFromType(), SCS1.getToType(2));
4565 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4566 SCS2.getFromType(), SCS2.getToType(2));
4567
4568 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4569 return SCS1IsCompatibleVectorConversion
4572 }
4573
4574 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4576 bool SCS1IsCompatibleSVEVectorConversion =
4578 bool SCS2IsCompatibleSVEVectorConversion =
4580
4581 if (SCS1IsCompatibleSVEVectorConversion !=
4582 SCS2IsCompatibleSVEVectorConversion)
4583 return SCS1IsCompatibleSVEVectorConversion
4586 }
4587
4588 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4590 bool SCS1IsCompatibleRVVVectorConversion =
4592 bool SCS2IsCompatibleRVVVectorConversion =
4594
4595 if (SCS1IsCompatibleRVVVectorConversion !=
4596 SCS2IsCompatibleRVVVectorConversion)
4597 return SCS1IsCompatibleRVVVectorConversion
4600 }
4601
4602 if (S.getLangOpts().HLSL) {
4603 // On a promotion we prefer the lower rank to disambiguate.
4604 if ((SCS1.Second == ICK_Floating_Promotion &&
4605 SCS2.Second == ICK_Floating_Promotion) ||
4608 return HLSLCompareFloatingRank(SCS1.getToType(2), SCS2.getToType(2));
4609 // On a conversion we prefer the higher rank to disambiguate.
4610 if ((SCS1.Second == ICK_Floating_Conversion &&
4614 return HLSLCompareFloatingRank(SCS2.getToType(2), SCS1.getToType(2));
4615 }
4616
4618}
4619
4620/// CompareQualificationConversions - Compares two standard conversion
4621/// sequences to determine whether they can be ranked based on their
4622/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4625 const StandardConversionSequence& SCS1,
4626 const StandardConversionSequence& SCS2) {
4627 // C++ [over.ics.rank]p3:
4628 // -- S1 and S2 differ only in their qualification conversion and
4629 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4630 // [C++98]
4631 // [...] and the cv-qualification signature of type T1 is a proper subset
4632 // of the cv-qualification signature of type T2, and S1 is not the
4633 // deprecated string literal array-to-pointer conversion (4.2).
4634 // [C++2a]
4635 // [...] where T1 can be converted to T2 by a qualification conversion.
4636 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4637 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4639
4640 // FIXME: the example in the standard doesn't use a qualification
4641 // conversion (!)
4642 QualType T1 = SCS1.getToType(2);
4643 QualType T2 = SCS2.getToType(2);
4644 T1 = S.Context.getCanonicalType(T1);
4645 T2 = S.Context.getCanonicalType(T2);
4646 assert(!T1->isReferenceType() && !T2->isReferenceType());
4647 Qualifiers T1Quals, T2Quals;
4648 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4649 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4650
4651 // If the types are the same, we won't learn anything by unwrapping
4652 // them.
4653 if (UnqualT1 == UnqualT2)
4655
4656 // Don't ever prefer a standard conversion sequence that uses the deprecated
4657 // string literal array to pointer conversion.
4658 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4659 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4660
4661 // Objective-C++ ARC:
4662 // Prefer qualification conversions not involving a change in lifetime
4663 // to qualification conversions that do change lifetime.
4666 CanPick1 = false;
4669 CanPick2 = false;
4670
4671 bool ObjCLifetimeConversion;
4672 if (CanPick1 &&
4673 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4674 CanPick1 = false;
4675 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4676 // directions, so we can't short-cut this second check in general.
4677 if (CanPick2 &&
4678 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4679 CanPick2 = false;
4680
4681 if (CanPick1 != CanPick2)
4682 return CanPick1 ? ImplicitConversionSequence::Better
4685}
4686
4687/// CompareDerivedToBaseConversions - Compares two standard conversion
4688/// sequences to determine whether they can be ranked based on their
4689/// various kinds of derived-to-base conversions (C++
4690/// [over.ics.rank]p4b3). As part of these checks, we also look at
4691/// conversions between Objective-C interface types.
4694 const StandardConversionSequence& SCS1,
4695 const StandardConversionSequence& SCS2) {
4696 QualType FromType1 = SCS1.getFromType();
4697 QualType ToType1 = SCS1.getToType(1);
4698 QualType FromType2 = SCS2.getFromType();
4699 QualType ToType2 = SCS2.getToType(1);
4700
4701 // Adjust the types we're converting from via the array-to-pointer
4702 // conversion, if we need to.
4703 if (SCS1.First == ICK_Array_To_Pointer)
4704 FromType1 = S.Context.getArrayDecayedType(FromType1);
4705 if (SCS2.First == ICK_Array_To_Pointer)
4706 FromType2 = S.Context.getArrayDecayedType(FromType2);
4707
4708 // Canonicalize all of the types.
4709 FromType1 = S.Context.getCanonicalType(FromType1);
4710 ToType1 = S.Context.getCanonicalType(ToType1);
4711 FromType2 = S.Context.getCanonicalType(FromType2);
4712 ToType2 = S.Context.getCanonicalType(ToType2);
4713
4714 // C++ [over.ics.rank]p4b3:
4715 //
4716 // If class B is derived directly or indirectly from class A and
4717 // class C is derived directly or indirectly from B,
4718 //
4719 // Compare based on pointer conversions.
4720 if (SCS1.Second == ICK_Pointer_Conversion &&
4722 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4723 FromType1->isPointerType() && FromType2->isPointerType() &&
4724 ToType1->isPointerType() && ToType2->isPointerType()) {
4725 QualType FromPointee1 =
4726 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4727 QualType ToPointee1 =
4728 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4729 QualType FromPointee2 =
4730 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4731 QualType ToPointee2 =
4732 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4733
4734 // -- conversion of C* to B* is better than conversion of C* to A*,
4735 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4736 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4738 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4740 }
4741
4742 // -- conversion of B* to A* is better than conversion of C* to A*,
4743 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4744 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4746 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4748 }
4749 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4751 const ObjCObjectPointerType *FromPtr1
4752 = FromType1->getAs<ObjCObjectPointerType>();
4753 const ObjCObjectPointerType *FromPtr2
4754 = FromType2->getAs<ObjCObjectPointerType>();
4755 const ObjCObjectPointerType *ToPtr1
4756 = ToType1->getAs<ObjCObjectPointerType>();
4757 const ObjCObjectPointerType *ToPtr2
4758 = ToType2->getAs<ObjCObjectPointerType>();
4759
4760 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4761 // Apply the same conversion ranking rules for Objective-C pointer types
4762 // that we do for C++ pointers to class types. However, we employ the
4763 // Objective-C pseudo-subtyping relationship used for assignment of
4764 // Objective-C pointer types.
4765 bool FromAssignLeft
4766 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4767 bool FromAssignRight
4768 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4769 bool ToAssignLeft
4770 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4771 bool ToAssignRight
4772 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4773
4774 // A conversion to an a non-id object pointer type or qualified 'id'
4775 // type is better than a conversion to 'id'.
4776 if (ToPtr1->isObjCIdType() &&
4777 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4779 if (ToPtr2->isObjCIdType() &&
4780 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4782
4783 // A conversion to a non-id object pointer type is better than a
4784 // conversion to a qualified 'id' type
4785 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4787 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4789
4790 // A conversion to an a non-Class object pointer type or qualified 'Class'
4791 // type is better than a conversion to 'Class'.
4792 if (ToPtr1->isObjCClassType() &&
4793 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4795 if (ToPtr2->isObjCClassType() &&
4796 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4798
4799 // A conversion to a non-Class object pointer type is better than a
4800 // conversion to a qualified 'Class' type.
4801 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4803 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4805
4806 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4807 if (S.Context.hasSameType(FromType1, FromType2) &&
4808 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4809 (ToAssignLeft != ToAssignRight)) {
4810 if (FromPtr1->isSpecialized()) {
4811 // "conversion of B<A> * to B * is better than conversion of B * to
4812 // C *.
4813 bool IsFirstSame =
4814 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4815 bool IsSecondSame =
4816 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4817 if (IsFirstSame) {
4818 if (!IsSecondSame)
4820 } else if (IsSecondSame)
4822 }
4823 return ToAssignLeft? ImplicitConversionSequence::Worse
4825 }
4826
4827 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4828 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4829 (FromAssignLeft != FromAssignRight))
4830 return FromAssignLeft? ImplicitConversionSequence::Better
4832 }
4833 }
4834
4835 // Ranking of member-pointer types.
4836 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4837 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4838 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4839 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4840 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4841 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4842 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4843 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4844 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4845 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4846 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4847 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4848 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4849 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4850 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4851 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4852 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4853 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4855 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4857 }
4858 // conversion of B::* to C::* is better than conversion of A::* to C::*
4859 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4860 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4862 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4864 }
4865 }
4866
4867 if (SCS1.Second == ICK_Derived_To_Base) {
4868 // -- conversion of C to B is better than conversion of C to A,
4869 // -- binding of an expression of type C to a reference of type
4870 // B& is better than binding an expression of type C to a
4871 // reference of type A&,
4872 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4873 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4874 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4876 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4878 }
4879
4880 // -- conversion of B to A is better than conversion of C to A.
4881 // -- binding of an expression of type B to a reference of type
4882 // A& is better than binding an expression of type C to a
4883 // reference of type A&,
4884 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4885 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4886 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4888 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4890 }
4891 }
4892
4894}
4895
4897 if (!T.getQualifiers().hasUnaligned())
4898 return T;
4899
4900 Qualifiers Q;
4901 T = Ctx.getUnqualifiedArrayType(T, Q);
4902 Q.removeUnaligned();
4903 return Ctx.getQualifiedType(T, Q);
4904}
4905
4906/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4907/// determine whether they are reference-compatible,
4908/// reference-related, or incompatible, for use in C++ initialization by
4909/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4910/// type, and the first type (T1) is the pointee type of the reference
4911/// type being initialized.
4914 QualType OrigT1, QualType OrigT2,
4915 ReferenceConversions *ConvOut) {
4916 assert(!OrigT1->isReferenceType() &&
4917 "T1 must be the pointee type of the reference type");
4918 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4919
4920 QualType T1 = Context.getCanonicalType(OrigT1);
4921 QualType T2 = Context.getCanonicalType(OrigT2);
4922 Qualifiers T1Quals, T2Quals;
4923 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4924 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4925
4926 ReferenceConversions ConvTmp;
4927 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4928 Conv = ReferenceConversions();
4929
4930 // C++2a [dcl.init.ref]p4:
4931 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4932 // reference-related to "cv2 T2" if T1 is similar to T2, or
4933 // T1 is a base class of T2.
4934 // "cv1 T1" is reference-compatible with "cv2 T2" if
4935 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4936 // "pointer to cv1 T1" via a standard conversion sequence.
4937
4938 // Check for standard conversions we can apply to pointers: derived-to-base
4939 // conversions, ObjC pointer conversions, and function pointer conversions.
4940 // (Qualification conversions are checked last.)
4941 QualType ConvertedT2;
4942 if (UnqualT1 == UnqualT2) {
4943 // Nothing to do.
4944 } else if (isCompleteType(Loc, OrigT2) &&
4945 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4946 Conv |= ReferenceConversions::DerivedToBase;
4947 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4948 UnqualT2->isObjCObjectOrInterfaceType() &&
4949 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4950 Conv |= ReferenceConversions::ObjC;
4951 else if (UnqualT2->isFunctionType() &&
4952 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4953 Conv |= ReferenceConversions::Function;
4954 // No need to check qualifiers; function types don't have them.
4955 return Ref_Compatible;
4956 }
4957 bool ConvertedReferent = Conv != 0;
4958
4959 // We can have a qualification conversion. Compute whether the types are
4960 // similar at the same time.
4961 bool PreviousToQualsIncludeConst = true;
4962 bool TopLevel = true;
4963 do {
4964 if (T1 == T2)
4965 break;
4966
4967 // We will need a qualification conversion.
4968 Conv |= ReferenceConversions::Qualification;
4969
4970 // Track whether we performed a qualification conversion anywhere other
4971 // than the top level. This matters for ranking reference bindings in
4972 // overload resolution.
4973 if (!TopLevel)
4974 Conv |= ReferenceConversions::NestedQualification;
4975
4976 // MS compiler ignores __unaligned qualifier for references; do the same.
4977 T1 = withoutUnaligned(Context, T1);
4978 T2 = withoutUnaligned(Context, T2);
4979
4980 // If we find a qualifier mismatch, the types are not reference-compatible,
4981 // but are still be reference-related if they're similar.
4982 bool ObjCLifetimeConversion = false;
4983 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4984 PreviousToQualsIncludeConst,
4985 ObjCLifetimeConversion))
4986 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4987 ? Ref_Related
4988 : Ref_Incompatible;
4989
4990 // FIXME: Should we track this for any level other than the first?
4991 if (ObjCLifetimeConversion)
4992 Conv |= ReferenceConversions::ObjCLifetime;
4993
4994 TopLevel = false;
4995 } while (Context.UnwrapSimilarTypes(T1, T2));
4996
4997 // At this point, if the types are reference-related, we must either have the
4998 // same inner type (ignoring qualifiers), or must have already worked out how
4999 // to convert the referent.
5000 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5001 ? Ref_Compatible
5002 : Ref_Incompatible;
5003}
5004
5005/// Look for a user-defined conversion to a value reference-compatible
5006/// with DeclType. Return true if something definite is found.
5007static bool
5009 QualType DeclType, SourceLocation DeclLoc,
5010 Expr *Init, QualType T2, bool AllowRvalues,
5011 bool AllowExplicit) {
5012 assert(T2->isRecordType() && "Can only find conversions of record types.");
5013 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5014
5015 OverloadCandidateSet CandidateSet(
5017 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5018 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5019 NamedDecl *D = *I;
5020 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5021 if (isa<UsingShadowDecl>(D))
5022 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5023
5024 FunctionTemplateDecl *ConvTemplate
5025 = dyn_cast<FunctionTemplateDecl>(D);
5026 CXXConversionDecl *Conv;
5027 if (ConvTemplate)
5028 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5029 else
5030 Conv = cast<CXXConversionDecl>(D);
5031
5032 if (AllowRvalues) {
5033 // If we are initializing an rvalue reference, don't permit conversion
5034 // functions that return lvalues.
5035 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5036 const ReferenceType *RefType
5038 if (RefType && !RefType->getPointeeType()->isFunctionType())
5039 continue;
5040 }
5041
5042 if (!ConvTemplate &&
5044 DeclLoc,
5045 Conv->getConversionType()
5050 continue;
5051 } else {
5052 // If the conversion function doesn't return a reference type,
5053 // it can't be considered for this conversion. An rvalue reference
5054 // is only acceptable if its referencee is a function type.
5055
5056 const ReferenceType *RefType =
5058 if (!RefType ||
5059 (!RefType->isLValueReferenceType() &&
5060 !RefType->getPointeeType()->isFunctionType()))
5061 continue;
5062 }
5063
5064 if (ConvTemplate)
5066 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5067 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5068 else
5070 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5071 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5072 }
5073
5074 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5075
5077 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5078 case OR_Success:
5079 // C++ [over.ics.ref]p1:
5080 //
5081 // [...] If the parameter binds directly to the result of
5082 // applying a conversion function to the argument
5083 // expression, the implicit conversion sequence is a
5084 // user-defined conversion sequence (13.3.3.1.2), with the
5085 // second standard conversion sequence either an identity
5086 // conversion or, if the conversion function returns an
5087 // entity of a type that is a derived class of the parameter
5088 // type, a derived-to-base Conversion.
5089 if (!Best->FinalConversion.DirectBinding)
5090 return false;
5091
5092 ICS.setUserDefined();
5093 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5094 ICS.UserDefined.After = Best->FinalConversion;
5095 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5096 ICS.UserDefined.ConversionFunction = Best->Function;
5097 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5098 ICS.UserDefined.EllipsisConversion = false;
5099 assert(ICS.UserDefined.After.ReferenceBinding &&
5101 "Expected a direct reference binding!");
5102 return true;
5103
5104 case OR_Ambiguous:
5105 ICS.setAmbiguous();
5106 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5107 Cand != CandidateSet.end(); ++Cand)
5108 if (Cand->Best)
5109 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5110 return true;
5111
5113 case OR_Deleted:
5114 // There was no suitable conversion, or we found a deleted
5115 // conversion; continue with other checks.
5116 return false;
5117 }
5118
5119 llvm_unreachable("Invalid OverloadResult!");
5120}
5121
5122/// Compute an implicit conversion sequence for reference
5123/// initialization.
5126 SourceLocation DeclLoc,
5127 bool SuppressUserConversions,
5128 bool AllowExplicit) {
5129 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5130
5131 // Most paths end in a failed conversion.
5134
5135 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5136 QualType T2 = Init->getType();
5137
5138 // If the initializer is the address of an overloaded function, try
5139 // to resolve the overloaded function. If all goes well, T2 is the
5140 // type of the resulting function.
5141 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5142 DeclAccessPair Found;
5144 false, Found))
5145 T2 = Fn->getType();
5146 }
5147
5148 // Compute some basic properties of the types and the initializer.
5149 bool isRValRef = DeclType->isRValueReferenceType();
5150 Expr::Classification InitCategory = Init->Classify(S.Context);
5151
5153 Sema::ReferenceCompareResult RefRelationship =
5154 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5155
5156 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5157 ICS.setStandard();
5159 // FIXME: A reference binding can be a function conversion too. We should
5160 // consider that when ordering reference-to-function bindings.
5161 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5163 : (RefConv & Sema::ReferenceConversions::ObjC)
5165 : ICK_Identity;
5167 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5168 // a reference binding that performs a non-top-level qualification
5169 // conversion as a qualification conversion, not as an identity conversion.
5170 ICS.Standard.Third = (RefConv &
5171 Sema::ReferenceConversions::NestedQualification)
5173 : ICK_Identity;
5174 ICS.Standard.setFromType(T2);
5175 ICS.Standard.setToType(0, T2);
5176 ICS.Standard.setToType(1, T1);
5177 ICS.Standard.setToType(2, T1);
5178 ICS.Standard.ReferenceBinding = true;
5179 ICS.Standard.DirectBinding = BindsDirectly;
5180 ICS.Standard.IsLvalueReference = !isRValRef;
5182 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5185 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5186 ICS.Standard.CopyConstructor = nullptr;
5188 };
5189
5190 // C++0x [dcl.init.ref]p5:
5191 // A reference to type "cv1 T1" is initialized by an expression
5192 // of type "cv2 T2" as follows:
5193
5194 // -- If reference is an lvalue reference and the initializer expression
5195 if (!isRValRef) {
5196 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5197 // reference-compatible with "cv2 T2," or
5198 //
5199 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5200 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5201 // C++ [over.ics.ref]p1:
5202 // When a parameter of reference type binds directly (8.5.3)
5203 // to an argument expression, the implicit conversion sequence
5204 // is the identity conversion, unless the argument expression
5205 // has a type that is a derived class of the parameter type,
5206 // in which case the implicit conversion sequence is a
5207 // derived-to-base Conversion (13.3.3.1).
5208 SetAsReferenceBinding(/*BindsDirectly=*/true);
5209
5210 // Nothing more to do: the inaccessibility/ambiguity check for
5211 // derived-to-base conversions is suppressed when we're
5212 // computing the implicit conversion sequence (C++
5213 // [over.best.ics]p2).
5214 return ICS;
5215 }
5216
5217 // -- has a class type (i.e., T2 is a class type), where T1 is
5218 // not reference-related to T2, and can be implicitly
5219 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5220 // is reference-compatible with "cv3 T3" 92) (this
5221 // conversion is selected by enumerating the applicable
5222 // conversion functions (13.3.1.6) and choosing the best
5223 // one through overload resolution (13.3)),
5224 if (!SuppressUserConversions && T2->isRecordType() &&
5225 S.isCompleteType(DeclLoc, T2) &&
5226 RefRelationship == Sema::Ref_Incompatible) {
5227 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5228 Init, T2, /*AllowRvalues=*/false,
5229 AllowExplicit))
5230 return ICS;
5231 }
5232 }
5233
5234 // -- Otherwise, the reference shall be an lvalue reference to a
5235 // non-volatile const type (i.e., cv1 shall be const), or the reference
5236 // shall be an rvalue reference.
5237 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5238 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5240 return ICS;
5241 }
5242
5243 // -- If the initializer expression
5244 //
5245 // -- is an xvalue, class prvalue, array prvalue or function
5246 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5247 if (RefRelationship == Sema::Ref_Compatible &&
5248 (InitCategory.isXValue() ||
5249 (InitCategory.isPRValue() &&
5250 (T2->isRecordType() || T2->isArrayType())) ||
5251 (InitCategory.isLValue() && T2->isFunctionType()))) {
5252 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5253 // binding unless we're binding to a class prvalue.
5254 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5255 // allow the use of rvalue references in C++98/03 for the benefit of
5256 // standard library implementors; therefore, we need the xvalue check here.
5257 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5258 !(InitCategory.isPRValue() || T2->isRecordType()));
5259 return ICS;
5260 }
5261
5262 // -- has a class type (i.e., T2 is a class type), where T1 is not
5263 // reference-related to T2, and can be implicitly converted to
5264 // an xvalue, class prvalue, or function lvalue of type
5265 // "cv3 T3", where "cv1 T1" is reference-compatible with
5266 // "cv3 T3",
5267 //
5268 // then the reference is bound to the value of the initializer
5269 // expression in the first case and to the result of the conversion
5270 // in the second case (or, in either case, to an appropriate base
5271 // class subobject).
5272 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5273 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5274 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5275 Init, T2, /*AllowRvalues=*/true,
5276 AllowExplicit)) {
5277 // In the second case, if the reference is an rvalue reference
5278 // and the second standard conversion sequence of the
5279 // user-defined conversion sequence includes an lvalue-to-rvalue
5280 // conversion, the program is ill-formed.
5281 if (ICS.isUserDefined() && isRValRef &&
5284
5285 return ICS;
5286 }
5287
5288 // A temporary of function type cannot be created; don't even try.
5289 if (T1->isFunctionType())
5290 return ICS;
5291
5292 // -- Otherwise, a temporary of type "cv1 T1" is created and
5293 // initialized from the initializer expression using the
5294 // rules for a non-reference copy initialization (8.5). The
5295 // reference is then bound to the temporary. If T1 is
5296 // reference-related to T2, cv1 must be the same
5297 // cv-qualification as, or greater cv-qualification than,
5298 // cv2; otherwise, the program is ill-formed.
5299 if (RefRelationship == Sema::Ref_Related) {
5300 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5301 // we would be reference-compatible or reference-compatible with
5302 // added qualification. But that wasn't the case, so the reference
5303 // initialization fails.
5304 //
5305 // Note that we only want to check address spaces and cvr-qualifiers here.
5306 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5307 Qualifiers T1Quals = T1.getQualifiers();
5308 Qualifiers T2Quals = T2.getQualifiers();
5309 T1Quals.removeObjCGCAttr();
5310 T1Quals.removeObjCLifetime();
5311 T2Quals.removeObjCGCAttr();
5312 T2Quals.removeObjCLifetime();
5313 // MS compiler ignores __unaligned qualifier for references; do the same.
5314 T1Quals.removeUnaligned();
5315 T2Quals.removeUnaligned();
5316 if (!T1Quals.compatiblyIncludes(T2Quals))
5317 return ICS;
5318 }
5319
5320 // If at least one of the types is a class type, the types are not
5321 // related, and we aren't allowed any user conversions, the
5322 // reference binding fails. This case is important for breaking
5323 // recursion, since TryImplicitConversion below will attempt to
5324 // create a temporary through the use of a copy constructor.
5325 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5326 (T1->isRecordType() || T2->isRecordType()))
5327 return ICS;
5328
5329 // If T1 is reference-related to T2 and the reference is an rvalue
5330 // reference, the initializer expression shall not be an lvalue.
5331 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5332 Init->Classify(S.Context).isLValue()) {
5334 return ICS;
5335 }
5336
5337 // C++ [over.ics.ref]p2:
5338 // When a parameter of reference type is not bound directly to
5339 // an argument expression, the conversion sequence is the one
5340 // required to convert the argument expression to the
5341 // underlying type of the reference according to
5342 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5343 // to copy-initializing a temporary of the underlying type with
5344 // the argument expression. Any difference in top-level
5345 // cv-qualification is subsumed by the initialization itself
5346 // and does not constitute a conversion.
5347 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5348 AllowedExplicit::None,
5349 /*InOverloadResolution=*/false,
5350 /*CStyle=*/false,
5351 /*AllowObjCWritebackConversion=*/false,
5352 /*AllowObjCConversionOnExplicit=*/false);
5353
5354 // Of course, that's still a reference binding.
5355 if (ICS.isStandard()) {
5356 ICS.Standard.ReferenceBinding = true;
5357 ICS.Standard.IsLvalueReference = !isRValRef;
5358 ICS.Standard.BindsToFunctionLvalue = false;
5359 ICS.Standard.BindsToRvalue = true;
5362 } else if (ICS.isUserDefined()) {
5363 const ReferenceType *LValRefType =
5366
5367 // C++ [over.ics.ref]p3:
5368 // Except for an implicit object parameter, for which see 13.3.1, a
5369 // standard conversion sequence cannot be formed if it requires [...]
5370 // binding an rvalue reference to an lvalue other than a function
5371 // lvalue.
5372 // Note that the function case is not possible here.
5373 if (isRValRef && LValRefType) {
5375 return ICS;
5376 }
5377
5379 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5381 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5384 }
5385
5386 return ICS;
5387}
5388
5390TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5391 bool SuppressUserConversions,
5392 bool InOverloadResolution,
5393 bool AllowObjCWritebackConversion,
5394 bool AllowExplicit = false);
5395
5396/// TryListConversion - Try to copy-initialize a value of type ToType from the
5397/// initializer list From.
5400 bool SuppressUserConversions,
5401 bool InOverloadResolution,
5402 bool AllowObjCWritebackConversion) {
5403 // C++11 [over.ics.list]p1:
5404 // When an argument is an initializer list, it is not an expression and
5405 // special rules apply for converting it to a parameter type.
5406
5408 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5409
5410 // We need a complete type for what follows. With one C++20 exception,
5411 // incomplete types can never be initialized from init lists.
5412 QualType InitTy = ToType;
5413 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5414 if (AT && S.getLangOpts().CPlusPlus20)
5415 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5416 // C++20 allows list initialization of an incomplete array type.
5417 InitTy = IAT->getElementType();
5418 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5419 return Result;
5420
5421 // C++20 [over.ics.list]/2:
5422 // If the initializer list is a designated-initializer-list, a conversion
5423 // is only possible if the parameter has an aggregate type
5424 //
5425 // FIXME: The exception for reference initialization here is not part of the
5426 // language rules, but follow other compilers in adding it as a tentative DR
5427 // resolution.
5428 bool IsDesignatedInit = From->hasDesignatedInit();
5429 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5430 IsDesignatedInit)
5431 return Result;
5432
5433 // Per DR1467:
5434 // If the parameter type is a class X and the initializer list has a single
5435 // element of type cv U, where U is X or a class derived from X, the
5436 // implicit conversion sequence is the one required to convert the element
5437 // to the parameter type.
5438 //
5439 // Otherwise, if the parameter type is a character array [... ]
5440 // and the initializer list has a single element that is an
5441 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5442 // implicit conversion sequence is the identity conversion.
5443 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5444 if (ToType->isRecordType()) {
5445 QualType InitType = From->getInit(0)->getType();
5446 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5447 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5448 return TryCopyInitialization(S, From->getInit(0), ToType,
5449 SuppressUserConversions,
5450 InOverloadResolution,
5451 AllowObjCWritebackConversion);
5452 }
5453
5454 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5455 InitializedEntity Entity =
5457 /*Consumed=*/false);
5458 if (S.CanPerformCopyInitialization(Entity, From)) {
5459 Result.setStandard();
5460 Result.Standard.setAsIdentityConversion();
5461 Result.Standard.setFromType(ToType);
5462 Result.Standard.setAllToTypes(ToType);
5463 return Result;
5464 }
5465 }
5466 }
5467
5468 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5469 // C++11 [over.ics.list]p2:
5470 // If the parameter type is std::initializer_list<X> or "array of X" and
5471 // all the elements can be implicitly converted to X, the implicit
5472 // conversion sequence is the worst conversion necessary to convert an
5473 // element of the list to X.
5474 //
5475 // C++14 [over.ics.list]p3:
5476 // Otherwise, if the parameter type is "array of N X", if the initializer
5477 // list has exactly N elements or if it has fewer than N elements and X is
5478 // default-constructible, and if all the elements of the initializer list
5479 // can be implicitly converted to X, the implicit conversion sequence is
5480 // the worst conversion necessary to convert an element of the list to X.
5481 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5482 unsigned e = From->getNumInits();
5485 QualType());
5486 QualType ContTy = ToType;
5487 bool IsUnbounded = false;
5488 if (AT) {
5489 InitTy = AT->getElementType();
5490 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5491 if (CT->getSize().ult(e)) {
5492 // Too many inits, fatally bad
5494 ToType);
5495 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5496 return Result;
5497 }
5498 if (CT->getSize().ugt(e)) {
5499 // Need an init from empty {}, is there one?
5500 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5501 From->getEndLoc());
5502 EmptyList.setType(S.Context.VoidTy);
5503 DfltElt = TryListConversion(
5504 S, &EmptyList, InitTy, SuppressUserConversions,
5505 InOverloadResolution, AllowObjCWritebackConversion);
5506 if (DfltElt.isBad()) {
5507 // No {} init, fatally bad
5509 ToType);
5510 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5511 return Result;
5512 }
5513 }
5514 } else {
5515 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5516 IsUnbounded = true;
5517 if (!e) {
5518 // Cannot convert to zero-sized.
5520 ToType);
5521 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5522 return Result;
5523 }
5524 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5525 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5527 }
5528 }
5529
5530 Result.setStandard();
5531 Result.Standard.setAsIdentityConversion();
5532 Result.Standard.setFromType(InitTy);
5533 Result.Standard.setAllToTypes(InitTy);
5534 for (unsigned i = 0; i < e; ++i) {
5535 Expr *Init = From->getInit(i);
5537 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5538 AllowObjCWritebackConversion);
5539
5540 // Keep the worse conversion seen so far.
5541 // FIXME: Sequences are not totally ordered, so 'worse' can be
5542 // ambiguous. CWG has been informed.
5544 Result) ==
5546 Result = ICS;
5547 // Bail as soon as we find something unconvertible.
5548 if (Result.isBad()) {
5549 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5550 return Result;
5551 }
5552 }
5553 }
5554
5555 // If we needed any implicit {} initialization, compare that now.
5556 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5557 // has been informed that this might not be the best thing.
5558 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5559 S, From->getEndLoc(), DfltElt, Result) ==
5561 Result = DfltElt;
5562 // Record the type being initialized so that we may compare sequences
5563 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5564 return Result;
5565 }
5566
5567 // C++14 [over.ics.list]p4:
5568 // C++11 [over.ics.list]p3:
5569 // Otherwise, if the parameter is a non-aggregate class X and overload
5570 // resolution chooses a single best constructor [...] the implicit
5571 // conversion sequence is a user-defined conversion sequence. If multiple
5572 // constructors are viable but none is better than the others, the
5573 // implicit conversion sequence is a user-defined conversion sequence.
5574 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5575 // This function can deal with initializer lists.
5576 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5577 AllowedExplicit::None,
5578 InOverloadResolution, /*CStyle=*/false,
5579 AllowObjCWritebackConversion,
5580 /*AllowObjCConversionOnExplicit=*/false);
5581 }
5582
5583 // C++14 [over.ics.list]p5:
5584 // C++11 [over.ics.list]p4:
5585 // Otherwise, if the parameter has an aggregate type which can be
5586 // initialized from the initializer list [...] the implicit conversion
5587 // sequence is a user-defined conversion sequence.
5588 if (ToType->isAggregateType()) {
5589 // Type is an aggregate, argument is an init list. At this point it comes
5590 // down to checking whether the initialization works.
5591 // FIXME: Find out whether this parameter is consumed or not.
5592 InitializedEntity Entity =
5594 /*Consumed=*/false);
5596 From)) {
5597 Result.setUserDefined();
5598 Result.UserDefined.Before.setAsIdentityConversion();
5599 // Initializer lists don't have a type.
5600 Result.UserDefined.Before.setFromType(QualType());
5601 Result.UserDefined.Before.setAllToTypes(QualType());
5602
5603 Result.UserDefined.After.setAsIdentityConversion();
5604 Result.UserDefined.After.setFromType(ToType);
5605 Result.UserDefined.After.setAllToTypes(ToType);
5606 Result.UserDefined.ConversionFunction = nullptr;
5607 }
5608 return Result;
5609 }
5610
5611 // C++14 [over.ics.list]p6:
5612 // C++11 [over.ics.list]p5:
5613 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5614 if (ToType->isReferenceType()) {
5615 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5616 // mention initializer lists in any way. So we go by what list-
5617 // initialization would do and try to extrapolate from that.
5618
5619 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5620
5621 // If the initializer list has a single element that is reference-related
5622 // to the parameter type, we initialize the reference from that.
5623 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5624 Expr *Init = From->getInit(0);
5625
5626 QualType T2 = Init->getType();
5627
5628 // If the initializer is the address of an overloaded function, try
5629 // to resolve the overloaded function. If all goes well, T2 is the
5630 // type of the resulting function.
5631 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5632 DeclAccessPair Found;
5634 Init, ToType, false, Found))
5635 T2 = Fn->getType();
5636 }
5637
5638 // Compute some basic properties of the types and the initializer.
5639 Sema::ReferenceCompareResult RefRelationship =
5640 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5641
5642 if (RefRelationship >= Sema::Ref_Related) {
5643 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5644 SuppressUserConversions,
5645 /*AllowExplicit=*/false);
5646 }
5647 }
5648
5649 // Otherwise, we bind the reference to a temporary created from the
5650 // initializer list.
5651 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5652 InOverloadResolution,
5653 AllowObjCWritebackConversion);
5654 if (Result.isFailure())
5655 return Result;
5656 assert(!Result.isEllipsis() &&
5657 "Sub-initialization cannot result in ellipsis conversion.");
5658
5659 // Can we even bind to a temporary?
5660 if (ToType->isRValueReferenceType() ||
5661 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5662 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5663 Result.UserDefined.After;
5664 SCS.ReferenceBinding = true;
5666 SCS.BindsToRvalue = true;
5667 SCS.BindsToFunctionLvalue = false;
5670 } else
5672 From, ToType);
5673 return Result;
5674 }
5675
5676 // C++14 [over.ics.list]p7:
5677 // C++11 [over.ics.list]p6:
5678 // Otherwise, if the parameter type is not a class:
5679 if (!ToType->isRecordType()) {
5680 // - if the initializer list has one element that is not itself an
5681 // initializer list, the implicit conversion sequence is the one
5682 // required to convert the element to the parameter type.
5683 unsigned NumInits = From->getNumInits();
5684 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5685 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5686 SuppressUserConversions,
5687 InOverloadResolution,
5688 AllowObjCWritebackConversion);
5689 // - if the initializer list has no elements, the implicit conversion
5690 // sequence is the identity conversion.
5691 else if (NumInits == 0) {
5692 Result.setStandard();
5693 Result.Standard.setAsIdentityConversion();
5694 Result.Standard.setFromType(ToType);
5695 Result.Standard.setAllToTypes(ToType);
5696 }
5697 return Result;
5698 }
5699
5700 // C++14 [over.ics.list]p8:
5701 // C++11 [over.ics.list]p7:
5702 // In all cases other than those enumerated above, no conversion is possible
5703 return Result;
5704}
5705
5706/// TryCopyInitialization - Try to copy-initialize a value of type
5707/// ToType from the expression From. Return the implicit conversion
5708/// sequence required to pass this argument, which may be a bad
5709/// conversion sequence (meaning that the argument cannot be passed to
5710/// a parameter of this type). If @p SuppressUserConversions, then we
5711/// do not permit any user-defined conversion sequences.
5714 bool SuppressUserConversions,
5715 bool InOverloadResolution,
5716 bool AllowObjCWritebackConversion,
5717 bool AllowExplicit) {
5718 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5719 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5720 InOverloadResolution,AllowObjCWritebackConversion);
5721
5722 if (ToType->isReferenceType())
5723 return TryReferenceInit(S, From, ToType,
5724 /*FIXME:*/ From->getBeginLoc(),
5725 SuppressUserConversions, AllowExplicit);
5726
5727 return TryImplicitConversion(S, From, ToType,
5728 SuppressUserConversions,
5729 AllowedExplicit::None,
5730 InOverloadResolution,
5731 /*CStyle=*/false,
5732 AllowObjCWritebackConversion,
5733 /*AllowObjCConversionOnExplicit=*/false);
5734}
5735
5736static bool TryCopyInitialization(const CanQualType FromQTy,
5737 const CanQualType ToQTy,
5738 Sema &S,
5739 SourceLocation Loc,
5740 ExprValueKind FromVK) {
5741 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5743 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5744
5745 return !ICS.isBad();
5746}
5747
5748/// TryObjectArgumentInitialization - Try to initialize the object
5749/// parameter of the given member function (@c Method) from the
5750/// expression @p From.
5752 Sema &S, SourceLocation Loc, QualType FromType,
5753 Expr::Classification FromClassification, CXXMethodDecl *Method,
5754 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5755 QualType ExplicitParameterType = QualType(),
5756 bool SuppressUserConversion = false) {
5757
5758 // We need to have an object of class type.
5759 if (const auto *PT = FromType->getAs<PointerType>()) {
5760 FromType = PT->getPointeeType();
5761
5762 // When we had a pointer, it's implicitly dereferenced, so we
5763 // better have an lvalue.
5764 assert(FromClassification.isLValue());
5765 }
5766
5767 auto ValueKindFromClassification = [](Expr::Classification C) {
5768 if (C.isPRValue())
5769 return clang::VK_PRValue;
5770 if (C.isXValue())
5771 return VK_XValue;
5772 return clang::VK_LValue;
5773 };
5774
5775 if (Method->isExplicitObjectMemberFunction()) {
5776 if (ExplicitParameterType.isNull())
5777 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5778 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5779 ValueKindFromClassification(FromClassification));
5781 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5782 /*InOverloadResolution=*/true, false);
5783 if (ICS.isBad())
5784 ICS.Bad.FromExpr = nullptr;
5785 return ICS;
5786 }
5787
5788 assert(FromType->isRecordType());
5789
5790 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5791 // C++98 [class.dtor]p2:
5792 // A destructor can be invoked for a const, volatile or const volatile
5793 // object.
5794 // C++98 [over.match.funcs]p4:
5795 // For static member functions, the implicit object parameter is considered
5796 // to match any object (since if the function is selected, the object is
5797 // discarded).
5798 Qualifiers Quals = Method->getMethodQualifiers();
5799 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5800 Quals.addConst();
5801 Quals.addVolatile();
5802 }
5803
5804 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5805
5806 // Set up the conversion sequence as a "bad" conversion, to allow us
5807 // to exit early.
5809
5810 // C++0x [over.match.funcs]p4:
5811 // For non-static member functions, the type of the implicit object
5812 // parameter is
5813 //
5814 // - "lvalue reference to cv X" for functions declared without a
5815 // ref-qualifier or with the & ref-qualifier
5816 // - "rvalue reference to cv X" for functions declared with the &&
5817 // ref-qualifier
5818 //
5819 // where X is the class of which the function is a member and cv is the
5820 // cv-qualification on the member function declaration.
5821 //
5822 // However, when finding an implicit conversion sequence for the argument, we
5823 // are not allowed to perform user-defined conversions
5824 // (C++ [over.match.funcs]p5). We perform a simplified version of
5825 // reference binding here, that allows class rvalues to bind to
5826 // non-constant references.
5827
5828 // First check the qualifiers.
5829 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5830 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5831 if (ImplicitParamType.getCVRQualifiers() !=
5832 FromTypeCanon.getLocalCVRQualifiers() &&
5833 !ImplicitParamType.isAtLeastAsQualifiedAs(
5834 withoutUnaligned(S.Context, FromTypeCanon))) {
5836 FromType, ImplicitParamType);
5837 return ICS;
5838 }
5839
5840 if (FromTypeCanon.hasAddressSpace()) {
5841 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5842 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5843 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5845 FromType, ImplicitParamType);
5846 return ICS;
5847 }
5848 }
5849
5850 // Check that we have either the same type or a derived type. It
5851 // affects the conversion rank.
5852 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5853 ImplicitConversionKind SecondKind;
5854 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5855 SecondKind = ICK_Identity;
5856 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5857 SecondKind = ICK_Derived_To_Base;
5858 } else if (!Method->isExplicitObjectMemberFunction()) {
5860 FromType, ImplicitParamType);
5861 return ICS;
5862 }
5863
5864 // Check the ref-qualifier.
5865 switch (Method->getRefQualifier()) {
5866 case RQ_None:
5867 // Do nothing; we don't care about lvalueness or rvalueness.
5868 break;
5869
5870 case RQ_LValue:
5871 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5872 // non-const lvalue reference cannot bind to an rvalue
5874 ImplicitParamType);
5875 return ICS;
5876 }
5877 break;
5878
5879 case RQ_RValue:
5880 if (!FromClassification.isRValue()) {
5881 // rvalue reference cannot bind to an lvalue
5883 ImplicitParamType);
5884 return ICS;
5885 }
5886 break;
5887 }
5888
5889 // Success. Mark this as a reference binding.
5890 ICS.setStandard();
5892 ICS.Standard.Second = SecondKind;
5893 ICS.Standard.setFromType(FromType);
5894 ICS.Standard.setAllToTypes(ImplicitParamType);
5895 ICS.Standard.ReferenceBinding = true;
5896 ICS.Standard.DirectBinding = true;
5898 ICS.Standard.BindsToFunctionLvalue = false;
5899 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5901 = (Method->getRefQualifier() == RQ_None);
5902 return ICS;
5903}
5904
5905/// PerformObjectArgumentInitialization - Perform initialization of
5906/// the implicit object parameter for the given Method with the given
5907/// expression.
5909 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5910 CXXMethodDecl *Method) {
5911 QualType FromRecordType, DestType;
5912 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5913
5914 Expr::Classification FromClassification;
5915 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5916 FromRecordType = PT->getPointeeType();
5917 DestType = Method->getThisType();
5918 FromClassification = Expr::Classification::makeSimpleLValue();
5919 } else {
5920 FromRecordType = From->getType();
5921 DestType = ImplicitParamRecordType;
5922 FromClassification = From->Classify(Context);
5923
5924 // When performing member access on a prvalue, materialize a temporary.
5925 if (From->isPRValue()) {
5926 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5927 Method->getRefQualifier() !=
5929 }
5930 }
5931
5932 // Note that we always use the true parent context when performing
5933 // the actual argument initialization.
5935 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5936 Method->getParent());
5937 if (ICS.isBad()) {
5938 switch (ICS.Bad.Kind) {
5940 Qualifiers FromQs = FromRecordType.getQualifiers();
5941 Qualifiers ToQs = DestType.getQualifiers();
5942 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5943 if (CVR) {
5944 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5945 << Method->getDeclName() << FromRecordType << (CVR - 1)
5946 << From->getSourceRange();
5947 Diag(Method->getLocation(), diag::note_previous_decl)
5948 << Method->getDeclName();
5949 return ExprError();
5950 }
5951 break;
5952 }
5953
5956 bool IsRValueQualified =
5958 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5959 << Method->getDeclName() << FromClassification.isRValue()
5960 << IsRValueQualified;
5961 Diag(Method->getLocation(), diag::note_previous_decl)
5962 << Method->getDeclName();
5963 return ExprError();
5964 }
5965
5968 break;
5969
5972 llvm_unreachable("Lists are not objects");
5973 }
5974
5975 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5976 << ImplicitParamRecordType << FromRecordType
5977 << From->getSourceRange();
5978 }
5979
5980 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5981 ExprResult FromRes =
5982 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5983 if (FromRes.isInvalid())
5984 return ExprError();
5985 From = FromRes.get();
5986 }
5987
5988 if (!Context.hasSameType(From->getType(), DestType)) {
5989 CastKind CK;
5990 QualType PteeTy = DestType->getPointeeType();
5991 LangAS DestAS =
5992 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5993 if (FromRecordType.getAddressSpace() != DestAS)
5994 CK = CK_AddressSpaceConversion;
5995 else
5996 CK = CK_NoOp;
5997 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5998 }
5999 return From;
6000}
6001
6002/// TryContextuallyConvertToBool - Attempt to contextually convert the
6003/// expression From to bool (C++0x [conv]p3).
6006 // C++ [dcl.init]/17.8:
6007 // - Otherwise, if the initialization is direct-initialization, the source
6008 // type is std::nullptr_t, and the destination type is bool, the initial
6009 // value of the object being initialized is false.
6010 if (From->getType()->isNullPtrType())
6012 S.Context.BoolTy,
6013 From->isGLValue());
6014
6015 // All other direct-initialization of bool is equivalent to an implicit
6016 // conversion to bool in which explicit conversions are permitted.
6017 return TryImplicitConversion(S, From, S.Context.BoolTy,
6018 /*SuppressUserConversions=*/false,
6019 AllowedExplicit::Conversions,
6020 /*InOverloadResolution=*/false,
6021 /*CStyle=*/false,
6022 /*AllowObjCWritebackConversion=*/false,
6023 /*AllowObjCConversionOnExplicit=*/false);
6024}
6025
6026/// PerformContextuallyConvertToBool - Perform a contextual conversion
6027/// of the expression From to bool (C++0x [conv]p3).
6029 if (checkPlaceholderForOverload(*this, From))
6030 return ExprError();
6031
6033 if (!ICS.isBad())
6034 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
6035
6036 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6037 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6038 << From->getType() << From->getSourceRange();
6039 return ExprError();
6040}
6041
6042/// Check that the specified conversion is permitted in a converted constant
6043/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6044/// is acceptable.
6047 // Since we know that the target type is an integral or unscoped enumeration
6048 // type, most conversion kinds are impossible. All possible First and Third
6049 // conversions are fine.
6050 switch (SCS.Second) {
6051 case ICK_Identity:
6053 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6055 return true;
6056
6058 // Conversion from an integral or unscoped enumeration type to bool is
6059 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6060 // conversion, so we allow it in a converted constant expression.
6061 //
6062 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6063 // a lot of popular code. We should at least add a warning for this
6064 // (non-conforming) extension.
6066 SCS.getToType(2)->isBooleanType();
6067
6069 case ICK_Pointer_Member:
6070 // C++1z: null pointer conversions and null member pointer conversions are
6071 // only permitted if the source type is std::nullptr_t.
6072 return SCS.getFromType()->isNullPtrType();
6073
6084 case ICK_Vector_Splat:
6085 case ICK_Complex_Real:
6094 return false;
6095
6100 llvm_unreachable("found a first conversion kind in Second");
6101
6103 case ICK_Qualification:
6104 llvm_unreachable("found a third conversion kind in Second");
6105
6107 break;
6108 }
6109
6110 llvm_unreachable("unknown conversion kind");
6111}
6112
6113/// BuildConvertedConstantExpression - Check that the expression From is a
6114/// converted constant expression of type T, perform the conversion but
6115/// does not evaluate the expression
6117 QualType T,
6118 Sema::CCEKind CCE,
6119 NamedDecl *Dest,
6120 APValue &PreNarrowingValue) {
6121 assert(S.getLangOpts().CPlusPlus11 &&
6122 "converted constant expression outside C++11");
6123
6124 if (checkPlaceholderForOverload(S, From))
6125 return ExprError();
6126
6127 // C++1z [expr.const]p3:
6128 // A converted constant expression of type T is an expression,
6129 // implicitly converted to type T, where the converted
6130 // expression is a constant expression and the implicit conversion
6131 // sequence contains only [... list of conversions ...].
6135 : TryCopyInitialization(S, From, T,
6136 /*SuppressUserConversions=*/false,
6137 /*InOverloadResolution=*/false,
6138 /*AllowObjCWritebackConversion=*/false,
6139 /*AllowExplicit=*/false);
6140 StandardConversionSequence *SCS = nullptr;
6141 switch (ICS.getKind()) {
6143 SCS = &ICS.Standard;
6144 break;
6146 if (T->isRecordType())
6147 SCS = &ICS.UserDefined.Before;
6148 else
6149 SCS = &ICS.UserDefined.After;
6150 break;
6154 return S.Diag(From->getBeginLoc(),
6155 diag::err_typecheck_converted_constant_expression)
6156 << From->getType() << From->getSourceRange() << T;
6157 return ExprError();
6158
6161 llvm_unreachable("bad conversion in converted constant expression");
6162 }
6163
6164 // Check that we would only use permitted conversions.
6165 if (!CheckConvertedConstantConversions(S, *SCS)) {
6166 return S.Diag(From->getBeginLoc(),
6167 diag::err_typecheck_converted_constant_expression_disallowed)
6168 << From->getType() << From->getSourceRange() << T;
6169 }
6170 // [...] and where the reference binding (if any) binds directly.
6171 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6172 return S.Diag(From->getBeginLoc(),
6173 diag::err_typecheck_converted_constant_expression_indirect)
6174 << From->getType() << From->getSourceRange() << T;
6175 }
6176 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6177 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6178 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6179 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6180 // case explicitly.
6181 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6182 return S.Diag(From->getBeginLoc(),
6183 diag::err_reference_bind_to_bitfield_in_cce)
6184 << From->getSourceRange();
6185 }
6186
6187 // Usually we can simply apply the ImplicitConversionSequence we formed
6188 // earlier, but that's not guaranteed to work when initializing an object of
6189 // class type.
6191 if (T->isRecordType()) {
6192 assert(CCE == Sema::CCEK_TemplateArg &&
6193 "unexpected class type converted constant expr");
6196 T, cast<NonTypeTemplateParmDecl>(Dest)),
6197 SourceLocation(), From);
6198 } else {
6200 }
6201 if (Result.isInvalid())
6202 return Result;
6203
6204 // C++2a [intro.execution]p5:
6205 // A full-expression is [...] a constant-expression [...]
6206 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6207 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6209 if (Result.isInvalid())
6210 return Result;
6211
6212 // Check for a narrowing implicit conversion.
6213 bool ReturnPreNarrowingValue = false;
6214 QualType PreNarrowingType;
6215 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6216 PreNarrowingType)) {
6218 // Implicit conversion to a narrower type, but the expression is
6219 // value-dependent so we can't tell whether it's actually narrowing.
6221 // Implicit conversion to a narrower type, and the value is not a constant
6222 // expression. We'll diagnose this in a moment.
6223 case NK_Not_Narrowing:
6224 break;
6225
6227 if (CCE == Sema::CCEK_ArrayBound &&
6228 PreNarrowingType->isIntegralOrEnumerationType() &&
6229 PreNarrowingValue.isInt()) {
6230 // Don't diagnose array bound narrowing here; we produce more precise
6231 // errors by allowing the un-narrowed value through.
6232 ReturnPreNarrowingValue = true;
6233 break;
6234 }
6235 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6236 << CCE << /*Constant*/ 1
6237 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6238 break;
6239
6240 case NK_Type_Narrowing:
6241 // FIXME: It would be better to diagnose that the expression is not a
6242 // constant expression.
6243 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6244 << CCE << /*Constant*/ 0 << From->getType() << T;
6245 break;
6246 }
6247 if (!ReturnPreNarrowingValue)
6248 PreNarrowingValue = {};
6249
6250 return Result;
6251}
6252
6253/// CheckConvertedConstantExpression - Check that the expression From is a
6254/// converted constant expression of type T, perform the conversion and produce
6255/// the converted expression, per C++11 [expr.const]p3.
6258 Sema::CCEKind CCE,
6259 bool RequireInt,
6260 NamedDecl *Dest) {
6261
6262 APValue PreNarrowingValue;
6264 PreNarrowingValue);
6265 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6266 Value = APValue();
6267 return Result;
6268 }
6269 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6270 RequireInt, PreNarrowingValue);
6271}
6272
6274 CCEKind CCE,
6275 NamedDecl *Dest) {
6276 APValue PreNarrowingValue;
6277 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6278 PreNarrowingValue);
6279}
6280
6282 APValue &Value, CCEKind CCE,
6283 NamedDecl *Dest) {
6284 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6285 Dest);
6286}
6287
6289 llvm::APSInt &Value,
6290 CCEKind CCE) {
6291 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6292
6293 APValue V;
6294 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6295 /*Dest=*/nullptr);
6296 if (!R.isInvalid() && !R.get()->isValueDependent())
6297 Value = V.getInt();
6298 return R;
6299}
6300
6301/// EvaluateConvertedConstantExpression - Evaluate an Expression
6302/// That is a converted constant expression
6303/// (which was built with BuildConvertedConstantExpression)
6306 Sema::CCEKind CCE, bool RequireInt,
6307 const APValue &PreNarrowingValue) {
6308
6309 ExprResult Result = E;
6310 // Check the expression is a constant expression.
6312 Expr::EvalResult Eval;
6313 Eval.Diag = &Notes;
6314
6315 ConstantExprKind Kind;
6316 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6317 Kind = ConstantExprKind::ClassTemplateArgument;
6318 else if (CCE == Sema::CCEK_TemplateArg)
6319 Kind = ConstantExprKind::NonClassTemplateArgument;
6320 else
6321 Kind = ConstantExprKind::Normal;
6322
6323 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6324 (RequireInt && !Eval.Val.isInt())) {
6325 // The expression can't be folded, so we can't keep it at this position in
6326 // the AST.
6327 Result = ExprError();
6328 } else {
6329 Value = Eval.Val;
6330
6331 if (Notes.empty()) {
6332 // It's a constant expression.
6333 Expr *E = Result.get();
6334 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6335 // We expect a ConstantExpr to have a value associated with it
6336 // by this point.
6337 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6338 "ConstantExpr has no value associated with it");
6339 (void)CE;
6340 } else {
6341 E = ConstantExpr::Create(Context, Result.get(), Value);
6342 }
6343 if (!PreNarrowingValue.isAbsent())
6344 Value = std::move(PreNarrowingValue);
6345 return E;
6346 }
6347 }
6348
6349 // It's not a constant expression. Produce an appropriate diagnostic.
6350 if (Notes.size() == 1 &&
6351 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6352 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6353 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6354 diag::note_constexpr_invalid_template_arg) {
6355 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6356 for (unsigned I = 0; I < Notes.size(); ++I)
6357 Diag(Notes[I].first, Notes[I].second);
6358 } else {
6359 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6360 << CCE << E->getSourceRange();
6361 for (unsigned I = 0; I < Notes.size(); ++I)
6362 Diag(Notes[I].first, Notes[I].second);
6363 }
6364 return ExprError();
6365}
6366
6367/// dropPointerConversions - If the given standard conversion sequence
6368/// involves any pointer conversions, remove them. This may change
6369/// the result type of the conversion sequence.
6371 if (SCS.Second == ICK_Pointer_Conversion) {
6372 SCS.Second = ICK_Identity;
6373 SCS.Element = ICK_Identity;
6374 SCS.Third = ICK_Identity;
6375 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6376 }
6377}
6378
6379/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6380/// convert the expression From to an Objective-C pointer type.
6383 // Do an implicit conversion to 'id'.
6386 = TryImplicitConversion(S, From, Ty,
6387 // FIXME: Are these flags correct?
6388 /*SuppressUserConversions=*/false,
6389 AllowedExplicit::Conversions,
6390 /*InOverloadResolution=*/false,
6391 /*CStyle=*/false,
6392 /*AllowObjCWritebackConversion=*/false,
6393 /*AllowObjCConversionOnExplicit=*/true);
6394
6395 // Strip off any final conversions to 'id'.
6396 switch (ICS.getKind()) {
6401 break;
6402
6405 break;
6406
6409 break;
6410 }
6411
6412 return ICS;
6413}
6414
6415/// PerformContextuallyConvertToObjCPointer - Perform a contextual
6416/// conversion of the expression From to an Objective-C pointer type.
6417/// Returns a valid but null ExprResult if no conversion sequence exists.
6419 if (checkPlaceholderForOverload(*this, From))
6420 return ExprError();
6421
6422 QualType Ty = Context.getObjCIdType();
6425 if (!ICS.isBad())
6426 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6427 return ExprResult();
6428}
6429
6430static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6431 const Expr *Base = nullptr;
6432 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6433 "expected a member expression");
6434
6435 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6436 M && !M->isImplicitAccess())
6437 Base = M->getBase();
6438 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6439 M && !M->isImplicitAccess())
6440 Base = M->getBase();
6441
6442 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6443
6444 if (T->isPointerType())
6445 T = T->getPointeeType();
6446
6447 return T;
6448}
6449
6451 const FunctionDecl *Fun) {
6452 QualType ObjType = Obj->getType();
6453 if (ObjType->isPointerType()) {
6454 ObjType = ObjType->getPointeeType();
6455 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6457 /*CanOverflow=*/false, FPOptionsOverride());
6458 }
6459 if (Obj->Classify(S.getASTContext()).isPRValue()) {
6461 ObjType, Obj,
6463 }
6464 return Obj;
6465}
6466
6468 FunctionDecl *Fun) {
6469 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6472 Obj->getExprLoc(), Obj);
6473}
6474
6476 Expr *Object, MultiExprArg &Args,
6477 SmallVectorImpl<Expr *> &NewArgs) {
6478 assert(Method->isExplicitObjectMemberFunction() &&
6479 "Method is not an explicit member function");
6480 assert(NewArgs.empty() && "NewArgs should be empty");
6481 NewArgs.reserve(Args.size() + 1);
6482 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6483 NewArgs.push_back(This);
6484 NewArgs.append(Args.begin(), Args.end());
6485 Args = NewArgs;
6486}
6487
6488/// Determine whether the provided type is an integral type, or an enumeration
6489/// type of a permitted flavor.
6491 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6493}
6494
6495static ExprResult
6498 QualType T, UnresolvedSetImpl &ViableConversions) {
6499
6500 if (Converter.Suppress)
6501 return ExprError();
6502
6503 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6504 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6505 CXXConversionDecl *Conv =
6506 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6508 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6509 }
6510 return From;
6511}
6512
6513static bool
6516 QualType T, bool HadMultipleCandidates,
6517 UnresolvedSetImpl &ExplicitConversions) {
6518 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6519 DeclAccessPair Found = ExplicitConversions[0];
6520 CXXConversionDecl *Conversion =
6521 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6522
6523 // The user probably meant to invoke the given explicit
6524 // conversion; use it.
6525 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6526 std::string TypeStr;
6527 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6528
6529 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6531 "static_cast<" + TypeStr + ">(")
6533 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6534 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6535
6536 // If we aren't in a SFINAE context, build a call to the
6537 // explicit conversion function.
6538 if (SemaRef.isSFINAEContext())
6539 return true;
6540
6541 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6542 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6543 HadMultipleCandidates);
6544 if (Result.isInvalid())
6545 return true;
6546
6547 // Replace the conversion with a RecoveryExpr, so we don't try to
6548 // instantiate it later, but can further diagnose here.
6549 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6550 From, Result.get()->getType());
6551 if (Result.isInvalid())
6552 return true;
6553 From = Result.get();
6554 }
6555 return false;
6556}
6557
6558static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6560 QualType T, bool HadMultipleCandidates,
6561 DeclAccessPair &Found) {
6562 CXXConversionDecl *Conversion =
6563 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6564 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6565
6566 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6567 if (!Converter.SuppressConversion) {
6568 if (SemaRef.isSFINAEContext())
6569 return true;
6570
6571 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6572 << From->getSourceRange();
6573 }
6574
6575 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6576 HadMultipleCandidates);
6577 if (Result.isInvalid())
6578 return true;
6579 // Record usage of conversion in an implicit cast.
6580 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6581 CK_UserDefinedConversion, Result.get(),
6582 nullptr, Result.get()->getValueKind(),
6583 SemaRef.CurFPFeatureOverrides());
6584 return false;
6585}
6586
6588 Sema &SemaRef, SourceLocation Loc, Expr *From,
6590 if (!Converter.match(From->getType()) && !Converter.Suppress)
6591 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6592 << From->getSourceRange();
6593
6594 return SemaRef.DefaultLvalueConversion(From);
6595}
6596
6597static void
6599 UnresolvedSetImpl &ViableConversions,
6600 OverloadCandidateSet &CandidateSet) {
6601 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6602 DeclAccessPair FoundDecl = ViableConversions[I];
6603 NamedDecl *D = FoundDecl.getDecl();
6604 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6605 if (isa<UsingShadowDecl>(D))
6606 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6607
6608 CXXConversionDecl *Conv;
6609 FunctionTemplateDecl *ConvTemplate;
6610 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6611 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6612 else
6613 Conv = cast<CXXConversionDecl>(D);
6614
6615 if (ConvTemplate)
6617 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6618 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6619 else
6620 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6621 ToType, CandidateSet,
6622 /*AllowObjCConversionOnExplicit=*/false,
6623 /*AllowExplicit*/ true);
6624 }
6625}
6626
6627/// Attempt to convert the given expression to a type which is accepted
6628/// by the given converter.
6629///
6630/// This routine will attempt to convert an expression of class type to a
6631/// type accepted by the specified converter. In C++11 and before, the class
6632/// must have a single non-explicit conversion function converting to a matching
6633/// type. In C++1y, there can be multiple such conversion functions, but only
6634/// one target type.
6635///
6636/// \param Loc The source location of the construct that requires the
6637/// conversion.
6638///
6639/// \param From The expression we're converting from.
6640///
6641/// \param Converter Used to control and diagnose the conversion process.
6642///
6643/// \returns The expression, converted to an integral or enumeration type if
6644/// successful.
6646 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6647 // We can't perform any more checking for type-dependent expressions.
6648 if (From->isTypeDependent())
6649 return From;
6650
6651 // Process placeholders immediately.
6652 if (From->hasPlaceholderType()) {
6653 ExprResult result = CheckPlaceholderExpr(From);
6654 if (result.isInvalid())
6655 return result;
6656 From = result.get();
6657 }
6658
6659 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6660 ExprResult Converted = DefaultLvalueConversion(From);
6661 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6662 // If the expression already has a matching type, we're golden.
6663 if (Converter.match(T))
6664 return Converted;
6665
6666 // FIXME: Check for missing '()' if T is a function type?
6667
6668 // We can only perform contextual implicit conversions on objects of class
6669 // type.
6670 const RecordType *RecordTy = T->getAs<RecordType>();
6671 if (!RecordTy || !getLangOpts().CPlusPlus) {
6672 if (!Converter.Suppress)
6673 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6674 return From;
6675 }
6676
6677 // We must have a complete class type.
6678 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6679 ContextualImplicitConverter &Converter;
6680 Expr *From;
6681
6682 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6683 : Converter(Converter), From(From) {}
6684
6685 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6686 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6687 }
6688 } IncompleteDiagnoser(Converter, From);
6689
6690 if (Converter.Suppress ? !isCompleteType(Loc, T)
6691 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6692 return From;
6693
6694 // Look for a conversion to an integral or enumeration type.
6696 ViableConversions; // These are *potentially* viable in C++1y.
6697 UnresolvedSet<4> ExplicitConversions;
6698 const auto &Conversions =
6699 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6700
6701 bool HadMultipleCandidates =
6702 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6703
6704 // To check that there is only one target type, in C++1y:
6705 QualType ToType;
6706 bool HasUniqueTargetType = true;
6707
6708 // Collect explicit or viable (potentially in C++1y) conversions.
6709 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6710 NamedDecl *D = (*I)->getUnderlyingDecl();
6711 CXXConversionDecl *Conversion;
6712 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6713 if (ConvTemplate) {
6714 if (getLangOpts().CPlusPlus14)
6715 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6716 else
6717 continue; // C++11 does not consider conversion operator templates(?).
6718 } else
6719 Conversion = cast<CXXConversionDecl>(D);
6720
6721 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6722 "Conversion operator templates are considered potentially "
6723 "viable in C++1y");
6724
6725 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6726 if (Converter.match(CurToType) || ConvTemplate) {
6727
6728 if (Conversion->isExplicit()) {
6729 // FIXME: For C++1y, do we need this restriction?
6730 // cf. diagnoseNoViableConversion()
6731 if (!ConvTemplate)
6732 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6733 } else {
6734 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6735 if (ToType.isNull())
6736 ToType = CurToType.getUnqualifiedType();
6737 else if (HasUniqueTargetType &&
6738 (CurToType.getUnqualifiedType() != ToType))
6739 HasUniqueTargetType = false;
6740 }
6741 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6742 }
6743 }
6744 }
6745
6746 if (getLangOpts().CPlusPlus14) {
6747 // C++1y [conv]p6:
6748 // ... An expression e of class type E appearing in such a context
6749 // is said to be contextually implicitly converted to a specified
6750 // type T and is well-formed if and only if e can be implicitly
6751 // converted to a type T that is determined as follows: E is searched
6752 // for conversion functions whose return type is cv T or reference to
6753 // cv T such that T is allowed by the context. There shall be
6754 // exactly one such T.
6755
6756 // If no unique T is found:
6757 if (ToType.isNull()) {
6758 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6759 HadMultipleCandidates,
6760 ExplicitConversions))
6761 return ExprError();
6762 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6763 }
6764
6765 // If more than one unique Ts are found:
6766 if (!HasUniqueTargetType)
6767 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6768 ViableConversions);
6769
6770 // If one unique T is found:
6771 // First, build a candidate set from the previously recorded
6772 // potentially viable conversions.
6774 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6775 CandidateSet);
6776
6777 // Then, perform overload resolution over the candidate set.
6779 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6780 case OR_Success: {
6781 // Apply this conversion.
6782 DeclAccessPair Found =
6783 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6784 if (recordConversion(*this, Loc, From, Converter, T,
6785 HadMultipleCandidates, Found))
6786 return ExprError();
6787 break;
6788 }
6789 case OR_Ambiguous:
6790 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6791 ViableConversions);
6793 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6794 HadMultipleCandidates,
6795 ExplicitConversions))
6796 return ExprError();
6797 [[fallthrough]];
6798 case OR_Deleted:
6799 // We'll complain below about a non-integral condition type.
6800 break;
6801 }
6802 } else {
6803 switch (ViableConversions.size()) {
6804 case 0: {
6805 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6806 HadMultipleCandidates,
6807 ExplicitConversions))
6808 return ExprError();
6809
6810 // We'll complain below about a non-integral condition type.
6811 break;
6812 }
6813 case 1: {
6814 // Apply this conversion.
6815 DeclAccessPair Found = ViableConversions[0];
6816 if (recordConversion(*this, Loc, From, Converter, T,
6817 HadMultipleCandidates, Found))
6818 return ExprError();
6819 break;
6820 }
6821 default:
6822 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6823 ViableConversions);
6824 }
6825 }
6826
6827 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6828}
6829
6830/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6831/// an acceptable non-member overloaded operator for a call whose
6832/// arguments have types T1 (and, if non-empty, T2). This routine
6833/// implements the check in C++ [over.match.oper]p3b2 concerning
6834/// enumeration types.
6836 FunctionDecl *Fn,
6837 ArrayRef<Expr *> Args) {
6838 QualType T1 = Args[0]->getType();
6839 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6840
6841 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6842 return true;
6843
6844 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6845 return true;
6846
6847 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6848 if (Proto->getNumParams() < 1)
6849 return false;
6850
6851 if (T1->isEnumeralType()) {
6852 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6853 if (Context.hasSameUnqualifiedType(T1, ArgType))
6854 return true;
6855 }
6856
6857 if (Proto->getNumParams() < 2)
6858 return false;
6859
6860 if (!T2.isNull() && T2->isEnumeralType()) {
6861 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6862 if (Context.hasSameUnqualifiedType(T2, ArgType))
6863 return true;
6864 }
6865
6866 return false;
6867}
6868
6871 return false;
6872
6873 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6874 return FD->isTargetMultiVersion();
6875
6876 if (!FD->isMultiVersion())
6877 return false;
6878
6879 // Among multiple target versions consider either the default,
6880 // or the first non-default in the absence of default version.
6881 unsigned SeenAt = 0;
6882 unsigned I = 0;
6883 bool HasDefault = false;
6885 FD, [&](const FunctionDecl *CurFD) {
6886 if (FD == CurFD)
6887 SeenAt = I;
6888 else if (CurFD->isTargetMultiVersionDefault())
6889 HasDefault = true;
6890 ++I;
6891 });
6892 return HasDefault || SeenAt != 0;
6893}
6894
6895/// AddOverloadCandidate - Adds the given function to the set of
6896/// candidate functions, using the given function call arguments. If
6897/// @p SuppressUserConversions, then don't allow user-defined
6898/// conversions via constructors or conversion operators.
6899///
6900/// \param PartialOverloading true if we are performing "partial" overloading
6901/// based on an incomplete set of function arguments. This feature is used by
6902/// code completion.
6905 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6906 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6907 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6908 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6909 const FunctionProtoType *Proto
6910 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6911 assert(Proto && "Functions without a prototype cannot be overloaded");
6912 assert(!Function->getDescribedFunctionTemplate() &&
6913 "Use AddTemplateOverloadCandidate for function templates");
6914
6915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6916 if (!isa<CXXConstructorDecl>(Method)) {
6917 // If we get here, it's because we're calling a member function
6918 // that is named without a member access expression (e.g.,
6919 // "this->f") that was either written explicitly or created
6920 // implicitly. This can happen with a qualified call to a member
6921 // function, e.g., X::f(). We use an empty type for the implied
6922 // object argument (C++ [over.call.func]p3), and the acting context
6923 // is irrelevant.
6924 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6926 CandidateSet, SuppressUserConversions,
6927 PartialOverloading, EarlyConversions, PO);
6928 return;
6929 }
6930 // We treat a constructor like a non-member function, since its object
6931 // argument doesn't participate in overload resolution.
6932 }
6933
6934 if (!CandidateSet.isNewCandidate(Function, PO))
6935 return;
6936
6937 // C++11 [class.copy]p11: [DR1402]
6938 // A defaulted move constructor that is defined as deleted is ignored by
6939 // overload resolution.
6940 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6941 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6942 Constructor->isMoveConstructor())
6943 return;
6944
6945 // Overload resolution is always an unevaluated context.
6948
6949 // C++ [over.match.oper]p3:
6950 // if no operand has a class type, only those non-member functions in the
6951 // lookup set that have a first parameter of type T1 or "reference to
6952 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6953 // is a right operand) a second parameter of type T2 or "reference to
6954 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6955 // candidate functions.
6956 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6958 return;
6959
6960 // Add this candidate
6961 OverloadCandidate &Candidate =
6962 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6963 Candidate.FoundDecl = FoundDecl;
6964 Candidate.Function = Function;
6965 Candidate.Viable = true;
6966 Candidate.RewriteKind =
6967 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6968 Candidate.IsSurrogate = false;
6969 Candidate.IsADLCandidate = IsADLCandidate;
6970 Candidate.IgnoreObjectArgument = false;
6971 Candidate.ExplicitCallArguments = Args.size();
6972
6973 // Explicit functions are not actually candidates at all if we're not
6974 // allowing them in this context, but keep them around so we can point
6975 // to them in diagnostics.
6976 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6977 Candidate.Viable = false;
6978 Candidate.FailureKind = ovl_fail_explicit;
6979 return;
6980 }
6981
6982 // Functions with internal linkage are only viable in the same module unit.
6983 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6984 /// FIXME: Currently, the semantics of linkage in clang is slightly
6985 /// different from the semantics in C++ spec. In C++ spec, only names
6986 /// have linkage. So that all entities of the same should share one
6987 /// linkage. But in clang, different entities of the same could have
6988 /// different linkage.
6989 NamedDecl *ND = Function;
6990 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6991 ND = SpecInfo->getTemplate();
6992
6993 if (ND->getFormalLinkage() == Linkage::Internal) {
6994 Candidate.Viable = false;
6996 return;
6997 }
6998 }
6999
7001 Candidate.Viable = false;
7003 return;
7004 }
7005
7006 if (Constructor) {
7007 // C++ [class.copy]p3:
7008 // A member function template is never instantiated to perform the copy
7009 // of a class object to an object of its class type.
7010 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7011 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7012 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7013 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7014 ClassType))) {
7015 Candidate.Viable = false;
7017 return;
7018 }
7019
7020 // C++ [over.match.funcs]p8: (proposed DR resolution)
7021 // A constructor inherited from class type C that has a first parameter
7022 // of type "reference to P" (including such a constructor instantiated
7023 // from a template) is excluded from the set of candidate functions when
7024 // constructing an object of type cv D if the argument list has exactly
7025 // one argument and D is reference-related to P and P is reference-related
7026 // to C.
7027 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7028 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7029 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7030 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7031 QualType C = Context.getRecordType(Constructor->getParent());
7032 QualType D = Context.getRecordType(Shadow->getParent());
7033 SourceLocation Loc = Args.front()->getExprLoc();
7034 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7035 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7036 Candidate.Viable = false;
7038 return;
7039 }
7040 }
7041
7042 // Check that the constructor is capable of constructing an object in the
7043 // destination address space.
7045 Constructor->getMethodQualifiers().getAddressSpace(),
7046 CandidateSet.getDestAS())) {
7047 Candidate.Viable = false;
7049 }
7050 }
7051
7052 unsigned NumParams = Proto->getNumParams();
7053
7054 // (C++ 13.3.2p2): A candidate function having fewer than m
7055 // parameters is viable only if it has an ellipsis in its parameter
7056 // list (8.3.5).
7057 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7058 !Proto->isVariadic() &&
7059 shouldEnforceArgLimit(PartialOverloading, Function)) {
7060 Candidate.Viable = false;
7062 return;
7063 }
7064
7065 // (C++ 13.3.2p2): A candidate function having more than m parameters
7066 // is viable only if the (m+1)st parameter has a default argument
7067 // (8.3.6). For the purposes of overload resolution, the
7068 // parameter list is truncated on the right, so that there are
7069 // exactly m parameters.
7070 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7071 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7072 !PartialOverloading) {
7073 // Not enough arguments.
7074 Candidate.Viable = false;
7076 return;
7077 }
7078
7079 // (CUDA B.1): Check for invalid calls between targets.
7080 if (getLangOpts().CUDA) {
7081 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7082 // Skip the check for callers that are implicit members, because in this
7083 // case we may not yet know what the member's target is; the target is
7084 // inferred for the member automatically, based on the bases and fields of
7085 // the class.
7086 if (!(Caller && Caller->isImplicit()) &&
7087 !CUDA().IsAllowedCall(Caller, Function)) {
7088 Candidate.Viable = false;
7089 Candidate.FailureKind = ovl_fail_bad_target;
7090 return;
7091 }
7092 }
7093
7094 if (Function->getTrailingRequiresClause()) {
7095 ConstraintSatisfaction Satisfaction;
7096 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7097 /*ForOverloadResolution*/ true) ||
7098 !Satisfaction.IsSatisfied) {
7099 Candidate.Viable = false;
7101 return;
7102 }
7103 }
7104
7105 // Determine the implicit conversion sequences for each of the
7106 // arguments.
7107 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7108 unsigned ConvIdx =
7109 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7110 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7111 // We already formed a conversion sequence for this parameter during
7112 // template argument deduction.
7113 } else if (ArgIdx < NumParams) {
7114 // (C++ 13.3.2p3): for F to be a viable function, there shall
7115 // exist for each argument an implicit conversion sequence
7116 // (13.3.3.1) that converts that argument to the corresponding
7117 // parameter of F.
7118 QualType ParamType = Proto->getParamType(ArgIdx);
7119 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7120 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7121 /*InOverloadResolution=*/true,
7122 /*AllowObjCWritebackConversion=*/
7123 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7124 if (Candidate.Conversions[ConvIdx].isBad()) {
7125 Candidate.Viable = false;
7127 return;
7128 }
7129 } else {
7130 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7131 // argument for which there is no corresponding parameter is
7132 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7133 Candidate.Conversions[ConvIdx].setEllipsis();
7134 }
7135 }
7136
7137 if (EnableIfAttr *FailedAttr =
7138 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7139 Candidate.Viable = false;
7140 Candidate.FailureKind = ovl_fail_enable_if;
7141 Candidate.DeductionFailure.Data = FailedAttr;
7142 return;
7143 }
7144}
7145
7149 if (Methods.size() <= 1)
7150 return nullptr;
7151
7152 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7153 bool Match = true;
7154 ObjCMethodDecl *Method = Methods[b];
7155 unsigned NumNamedArgs = Sel.getNumArgs();
7156 // Method might have more arguments than selector indicates. This is due
7157 // to addition of c-style arguments in method.
7158 if (Method->param_size() > NumNamedArgs)
7159 NumNamedArgs = Method->param_size();
7160 if (Args.size() < NumNamedArgs)
7161 continue;
7162
7163 for (unsigned i = 0; i < NumNamedArgs; i++) {
7164 // We can't do any type-checking on a type-dependent argument.
7165 if (Args[i]->isTypeDependent()) {
7166 Match = false;
7167 break;
7168 }
7169
7170 ParmVarDecl *param = Method->parameters()[i];
7171 Expr *argExpr = Args[i];
7172 assert(argExpr && "SelectBestMethod(): missing expression");
7173
7174 // Strip the unbridged-cast placeholder expression off unless it's
7175 // a consumed argument.
7176 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7177 !param->hasAttr<CFConsumedAttr>())
7178 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7179
7180 // If the parameter is __unknown_anytype, move on to the next method.
7181 if (param->getType() == Context.UnknownAnyTy) {
7182 Match = false;
7183 break;
7184 }
7185
7186 ImplicitConversionSequence ConversionState
7187 = TryCopyInitialization(*this, argExpr, param->getType(),
7188 /*SuppressUserConversions*/false,
7189 /*InOverloadResolution=*/true,
7190 /*AllowObjCWritebackConversion=*/
7191 getLangOpts().ObjCAutoRefCount,
7192 /*AllowExplicit*/false);
7193 // This function looks for a reasonably-exact match, so we consider
7194 // incompatible pointer conversions to be a failure here.
7195 if (ConversionState.isBad() ||
7196 (ConversionState.isStandard() &&
7197 ConversionState.Standard.Second ==
7199 Match = false;
7200 break;
7201 }
7202 }
7203 // Promote additional arguments to variadic methods.
7204 if (Match && Method->isVariadic()) {
7205 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7206 if (Args[i]->isTypeDependent()) {
7207 Match = false;
7208 break;
7209 }
7210 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7211 nullptr);
7212 if (Arg.isInvalid()) {
7213 Match = false;
7214 break;
7215 }
7216 }
7217 } else {
7218 // Check for extra arguments to non-variadic methods.
7219 if (Args.size() != NumNamedArgs)
7220 Match = false;
7221 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7222 // Special case when selectors have no argument. In this case, select
7223 // one with the most general result type of 'id'.
7224 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7225 QualType ReturnT = Methods[b]->getReturnType();
7226 if (ReturnT->isObjCIdType())
7227 return Methods[b];
7228 }
7229 }
7230 }
7231
7232 if (Match)
7233 return Method;
7234 }
7235 return nullptr;
7236}
7237
7239 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7240 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7241 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7242 if (ThisArg) {
7243 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7244 assert(!isa<CXXConstructorDecl>(Method) &&
7245 "Shouldn't have `this` for ctors!");
7246 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7248 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7249 if (R.isInvalid())
7250 return false;
7251 ConvertedThis = R.get();
7252 } else {
7253 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7254 (void)MD;
7255 assert((MissingImplicitThis || MD->isStatic() ||
7256 isa<CXXConstructorDecl>(MD)) &&
7257 "Expected `this` for non-ctor instance methods");
7258 }
7259 ConvertedThis = nullptr;
7260 }
7261
7262 // Ignore any variadic arguments. Converting them is pointless, since the
7263 // user can't refer to them in the function condition.
7264 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7265
7266 // Convert the arguments.
7267 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7268 ExprResult R;
7270 S.Context, Function->getParamDecl(I)),
7271 SourceLocation(), Args[I]);
7272
7273 if (R.isInvalid())
7274 return false;
7275
7276 ConvertedArgs.push_back(R.get());
7277 }
7278
7279 if (Trap.hasErrorOccurred())
7280 return false;
7281
7282 // Push default arguments if needed.
7283 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7284 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7285 ParmVarDecl *P = Function->getParamDecl(i);
7286 if (!P->hasDefaultArg())
7287 return false;
7289 if (R.isInvalid())
7290 return false;
7291 ConvertedArgs.push_back(R.get());
7292 }
7293
7294 if (Trap.hasErrorOccurred())
7295 return false;
7296 }
7297 return true;
7298}
7299
7301 SourceLocation CallLoc,
7302 ArrayRef<Expr *> Args,
7303 bool MissingImplicitThis) {
7304 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7305 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7306 return nullptr;
7307
7308 SFINAETrap Trap(*this);
7309 SmallVector<Expr *, 16> ConvertedArgs;
7310 // FIXME: We should look into making enable_if late-parsed.
7311 Expr *DiscardedThis;
7313 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7314 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7315 return *EnableIfAttrs.begin();
7316
7317 for (auto *EIA : EnableIfAttrs) {
7319 // FIXME: This doesn't consider value-dependent cases, because doing so is
7320 // very difficult. Ideally, we should handle them more gracefully.
7321 if (EIA->getCond()->isValueDependent() ||
7322 !EIA->getCond()->EvaluateWithSubstitution(
7323 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7324 return EIA;
7325
7326 if (!Result.isInt() || !Result.getInt().getBoolValue())
7327 return EIA;
7328 }
7329 return nullptr;
7330}
7331
7332template <typename CheckFn>
7334 bool ArgDependent, SourceLocation Loc,
7335 CheckFn &&IsSuccessful) {
7337 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7338 if (ArgDependent == DIA->getArgDependent())
7339 Attrs.push_back(DIA);
7340 }
7341
7342 // Common case: No diagnose_if attributes, so we can quit early.
7343 if (Attrs.empty())
7344 return false;
7345
7346 auto WarningBegin = std::stable_partition(
7347 Attrs.begin(), Attrs.end(),
7348 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7349
7350 // Note that diagnose_if attributes are late-parsed, so they appear in the
7351 // correct order (unlike enable_if attributes).
7352 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7353 IsSuccessful);
7354 if (ErrAttr != WarningBegin) {
7355 const DiagnoseIfAttr *DIA = *ErrAttr;
7356 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7357 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7358 << DIA->getParent() << DIA->getCond()->getSourceRange();
7359 return true;
7360 }
7361
7362 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7363 if (IsSuccessful(DIA)) {
7364 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7365 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7366 << DIA->getParent() << DIA->getCond()->getSourceRange();
7367 }
7368
7369 return false;
7370}
7371
7373 const Expr *ThisArg,
7375 SourceLocation Loc) {
7377 *this, Function, /*ArgDependent=*/true, Loc,
7378 [&](const DiagnoseIfAttr *DIA) {
7380 // It's sane to use the same Args for any redecl of this function, since
7381 // EvaluateWithSubstitution only cares about the position of each
7382 // argument in the arg list, not the ParmVarDecl* it maps to.
7383 if (!DIA->getCond()->EvaluateWithSubstitution(
7384 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7385 return false;
7386 return Result.isInt() && Result.getInt().getBoolValue();
7387 });
7388}
7389
7391 SourceLocation Loc) {
7393 *this, ND, /*ArgDependent=*/false, Loc,
7394 [&](const DiagnoseIfAttr *DIA) {
7395 bool Result;
7396 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7397 Result;
7398 });
7399}
7400
7401/// Add all of the function declarations in the given function set to
7402/// the overload candidate set.
7404 ArrayRef<Expr *> Args,
7405 OverloadCandidateSet &CandidateSet,
7406 TemplateArgumentListInfo *ExplicitTemplateArgs,
7407 bool SuppressUserConversions,
7408 bool PartialOverloading,
7409 bool FirstArgumentIsBase) {
7410 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7411 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7412 ArrayRef<Expr *> FunctionArgs = Args;
7413
7414 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7415 FunctionDecl *FD =
7416 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7417
7418 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7419 QualType ObjectType;
7420 Expr::Classification ObjectClassification;
7421 if (Args.size() > 0) {
7422 if (Expr *E = Args[0]) {
7423 // Use the explicit base to restrict the lookup:
7424 ObjectType = E->getType();
7425 // Pointers in the object arguments are implicitly dereferenced, so we
7426 // always classify them as l-values.
7427 if (!ObjectType.isNull() && ObjectType->isPointerType())
7428 ObjectClassification = Expr::Classification::makeSimpleLValue();
7429 else
7430 ObjectClassification = E->Classify(Context);
7431 } // .. else there is an implicit base.
7432 FunctionArgs = Args.slice(1);
7433 }
7434 if (FunTmpl) {
7435 AddMethodTemplateCandidate(
7436 FunTmpl, F.getPair(),
7437 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7438 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7439 FunctionArgs, CandidateSet, SuppressUserConversions,
7440 PartialOverloading);
7441 } else {
7442 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7443 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7444 ObjectClassification, FunctionArgs, CandidateSet,
7445 SuppressUserConversions, PartialOverloading);
7446 }
7447 } else {
7448 // This branch handles both standalone functions and static methods.
7449
7450 // Slice the first argument (which is the base) when we access
7451 // static method as non-static.
7452 if (Args.size() > 0 &&
7453 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7454 !isa<CXXConstructorDecl>(FD)))) {
7455 assert(cast<CXXMethodDecl>(FD)->isStatic());
7456 FunctionArgs = Args.slice(1);
7457 }
7458 if (FunTmpl) {
7459 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7460 ExplicitTemplateArgs, FunctionArgs,
7461 CandidateSet, SuppressUserConversions,
7462 PartialOverloading);
7463 } else {
7464 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7465 SuppressUserConversions, PartialOverloading);
7466 }
7467 }
7468 }
7469}
7470
7471/// AddMethodCandidate - Adds a named decl (which is some kind of
7472/// method) as a method candidate to the given overload set.
7474 Expr::Classification ObjectClassification,
7475 ArrayRef<Expr *> Args,
7476 OverloadCandidateSet &CandidateSet,
7477 bool SuppressUserConversions,
7479 NamedDecl *Decl = FoundDecl.getDecl();
7480 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7481
7482 if (isa<UsingShadowDecl>(Decl))
7483 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7484
7485 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7486 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7487 "Expected a member function template");
7488 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7489 /*ExplicitArgs*/ nullptr, ObjectType,
7490 ObjectClassification, Args, CandidateSet,
7491 SuppressUserConversions, false, PO);
7492 } else {
7493 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7494 ObjectType, ObjectClassification, Args, CandidateSet,
7495 SuppressUserConversions, false, std::nullopt, PO);
7496 }
7497}
7498
7499/// AddMethodCandidate - Adds the given C++ member function to the set
7500/// of candidate functions, using the given function call arguments
7501/// and the object argument (@c Object). For example, in a call
7502/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7503/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7504/// allow user-defined conversions via constructors or conversion
7505/// operators.
7506void
7508 CXXRecordDecl *ActingContext, QualType ObjectType,
7509 Expr::Classification ObjectClassification,
7510 ArrayRef<Expr *> Args,
7511 OverloadCandidateSet &CandidateSet,
7512 bool SuppressUserConversions,
7513 bool PartialOverloading,
7514 ConversionSequenceList EarlyConversions,
7516 const FunctionProtoType *Proto
7517 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7518 assert(Proto && "Methods without a prototype cannot be overloaded");
7519 assert(!isa<CXXConstructorDecl>(Method) &&
7520 "Use AddOverloadCandidate for constructors");
7521
7522 if (!CandidateSet.isNewCandidate(Method, PO))
7523 return;
7524
7525 // C++11 [class.copy]p23: [DR1402]
7526 // A defaulted move assignment operator that is defined as deleted is
7527 // ignored by overload resolution.
7528 if (Method->isDefaulted() && Method->isDeleted() &&
7529 Method->isMoveAssignmentOperator())
7530 return;
7531
7532 // Overload resolution is always an unevaluated context.
7535
7536 // Add this candidate
7537 OverloadCandidate &Candidate =
7538 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7539 Candidate.FoundDecl = FoundDecl;
7540 Candidate.Function = Method;
7541 Candidate.RewriteKind =
7542 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7543 Candidate.IsSurrogate = false;
7544 Candidate.IgnoreObjectArgument = false;
7545 Candidate.ExplicitCallArguments = Args.size();
7546
7547 unsigned NumParams = Method->getNumExplicitParams();
7548 unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7549
7550 // (C++ 13.3.2p2): A candidate function having fewer than m
7551 // parameters is viable only if it has an ellipsis in its parameter
7552 // list (8.3.5).
7553 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7554 !Proto->isVariadic() &&
7555 shouldEnforceArgLimit(PartialOverloading, Method)) {
7556 Candidate.Viable = false;
7558 return;
7559 }
7560
7561 // (C++ 13.3.2p2): A candidate function having more than m parameters
7562 // is viable only if the (m+1)st parameter has a default argument
7563 // (8.3.6). For the purposes of overload resolution, the
7564 // parameter list is truncated on the right, so that there are
7565 // exactly m parameters.
7566 unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7567 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7568 // Not enough arguments.
7569 Candidate.Viable = false;
7571 return;
7572 }
7573
7574 Candidate.Viable = true;
7575
7576 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7577 if (ObjectType.isNull())
7578 Candidate.IgnoreObjectArgument = true;
7579 else if (Method->isStatic()) {
7580 // [over.best.ics.general]p8
7581 // When the parameter is the implicit object parameter of a static member
7582 // function, the implicit conversion sequence is a standard conversion
7583 // sequence that is neither better nor worse than any other standard
7584 // conversion sequence.
7585 //
7586 // This is a rule that was introduced in C++23 to support static lambdas. We
7587 // apply it retroactively because we want to support static lambdas as an
7588 // extension and it doesn't hurt previous code.
7589 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7590 } else {
7591 // Determine the implicit conversion sequence for the object
7592 // parameter.
7593 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7594 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7595 Method, ActingContext, /*InOverloadResolution=*/true);
7596 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7597 Candidate.Viable = false;
7599 return;
7600 }
7601 }
7602
7603 // (CUDA B.1): Check for invalid calls between targets.
7604 if (getLangOpts().CUDA)
7605 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7606 Method)) {
7607 Candidate.Viable = false;
7608 Candidate.FailureKind = ovl_fail_bad_target;
7609 return;
7610 }
7611
7612 if (Method->getTrailingRequiresClause()) {
7613 ConstraintSatisfaction Satisfaction;
7614 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7615 /*ForOverloadResolution*/ true) ||
7616 !Satisfaction.IsSatisfied) {
7617 Candidate.Viable = false;
7619 return;
7620 }
7621 }
7622
7623 // Determine the implicit conversion sequences for each of the
7624 // arguments.
7625 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7626 unsigned ConvIdx =
7627 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7628 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7629 // We already formed a conversion sequence for this parameter during
7630 // template argument deduction.
7631 } else if (ArgIdx < NumParams) {
7632 // (C++ 13.3.2p3): for F to be a viable function, there shall
7633 // exist for each argument an implicit conversion sequence
7634 // (13.3.3.1) that converts that argument to the corresponding
7635 // parameter of F.
7636 QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7637 Candidate.Conversions[ConvIdx]
7638 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7639 SuppressUserConversions,
7640 /*InOverloadResolution=*/true,
7641 /*AllowObjCWritebackConversion=*/
7642 getLangOpts().ObjCAutoRefCount);
7643 if (Candidate.Conversions[ConvIdx].isBad()) {
7644 Candidate.Viable = false;
7646 return;
7647 }
7648 } else {
7649 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7650 // argument for which there is no corresponding parameter is
7651 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7652 Candidate.Conversions[ConvIdx].setEllipsis();
7653 }
7654 }
7655
7656 if (EnableIfAttr *FailedAttr =
7657 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7658 Candidate.Viable = false;
7659 Candidate.FailureKind = ovl_fail_enable_if;
7660 Candidate.DeductionFailure.Data = FailedAttr;
7661 return;
7662 }
7663
7664 if (isNonViableMultiVersionOverload(Method)) {
7665 Candidate.Viable = false;
7667 }
7668}
7669
7670/// Add a C++ member function template as a candidate to the candidate
7671/// set, using template argument deduction to produce an appropriate member
7672/// function template specialization.
7674 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7675 CXXRecordDecl *ActingContext,
7676 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7677 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7678 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7679 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7680 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7681 return;
7682
7683 // C++ [over.match.funcs]p7:
7684 // In each case where a candidate is a function template, candidate
7685 // function template specializations are generated using template argument
7686 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7687 // candidate functions in the usual way.113) A given name can refer to one
7688 // or more function templates and also to a set of overloaded non-template
7689 // functions. In such a case, the candidate functions generated from each
7690 // function template are combined with the set of non-template candidate
7691 // functions.
7692 TemplateDeductionInfo Info(CandidateSet.getLocation());
7693 FunctionDecl *Specialization = nullptr;
7694 ConversionSequenceList Conversions;
7696 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7697 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7698 ObjectClassification,
7699 [&](ArrayRef<QualType> ParamTypes) {
7700 return CheckNonDependentConversions(
7701 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7702 SuppressUserConversions, ActingContext, ObjectType,
7703 ObjectClassification, PO);
7704 });
7706 OverloadCandidate &Candidate =
7707 CandidateSet.addCandidate(Conversions.size(), Conversions);
7708 Candidate.FoundDecl = FoundDecl;
7709 Candidate.Function = MethodTmpl->getTemplatedDecl();
7710 Candidate.Viable = false;
7711 Candidate.RewriteKind =
7712 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7713 Candidate.IsSurrogate = false;
7714 Candidate.IgnoreObjectArgument =
7715 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7716 ObjectType.isNull();
7717 Candidate.ExplicitCallArguments = Args.size();
7720 else {
7723 Info);
7724 }
7725 return;
7726 }
7727
7728 // Add the function template specialization produced by template argument
7729 // deduction as a candidate.
7730 assert(Specialization && "Missing member function template specialization?");
7731 assert(isa<CXXMethodDecl>(Specialization) &&
7732 "Specialization is not a member function?");
7733 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7734 ActingContext, ObjectType, ObjectClassification, Args,
7735 CandidateSet, SuppressUserConversions, PartialOverloading,
7736 Conversions, PO);
7737}
7738
7739/// Determine whether a given function template has a simple explicit specifier
7740/// or a non-value-dependent explicit-specification that evaluates to true.
7743}
7744
7745/// Add a C++ function template specialization as a candidate
7746/// in the candidate set, using template argument deduction to produce
7747/// an appropriate function template specialization.
7749 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7750 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7751 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7752 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7753 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7754 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7755 return;
7756
7757 // If the function template has a non-dependent explicit specification,
7758 // exclude it now if appropriate; we are not permitted to perform deduction
7759 // and substitution in this case.
7760 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7761 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7762 Candidate.FoundDecl = FoundDecl;
7763 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7764 Candidate.Viable = false;
7765 Candidate.FailureKind = ovl_fail_explicit;
7766 return;
7767 }
7768
7769 // C++ [over.match.funcs]p7:
7770 // In each case where a candidate is a function template, candidate
7771 // function template specializations are generated using template argument
7772 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7773 // candidate functions in the usual way.113) A given name can refer to one
7774 // or more function templates and also to a set of overloaded non-template
7775 // functions. In such a case, the candidate functions generated from each
7776 // function template are combined with the set of non-template candidate
7777 // functions.
7778 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7779 FunctionTemplate->getTemplateDepth());
7780 FunctionDecl *Specialization = nullptr;
7781 ConversionSequenceList Conversions;
7783 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7784 PartialOverloading, AggregateCandidateDeduction,
7785 /*ObjectType=*/QualType(),
7786 /*ObjectClassification=*/Expr::Classification(),
7787 [&](ArrayRef<QualType> ParamTypes) {
7788 return CheckNonDependentConversions(
7789 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7790 SuppressUserConversions, nullptr, QualType(), {}, PO);
7791 });
7793 OverloadCandidate &Candidate =
7794 CandidateSet.addCandidate(Conversions.size(), Conversions);
7795 Candidate.FoundDecl = FoundDecl;
7796 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7797 Candidate.Viable = false;
7798 Candidate.RewriteKind =
7799 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7800 Candidate.IsSurrogate = false;
7801 Candidate.IsADLCandidate = IsADLCandidate;
7802 // Ignore the object argument if there is one, since we don't have an object
7803 // type.
7804 Candidate.IgnoreObjectArgument =
7805 isa<CXXMethodDecl>(Candidate.Function) &&
7806 !isa<CXXConstructorDecl>(Candidate.Function);
7807 Candidate.ExplicitCallArguments = Args.size();
7810 else {
7813 Info);
7814 }
7815 return;
7816 }
7817
7818 // Add the function template specialization produced by template argument
7819 // deduction as a candidate.
7820 assert(Specialization && "Missing function template specialization?");
7821 AddOverloadCandidate(
7822 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7823 PartialOverloading, AllowExplicit,
7824 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7826}
7827
7828/// Check that implicit conversion sequences can be formed for each argument
7829/// whose corresponding parameter has a non-dependent type, per DR1391's
7830/// [temp.deduct.call]p10.
7832 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7833 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7834 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7835 CXXRecordDecl *ActingContext, QualType ObjectType,
7836 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7837 // FIXME: The cases in which we allow explicit conversions for constructor
7838 // arguments never consider calling a constructor template. It's not clear
7839 // that is correct.
7840 const bool AllowExplicit = false;
7841
7842 auto *FD = FunctionTemplate->getTemplatedDecl();
7843 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7844 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7845 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7846
7847 Conversions =
7848 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7849
7850 // Overload resolution is always an unevaluated context.
7853
7854 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7855 // require that, but this check should never result in a hard error, and
7856 // overload resolution is permitted to sidestep instantiations.
7857 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7858 !ObjectType.isNull()) {
7859 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7860 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7861 !ParamTypes[0]->isDependentType()) {
7862 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7863 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7864 Method, ActingContext, /*InOverloadResolution=*/true,
7865 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7866 : QualType());
7867 if (Conversions[ConvIdx].isBad())
7868 return true;
7869 }
7870 }
7871
7872 unsigned Offset =
7873 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7874
7875 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7876 I != N; ++I) {
7877 QualType ParamType = ParamTypes[I + Offset];
7878 if (!ParamType->isDependentType()) {
7879 unsigned ConvIdx;
7881 ConvIdx = Args.size() - 1 - I;
7882 assert(Args.size() + ThisConversions == 2 &&
7883 "number of args (including 'this') must be exactly 2 for "
7884 "reversed order");
7885 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7886 // would also be 0. 'this' got ConvIdx = 1 previously.
7887 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7888 } else {
7889 // For members, 'this' got ConvIdx = 0 previously.
7890 ConvIdx = ThisConversions + I;
7891 }
7892 Conversions[ConvIdx]
7893 = TryCopyInitialization(*this, Args[I], ParamType,
7894 SuppressUserConversions,
7895 /*InOverloadResolution=*/true,
7896 /*AllowObjCWritebackConversion=*/
7897 getLangOpts().ObjCAutoRefCount,
7898 AllowExplicit);
7899 if (Conversions[ConvIdx].isBad())
7900 return true;
7901 }
7902 }
7903
7904 return false;
7905}
7906
7907/// Determine whether this is an allowable conversion from the result
7908/// of an explicit conversion operator to the expected type, per C++
7909/// [over.match.conv]p1 and [over.match.ref]p1.
7910///
7911/// \param ConvType The return type of the conversion function.
7912///
7913/// \param ToType The type we are converting to.
7914///
7915/// \param AllowObjCPointerConversion Allow a conversion from one
7916/// Objective-C pointer to another.
7917///
7918/// \returns true if the conversion is allowable, false otherwise.
7920 QualType ConvType, QualType ToType,
7921 bool AllowObjCPointerConversion) {
7922 QualType ToNonRefType = ToType.getNonReferenceType();
7923
7924 // Easy case: the types are the same.
7925 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7926 return true;
7927
7928 // Allow qualification conversions.
7929 bool ObjCLifetimeConversion;
7930 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7931 ObjCLifetimeConversion))
7932 return true;
7933
7934 // If we're not allowed to consider Objective-C pointer conversions,
7935 // we're done.
7936 if (!AllowObjCPointerConversion)
7937 return false;
7938
7939 // Is this an Objective-C pointer conversion?
7940 bool IncompatibleObjC = false;
7941 QualType ConvertedType;
7942 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7943 IncompatibleObjC);
7944}
7945
7946/// AddConversionCandidate - Add a C++ conversion function as a
7947/// candidate in the candidate set (C++ [over.match.conv],
7948/// C++ [over.match.copy]). From is the expression we're converting from,
7949/// and ToType is the type that we're eventually trying to convert to
7950/// (which may or may not be the same type as the type that the
7951/// conversion function produces).
7953 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7954 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7955 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7956 bool AllowExplicit, bool AllowResultConversion) {
7957 assert(!Conversion->getDescribedFunctionTemplate() &&
7958 "Conversion function templates use AddTemplateConversionCandidate");
7959 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7960 if (!CandidateSet.isNewCandidate(Conversion))
7961 return;
7962
7963 // If the conversion function has an undeduced return type, trigger its
7964 // deduction now.
7965 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7966 if (DeduceReturnType(Conversion, From->getExprLoc()))
7967 return;
7968 ConvType = Conversion->getConversionType().getNonReferenceType();
7969 }
7970
7971 // If we don't allow any conversion of the result type, ignore conversion
7972 // functions that don't convert to exactly (possibly cv-qualified) T.
7973 if (!AllowResultConversion &&
7974 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7975 return;
7976
7977 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7978 // operator is only a candidate if its return type is the target type or
7979 // can be converted to the target type with a qualification conversion.
7980 //
7981 // FIXME: Include such functions in the candidate list and explain why we
7982 // can't select them.
7983 if (Conversion->isExplicit() &&
7984 !isAllowableExplicitConversion(*this, ConvType, ToType,
7985 AllowObjCConversionOnExplicit))
7986 return;
7987
7988 // Overload resolution is always an unevaluated context.
7991
7992 // Add this candidate
7993 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7994 Candidate.FoundDecl = FoundDecl;
7995 Candidate.Function = Conversion;
7996 Candidate.IsSurrogate = false;
7997 Candidate.IgnoreObjectArgument = false;
7999 Candidate.FinalConversion.setFromType(ConvType);
8000 Candidate.FinalConversion.setAllToTypes(ToType);
8001 Candidate.Viable = true;
8002 Candidate.ExplicitCallArguments = 1;
8003
8004 // Explicit functions are not actually candidates at all if we're not
8005 // allowing them in this context, but keep them around so we can point
8006 // to them in diagnostics.
8007 if (!AllowExplicit && Conversion->isExplicit()) {
8008 Candidate.Viable = false;
8009 Candidate.FailureKind = ovl_fail_explicit;
8010 return;
8011 }
8012
8013 // C++ [over.match.funcs]p4:
8014 // For conversion functions, the function is considered to be a member of
8015 // the class of the implicit implied object argument for the purpose of
8016 // defining the type of the implicit object parameter.
8017 //
8018 // Determine the implicit conversion sequence for the implicit
8019 // object parameter.
8020 QualType ObjectType = From->getType();
8021 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8022 ObjectType = FromPtrType->getPointeeType();
8023 const auto *ConversionContext =
8024 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8025
8026 // C++23 [over.best.ics.general]
8027 // However, if the target is [...]
8028 // - the object parameter of a user-defined conversion function
8029 // [...] user-defined conversion sequences are not considered.
8031 *this, CandidateSet.getLocation(), From->getType(),
8032 From->Classify(Context), Conversion, ConversionContext,
8033 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8034 /*SuppressUserConversion*/ true);
8035
8036 if (Candidate.Conversions[0].isBad()) {
8037 Candidate.Viable = false;
8039 return;
8040 }
8041
8042 if (Conversion->getTrailingRequiresClause()) {
8043 ConstraintSatisfaction Satisfaction;
8044 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8045 !Satisfaction.IsSatisfied) {
8046 Candidate.Viable = false;
8048 return;
8049 }
8050 }
8051
8052 // We won't go through a user-defined type conversion function to convert a
8053 // derived to base as such conversions are given Conversion Rank. They only
8054 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8055 QualType FromCanon
8056 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8057 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8058 if (FromCanon == ToCanon ||
8059 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8060 Candidate.Viable = false;
8062 return;
8063 }
8064
8065 // To determine what the conversion from the result of calling the
8066 // conversion function to the type we're eventually trying to
8067 // convert to (ToType), we need to synthesize a call to the
8068 // conversion function and attempt copy initialization from it. This
8069 // makes sure that we get the right semantics with respect to
8070 // lvalues/rvalues and the type. Fortunately, we can allocate this
8071 // call on the stack and we don't need its arguments to be
8072 // well-formed.
8073 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8074 VK_LValue, From->getBeginLoc());
8076 Context.getPointerType(Conversion->getType()),
8077 CK_FunctionToPointerDecay, &ConversionRef,
8079
8080 QualType ConversionType = Conversion->getConversionType();
8081 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8082 Candidate.Viable = false;
8084 return;
8085 }
8086
8087 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8088
8089 // Note that it is safe to allocate CallExpr on the stack here because
8090 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8091 // allocator).
8092 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8093
8094 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8095 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8096 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8097
8099 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8100 /*SuppressUserConversions=*/true,
8101 /*InOverloadResolution=*/false,
8102 /*AllowObjCWritebackConversion=*/false);
8103
8104 switch (ICS.getKind()) {
8106 Candidate.FinalConversion = ICS.Standard;
8107
8108 // C++ [over.ics.user]p3:
8109 // If the user-defined conversion is specified by a specialization of a
8110 // conversion function template, the second standard conversion sequence
8111 // shall have exact match rank.
8112 if (Conversion->getPrimaryTemplate() &&
8114 Candidate.Viable = false;
8116 return;
8117 }
8118
8119 // C++0x [dcl.init.ref]p5:
8120 // In the second case, if the reference is an rvalue reference and
8121 // the second standard conversion sequence of the user-defined
8122 // conversion sequence includes an lvalue-to-rvalue conversion, the
8123 // program is ill-formed.
8124 if (ToType->isRValueReferenceType() &&
8126 Candidate.Viable = false;
8128 return;
8129 }
8130 break;
8131
8133 Candidate.Viable = false;
8135 return;
8136
8137 default:
8138 llvm_unreachable(
8139 "Can only end up with a standard conversion sequence or failure");
8140 }
8141
8142 if (EnableIfAttr *FailedAttr =
8143 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8144 Candidate.Viable = false;
8145 Candidate.FailureKind = ovl_fail_enable_if;
8146 Candidate.DeductionFailure.Data = FailedAttr;
8147 return;
8148 }
8149
8150 if (isNonViableMultiVersionOverload(Conversion)) {
8151 Candidate.Viable = false;
8153 }
8154}
8155
8156/// Adds a conversion function template specialization
8157/// candidate to the overload set, using template argument deduction
8158/// to deduce the template arguments of the conversion function
8159/// template from the type that we are converting to (C++
8160/// [temp.deduct.conv]).
8162 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8163 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8164 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8165 bool AllowExplicit, bool AllowResultConversion) {
8166 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8167 "Only conversion function templates permitted here");
8168
8169 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8170 return;
8171
8172 // If the function template has a non-dependent explicit specification,
8173 // exclude it now if appropriate; we are not permitted to perform deduction
8174 // and substitution in this case.
8175 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8176 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8177 Candidate.FoundDecl = FoundDecl;
8178 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8179 Candidate.Viable = false;
8180 Candidate.FailureKind = ovl_fail_explicit;
8181 return;
8182 }
8183
8184 QualType ObjectType = From->getType();
8185 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8186
8187 TemplateDeductionInfo Info(CandidateSet.getLocation());
8190 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8191 Specialization, Info);
8193 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8194 Candidate.FoundDecl = FoundDecl;
8195 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8196 Candidate.Viable = false;
8198 Candidate.IsSurrogate = false;
8199 Candidate.IgnoreObjectArgument = false;
8200 Candidate.ExplicitCallArguments = 1;
8202 Info);
8203 return;
8204 }
8205
8206 // Add the conversion function template specialization produced by
8207 // template argument deduction as a candidate.
8208 assert(Specialization && "Missing function template specialization?");
8209 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8210 CandidateSet, AllowObjCConversionOnExplicit,
8211 AllowExplicit, AllowResultConversion);
8212}
8213
8214/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8215/// converts the given @c Object to a function pointer via the
8216/// conversion function @c Conversion, and then attempts to call it
8217/// with the given arguments (C++ [over.call.object]p2-4). Proto is
8218/// the type of function that we'll eventually be calling.
8220 DeclAccessPair FoundDecl,
8221 CXXRecordDecl *ActingContext,
8222 const FunctionProtoType *Proto,
8223 Expr *Object,
8224 ArrayRef<Expr *> Args,
8225 OverloadCandidateSet& CandidateSet) {
8226 if (!CandidateSet.isNewCandidate(Conversion))
8227 return;
8228
8229 // Overload resolution is always an unevaluated context.
8232
8233 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8234 Candidate.FoundDecl = FoundDecl;
8235 Candidate.Function = nullptr;
8236 Candidate.Surrogate = Conversion;
8237 Candidate.Viable = true;
8238 Candidate.IsSurrogate = true;
8239 Candidate.IgnoreObjectArgument = false;
8240 Candidate.ExplicitCallArguments = Args.size();
8241
8242 // Determine the implicit conversion sequence for the implicit
8243 // object parameter.
8244 ImplicitConversionSequence ObjectInit;
8245 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8246 ObjectInit = TryCopyInitialization(*this, Object,
8247 Conversion->getParamDecl(0)->getType(),
8248 /*SuppressUserConversions=*/false,
8249 /*InOverloadResolution=*/true, false);
8250 } else {
8252 *this, CandidateSet.getLocation(), Object->getType(),
8253 Object->Classify(Context), Conversion, ActingContext);
8254 }
8255
8256 if (ObjectInit.isBad()) {
8257 Candidate.Viable = false;
8259 Candidate.Conversions[0] = ObjectInit;
8260 return;
8261 }
8262
8263 // The first conversion is actually a user-defined conversion whose
8264 // first conversion is ObjectInit's standard conversion (which is
8265 // effectively a reference binding). Record it as such.
8266 Candidate.Conversions[0].setUserDefined();
8267 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8268 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8269 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8270 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8271 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8272 Candidate.Conversions[0].UserDefined.After
8273 = Candidate.Conversions[0].UserDefined.Before;
8274 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8275
8276 // Find the
8277 unsigned NumParams = Proto->getNumParams();
8278
8279 // (C++ 13.3.2p2): A candidate function having fewer than m
8280 // parameters is viable only if it has an ellipsis in its parameter
8281 // list (8.3.5).
8282 if (Args.size() > NumParams && !Proto->isVariadic()) {
8283 Candidate.Viable = false;
8285 return;
8286 }
8287
8288 // Function types don't have any default arguments, so just check if
8289 // we have enough arguments.
8290 if (Args.size() < NumParams) {
8291 // Not enough arguments.
8292 Candidate.Viable = false;
8294 return;
8295 }
8296
8297 // Determine the implicit conversion sequences for each of the
8298 // arguments.
8299 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8300 if (ArgIdx < NumParams) {
8301 // (C++ 13.3.2p3): for F to be a viable function, there shall
8302 // exist for each argument an implicit conversion sequence
8303 // (13.3.3.1) that converts that argument to the corresponding
8304 // parameter of F.
8305 QualType ParamType = Proto->getParamType(ArgIdx);
8306 Candidate.Conversions[ArgIdx + 1]
8307 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8308 /*SuppressUserConversions=*/false,
8309 /*InOverloadResolution=*/false,
8310 /*AllowObjCWritebackConversion=*/
8311 getLangOpts().ObjCAutoRefCount);
8312 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8313 Candidate.Viable = false;
8315 return;
8316 }
8317 } else {
8318 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8319 // argument for which there is no corresponding parameter is
8320 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8321 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8322 }
8323 }
8324
8325 if (Conversion->getTrailingRequiresClause()) {
8326 ConstraintSatisfaction Satisfaction;
8327 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8328 /*ForOverloadResolution*/ true) ||
8329 !Satisfaction.IsSatisfied) {
8330 Candidate.Viable = false;
8332 return;
8333 }
8334 }
8335
8336 if (EnableIfAttr *FailedAttr =
8337 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8338 Candidate.Viable = false;
8339 Candidate.FailureKind = ovl_fail_enable_if;
8340 Candidate.DeductionFailure.Data = FailedAttr;
8341 return;
8342 }
8343}
8344
8345/// Add all of the non-member operator function declarations in the given
8346/// function set to the overload candidate set.
8348 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8349 OverloadCandidateSet &CandidateSet,
8350 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8351 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8352 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8353 ArrayRef<Expr *> FunctionArgs = Args;
8354
8355 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8356 FunctionDecl *FD =
8357 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8358
8359 // Don't consider rewritten functions if we're not rewriting.
8360 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8361 continue;
8362
8363 assert(!isa<CXXMethodDecl>(FD) &&
8364 "unqualified operator lookup found a member function");
8365
8366 if (FunTmpl) {
8367 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8368 FunctionArgs, CandidateSet);
8369 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8370 AddTemplateOverloadCandidate(
8371 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8372 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8373 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8374 } else {
8375 if (ExplicitTemplateArgs)
8376 continue;
8377 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8378 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8379 AddOverloadCandidate(
8380 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8381 false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8383 }
8384 }
8385}
8386
8387/// Add overload candidates for overloaded operators that are
8388/// member functions.
8389///
8390/// Add the overloaded operator candidates that are member functions
8391/// for the operator Op that was used in an operator expression such
8392/// as "x Op y". , Args/NumArgs provides the operator arguments, and
8393/// CandidateSet will store the added overload candidates. (C++
8394/// [over.match.oper]).
8396 SourceLocation OpLoc,
8397 ArrayRef<Expr *> Args,
8398 OverloadCandidateSet &CandidateSet,
8401
8402 // C++ [over.match.oper]p3:
8403 // For a unary operator @ with an operand of a type whose
8404 // cv-unqualified version is T1, and for a binary operator @ with
8405 // a left operand of a type whose cv-unqualified version is T1 and
8406 // a right operand of a type whose cv-unqualified version is T2,
8407 // three sets of candidate functions, designated member
8408 // candidates, non-member candidates and built-in candidates, are
8409 // constructed as follows:
8410 QualType T1 = Args[0]->getType();
8411
8412 // -- If T1 is a complete class type or a class currently being
8413 // defined, the set of member candidates is the result of the
8414 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8415 // the set of member candidates is empty.
8416 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8417 // Complete the type if it can be completed.
8418 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8419 return;
8420 // If the type is neither complete nor being defined, bail out now.
8421 if (!T1Rec->getDecl()->getDefinition())
8422 return;
8423
8424 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8425 LookupQualifiedName(Operators, T1Rec->getDecl());
8426 Operators.suppressAccessDiagnostics();
8427
8428 for (LookupResult::iterator Oper = Operators.begin(),
8429 OperEnd = Operators.end();
8430 Oper != OperEnd; ++Oper) {
8431 if (Oper->getAsFunction() &&
8433 !CandidateSet.getRewriteInfo().shouldAddReversed(
8434 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8435 continue;
8436 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8437 Args[0]->Classify(Context), Args.slice(1),
8438 CandidateSet, /*SuppressUserConversion=*/false, PO);
8439 }
8440 }
8441}
8442
8443/// AddBuiltinCandidate - Add a candidate for a built-in
8444/// operator. ResultTy and ParamTys are the result and parameter types
8445/// of the built-in candidate, respectively. Args and NumArgs are the
8446/// arguments being passed to the candidate. IsAssignmentOperator
8447/// should be true when this built-in candidate is an assignment
8448/// operator. NumContextualBoolArguments is the number of arguments
8449/// (at the beginning of the argument list) that will be contextually
8450/// converted to bool.
8452 OverloadCandidateSet& CandidateSet,
8453 bool IsAssignmentOperator,
8454 unsigned NumContextualBoolArguments) {
8455 // Overload resolution is always an unevaluated context.
8458
8459 // Add this candidate
8460 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8461 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8462 Candidate.Function = nullptr;
8463 Candidate.IsSurrogate = false;
8464 Candidate.IgnoreObjectArgument = false;
8465 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8466
8467 // Determine the implicit conversion sequences for each of the
8468 // arguments.
8469 Candidate.Viable = true;
8470 Candidate.ExplicitCallArguments = Args.size();
8471 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8472 // C++ [over.match.oper]p4:
8473 // For the built-in assignment operators, conversions of the
8474 // left operand are restricted as follows:
8475 // -- no temporaries are introduced to hold the left operand, and
8476 // -- no user-defined conversions are applied to the left
8477 // operand to achieve a type match with the left-most
8478 // parameter of a built-in candidate.
8479 //
8480 // We block these conversions by turning off user-defined
8481 // conversions, since that is the only way that initialization of
8482 // a reference to a non-class type can occur from something that
8483 // is not of the same type.
8484 if (ArgIdx < NumContextualBoolArguments) {
8485 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8486 "Contextual conversion to bool requires bool type");
8487 Candidate.Conversions[ArgIdx]
8488 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8489 } else {
8490 Candidate.Conversions[ArgIdx]
8491 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8492 ArgIdx == 0 && IsAssignmentOperator,
8493 /*InOverloadResolution=*/false,
8494 /*AllowObjCWritebackConversion=*/
8495 getLangOpts().ObjCAutoRefCount);
8496 }
8497 if (Candidate.Conversions[ArgIdx].isBad()) {
8498 Candidate.Viable = false;
8500 break;
8501 }
8502 }
8503}
8504
8505namespace {
8506
8507/// BuiltinCandidateTypeSet - A set of types that will be used for the
8508/// candidate operator functions for built-in operators (C++
8509/// [over.built]). The types are separated into pointer types and
8510/// enumeration types.
8511class BuiltinCandidateTypeSet {
8512 /// TypeSet - A set of types.
8513 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8514
8515 /// PointerTypes - The set of pointer types that will be used in the
8516 /// built-in candidates.
8517 TypeSet PointerTypes;
8518
8519 /// MemberPointerTypes - The set of member pointer types that will be
8520 /// used in the built-in candidates.
8521 TypeSet MemberPointerTypes;
8522
8523 /// EnumerationTypes - The set of enumeration types that will be
8524 /// used in the built-in candidates.
8525 TypeSet EnumerationTypes;
8526
8527 /// The set of vector types that will be used in the built-in
8528 /// candidates.
8529 TypeSet VectorTypes;
8530
8531 /// The set of matrix types that will be used in the built-in
8532 /// candidates.
8533 TypeSet MatrixTypes;
8534
8535 /// The set of _BitInt types that will be used in the built-in candidates.
8536 TypeSet BitIntTypes;
8537
8538 /// A flag indicating non-record types are viable candidates
8539 bool HasNonRecordTypes;
8540
8541 /// A flag indicating whether either arithmetic or enumeration types
8542 /// were present in the candidate set.
8543 bool HasArithmeticOrEnumeralTypes;
8544
8545 /// A flag indicating whether the nullptr type was present in the
8546 /// candidate set.
8547 bool HasNullPtrType;
8548
8549 /// Sema - The semantic analysis instance where we are building the
8550 /// candidate type set.
8551 Sema &SemaRef;
8552
8553 /// Context - The AST context in which we will build the type sets.
8554 ASTContext &Context;
8555
8556 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8557 const Qualifiers &VisibleQuals);
8558 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8559
8560public:
8561 /// iterator - Iterates through the types that are part of the set.
8562 typedef TypeSet::iterator iterator;
8563
8564 BuiltinCandidateTypeSet(Sema &SemaRef)
8565 : HasNonRecordTypes(false),
8566 HasArithmeticOrEnumeralTypes(false),
8567 HasNullPtrType(false),
8568 SemaRef(SemaRef),
8569 Context(SemaRef.Context) { }
8570
8571 void AddTypesConvertedFrom(QualType Ty,
8573 bool AllowUserConversions,
8574 bool AllowExplicitConversions,
8575 const Qualifiers &VisibleTypeConversionsQuals);
8576
8577 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8578 llvm::iterator_range<iterator> member_pointer_types() {
8579 return MemberPointerTypes;
8580 }
8581 llvm::iterator_range<iterator> enumeration_types() {
8582 return EnumerationTypes;
8583 }
8584 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8585 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8586 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8587
8588 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8589 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8590 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8591 bool hasNullPtrType() const { return HasNullPtrType; }
8592};
8593
8594} // end anonymous namespace
8595
8596/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8597/// the set of pointer types along with any more-qualified variants of
8598/// that type. For example, if @p Ty is "int const *", this routine
8599/// will add "int const *", "int const volatile *", "int const
8600/// restrict *", and "int const volatile restrict *" to the set of
8601/// pointer types. Returns true if the add of @p Ty itself succeeded,
8602/// false otherwise.
8603///
8604/// FIXME: what to do about extended qualifiers?
8605bool
8606BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8607 const Qualifiers &VisibleQuals) {
8608
8609 // Insert this type.
8610 if (!PointerTypes.insert(Ty))
8611 return false;
8612
8613 QualType PointeeTy;
8614 const PointerType *PointerTy = Ty->getAs<PointerType>();
8615 bool buildObjCPtr = false;
8616 if (!PointerTy) {
8618 PointeeTy = PTy->getPointeeType();
8619 buildObjCPtr = true;
8620 } else {
8621 PointeeTy = PointerTy->getPointeeType();
8622 }
8623
8624 // Don't add qualified variants of arrays. For one, they're not allowed
8625 // (the qualifier would sink to the element type), and for another, the
8626 // only overload situation where it matters is subscript or pointer +- int,
8627 // and those shouldn't have qualifier variants anyway.
8628 if (PointeeTy->isArrayType())
8629 return true;
8630
8631 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8632 bool hasVolatile = VisibleQuals.hasVolatile();
8633 bool hasRestrict = VisibleQuals.hasRestrict();
8634
8635 // Iterate through all strict supersets of BaseCVR.
8636 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8637 if ((CVR | BaseCVR) != CVR) continue;
8638 // Skip over volatile if no volatile found anywhere in the types.
8639 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8640
8641 // Skip over restrict if no restrict found anywhere in the types, or if
8642 // the type cannot be restrict-qualified.
8643 if ((CVR & Qualifiers::Restrict) &&
8644 (!hasRestrict ||
8645 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8646 continue;
8647
8648 // Build qualified pointee type.
8649 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8650
8651 // Build qualified pointer type.
8652 QualType QPointerTy;
8653 if (!buildObjCPtr)
8654 QPointerTy = Context.getPointerType(QPointeeTy);
8655 else
8656 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8657
8658 // Insert qualified pointer type.
8659 PointerTypes.insert(QPointerTy);
8660 }
8661
8662 return true;
8663}
8664
8665/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8666/// to the set of pointer types along with any more-qualified variants of
8667/// that type. For example, if @p Ty is "int const *", this routine
8668/// will add "int const *", "int const volatile *", "int const
8669/// restrict *", and "int const volatile restrict *" to the set of
8670/// pointer types. Returns true if the add of @p Ty itself succeeded,
8671/// false otherwise.
8672///
8673/// FIXME: what to do about extended qualifiers?
8674bool
8675BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8676 QualType Ty) {
8677 // Insert this type.
8678 if (!MemberPointerTypes.insert(Ty))
8679 return false;
8680
8681 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8682 assert(PointerTy && "type was not a member pointer type!");
8683
8684 QualType PointeeTy = PointerTy->getPointeeType();
8685 // Don't add qualified variants of arrays. For one, they're not allowed
8686 // (the qualifier would sink to the element type), and for another, the
8687 // only overload situation where it matters is subscript or pointer +- int,
8688 // and those shouldn't have qualifier variants anyway.
8689 if (PointeeTy->isArrayType())
8690 return true;
8691 const Type *ClassTy = PointerTy->getClass();
8692
8693 // Iterate through all strict supersets of the pointee type's CVR
8694 // qualifiers.
8695 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8696 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8697 if ((CVR | BaseCVR) != CVR) continue;
8698
8699 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8700 MemberPointerTypes.insert(
8701 Context.getMemberPointerType(QPointeeTy, ClassTy));
8702 }
8703
8704 return true;
8705}
8706
8707/// AddTypesConvertedFrom - Add each of the types to which the type @p
8708/// Ty can be implicit converted to the given set of @p Types. We're
8709/// primarily interested in pointer types and enumeration types. We also
8710/// take member pointer types, for the conditional operator.
8711/// AllowUserConversions is true if we should look at the conversion
8712/// functions of a class type, and AllowExplicitConversions if we
8713/// should also include the explicit conversion functions of a class
8714/// type.
8715void
8716BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8717 SourceLocation Loc,
8718 bool AllowUserConversions,
8719 bool AllowExplicitConversions,
8720 const Qualifiers &VisibleQuals) {
8721 // Only deal with canonical types.
8722 Ty = Context.getCanonicalType(Ty);
8723
8724 // Look through reference types; they aren't part of the type of an
8725 // expression for the purposes of conversions.
8726 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8727 Ty = RefTy->getPointeeType();
8728
8729 // If we're dealing with an array type, decay to the pointer.
8730 if (Ty->isArrayType())
8731 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8732
8733 // Otherwise, we don't care about qualifiers on the type.
8734 Ty = Ty.getLocalUnqualifiedType();
8735
8736 // Flag if we ever add a non-record type.
8737 const RecordType *TyRec = Ty->getAs<RecordType>();
8738 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8739
8740 // Flag if we encounter an arithmetic type.
8741 HasArithmeticOrEnumeralTypes =
8742 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8743
8744 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8745 PointerTypes.insert(Ty);
8746 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8747 // Insert our type, and its more-qualified variants, into the set
8748 // of types.
8749 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8750 return;
8751 } else if (Ty->isMemberPointerType()) {
8752 // Member pointers are far easier, since the pointee can't be converted.
8753 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8754 return;
8755 } else if (Ty->isEnumeralType()) {
8756 HasArithmeticOrEnumeralTypes = true;
8757 EnumerationTypes.insert(Ty);
8758 } else if (Ty->isBitIntType()) {
8759 HasArithmeticOrEnumeralTypes = true;
8760 BitIntTypes.insert(Ty);
8761 } else if (Ty->isVectorType()) {
8762 // We treat vector types as arithmetic types in many contexts as an
8763 // extension.
8764 HasArithmeticOrEnumeralTypes = true;
8765 VectorTypes.insert(Ty);
8766 } else if (Ty->isMatrixType()) {
8767 // Similar to vector types, we treat vector types as arithmetic types in
8768 // many contexts as an extension.
8769 HasArithmeticOrEnumeralTypes = true;
8770 MatrixTypes.insert(Ty);
8771 } else if (Ty->isNullPtrType()) {
8772 HasNullPtrType = true;
8773 } else if (AllowUserConversions && TyRec) {
8774 // No conversion functions in incomplete types.
8775 if (!SemaRef.isCompleteType(Loc, Ty))
8776 return;
8777
8778 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8779 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8780 if (isa<UsingShadowDecl>(D))
8781 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8782
8783 // Skip conversion function templates; they don't tell us anything
8784 // about which builtin types we can convert to.
8785 if (isa<FunctionTemplateDecl>(D))
8786 continue;
8787
8788 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8789 if (AllowExplicitConversions || !Conv->isExplicit()) {
8790 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8791 VisibleQuals);
8792 }
8793 }
8794 }
8795}
8796/// Helper function for adjusting address spaces for the pointer or reference
8797/// operands of builtin operators depending on the argument.
8799 Expr *Arg) {
8801}
8802
8803/// Helper function for AddBuiltinOperatorCandidates() that adds
8804/// the volatile- and non-volatile-qualified assignment operators for the
8805/// given type to the candidate set.
8807 QualType T,
8808 ArrayRef<Expr *> Args,
8809 OverloadCandidateSet &CandidateSet) {
8810 QualType ParamTypes[2];
8811
8812 // T& operator=(T&, T)
8813 ParamTypes[0] = S.Context.getLValueReferenceType(
8815 ParamTypes[1] = T;
8816 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8817 /*IsAssignmentOperator=*/true);
8818
8820 // volatile T& operator=(volatile T&, T)
8821 ParamTypes[0] = S.Context.getLValueReferenceType(
8823 Args[0]));
8824 ParamTypes[1] = T;
8825 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8826 /*IsAssignmentOperator=*/true);
8827 }
8828}
8829
8830/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8831/// if any, found in visible type conversion functions found in ArgExpr's type.
8832static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8833 Qualifiers VRQuals;
8834 const RecordType *TyRec;
8835 if (const MemberPointerType *RHSMPType =
8836 ArgExpr->getType()->getAs<MemberPointerType>())
8837 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8838 else
8839 TyRec = ArgExpr->getType()->getAs<RecordType>();
8840 if (!TyRec) {
8841 // Just to be safe, assume the worst case.
8842 VRQuals.addVolatile();
8843 VRQuals.addRestrict();
8844 return VRQuals;
8845 }
8846
8847 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8848 if (!ClassDecl->hasDefinition())
8849 return VRQuals;
8850
8851 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8852 if (isa<UsingShadowDecl>(D))
8853 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8854 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8855 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8856 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8857 CanTy = ResTypeRef->getPointeeType();
8858 // Need to go down the pointer/mempointer chain and add qualifiers
8859 // as see them.
8860 bool done = false;
8861 while (!done) {
8862 if (CanTy.isRestrictQualified())
8863 VRQuals.addRestrict();
8864 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8865 CanTy = ResTypePtr->getPointeeType();
8866 else if (const MemberPointerType *ResTypeMPtr =
8867 CanTy->getAs<MemberPointerType>())
8868 CanTy = ResTypeMPtr->getPointeeType();
8869 else
8870 done = true;
8871 if (CanTy.isVolatileQualified())
8872 VRQuals.addVolatile();
8873 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8874 return VRQuals;
8875 }
8876 }
8877 }
8878 return VRQuals;
8879}
8880
8881// Note: We're currently only handling qualifiers that are meaningful for the
8882// LHS of compound assignment overloading.
8884 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8885 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8886 // _Atomic
8887 if (Available.hasAtomic()) {
8888 Available.removeAtomic();
8889 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8890 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8891 return;
8892 }
8893
8894 // volatile
8895 if (Available.hasVolatile()) {
8896 Available.removeVolatile();
8897 assert(!Applied.hasVolatile());
8898 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8899 Callback);
8900 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8901 return;
8902 }
8903
8904 Callback(Applied);
8905}
8906
8908 QualifiersAndAtomic Quals,
8909 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8911 Callback);
8912}
8913
8915 QualifiersAndAtomic Quals,
8916 Sema &S) {
8917 if (Quals.hasAtomic())
8919 if (Quals.hasVolatile())
8922}
8923
8924namespace {
8925
8926/// Helper class to manage the addition of builtin operator overload
8927/// candidates. It provides shared state and utility methods used throughout
8928/// the process, as well as a helper method to add each group of builtin
8929/// operator overloads from the standard to a candidate set.
8930class BuiltinOperatorOverloadBuilder {
8931 // Common instance state available to all overload candidate addition methods.
8932 Sema &S;
8933 ArrayRef<Expr *> Args;
8934 QualifiersAndAtomic VisibleTypeConversionsQuals;
8935 bool HasArithmeticOrEnumeralCandidateType;
8937 OverloadCandidateSet &CandidateSet;
8938
8939 static constexpr int ArithmeticTypesCap = 26;
8941
8942 // Define some indices used to iterate over the arithmetic types in
8943 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8944 // types are that preserved by promotion (C++ [over.built]p2).
8945 unsigned FirstIntegralType,
8946 LastIntegralType;
8947 unsigned FirstPromotedIntegralType,
8948 LastPromotedIntegralType;
8949 unsigned FirstPromotedArithmeticType,
8950 LastPromotedArithmeticType;
8951 unsigned NumArithmeticTypes;
8952
8953 void InitArithmeticTypes() {
8954 // Start of promoted types.
8955 FirstPromotedArithmeticType = 0;
8956 ArithmeticTypes.push_back(S.Context.FloatTy);
8957 ArithmeticTypes.push_back(S.Context.DoubleTy);
8958 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8960 ArithmeticTypes.push_back(S.Context.Float128Ty);
8962 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8963
8964 // Start of integral types.
8965 FirstIntegralType = ArithmeticTypes.size();
8966 FirstPromotedIntegralType = ArithmeticTypes.size();
8967 ArithmeticTypes.push_back(S.Context.IntTy);
8968 ArithmeticTypes.push_back(S.Context.LongTy);
8969 ArithmeticTypes.push_back(S.Context.LongLongTy);
8973 ArithmeticTypes.push_back(S.Context.Int128Ty);
8974 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8975 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8976 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8980 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8981
8982 /// We add candidates for the unique, unqualified _BitInt types present in
8983 /// the candidate type set. The candidate set already handled ensuring the
8984 /// type is unqualified and canonical, but because we're adding from N
8985 /// different sets, we need to do some extra work to unique things. Insert
8986 /// the candidates into a unique set, then move from that set into the list
8987 /// of arithmetic types.
8988 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8989 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8990 BuiltinCandidateTypeSet &Candidate) {
8991 for (QualType BitTy : Candidate.bitint_types())
8992 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8993 });
8994 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8995 LastPromotedIntegralType = ArithmeticTypes.size();
8996 LastPromotedArithmeticType = ArithmeticTypes.size();
8997 // End of promoted types.
8998
8999 ArithmeticTypes.push_back(S.Context.BoolTy);
9000 ArithmeticTypes.push_back(S.Context.CharTy);
9001 ArithmeticTypes.push_back(S.Context.WCharTy);
9002 if (S.Context.getLangOpts().Char8)
9003 ArithmeticTypes.push_back(S.Context.Char8Ty);
9004 ArithmeticTypes.push_back(S.Context.Char16Ty);
9005 ArithmeticTypes.push_back(S.Context.Char32Ty);
9006 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9007 ArithmeticTypes.push_back(S.Context.ShortTy);
9008 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9009 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9010 LastIntegralType = ArithmeticTypes.size();
9011 NumArithmeticTypes = ArithmeticTypes.size();
9012 // End of integral types.
9013 // FIXME: What about complex? What about half?
9014
9015 // We don't know for sure how many bit-precise candidates were involved, so
9016 // we subtract those from the total when testing whether we're under the
9017 // cap or not.
9018 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9019 ArithmeticTypesCap &&
9020 "Enough inline storage for all arithmetic types.");
9021 }
9022
9023 /// Helper method to factor out the common pattern of adding overloads
9024 /// for '++' and '--' builtin operators.
9025 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9026 bool HasVolatile,
9027 bool HasRestrict) {
9028 QualType ParamTypes[2] = {
9029 S.Context.getLValueReferenceType(CandidateTy),
9030 S.Context.IntTy
9031 };
9032
9033 // Non-volatile version.
9034 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9035
9036 // Use a heuristic to reduce number of builtin candidates in the set:
9037 // add volatile version only if there are conversions to a volatile type.
9038 if (HasVolatile) {
9039 ParamTypes[0] =
9041 S.Context.getVolatileType(CandidateTy));
9042 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9043 }
9044
9045 // Add restrict version only if there are conversions to a restrict type
9046 // and our candidate type is a non-restrict-qualified pointer.
9047 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9048 !CandidateTy.isRestrictQualified()) {
9049 ParamTypes[0]
9052 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9053
9054 if (HasVolatile) {
9055 ParamTypes[0]
9057 S.Context.getCVRQualifiedType(CandidateTy,
9060 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9061 }
9062 }
9063
9064 }
9065
9066 /// Helper to add an overload candidate for a binary builtin with types \p L
9067 /// and \p R.
9068 void AddCandidate(QualType L, QualType R) {
9069 QualType LandR[2] = {L, R};
9070 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9071 }
9072
9073public:
9074 BuiltinOperatorOverloadBuilder(
9075 Sema &S, ArrayRef<Expr *> Args,
9076 QualifiersAndAtomic VisibleTypeConversionsQuals,
9077 bool HasArithmeticOrEnumeralCandidateType,
9079 OverloadCandidateSet &CandidateSet)
9080 : S(S), Args(Args),
9081 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9082 HasArithmeticOrEnumeralCandidateType(
9083 HasArithmeticOrEnumeralCandidateType),
9084 CandidateTypes(CandidateTypes),
9085 CandidateSet(CandidateSet) {
9086
9087 InitArithmeticTypes();
9088 }
9089
9090 // Increment is deprecated for bool since C++17.
9091 //
9092 // C++ [over.built]p3:
9093 //
9094 // For every pair (T, VQ), where T is an arithmetic type other
9095 // than bool, and VQ is either volatile or empty, there exist
9096 // candidate operator functions of the form
9097 //
9098 // VQ T& operator++(VQ T&);
9099 // T operator++(VQ T&, int);
9100 //
9101 // C++ [over.built]p4:
9102 //
9103 // For every pair (T, VQ), where T is an arithmetic type other
9104 // than bool, and VQ is either volatile or empty, there exist
9105 // candidate operator functions of the form
9106 //
9107 // VQ T& operator--(VQ T&);
9108 // T operator--(VQ T&, int);
9109 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9110 if (!HasArithmeticOrEnumeralCandidateType)
9111 return;
9112
9113 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9114 const auto TypeOfT = ArithmeticTypes[Arith];
9115 if (TypeOfT == S.Context.BoolTy) {
9116 if (Op == OO_MinusMinus)
9117 continue;
9118 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9119 continue;
9120 }
9121 addPlusPlusMinusMinusStyleOverloads(
9122 TypeOfT,
9123 VisibleTypeConversionsQuals.hasVolatile(),
9124 VisibleTypeConversionsQuals.hasRestrict());
9125 }
9126 }
9127
9128 // C++ [over.built]p5:
9129 //
9130 // For every pair (T, VQ), where T is a cv-qualified or
9131 // cv-unqualified object type, and VQ is either volatile or
9132 // empty, there exist candidate operator functions of the form
9133 //
9134 // T*VQ& operator++(T*VQ&);
9135 // T*VQ& operator--(T*VQ&);
9136 // T* operator++(T*VQ&, int);
9137 // T* operator--(T*VQ&, int);
9138 void addPlusPlusMinusMinusPointerOverloads() {
9139 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9140 // Skip pointer types that aren't pointers to object types.
9141 if (!PtrTy->getPointeeType()->isObjectType())
9142 continue;
9143
9144 addPlusPlusMinusMinusStyleOverloads(
9145 PtrTy,
9146 (!PtrTy.isVolatileQualified() &&
9147 VisibleTypeConversionsQuals.hasVolatile()),
9148 (!PtrTy.isRestrictQualified() &&
9149 VisibleTypeConversionsQuals.hasRestrict()));
9150 }
9151 }
9152
9153 // C++ [over.built]p6:
9154 // For every cv-qualified or cv-unqualified object type T, there
9155 // exist candidate operator functions of the form
9156 //
9157 // T& operator*(T*);
9158 //
9159 // C++ [over.built]p7:
9160 // For every function type T that does not have cv-qualifiers or a
9161 // ref-qualifier, there exist candidate operator functions of the form
9162 // T& operator*(T*);
9163 void addUnaryStarPointerOverloads() {
9164 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9165 QualType PointeeTy = ParamTy->getPointeeType();
9166 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9167 continue;
9168
9169 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9170 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9171 continue;
9172
9173 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9174 }
9175 }
9176
9177 // C++ [over.built]p9:
9178 // For every promoted arithmetic type T, there exist candidate
9179 // operator functions of the form
9180 //
9181 // T operator+(T);
9182 // T operator-(T);
9183 void addUnaryPlusOrMinusArithmeticOverloads() {
9184 if (!HasArithmeticOrEnumeralCandidateType)
9185 return;
9186
9187 for (unsigned Arith = FirstPromotedArithmeticType;
9188 Arith < LastPromotedArithmeticType; ++Arith) {
9189 QualType ArithTy = ArithmeticTypes[Arith];
9190 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9191 }
9192
9193 // Extension: We also add these operators for vector types.
9194 for (QualType VecTy : CandidateTypes[0].vector_types())
9195 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9196 }
9197
9198 // C++ [over.built]p8:
9199 // For every type T, there exist candidate operator functions of
9200 // the form
9201 //
9202 // T* operator+(T*);
9203 void addUnaryPlusPointerOverloads() {
9204 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9205 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9206 }
9207
9208 // C++ [over.built]p10:
9209 // For every promoted integral type T, there exist candidate
9210 // operator functions of the form
9211 //
9212 // T operator~(T);
9213 void addUnaryTildePromotedIntegralOverloads() {
9214 if (!HasArithmeticOrEnumeralCandidateType)
9215 return;
9216
9217 for (unsigned Int = FirstPromotedIntegralType;
9218 Int < LastPromotedIntegralType; ++Int) {
9219 QualType IntTy = ArithmeticTypes[Int];
9220 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9221 }
9222
9223 // Extension: We also add this operator for vector types.
9224 for (QualType VecTy : CandidateTypes[0].vector_types())
9225 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9226 }
9227
9228 // C++ [over.match.oper]p16:
9229 // For every pointer to member type T or type std::nullptr_t, there
9230 // exist candidate operator functions of the form
9231 //
9232 // bool operator==(T,T);
9233 // bool operator!=(T,T);
9234 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9235 /// Set of (canonical) types that we've already handled.
9237
9238 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9239 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9240 // Don't add the same builtin candidate twice.
9241 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9242 continue;
9243
9244 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9245 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9246 }
9247
9248 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9250 if (AddedTypes.insert(NullPtrTy).second) {
9251 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9252 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9253 }
9254 }
9255 }
9256 }
9257
9258 // C++ [over.built]p15:
9259 //
9260 // For every T, where T is an enumeration type or a pointer type,
9261 // there exist candidate operator functions of the form
9262 //
9263 // bool operator<(T, T);
9264 // bool operator>(T, T);
9265 // bool operator<=(T, T);
9266 // bool operator>=(T, T);
9267 // bool operator==(T, T);
9268 // bool operator!=(T, T);
9269 // R operator<=>(T, T)
9270 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9271 // C++ [over.match.oper]p3:
9272 // [...]the built-in candidates include all of the candidate operator
9273 // functions defined in 13.6 that, compared to the given operator, [...]
9274 // do not have the same parameter-type-list as any non-template non-member
9275 // candidate.
9276 //
9277 // Note that in practice, this only affects enumeration types because there
9278 // aren't any built-in candidates of record type, and a user-defined operator
9279 // must have an operand of record or enumeration type. Also, the only other
9280 // overloaded operator with enumeration arguments, operator=,
9281 // cannot be overloaded for enumeration types, so this is the only place
9282 // where we must suppress candidates like this.
9284 UserDefinedBinaryOperators;
9285
9286 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9287 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9288 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9289 CEnd = CandidateSet.end();
9290 C != CEnd; ++C) {
9291 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9292 continue;
9293
9294 if (C->Function->isFunctionTemplateSpecialization())
9295 continue;
9296
9297 // We interpret "same parameter-type-list" as applying to the
9298 // "synthesized candidate, with the order of the two parameters
9299 // reversed", not to the original function.
9300 bool Reversed = C->isReversed();
9301 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9302 ->getType()
9303 .getUnqualifiedType();
9304 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9305 ->getType()
9306 .getUnqualifiedType();
9307
9308 // Skip if either parameter isn't of enumeral type.
9309 if (!FirstParamType->isEnumeralType() ||
9310 !SecondParamType->isEnumeralType())
9311 continue;
9312
9313 // Add this operator to the set of known user-defined operators.
9314 UserDefinedBinaryOperators.insert(
9315 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9316 S.Context.getCanonicalType(SecondParamType)));
9317 }
9318 }
9319 }
9320
9321 /// Set of (canonical) types that we've already handled.
9323
9324 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9325 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9326 // Don't add the same builtin candidate twice.
9327 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9328 continue;
9329 if (IsSpaceship && PtrTy->isFunctionPointerType())
9330 continue;
9331
9332 QualType ParamTypes[2] = {PtrTy, PtrTy};
9333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9334 }
9335 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9336 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9337
9338 // Don't add the same builtin candidate twice, or if a user defined
9339 // candidate exists.
9340 if (!AddedTypes.insert(CanonType).second ||
9341 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9342 CanonType)))
9343 continue;
9344 QualType ParamTypes[2] = {EnumTy, EnumTy};
9345 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9346 }
9347 }
9348 }
9349
9350 // C++ [over.built]p13:
9351 //
9352 // For every cv-qualified or cv-unqualified object type T
9353 // there exist candidate operator functions of the form
9354 //
9355 // T* operator+(T*, ptrdiff_t);
9356 // T& operator[](T*, ptrdiff_t); [BELOW]
9357 // T* operator-(T*, ptrdiff_t);
9358 // T* operator+(ptrdiff_t, T*);
9359 // T& operator[](ptrdiff_t, T*); [BELOW]
9360 //
9361 // C++ [over.built]p14:
9362 //
9363 // For every T, where T is a pointer to object type, there
9364 // exist candidate operator functions of the form
9365 //
9366 // ptrdiff_t operator-(T, T);
9367 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9368 /// Set of (canonical) types that we've already handled.
9370
9371 for (int Arg = 0; Arg < 2; ++Arg) {
9372 QualType AsymmetricParamTypes[2] = {
9375 };
9376 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9377 QualType PointeeTy = PtrTy->getPointeeType();
9378 if (!PointeeTy->isObjectType())
9379 continue;
9380
9381 AsymmetricParamTypes[Arg] = PtrTy;
9382 if (Arg == 0 || Op == OO_Plus) {
9383 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9384 // T* operator+(ptrdiff_t, T*);
9385 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9386 }
9387 if (Op == OO_Minus) {
9388 // ptrdiff_t operator-(T, T);
9389 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9390 continue;
9391
9392 QualType ParamTypes[2] = {PtrTy, PtrTy};
9393 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9394 }
9395 }
9396 }
9397 }
9398
9399 // C++ [over.built]p12:
9400 //
9401 // For every pair of promoted arithmetic types L and R, there
9402 // exist candidate operator functions of the form
9403 //
9404 // LR operator*(L, R);
9405 // LR operator/(L, R);
9406 // LR operator+(L, R);
9407 // LR operator-(L, R);
9408 // bool operator<(L, R);
9409 // bool operator>(L, R);
9410 // bool operator<=(L, R);
9411 // bool operator>=(L, R);
9412 // bool operator==(L, R);
9413 // bool operator!=(L, R);
9414 //
9415 // where LR is the result of the usual arithmetic conversions
9416 // between types L and R.
9417 //
9418 // C++ [over.built]p24:
9419 //
9420 // For every pair of promoted arithmetic types L and R, there exist
9421 // candidate operator functions of the form
9422 //
9423 // LR operator?(bool, L, R);
9424 //
9425 // where LR is the result of the usual arithmetic conversions
9426 // between types L and R.
9427 // Our candidates ignore the first parameter.
9428 void addGenericBinaryArithmeticOverloads() {
9429 if (!HasArithmeticOrEnumeralCandidateType)
9430 return;
9431
9432 for (unsigned Left = FirstPromotedArithmeticType;
9433 Left < LastPromotedArithmeticType; ++Left) {
9434 for (unsigned Right = FirstPromotedArithmeticType;
9435 Right < LastPromotedArithmeticType; ++Right) {
9436 QualType LandR[2] = { ArithmeticTypes[Left],
9437 ArithmeticTypes[Right] };
9438 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9439 }
9440 }
9441
9442 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9443 // conditional operator for vector types.
9444 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9445 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9446 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9447 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9448 }
9449 }
9450
9451 /// Add binary operator overloads for each candidate matrix type M1, M2:
9452 /// * (M1, M1) -> M1
9453 /// * (M1, M1.getElementType()) -> M1
9454 /// * (M2.getElementType(), M2) -> M2
9455 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9456 void addMatrixBinaryArithmeticOverloads() {
9457 if (!HasArithmeticOrEnumeralCandidateType)
9458 return;
9459
9460 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9461 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9462 AddCandidate(M1, M1);
9463 }
9464
9465 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9466 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9467 if (!CandidateTypes[0].containsMatrixType(M2))
9468 AddCandidate(M2, M2);
9469 }
9470 }
9471
9472 // C++2a [over.built]p14:
9473 //
9474 // For every integral type T there exists a candidate operator function
9475 // of the form
9476 //
9477 // std::strong_ordering operator<=>(T, T)
9478 //
9479 // C++2a [over.built]p15:
9480 //
9481 // For every pair of floating-point types L and R, there exists a candidate
9482 // operator function of the form
9483 //
9484 // std::partial_ordering operator<=>(L, R);
9485 //
9486 // FIXME: The current specification for integral types doesn't play nice with
9487 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9488 // comparisons. Under the current spec this can lead to ambiguity during
9489 // overload resolution. For example:
9490 //
9491 // enum A : int {a};
9492 // auto x = (a <=> (long)42);
9493 //
9494 // error: call is ambiguous for arguments 'A' and 'long'.
9495 // note: candidate operator<=>(int, int)
9496 // note: candidate operator<=>(long, long)
9497 //
9498 // To avoid this error, this function deviates from the specification and adds
9499 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9500 // arithmetic types (the same as the generic relational overloads).
9501 //
9502 // For now this function acts as a placeholder.
9503 void addThreeWayArithmeticOverloads() {
9504 addGenericBinaryArithmeticOverloads();
9505 }
9506
9507 // C++ [over.built]p17:
9508 //
9509 // For every pair of promoted integral types L and R, there
9510 // exist candidate operator functions of the form
9511 //
9512 // LR operator%(L, R);
9513 // LR operator&(L, R);
9514 // LR operator^(L, R);
9515 // LR operator|(L, R);
9516 // L operator<<(L, R);
9517 // L operator>>(L, R);
9518 //
9519 // where LR is the result of the usual arithmetic conversions
9520 // between types L and R.
9521 void addBinaryBitwiseArithmeticOverloads() {
9522 if (!HasArithmeticOrEnumeralCandidateType)
9523 return;
9524
9525 for (unsigned Left = FirstPromotedIntegralType;
9526 Left < LastPromotedIntegralType; ++Left) {
9527 for (unsigned Right = FirstPromotedIntegralType;
9528 Right < LastPromotedIntegralType; ++Right) {
9529 QualType LandR[2] = { ArithmeticTypes[Left],
9530 ArithmeticTypes[Right] };
9531 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9532 }
9533 }
9534 }
9535
9536 // C++ [over.built]p20:
9537 //
9538 // For every pair (T, VQ), where T is an enumeration or
9539 // pointer to member type and VQ is either volatile or
9540 // empty, there exist candidate operator functions of the form
9541 //
9542 // VQ T& operator=(VQ T&, T);
9543 void addAssignmentMemberPointerOrEnumeralOverloads() {
9544 /// Set of (canonical) types that we've already handled.
9546
9547 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9548 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9549 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9550 continue;
9551
9552 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9553 }
9554
9555 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9556 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9557 continue;
9558
9559 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9560 }
9561 }
9562 }
9563
9564 // C++ [over.built]p19:
9565 //
9566 // For every pair (T, VQ), where T is any type and VQ is either
9567 // volatile or empty, there exist candidate operator functions
9568 // of the form
9569 //
9570 // T*VQ& operator=(T*VQ&, T*);
9571 //
9572 // C++ [over.built]p21:
9573 //
9574 // For every pair (T, VQ), where T is a cv-qualified or
9575 // cv-unqualified object type and VQ is either volatile or
9576 // empty, there exist candidate operator functions of the form
9577 //
9578 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9579 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9580 void addAssignmentPointerOverloads(bool isEqualOp) {
9581 /// Set of (canonical) types that we've already handled.
9583
9584 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9585 // If this is operator=, keep track of the builtin candidates we added.
9586 if (isEqualOp)
9587 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9588 else if (!PtrTy->getPointeeType()->isObjectType())
9589 continue;
9590
9591 // non-volatile version
9592 QualType ParamTypes[2] = {
9594 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9595 };
9596 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9597 /*IsAssignmentOperator=*/ isEqualOp);
9598
9599 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9600 VisibleTypeConversionsQuals.hasVolatile();
9601 if (NeedVolatile) {
9602 // volatile version
9603 ParamTypes[0] =
9605 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9606 /*IsAssignmentOperator=*/isEqualOp);
9607 }
9608
9609 if (!PtrTy.isRestrictQualified() &&
9610 VisibleTypeConversionsQuals.hasRestrict()) {
9611 // restrict version
9612 ParamTypes[0] =
9614 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9615 /*IsAssignmentOperator=*/isEqualOp);
9616
9617 if (NeedVolatile) {
9618 // volatile restrict version
9619 ParamTypes[0] =
9622 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9623 /*IsAssignmentOperator=*/isEqualOp);
9624 }
9625 }
9626 }
9627
9628 if (isEqualOp) {
9629 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9630 // Make sure we don't add the same candidate twice.
9631 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9632 continue;
9633
9634 QualType ParamTypes[2] = {
9636 PtrTy,
9637 };
9638
9639 // non-volatile version
9640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9641 /*IsAssignmentOperator=*/true);
9642
9643 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9644 VisibleTypeConversionsQuals.hasVolatile();
9645 if (NeedVolatile) {
9646 // volatile version
9647 ParamTypes[0] = S.Context.getLValueReferenceType(
9648 S.Context.getVolatileType(PtrTy));
9649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9650 /*IsAssignmentOperator=*/true);
9651 }
9652
9653 if (!PtrTy.isRestrictQualified() &&
9654 VisibleTypeConversionsQuals.hasRestrict()) {
9655 // restrict version
9656 ParamTypes[0] = S.Context.getLValueReferenceType(
9657 S.Context.getRestrictType(PtrTy));
9658 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9659 /*IsAssignmentOperator=*/true);
9660
9661 if (NeedVolatile) {
9662 // volatile restrict version
9663 ParamTypes[0] =
9666 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9667 /*IsAssignmentOperator=*/true);
9668 }
9669 }
9670 }
9671 }
9672 }
9673
9674 // C++ [over.built]p18:
9675 //
9676 // For every triple (L, VQ, R), where L is an arithmetic type,
9677 // VQ is either volatile or empty, and R is a promoted
9678 // arithmetic type, there exist candidate operator functions of
9679 // the form
9680 //
9681 // VQ L& operator=(VQ L&, R);
9682 // VQ L& operator*=(VQ L&, R);
9683 // VQ L& operator/=(VQ L&, R);
9684 // VQ L& operator+=(VQ L&, R);
9685 // VQ L& operator-=(VQ L&, R);
9686 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9687 if (!HasArithmeticOrEnumeralCandidateType)
9688 return;
9689
9690 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9691 for (unsigned Right = FirstPromotedArithmeticType;
9692 Right < LastPromotedArithmeticType; ++Right) {
9693 QualType ParamTypes[2];
9694 ParamTypes[1] = ArithmeticTypes[Right];
9696 S, ArithmeticTypes[Left], Args[0]);
9697
9699 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9700 ParamTypes[0] =
9701 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9702 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9703 /*IsAssignmentOperator=*/isEqualOp);
9704 });
9705 }
9706 }
9707
9708 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9709 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9710 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9711 QualType ParamTypes[2];
9712 ParamTypes[1] = Vec2Ty;
9713 // Add this built-in operator as a candidate (VQ is empty).
9714 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9715 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9716 /*IsAssignmentOperator=*/isEqualOp);
9717
9718 // Add this built-in operator as a candidate (VQ is 'volatile').
9719 if (VisibleTypeConversionsQuals.hasVolatile()) {
9720 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9721 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9722 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9723 /*IsAssignmentOperator=*/isEqualOp);
9724 }
9725 }
9726 }
9727
9728 // C++ [over.built]p22:
9729 //
9730 // For every triple (L, VQ, R), where L is an integral type, VQ
9731 // is either volatile or empty, and R is a promoted integral
9732 // type, there exist candidate operator functions of the form
9733 //
9734 // VQ L& operator%=(VQ L&, R);
9735 // VQ L& operator<<=(VQ L&, R);
9736 // VQ L& operator>>=(VQ L&, R);
9737 // VQ L& operator&=(VQ L&, R);
9738 // VQ L& operator^=(VQ L&, R);
9739 // VQ L& operator|=(VQ L&, R);
9740 void addAssignmentIntegralOverloads() {
9741 if (!HasArithmeticOrEnumeralCandidateType)
9742 return;
9743
9744 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9745 for (unsigned Right = FirstPromotedIntegralType;
9746 Right < LastPromotedIntegralType; ++Right) {
9747 QualType ParamTypes[2];
9748 ParamTypes[1] = ArithmeticTypes[Right];
9750 S, ArithmeticTypes[Left], Args[0]);
9751
9753 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9754 ParamTypes[0] =
9755 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9756 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9757 });
9758 }
9759 }
9760 }
9761
9762 // C++ [over.operator]p23:
9763 //
9764 // There also exist candidate operator functions of the form
9765 //
9766 // bool operator!(bool);
9767 // bool operator&&(bool, bool);
9768 // bool operator||(bool, bool);
9769 void addExclaimOverload() {
9770 QualType ParamTy = S.Context.BoolTy;
9771 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9772 /*IsAssignmentOperator=*/false,
9773 /*NumContextualBoolArguments=*/1);
9774 }
9775 void addAmpAmpOrPipePipeOverload() {
9776 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9777 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9778 /*IsAssignmentOperator=*/false,
9779 /*NumContextualBoolArguments=*/2);
9780 }
9781
9782 // C++ [over.built]p13:
9783 //
9784 // For every cv-qualified or cv-unqualified object type T there
9785 // exist candidate operator functions of the form
9786 //
9787 // T* operator+(T*, ptrdiff_t); [ABOVE]
9788 // T& operator[](T*, ptrdiff_t);
9789 // T* operator-(T*, ptrdiff_t); [ABOVE]
9790 // T* operator+(ptrdiff_t, T*); [ABOVE]
9791 // T& operator[](ptrdiff_t, T*);
9792 void addSubscriptOverloads() {
9793 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9794 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9795 QualType PointeeType = PtrTy->getPointeeType();
9796 if (!PointeeType->isObjectType())
9797 continue;
9798
9799 // T& operator[](T*, ptrdiff_t)
9800 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9801 }
9802
9803 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9804 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9805 QualType PointeeType = PtrTy->getPointeeType();
9806 if (!PointeeType->isObjectType())
9807 continue;
9808
9809 // T& operator[](ptrdiff_t, T*)
9810 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9811 }
9812 }
9813
9814 // C++ [over.built]p11:
9815 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9816 // C1 is the same type as C2 or is a derived class of C2, T is an object
9817 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9818 // there exist candidate operator functions of the form
9819 //
9820 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9821 //
9822 // where CV12 is the union of CV1 and CV2.
9823 void addArrowStarOverloads() {
9824 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9825 QualType C1Ty = PtrTy;
9826 QualType C1;
9828 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9829 if (!isa<RecordType>(C1))
9830 continue;
9831 // heuristic to reduce number of builtin candidates in the set.
9832 // Add volatile/restrict version only if there are conversions to a
9833 // volatile/restrict type.
9834 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9835 continue;
9836 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9837 continue;
9838 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9839 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9840 QualType C2 = QualType(mptr->getClass(), 0);
9841 C2 = C2.getUnqualifiedType();
9842 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9843 break;
9844 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9845 // build CV12 T&
9846 QualType T = mptr->getPointeeType();
9847 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9848 T.isVolatileQualified())
9849 continue;
9850 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9851 T.isRestrictQualified())
9852 continue;
9853 T = Q1.apply(S.Context, T);
9854 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9855 }
9856 }
9857 }
9858
9859 // Note that we don't consider the first argument, since it has been
9860 // contextually converted to bool long ago. The candidates below are
9861 // therefore added as binary.
9862 //
9863 // C++ [over.built]p25:
9864 // For every type T, where T is a pointer, pointer-to-member, or scoped
9865 // enumeration type, there exist candidate operator functions of the form
9866 //
9867 // T operator?(bool, T, T);
9868 //
9869 void addConditionalOperatorOverloads() {
9870 /// Set of (canonical) types that we've already handled.
9872
9873 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9874 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9875 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9876 continue;
9877
9878 QualType ParamTypes[2] = {PtrTy, PtrTy};
9879 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9880 }
9881
9882 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9883 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9884 continue;
9885
9886 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9887 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9888 }
9889
9890 if (S.getLangOpts().CPlusPlus11) {
9891 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9892 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9893 continue;
9894
9895 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9896 continue;
9897
9898 QualType ParamTypes[2] = {EnumTy, EnumTy};
9899 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9900 }
9901 }
9902 }
9903 }
9904};
9905
9906} // end anonymous namespace
9907
9908/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9909/// operator overloads to the candidate set (C++ [over.built]), based
9910/// on the operator @p Op and the arguments given. For example, if the
9911/// operator is a binary '+', this routine might add "int
9912/// operator+(int, int)" to cover integer addition.
9914 SourceLocation OpLoc,
9915 ArrayRef<Expr *> Args,
9916 OverloadCandidateSet &CandidateSet) {
9917 // Find all of the types that the arguments can convert to, but only
9918 // if the operator we're looking at has built-in operator candidates
9919 // that make use of these types. Also record whether we encounter non-record
9920 // candidate types or either arithmetic or enumeral candidate types.
9921 QualifiersAndAtomic VisibleTypeConversionsQuals;
9922 VisibleTypeConversionsQuals.addConst();
9923 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9924 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9925 if (Args[ArgIdx]->getType()->isAtomicType())
9926 VisibleTypeConversionsQuals.addAtomic();
9927 }
9928
9929 bool HasNonRecordCandidateType = false;
9930 bool HasArithmeticOrEnumeralCandidateType = false;
9932 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9933 CandidateTypes.emplace_back(*this);
9934 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9935 OpLoc,
9936 true,
9937 (Op == OO_Exclaim ||
9938 Op == OO_AmpAmp ||
9939 Op == OO_PipePipe),
9940 VisibleTypeConversionsQuals);
9941 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9942 CandidateTypes[ArgIdx].hasNonRecordTypes();
9943 HasArithmeticOrEnumeralCandidateType =
9944 HasArithmeticOrEnumeralCandidateType ||
9945 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9946 }
9947
9948 // Exit early when no non-record types have been added to the candidate set
9949 // for any of the arguments to the operator.
9950 //
9951 // We can't exit early for !, ||, or &&, since there we have always have
9952 // 'bool' overloads.
9953 if (!HasNonRecordCandidateType &&
9954 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9955 return;
9956
9957 // Setup an object to manage the common state for building overloads.
9958 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9959 VisibleTypeConversionsQuals,
9960 HasArithmeticOrEnumeralCandidateType,
9961 CandidateTypes, CandidateSet);
9962
9963 // Dispatch over the operation to add in only those overloads which apply.
9964 switch (Op) {
9965 case OO_None:
9967 llvm_unreachable("Expected an overloaded operator");
9968
9969 case OO_New:
9970 case OO_Delete:
9971 case OO_Array_New:
9972 case OO_Array_Delete:
9973 case OO_Call:
9974 llvm_unreachable(
9975 "Special operators don't use AddBuiltinOperatorCandidates");
9976
9977 case OO_Comma:
9978 case OO_Arrow:
9979 case OO_Coawait:
9980 // C++ [over.match.oper]p3:
9981 // -- For the operator ',', the unary operator '&', the
9982 // operator '->', or the operator 'co_await', the
9983 // built-in candidates set is empty.
9984 break;
9985
9986 case OO_Plus: // '+' is either unary or binary
9987 if (Args.size() == 1)
9988 OpBuilder.addUnaryPlusPointerOverloads();
9989 [[fallthrough]];
9990
9991 case OO_Minus: // '-' is either unary or binary
9992 if (Args.size() == 1) {
9993 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9994 } else {
9995 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9996 OpBuilder.addGenericBinaryArithmeticOverloads();
9997 OpBuilder.addMatrixBinaryArithmeticOverloads();
9998 }
9999 break;
10000
10001 case OO_Star: // '*' is either unary or binary
10002 if (Args.size() == 1)
10003 OpBuilder.addUnaryStarPointerOverloads();
10004 else {
10005 OpBuilder.addGenericBinaryArithmeticOverloads();
10006 OpBuilder.addMatrixBinaryArithmeticOverloads();
10007 }
10008 break;
10009
10010 case OO_Slash:
10011 OpBuilder.addGenericBinaryArithmeticOverloads();
10012 break;
10013
10014 case OO_PlusPlus:
10015 case OO_MinusMinus:
10016 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10017 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10018 break;
10019
10020 case OO_EqualEqual:
10021 case OO_ExclaimEqual:
10022 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10023 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10024 OpBuilder.addGenericBinaryArithmeticOverloads();
10025 break;
10026
10027 case OO_Less:
10028 case OO_Greater:
10029 case OO_LessEqual:
10030 case OO_GreaterEqual:
10031 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10032 OpBuilder.addGenericBinaryArithmeticOverloads();
10033 break;
10034
10035 case OO_Spaceship:
10036 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10037 OpBuilder.addThreeWayArithmeticOverloads();
10038 break;
10039
10040 case OO_Percent:
10041 case OO_Caret:
10042 case OO_Pipe:
10043 case OO_LessLess:
10044 case OO_GreaterGreater:
10045 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10046 break;
10047
10048 case OO_Amp: // '&' is either unary or binary
10049 if (Args.size() == 1)
10050 // C++ [over.match.oper]p3:
10051 // -- For the operator ',', the unary operator '&', or the
10052 // operator '->', the built-in candidates set is empty.
10053 break;
10054
10055 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10056 break;
10057
10058 case OO_Tilde:
10059 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10060 break;
10061
10062 case OO_Equal:
10063 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10064 [[fallthrough]];
10065
10066 case OO_PlusEqual:
10067 case OO_MinusEqual:
10068 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10069 [[fallthrough]];
10070
10071 case OO_StarEqual:
10072 case OO_SlashEqual:
10073 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10074 break;
10075
10076 case OO_PercentEqual:
10077 case OO_LessLessEqual:
10078 case OO_GreaterGreaterEqual:
10079 case OO_AmpEqual:
10080 case OO_CaretEqual:
10081 case OO_PipeEqual:
10082 OpBuilder.addAssignmentIntegralOverloads();
10083 break;
10084
10085 case OO_Exclaim:
10086 OpBuilder.addExclaimOverload();
10087 break;
10088
10089 case OO_AmpAmp:
10090 case OO_PipePipe:
10091 OpBuilder.addAmpAmpOrPipePipeOverload();
10092 break;
10093
10094 case OO_Subscript:
10095 if (Args.size() == 2)
10096 OpBuilder.addSubscriptOverloads();
10097 break;
10098
10099 case OO_ArrowStar:
10100 OpBuilder.addArrowStarOverloads();
10101 break;
10102
10103 case OO_Conditional:
10104 OpBuilder.addConditionalOperatorOverloads();
10105 OpBuilder.addGenericBinaryArithmeticOverloads();
10106 break;
10107 }
10108}
10109
10110/// Add function candidates found via argument-dependent lookup
10111/// to the set of overloading candidates.
10112///
10113/// This routine performs argument-dependent name lookup based on the
10114/// given function name (which may also be an operator name) and adds
10115/// all of the overload candidates found by ADL to the overload
10116/// candidate set (C++ [basic.lookup.argdep]).
10117void
10119 SourceLocation Loc,
10120 ArrayRef<Expr *> Args,
10121 TemplateArgumentListInfo *ExplicitTemplateArgs,
10122 OverloadCandidateSet& CandidateSet,
10123 bool PartialOverloading) {
10124 ADLResult Fns;
10125
10126 // FIXME: This approach for uniquing ADL results (and removing
10127 // redundant candidates from the set) relies on pointer-equality,
10128 // which means we need to key off the canonical decl. However,
10129 // always going back to the canonical decl might not get us the
10130 // right set of default arguments. What default arguments are
10131 // we supposed to consider on ADL candidates, anyway?
10132
10133 // FIXME: Pass in the explicit template arguments?
10134 ArgumentDependentLookup(Name, Loc, Args, Fns);
10135
10136 // Erase all of the candidates we already knew about.
10137 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10138 CandEnd = CandidateSet.end();
10139 Cand != CandEnd; ++Cand)
10140 if (Cand->Function) {
10141 Fns.erase(Cand->Function);
10142 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
10143 Fns.erase(FunTmpl);
10144 }
10145
10146 // For each of the ADL candidates we found, add it to the overload
10147 // set.
10148 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10150
10151 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10152 if (ExplicitTemplateArgs)
10153 continue;
10154
10155 AddOverloadCandidate(
10156 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10157 PartialOverloading, /*AllowExplicit=*/true,
10158 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10159 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10160 AddOverloadCandidate(
10161 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10162 /*SuppressUserConversions=*/false, PartialOverloading,
10163 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10164 ADLCallKind::UsesADL, std::nullopt,
10166 }
10167 } else {
10168 auto *FTD = cast<FunctionTemplateDecl>(*I);
10169 AddTemplateOverloadCandidate(
10170 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10171 /*SuppressUserConversions=*/false, PartialOverloading,
10172 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10173 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10174 *this, Args, FTD->getTemplatedDecl())) {
10175 AddTemplateOverloadCandidate(
10176 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10177 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10178 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10180 }
10181 }
10182 }
10183}
10184
10185namespace {
10186enum class Comparison { Equal, Better, Worse };
10187}
10188
10189/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10190/// overload resolution.
10191///
10192/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10193/// Cand1's first N enable_if attributes have precisely the same conditions as
10194/// Cand2's first N enable_if attributes (where N = the number of enable_if
10195/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10196///
10197/// Note that you can have a pair of candidates such that Cand1's enable_if
10198/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10199/// worse than Cand1's.
10200static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10201 const FunctionDecl *Cand2) {
10202 // Common case: One (or both) decls don't have enable_if attrs.
10203 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10204 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10205 if (!Cand1Attr || !Cand2Attr) {
10206 if (Cand1Attr == Cand2Attr)
10207 return Comparison::Equal;
10208 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10209 }
10210
10211 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10212 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10213
10214 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10215 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10216 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10217 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10218
10219 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10220 // has fewer enable_if attributes than Cand2, and vice versa.
10221 if (!Cand1A)
10222 return Comparison::Worse;
10223 if (!Cand2A)
10224 return Comparison::Better;
10225
10226 Cand1ID.clear();
10227 Cand2ID.clear();
10228
10229 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10230 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10231 if (Cand1ID != Cand2ID)
10232 return Comparison::Worse;
10233 }
10234
10235 return Comparison::Equal;
10236}
10237
10238static Comparison
10240 const OverloadCandidate &Cand2) {
10241 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10242 !Cand2.Function->isMultiVersion())
10243 return Comparison::Equal;
10244
10245 // If both are invalid, they are equal. If one of them is invalid, the other
10246 // is better.
10247 if (Cand1.Function->isInvalidDecl()) {
10248 if (Cand2.Function->isInvalidDecl())
10249 return Comparison::Equal;
10250 return Comparison::Worse;
10251 }
10252 if (Cand2.Function->isInvalidDecl())
10253 return Comparison::Better;
10254
10255 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10256 // cpu_dispatch, else arbitrarily based on the identifiers.
10257 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10258 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10259 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10260 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10261
10262 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10263 return Comparison::Equal;
10264
10265 if (Cand1CPUDisp && !Cand2CPUDisp)
10266 return Comparison::Better;
10267 if (Cand2CPUDisp && !Cand1CPUDisp)
10268 return Comparison::Worse;
10269
10270 if (Cand1CPUSpec && Cand2CPUSpec) {
10271 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10272 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10273 ? Comparison::Better
10274 : Comparison::Worse;
10275
10276 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10277 FirstDiff = std::mismatch(
10278 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10279 Cand2CPUSpec->cpus_begin(),
10280 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10281 return LHS->getName() == RHS->getName();
10282 });
10283
10284 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10285 "Two different cpu-specific versions should not have the same "
10286 "identifier list, otherwise they'd be the same decl!");
10287 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10288 ? Comparison::Better
10289 : Comparison::Worse;
10290 }
10291 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10292}
10293
10294/// Compute the type of the implicit object parameter for the given function,
10295/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10296/// null QualType if there is a 'matches anything' implicit object parameter.
10297static std::optional<QualType>
10299 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10300 return std::nullopt;
10301
10302 auto *M = cast<CXXMethodDecl>(F);
10303 // Static member functions' object parameters match all types.
10304 if (M->isStatic())
10305 return QualType();
10306 return M->getFunctionObjectParameterReferenceType();
10307}
10308
10309// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10310// represent the same entity.
10311static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10312 const FunctionDecl *F2) {
10313 if (declaresSameEntity(F1, F2))
10314 return true;
10315 auto PT1 = F1->getPrimaryTemplate();
10316 auto PT2 = F2->getPrimaryTemplate();
10317 if (PT1 && PT2) {
10318 if (declaresSameEntity(PT1, PT2) ||
10319 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10320 PT2->getInstantiatedFromMemberTemplate()))
10321 return true;
10322 }
10323 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10324 // different functions with same params). Consider removing this (as no test
10325 // fail w/o it).
10326 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10327 if (First) {
10328 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10329 return *T;
10330 }
10331 assert(I < F->getNumParams());
10332 return F->getParamDecl(I++)->getType();
10333 };
10334
10335 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10336 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10337
10338 if (F1NumParams != F2NumParams)
10339 return false;
10340
10341 unsigned I1 = 0, I2 = 0;
10342 for (unsigned I = 0; I != F1NumParams; ++I) {
10343 QualType T1 = NextParam(F1, I1, I == 0);
10344 QualType T2 = NextParam(F2, I2, I == 0);
10345 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10346 if (!Context.hasSameUnqualifiedType(T1, T2))
10347 return false;
10348 }
10349 return true;
10350}
10351
10352/// We're allowed to use constraints partial ordering only if the candidates
10353/// have the same parameter types:
10354/// [over.match.best.general]p2.6
10355/// F1 and F2 are non-template functions with the same
10356/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10358 const OverloadCandidate &Cand1,
10359 const OverloadCandidate &Cand2) {
10360 if (!Cand1.Function || !Cand2.Function)
10361 return false;
10362
10363 FunctionDecl *Fn1 = Cand1.Function;
10364 FunctionDecl *Fn2 = Cand2.Function;
10365
10366 if (Fn1->isVariadic() != Fn1->isVariadic())
10367 return false;
10368
10370 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10371 return false;
10372
10373 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10374 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10375 if (Mem1 && Mem2) {
10376 // if they are member functions, both are direct members of the same class,
10377 // and
10378 if (Mem1->getParent() != Mem2->getParent())
10379 return false;
10380 // if both are non-static member functions, they have the same types for
10381 // their object parameters
10382 if (Mem1->isInstance() && Mem2->isInstance() &&
10384 Mem1->getFunctionObjectParameterReferenceType(),
10385 Mem1->getFunctionObjectParameterReferenceType()))
10386 return false;
10387 }
10388 return true;
10389}
10390
10391/// isBetterOverloadCandidate - Determines whether the first overload
10392/// candidate is a better candidate than the second (C++ 13.3.3p1).
10394 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10396 // Define viable functions to be better candidates than non-viable
10397 // functions.
10398 if (!Cand2.Viable)
10399 return Cand1.Viable;
10400 else if (!Cand1.Viable)
10401 return false;
10402
10403 // [CUDA] A function with 'never' preference is marked not viable, therefore
10404 // is never shown up here. The worst preference shown up here is 'wrong side',
10405 // e.g. an H function called by a HD function in device compilation. This is
10406 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10407 // function which is called only by an H function. A deferred diagnostic will
10408 // be triggered if it is emitted. However a wrong-sided function is still
10409 // a viable candidate here.
10410 //
10411 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10412 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10413 // can be emitted, Cand1 is not better than Cand2. This rule should have
10414 // precedence over other rules.
10415 //
10416 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10417 // other rules should be used to determine which is better. This is because
10418 // host/device based overloading resolution is mostly for determining
10419 // viability of a function. If two functions are both viable, other factors
10420 // should take precedence in preference, e.g. the standard-defined preferences
10421 // like argument conversion ranks or enable_if partial-ordering. The
10422 // preference for pass-object-size parameters is probably most similar to a
10423 // type-based-overloading decision and so should take priority.
10424 //
10425 // If other rules cannot determine which is better, CUDA preference will be
10426 // used again to determine which is better.
10427 //
10428 // TODO: Currently IdentifyPreference does not return correct values
10429 // for functions called in global variable initializers due to missing
10430 // correct context about device/host. Therefore we can only enforce this
10431 // rule when there is a caller. We should enforce this rule for functions
10432 // in global variable initializers once proper context is added.
10433 //
10434 // TODO: We can only enable the hostness based overloading resolution when
10435 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10436 // overloading resolution diagnostics.
10437 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10438 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10439 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10440 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10441 bool IsCand1ImplicitHD =
10443 bool IsCand2ImplicitHD =
10445 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10446 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10447 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10448 // The implicit HD function may be a function in a system header which
10449 // is forced by pragma. In device compilation, if we prefer HD candidates
10450 // over wrong-sided candidates, overloading resolution may change, which
10451 // may result in non-deferrable diagnostics. As a workaround, we let
10452 // implicit HD candidates take equal preference as wrong-sided candidates.
10453 // This will preserve the overloading resolution.
10454 // TODO: We still need special handling of implicit HD functions since
10455 // they may incur other diagnostics to be deferred. We should make all
10456 // host/device related diagnostics deferrable and remove special handling
10457 // of implicit HD functions.
10458 auto EmitThreshold =
10459 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10460 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10463 auto Cand1Emittable = P1 > EmitThreshold;
10464 auto Cand2Emittable = P2 > EmitThreshold;
10465 if (Cand1Emittable && !Cand2Emittable)
10466 return true;
10467 if (!Cand1Emittable && Cand2Emittable)
10468 return false;
10469 }
10470 }
10471
10472 // C++ [over.match.best]p1: (Changed in C++23)
10473 //
10474 // -- if F is a static member function, ICS1(F) is defined such
10475 // that ICS1(F) is neither better nor worse than ICS1(G) for
10476 // any function G, and, symmetrically, ICS1(G) is neither
10477 // better nor worse than ICS1(F).
10478 unsigned StartArg = 0;
10479 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10480 StartArg = 1;
10481
10482 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10483 // We don't allow incompatible pointer conversions in C++.
10484 if (!S.getLangOpts().CPlusPlus)
10485 return ICS.isStandard() &&
10486 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10487
10488 // The only ill-formed conversion we allow in C++ is the string literal to
10489 // char* conversion, which is only considered ill-formed after C++11.
10490 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10492 };
10493
10494 // Define functions that don't require ill-formed conversions for a given
10495 // argument to be better candidates than functions that do.
10496 unsigned NumArgs = Cand1.Conversions.size();
10497 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10498 bool HasBetterConversion = false;
10499 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10500 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10501 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10502 if (Cand1Bad != Cand2Bad) {
10503 if (Cand1Bad)
10504 return false;
10505 HasBetterConversion = true;
10506 }
10507 }
10508
10509 if (HasBetterConversion)
10510 return true;
10511
10512 // C++ [over.match.best]p1:
10513 // A viable function F1 is defined to be a better function than another
10514 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10515 // conversion sequence than ICSi(F2), and then...
10516 bool HasWorseConversion = false;
10517 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10519 Cand1.Conversions[ArgIdx],
10520 Cand2.Conversions[ArgIdx])) {
10522 // Cand1 has a better conversion sequence.
10523 HasBetterConversion = true;
10524 break;
10525
10527 if (Cand1.Function && Cand2.Function &&
10528 Cand1.isReversed() != Cand2.isReversed() &&
10529 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10530 // Work around large-scale breakage caused by considering reversed
10531 // forms of operator== in C++20:
10532 //
10533 // When comparing a function against a reversed function, if we have a
10534 // better conversion for one argument and a worse conversion for the
10535 // other, the implicit conversion sequences are treated as being equally
10536 // good.
10537 //
10538 // This prevents a comparison function from being considered ambiguous
10539 // with a reversed form that is written in the same way.
10540 //
10541 // We diagnose this as an extension from CreateOverloadedBinOp.
10542 HasWorseConversion = true;
10543 break;
10544 }
10545
10546 // Cand1 can't be better than Cand2.
10547 return false;
10548
10550 // Do nothing.
10551 break;
10552 }
10553 }
10554
10555 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10556 // ICSj(F2), or, if not that,
10557 if (HasBetterConversion && !HasWorseConversion)
10558 return true;
10559
10560 // -- the context is an initialization by user-defined conversion
10561 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10562 // from the return type of F1 to the destination type (i.e.,
10563 // the type of the entity being initialized) is a better
10564 // conversion sequence than the standard conversion sequence
10565 // from the return type of F2 to the destination type.
10567 Cand1.Function && Cand2.Function &&
10568 isa<CXXConversionDecl>(Cand1.Function) &&
10569 isa<CXXConversionDecl>(Cand2.Function)) {
10570 // First check whether we prefer one of the conversion functions over the
10571 // other. This only distinguishes the results in non-standard, extension
10572 // cases such as the conversion from a lambda closure type to a function
10573 // pointer or block.
10578 Cand1.FinalConversion,
10579 Cand2.FinalConversion);
10580
10583
10584 // FIXME: Compare kind of reference binding if conversion functions
10585 // convert to a reference type used in direct reference binding, per
10586 // C++14 [over.match.best]p1 section 2 bullet 3.
10587 }
10588
10589 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10590 // as combined with the resolution to CWG issue 243.
10591 //
10592 // When the context is initialization by constructor ([over.match.ctor] or
10593 // either phase of [over.match.list]), a constructor is preferred over
10594 // a conversion function.
10595 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10596 Cand1.Function && Cand2.Function &&
10597 isa<CXXConstructorDecl>(Cand1.Function) !=
10598 isa<CXXConstructorDecl>(Cand2.Function))
10599 return isa<CXXConstructorDecl>(Cand1.Function);
10600
10601 // -- F1 is a non-template function and F2 is a function template
10602 // specialization, or, if not that,
10603 bool Cand1IsSpecialization = Cand1.Function &&
10605 bool Cand2IsSpecialization = Cand2.Function &&
10607 if (Cand1IsSpecialization != Cand2IsSpecialization)
10608 return Cand2IsSpecialization;
10609
10610 // -- F1 and F2 are function template specializations, and the function
10611 // template for F1 is more specialized than the template for F2
10612 // according to the partial ordering rules described in 14.5.5.2, or,
10613 // if not that,
10614 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10615 const auto *Obj1Context =
10616 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10617 const auto *Obj2Context =
10618 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10619 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10622 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10623 : TPOC_Call,
10625 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10626 : QualType{},
10627 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10628 : QualType{},
10629 Cand1.isReversed() ^ Cand2.isReversed())) {
10630 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10631 }
10632 }
10633
10634 // -— F1 and F2 are non-template functions with the same
10635 // parameter-type-lists, and F1 is more constrained than F2 [...],
10636 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10637 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10639 Cand1.Function)
10640 return true;
10641
10642 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10643 // class B of D, and for all arguments the corresponding parameters of
10644 // F1 and F2 have the same type.
10645 // FIXME: Implement the "all parameters have the same type" check.
10646 bool Cand1IsInherited =
10647 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10648 bool Cand2IsInherited =
10649 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10650 if (Cand1IsInherited != Cand2IsInherited)
10651 return Cand2IsInherited;
10652 else if (Cand1IsInherited) {
10653 assert(Cand2IsInherited);
10654 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10655 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10656 if (Cand1Class->isDerivedFrom(Cand2Class))
10657 return true;
10658 if (Cand2Class->isDerivedFrom(Cand1Class))
10659 return false;
10660 // Inherited from sibling base classes: still ambiguous.
10661 }
10662
10663 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10664 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10665 // with reversed order of parameters and F1 is not
10666 //
10667 // We rank reversed + different operator as worse than just reversed, but
10668 // that comparison can never happen, because we only consider reversing for
10669 // the maximally-rewritten operator (== or <=>).
10670 if (Cand1.RewriteKind != Cand2.RewriteKind)
10671 return Cand1.RewriteKind < Cand2.RewriteKind;
10672
10673 // Check C++17 tie-breakers for deduction guides.
10674 {
10675 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10676 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10677 if (Guide1 && Guide2) {
10678 // -- F1 is generated from a deduction-guide and F2 is not
10679 if (Guide1->isImplicit() != Guide2->isImplicit())
10680 return Guide2->isImplicit();
10681
10682 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10683 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10684 return true;
10685 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10686 return false;
10687
10688 // --F1 is generated from a non-template constructor and F2 is generated
10689 // from a constructor template
10690 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10691 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10692 if (Constructor1 && Constructor2) {
10693 bool isC1Templated = Constructor1->getTemplatedKind() !=
10695 bool isC2Templated = Constructor2->getTemplatedKind() !=
10697 if (isC1Templated != isC2Templated)
10698 return isC2Templated;
10699 }
10700 }
10701 }
10702
10703 // Check for enable_if value-based overload resolution.
10704 if (Cand1.Function && Cand2.Function) {
10705 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10706 if (Cmp != Comparison::Equal)
10707 return Cmp == Comparison::Better;
10708 }
10709
10710 bool HasPS1 = Cand1.Function != nullptr &&
10712 bool HasPS2 = Cand2.Function != nullptr &&
10714 if (HasPS1 != HasPS2 && HasPS1)
10715 return true;
10716
10717 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10718 if (MV == Comparison::Better)
10719 return true;
10720 if (MV == Comparison::Worse)
10721 return false;
10722
10723 // If other rules cannot determine which is better, CUDA preference is used
10724 // to determine which is better.
10725 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10726 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10727 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10728 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10729 }
10730
10731 // General member function overloading is handled above, so this only handles
10732 // constructors with address spaces.
10733 // This only handles address spaces since C++ has no other
10734 // qualifier that can be used with constructors.
10735 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10736 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10737 if (CD1 && CD2) {
10738 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10739 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10740 if (AS1 != AS2) {
10742 return true;
10744 return false;
10745 }
10746 }
10747
10748 return false;
10749}
10750
10751/// Determine whether two declarations are "equivalent" for the purposes of
10752/// name lookup and overload resolution. This applies when the same internal/no
10753/// linkage entity is defined by two modules (probably by textually including
10754/// the same header). In such a case, we don't consider the declarations to
10755/// declare the same entity, but we also don't want lookups with both
10756/// declarations visible to be ambiguous in some cases (this happens when using
10757/// a modularized libstdc++).
10759 const NamedDecl *B) {
10760 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10761 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10762 if (!VA || !VB)
10763 return false;
10764
10765 // The declarations must be declaring the same name as an internal linkage
10766 // entity in different modules.
10767 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10768 VB->getDeclContext()->getRedeclContext()) ||
10769 getOwningModule(VA) == getOwningModule(VB) ||
10770 VA->isExternallyVisible() || VB->isExternallyVisible())
10771 return false;
10772
10773 // Check that the declarations appear to be equivalent.
10774 //
10775 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10776 // For constants and functions, we should check the initializer or body is
10777 // the same. For non-constant variables, we shouldn't allow it at all.
10778 if (Context.hasSameType(VA->getType(), VB->getType()))
10779 return true;
10780
10781 // Enum constants within unnamed enumerations will have different types, but
10782 // may still be similar enough to be interchangeable for our purposes.
10783 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10784 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10785 // Only handle anonymous enums. If the enumerations were named and
10786 // equivalent, they would have been merged to the same type.
10787 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10788 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10789 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10790 !Context.hasSameType(EnumA->getIntegerType(),
10791 EnumB->getIntegerType()))
10792 return false;
10793 // Allow this only if the value is the same for both enumerators.
10794 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10795 }
10796 }
10797
10798 // Nothing else is sufficiently similar.
10799 return false;
10800}
10801
10804 assert(D && "Unknown declaration");
10805 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10806
10807 Module *M = getOwningModule(D);
10808 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10809 << !M << (M ? M->getFullModuleName() : "");
10810
10811 for (auto *E : Equiv) {
10812 Module *M = getOwningModule(E);
10813 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10814 << !M << (M ? M->getFullModuleName() : "");
10815 }
10816}
10817
10819 return FailureKind == ovl_fail_bad_deduction &&
10820 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10822 static_cast<CNSInfo *>(DeductionFailure.Data)
10823 ->Satisfaction.ContainsErrors;
10824}
10825
10826/// Computes the best viable function (C++ 13.3.3)
10827/// within an overload candidate set.
10828///
10829/// \param Loc The location of the function name (or operator symbol) for
10830/// which overload resolution occurs.
10831///
10832/// \param Best If overload resolution was successful or found a deleted
10833/// function, \p Best points to the candidate function found.
10834///
10835/// \returns The result of overload resolution.
10838 iterator &Best) {
10840 std::transform(begin(), end(), std::back_inserter(Candidates),
10841 [](OverloadCandidate &Cand) { return &Cand; });
10842
10843 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10844 // are accepted by both clang and NVCC. However, during a particular
10845 // compilation mode only one call variant is viable. We need to
10846 // exclude non-viable overload candidates from consideration based
10847 // only on their host/device attributes. Specifically, if one
10848 // candidate call is WrongSide and the other is SameSide, we ignore
10849 // the WrongSide candidate.
10850 // We only need to remove wrong-sided candidates here if
10851 // -fgpu-exclude-wrong-side-overloads is off. When
10852 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10853 // uniformly in isBetterOverloadCandidate.
10854 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10855 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10856 bool ContainsSameSideCandidate =
10857 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10858 // Check viable function only.
10859 return Cand->Viable && Cand->Function &&
10860 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10862 });
10863 if (ContainsSameSideCandidate) {
10864 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10865 // Check viable function only to avoid unnecessary data copying/moving.
10866 return Cand->Viable && Cand->Function &&
10867 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10869 };
10870 llvm::erase_if(Candidates, IsWrongSideCandidate);
10871 }
10872 }
10873
10874 // Find the best viable function.
10875 Best = end();
10876 for (auto *Cand : Candidates) {
10877 Cand->Best = false;
10878 if (Cand->Viable) {
10879 if (Best == end() ||
10880 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10881 Best = Cand;
10882 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10883 // This candidate has constraint that we were unable to evaluate because
10884 // it referenced an expression that contained an error. Rather than fall
10885 // back onto a potentially unintended candidate (made worse by
10886 // subsuming constraints), treat this as 'no viable candidate'.
10887 Best = end();
10888 return OR_No_Viable_Function;
10889 }
10890 }
10891
10892 // If we didn't find any viable functions, abort.
10893 if (Best == end())
10894 return OR_No_Viable_Function;
10895
10897
10899 PendingBest.push_back(&*Best);
10900 Best->Best = true;
10901
10902 // Make sure that this function is better than every other viable
10903 // function. If not, we have an ambiguity.
10904 while (!PendingBest.empty()) {
10905 auto *Curr = PendingBest.pop_back_val();
10906 for (auto *Cand : Candidates) {
10907 if (Cand->Viable && !Cand->Best &&
10908 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10909 PendingBest.push_back(Cand);
10910 Cand->Best = true;
10911
10913 Curr->Function))
10914 EquivalentCands.push_back(Cand->Function);
10915 else
10916 Best = end();
10917 }
10918 }
10919 }
10920
10921 // If we found more than one best candidate, this is ambiguous.
10922 if (Best == end())
10923 return OR_Ambiguous;
10924
10925 // Best is the best viable function.
10926 if (Best->Function && Best->Function->isDeleted())
10927 return OR_Deleted;
10928
10929 if (!EquivalentCands.empty())
10931 EquivalentCands);
10932
10933 return OR_Success;
10934}
10935
10936namespace {
10937
10938enum OverloadCandidateKind {
10939 oc_function,
10940 oc_method,
10941 oc_reversed_binary_operator,
10942 oc_constructor,
10943 oc_implicit_default_constructor,
10944 oc_implicit_copy_constructor,
10945 oc_implicit_move_constructor,
10946 oc_implicit_copy_assignment,
10947 oc_implicit_move_assignment,
10948 oc_implicit_equality_comparison,
10949 oc_inherited_constructor
10950};
10951
10952enum OverloadCandidateSelect {
10953 ocs_non_template,
10954 ocs_template,
10955 ocs_described_template,
10956};
10957
10958static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10959ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10960 const FunctionDecl *Fn,
10962 std::string &Description) {
10963
10964 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10965 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10966 isTemplate = true;
10967 Description = S.getTemplateArgumentBindingsText(
10968 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10969 }
10970
10971 OverloadCandidateSelect Select = [&]() {
10972 if (!Description.empty())
10973 return ocs_described_template;
10974 return isTemplate ? ocs_template : ocs_non_template;
10975 }();
10976
10977 OverloadCandidateKind Kind = [&]() {
10978 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10979 return oc_implicit_equality_comparison;
10980
10981 if (CRK & CRK_Reversed)
10982 return oc_reversed_binary_operator;
10983
10984 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10985 if (!Ctor->isImplicit()) {
10986 if (isa<ConstructorUsingShadowDecl>(Found))
10987 return oc_inherited_constructor;
10988 else
10989 return oc_constructor;
10990 }
10991
10992 if (Ctor->isDefaultConstructor())
10993 return oc_implicit_default_constructor;
10994
10995 if (Ctor->isMoveConstructor())
10996 return oc_implicit_move_constructor;
10997
10998 assert(Ctor->isCopyConstructor() &&
10999 "unexpected sort of implicit constructor");
11000 return oc_implicit_copy_constructor;
11001 }
11002
11003 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11004 // This actually gets spelled 'candidate function' for now, but
11005 // it doesn't hurt to split it out.
11006 if (!Meth->isImplicit())
11007 return oc_method;
11008
11009 if (Meth->isMoveAssignmentOperator())
11010 return oc_implicit_move_assignment;
11011
11012 if (Meth->isCopyAssignmentOperator())
11013 return oc_implicit_copy_assignment;
11014
11015 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11016 return oc_method;
11017 }
11018
11019 return oc_function;
11020 }();
11021
11022 return std::make_pair(Kind, Select);
11023}
11024
11025void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11026 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11027 // set.
11028 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11029 S.Diag(FoundDecl->getLocation(),
11030 diag::note_ovl_candidate_inherited_constructor)
11031 << Shadow->getNominatedBaseClass();
11032}
11033
11034} // end anonymous namespace
11035
11037 const FunctionDecl *FD) {
11038 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11039 bool AlwaysTrue;
11040 if (EnableIf->getCond()->isValueDependent() ||
11041 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11042 return false;
11043 if (!AlwaysTrue)
11044 return false;
11045 }
11046 return true;
11047}
11048
11049/// Returns true if we can take the address of the function.
11050///
11051/// \param Complain - If true, we'll emit a diagnostic
11052/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11053/// we in overload resolution?
11054/// \param Loc - The location of the statement we're complaining about. Ignored
11055/// if we're not complaining, or if we're in overload resolution.
11057 bool Complain,
11058 bool InOverloadResolution,
11059 SourceLocation Loc) {
11060 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11061 if (Complain) {
11062 if (InOverloadResolution)
11063 S.Diag(FD->getBeginLoc(),
11064 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11065 else
11066 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11067 }
11068 return false;
11069 }
11070
11071 if (FD->getTrailingRequiresClause()) {
11072 ConstraintSatisfaction Satisfaction;
11073 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11074 return false;
11075 if (!Satisfaction.IsSatisfied) {
11076 if (Complain) {
11077 if (InOverloadResolution) {
11078 SmallString<128> TemplateArgString;
11079 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11080 TemplateArgString += " ";
11081 TemplateArgString += S.getTemplateArgumentBindingsText(
11082 FunTmpl->getTemplateParameters(),
11084 }
11085
11086 S.Diag(FD->getBeginLoc(),
11087 diag::note_ovl_candidate_unsatisfied_constraints)
11088 << TemplateArgString;
11089 } else
11090 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11091 << FD;
11092 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11093 }
11094 return false;
11095 }
11096 }
11097
11098 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11099 return P->hasAttr<PassObjectSizeAttr>();
11100 });
11101 if (I == FD->param_end())
11102 return true;
11103
11104 if (Complain) {
11105 // Add one to ParamNo because it's user-facing
11106 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11107 if (InOverloadResolution)
11108 S.Diag(FD->getLocation(),
11109 diag::note_ovl_candidate_has_pass_object_size_params)
11110 << ParamNo;
11111 else
11112 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11113 << FD << ParamNo;
11114 }
11115 return false;
11116}
11117
11119 const FunctionDecl *FD) {
11120 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11121 /*InOverloadResolution=*/true,
11122 /*Loc=*/SourceLocation());
11123}
11124
11126 bool Complain,
11127 SourceLocation Loc) {
11128 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11129 /*InOverloadResolution=*/false,
11130 Loc);
11131}
11132
11133// Don't print candidates other than the one that matches the calling
11134// convention of the call operator, since that is guaranteed to exist.
11136 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11137
11138 if (!ConvD)
11139 return false;
11140 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11141 if (!RD->isLambda())
11142 return false;
11143
11144 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11145 CallingConv CallOpCC =
11146 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11147 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11148 CallingConv ConvToCC =
11149 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11150
11151 return ConvToCC != CallOpCC;
11152}
11153
11154// Notes the location of an overload candidate.
11156 OverloadCandidateRewriteKind RewriteKind,
11157 QualType DestType, bool TakingAddress) {
11158 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11159 return;
11160 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11161 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11162 return;
11163 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11164 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11165 return;
11167 return;
11168
11169 std::string FnDesc;
11170 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11171 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11172 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11173 << (unsigned)KSPair.first << (unsigned)KSPair.second
11174 << Fn << FnDesc;
11175
11176 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11177 Diag(Fn->getLocation(), PD);
11178 MaybeEmitInheritedConstructorNote(*this, Found);
11179}
11180
11181static void
11183 // Perhaps the ambiguity was caused by two atomic constraints that are
11184 // 'identical' but not equivalent:
11185 //
11186 // void foo() requires (sizeof(T) > 4) { } // #1
11187 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11188 //
11189 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11190 // #2 to subsume #1, but these constraint are not considered equivalent
11191 // according to the subsumption rules because they are not the same
11192 // source-level construct. This behavior is quite confusing and we should try
11193 // to help the user figure out what happened.
11194
11195 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11196 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11197 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11198 if (!I->Function)
11199 continue;
11201 if (auto *Template = I->Function->getPrimaryTemplate())
11202 Template->getAssociatedConstraints(AC);
11203 else
11204 I->Function->getAssociatedConstraints(AC);
11205 if (AC.empty())
11206 continue;
11207 if (FirstCand == nullptr) {
11208 FirstCand = I->Function;
11209 FirstAC = AC;
11210 } else if (SecondCand == nullptr) {
11211 SecondCand = I->Function;
11212 SecondAC = AC;
11213 } else {
11214 // We have more than one pair of constrained functions - this check is
11215 // expensive and we'd rather not try to diagnose it.
11216 return;
11217 }
11218 }
11219 if (!SecondCand)
11220 return;
11221 // The diagnostic can only happen if there are associated constraints on
11222 // both sides (there needs to be some identical atomic constraint).
11223 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11224 SecondCand, SecondAC))
11225 // Just show the user one diagnostic, they'll probably figure it out
11226 // from here.
11227 return;
11228}
11229
11230// Notes the location of all overload candidates designated through
11231// OverloadedExpr
11232void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11233 bool TakingAddress) {
11234 assert(OverloadedExpr->getType() == Context.OverloadTy);
11235
11236 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11237 OverloadExpr *OvlExpr = Ovl.Expression;
11238
11239 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11240 IEnd = OvlExpr->decls_end();
11241 I != IEnd; ++I) {
11242 if (FunctionTemplateDecl *FunTmpl =
11243 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11244 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11245 TakingAddress);
11246 } else if (FunctionDecl *Fun
11247 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11248 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11249 }
11250 }
11251}
11252
11253/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11254/// "lead" diagnostic; it will be given two arguments, the source and
11255/// target types of the conversion.
11257 Sema &S,
11258 SourceLocation CaretLoc,
11259 const PartialDiagnostic &PDiag) const {
11260 S.Diag(CaretLoc, PDiag)
11261 << Ambiguous.getFromType() << Ambiguous.getToType();
11262 unsigned CandsShown = 0;
11264 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11265 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11266 break;
11267 ++CandsShown;
11268 S.NoteOverloadCandidate(I->first, I->second);
11269 }
11270 S.Diags.overloadCandidatesShown(CandsShown);
11271 if (I != E)
11272 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11273}
11274
11276 unsigned I, bool TakingCandidateAddress) {
11277 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11278 assert(Conv.isBad());
11279 assert(Cand->Function && "for now, candidate must be a function");
11280 FunctionDecl *Fn = Cand->Function;
11281
11282 // There's a conversion slot for the object argument if this is a
11283 // non-constructor method. Note that 'I' corresponds the
11284 // conversion-slot index.
11285 bool isObjectArgument = false;
11286 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11287 if (I == 0)
11288 isObjectArgument = true;
11289 else
11290 I--;
11291 }
11292
11293 std::string FnDesc;
11294 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11295 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11296 FnDesc);
11297
11298 Expr *FromExpr = Conv.Bad.FromExpr;
11299 QualType FromTy = Conv.Bad.getFromType();
11300 QualType ToTy = Conv.Bad.getToType();
11301 SourceRange ToParamRange =
11302 !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
11303
11304 if (FromTy == S.Context.OverloadTy) {
11305 assert(FromExpr && "overload set argument came from implicit argument?");
11306 Expr *E = FromExpr->IgnoreParens();
11307 if (isa<UnaryOperator>(E))
11308 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11309 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11310
11311 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11312 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11313 << ToParamRange << ToTy << Name << I + 1;
11314 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11315 return;
11316 }
11317
11318 // Do some hand-waving analysis to see if the non-viability is due
11319 // to a qualifier mismatch.
11320 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11321 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11322 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11323 CToTy = RT->getPointeeType();
11324 else {
11325 // TODO: detect and diagnose the full richness of const mismatches.
11326 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11327 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11328 CFromTy = FromPT->getPointeeType();
11329 CToTy = ToPT->getPointeeType();
11330 }
11331 }
11332
11333 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11334 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11335 Qualifiers FromQs = CFromTy.getQualifiers();
11336 Qualifiers ToQs = CToTy.getQualifiers();
11337
11338 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11339 if (isObjectArgument)
11340 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11341 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11342 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11343 else
11344 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11345 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11346 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11347 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11348 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11349 return;
11350 }
11351
11352 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11353 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11354 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11355 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11356 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11357 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11358 return;
11359 }
11360
11361 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11363 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11364 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11365 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11366 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11367 return;
11368 }
11369
11370 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11371 assert(CVR && "expected qualifiers mismatch");
11372
11373 if (isObjectArgument) {
11374 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11375 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11376 << FromTy << (CVR - 1);
11377 } else {
11378 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11379 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11380 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11381 }
11382 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11383 return;
11384 }
11385
11388 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11389 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11390 << (unsigned)isObjectArgument << I + 1
11392 << ToParamRange;
11393 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11394 return;
11395 }
11396
11397 // Special diagnostic for failure to convert an initializer list, since
11398 // telling the user that it has type void is not useful.
11399 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11400 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11401 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11402 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11405 ? 2
11406 : 0);
11407 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11408 return;
11409 }
11410
11411 // Diagnose references or pointers to incomplete types differently,
11412 // since it's far from impossible that the incompleteness triggered
11413 // the failure.
11414 QualType TempFromTy = FromTy.getNonReferenceType();
11415 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11416 TempFromTy = PTy->getPointeeType();
11417 if (TempFromTy->isIncompleteType()) {
11418 // Emit the generic diagnostic and, optionally, add the hints to it.
11419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11420 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11421 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11422 << (unsigned)(Cand->Fix.Kind);
11423
11424 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11425 return;
11426 }
11427
11428 // Diagnose base -> derived pointer conversions.
11429 unsigned BaseToDerivedConversion = 0;
11430 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11431 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11432 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11433 FromPtrTy->getPointeeType()) &&
11434 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11435 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11436 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11437 FromPtrTy->getPointeeType()))
11438 BaseToDerivedConversion = 1;
11439 }
11440 } else if (const ObjCObjectPointerType *FromPtrTy
11441 = FromTy->getAs<ObjCObjectPointerType>()) {
11442 if (const ObjCObjectPointerType *ToPtrTy
11443 = ToTy->getAs<ObjCObjectPointerType>())
11444 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11445 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11446 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11447 FromPtrTy->getPointeeType()) &&
11448 FromIface->isSuperClassOf(ToIface))
11449 BaseToDerivedConversion = 2;
11450 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11451 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11452 !FromTy->isIncompleteType() &&
11453 !ToRefTy->getPointeeType()->isIncompleteType() &&
11454 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11455 BaseToDerivedConversion = 3;
11456 }
11457 }
11458
11459 if (BaseToDerivedConversion) {
11460 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11461 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11462 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11463 << I + 1;
11464 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11465 return;
11466 }
11467
11468 if (isa<ObjCObjectPointerType>(CFromTy) &&
11469 isa<PointerType>(CToTy)) {
11470 Qualifiers FromQs = CFromTy.getQualifiers();
11471 Qualifiers ToQs = CToTy.getQualifiers();
11472 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11473 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11474 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11475 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11476 << I + 1;
11477 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11478 return;
11479 }
11480 }
11481
11482 if (TakingCandidateAddress &&
11484 return;
11485
11486 // Emit the generic diagnostic and, optionally, add the hints to it.
11487 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11488 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11489 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11490 << (unsigned)(Cand->Fix.Kind);
11491
11492 // Check that location of Fn is not in system header.
11493 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11494 // If we can fix the conversion, suggest the FixIts.
11495 for (const FixItHint &HI : Cand->Fix.Hints)
11496 FDiag << HI;
11497 }
11498
11499 S.Diag(Fn->getLocation(), FDiag);
11500
11501 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11502}
11503
11504/// Additional arity mismatch diagnosis specific to a function overload
11505/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11506/// over a candidate in any candidate set.
11508 unsigned NumArgs) {
11509 FunctionDecl *Fn = Cand->Function;
11510 unsigned MinParams = Fn->getMinRequiredArguments();
11511
11512 // With invalid overloaded operators, it's possible that we think we
11513 // have an arity mismatch when in fact it looks like we have the
11514 // right number of arguments, because only overloaded operators have
11515 // the weird behavior of overloading member and non-member functions.
11516 // Just don't report anything.
11517 if (Fn->isInvalidDecl() &&
11519 return true;
11520
11521 if (NumArgs < MinParams) {
11522 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11524 Cand->DeductionFailure.getResult() ==
11526 } else {
11527 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11529 Cand->DeductionFailure.getResult() ==
11531 }
11532
11533 return false;
11534}
11535
11536/// General arity mismatch diagnosis over a candidate in a candidate set.
11537static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11538 unsigned NumFormalArgs) {
11539 assert(isa<FunctionDecl>(D) &&
11540 "The templated declaration should at least be a function"
11541 " when diagnosing bad template argument deduction due to too many"
11542 " or too few arguments");
11543
11544 FunctionDecl *Fn = cast<FunctionDecl>(D);
11545
11546 // TODO: treat calls to a missing default constructor as a special case
11547 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11548 unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11549
11550 // at least / at most / exactly
11551 bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11552 unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11553 unsigned mode, modeCount;
11554 if (NumFormalArgs < MinParams) {
11555 if (MinParams != ParamCount || FnTy->isVariadic() ||
11556 FnTy->isTemplateVariadic())
11557 mode = 0; // "at least"
11558 else
11559 mode = 2; // "exactly"
11560 modeCount = MinParams;
11561 } else {
11562 if (MinParams != ParamCount)
11563 mode = 1; // "at most"
11564 else
11565 mode = 2; // "exactly"
11566 modeCount = ParamCount;
11567 }
11568
11569 std::string Description;
11570 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11571 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11572
11573 if (modeCount == 1 &&
11574 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11575 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11576 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11577 << Description << mode
11578 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11579 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11580 else
11581 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11582 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11583 << Description << mode << modeCount << NumFormalArgs
11584 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11585
11586 MaybeEmitInheritedConstructorNote(S, Found);
11587}
11588
11589/// Arity mismatch diagnosis specific to a function overload candidate.
11591 unsigned NumFormalArgs) {
11592 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11593 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11594}
11595
11597 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11598 return TD;
11599 llvm_unreachable("Unsupported: Getting the described template declaration"
11600 " for bad deduction diagnosis");
11601}
11602
11603/// Diagnose a failed template-argument deduction.
11604static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11605 DeductionFailureInfo &DeductionFailure,
11606 unsigned NumArgs,
11607 bool TakingCandidateAddress) {
11608 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11609 NamedDecl *ParamD;
11610 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11611 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11612 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11613 switch (DeductionFailure.getResult()) {
11615 llvm_unreachable(
11616 "TemplateDeductionResult::Success while diagnosing bad deduction");
11618 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11619 "while diagnosing bad deduction");
11622 return;
11623
11625 assert(ParamD && "no parameter found for incomplete deduction result");
11626 S.Diag(Templated->getLocation(),
11627 diag::note_ovl_candidate_incomplete_deduction)
11628 << ParamD->getDeclName();
11629 MaybeEmitInheritedConstructorNote(S, Found);
11630 return;
11631 }
11632
11634 assert(ParamD && "no parameter found for incomplete deduction result");
11635 S.Diag(Templated->getLocation(),
11636 diag::note_ovl_candidate_incomplete_deduction_pack)
11637 << ParamD->getDeclName()
11638 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11639 << *DeductionFailure.getFirstArg();
11640 MaybeEmitInheritedConstructorNote(S, Found);
11641 return;
11642 }
11643
11645 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11646 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11647
11648 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11649
11650 // Param will have been canonicalized, but it should just be a
11651 // qualified version of ParamD, so move the qualifiers to that.
11653 Qs.strip(Param);
11654 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11655 assert(S.Context.hasSameType(Param, NonCanonParam));
11656
11657 // Arg has also been canonicalized, but there's nothing we can do
11658 // about that. It also doesn't matter as much, because it won't
11659 // have any template parameters in it (because deduction isn't
11660 // done on dependent types).
11661 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11662
11663 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11664 << ParamD->getDeclName() << Arg << NonCanonParam;
11665 MaybeEmitInheritedConstructorNote(S, Found);
11666 return;
11667 }
11668
11670 assert(ParamD && "no parameter found for inconsistent deduction result");
11671 int which = 0;
11672 if (isa<TemplateTypeParmDecl>(ParamD))
11673 which = 0;
11674 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11675 // Deduction might have failed because we deduced arguments of two
11676 // different types for a non-type template parameter.
11677 // FIXME: Use a different TDK value for this.
11678 QualType T1 =
11679 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11680 QualType T2 =
11681 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11682 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11683 S.Diag(Templated->getLocation(),
11684 diag::note_ovl_candidate_inconsistent_deduction_types)
11685 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11686 << *DeductionFailure.getSecondArg() << T2;
11687 MaybeEmitInheritedConstructorNote(S, Found);
11688 return;
11689 }
11690
11691 which = 1;
11692 } else {
11693 which = 2;
11694 }
11695
11696 // Tweak the diagnostic if the problem is that we deduced packs of
11697 // different arities. We'll print the actual packs anyway in case that
11698 // includes additional useful information.
11699 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11700 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11701 DeductionFailure.getFirstArg()->pack_size() !=
11702 DeductionFailure.getSecondArg()->pack_size()) {
11703 which = 3;
11704 }
11705
11706 S.Diag(Templated->getLocation(),
11707 diag::note_ovl_candidate_inconsistent_deduction)
11708 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11709 << *DeductionFailure.getSecondArg();
11710 MaybeEmitInheritedConstructorNote(S, Found);
11711 return;
11712 }
11713
11715 assert(ParamD && "no parameter found for invalid explicit arguments");
11716 if (ParamD->getDeclName())
11717 S.Diag(Templated->getLocation(),
11718 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11719 << ParamD->getDeclName();
11720 else {
11721 int index = 0;
11722 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11723 index = TTP->getIndex();
11724 else if (NonTypeTemplateParmDecl *NTTP
11725 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11726 index = NTTP->getIndex();
11727 else
11728 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11729 S.Diag(Templated->getLocation(),
11730 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11731 << (index + 1);
11732 }
11733 MaybeEmitInheritedConstructorNote(S, Found);
11734 return;
11735
11737 // Format the template argument list into the argument string.
11738 SmallString<128> TemplateArgString;
11739 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11740 TemplateArgString = " ";
11741 TemplateArgString += S.getTemplateArgumentBindingsText(
11742 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11743 if (TemplateArgString.size() == 1)
11744 TemplateArgString.clear();
11745 S.Diag(Templated->getLocation(),
11746 diag::note_ovl_candidate_unsatisfied_constraints)
11747 << TemplateArgString;
11748
11750 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11751 return;
11752 }
11755 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11756 return;
11757
11759 S.Diag(Templated->getLocation(),
11760 diag::note_ovl_candidate_instantiation_depth);
11761 MaybeEmitInheritedConstructorNote(S, Found);
11762 return;
11763
11765 // Format the template argument list into the argument string.
11766 SmallString<128> TemplateArgString;
11767 if (TemplateArgumentList *Args =
11768 DeductionFailure.getTemplateArgumentList()) {
11769 TemplateArgString = " ";
11770 TemplateArgString += S.getTemplateArgumentBindingsText(
11771 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11772 if (TemplateArgString.size() == 1)
11773 TemplateArgString.clear();
11774 }
11775
11776 // If this candidate was disabled by enable_if, say so.
11777 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11778 if (PDiag && PDiag->second.getDiagID() ==
11779 diag::err_typename_nested_not_found_enable_if) {
11780 // FIXME: Use the source range of the condition, and the fully-qualified
11781 // name of the enable_if template. These are both present in PDiag.
11782 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11783 << "'enable_if'" << TemplateArgString;
11784 return;
11785 }
11786
11787 // We found a specific requirement that disabled the enable_if.
11788 if (PDiag && PDiag->second.getDiagID() ==
11789 diag::err_typename_nested_not_found_requirement) {
11790 S.Diag(Templated->getLocation(),
11791 diag::note_ovl_candidate_disabled_by_requirement)
11792 << PDiag->second.getStringArg(0) << TemplateArgString;
11793 return;
11794 }
11795
11796 // Format the SFINAE diagnostic into the argument string.
11797 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11798 // formatted message in another diagnostic.
11799 SmallString<128> SFINAEArgString;
11800 SourceRange R;
11801 if (PDiag) {
11802 SFINAEArgString = ": ";
11803 R = SourceRange(PDiag->first, PDiag->first);
11804 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11805 }
11806
11807 S.Diag(Templated->getLocation(),
11808 diag::note_ovl_candidate_substitution_failure)
11809 << TemplateArgString << SFINAEArgString << R;
11810 MaybeEmitInheritedConstructorNote(S, Found);
11811 return;
11812 }
11813
11816 // Format the template argument list into the argument string.
11817 SmallString<128> TemplateArgString;
11818 if (TemplateArgumentList *Args =
11819 DeductionFailure.getTemplateArgumentList()) {
11820 TemplateArgString = " ";
11821 TemplateArgString += S.getTemplateArgumentBindingsText(
11822 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11823 if (TemplateArgString.size() == 1)
11824 TemplateArgString.clear();
11825 }
11826
11827 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11828 << (*DeductionFailure.getCallArgIndex() + 1)
11829 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11830 << TemplateArgString
11831 << (DeductionFailure.getResult() ==
11833 break;
11834 }
11835
11837 // FIXME: Provide a source location to indicate what we couldn't match.
11838 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11839 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11840 if (FirstTA.getKind() == TemplateArgument::Template &&
11841 SecondTA.getKind() == TemplateArgument::Template) {
11842 TemplateName FirstTN = FirstTA.getAsTemplate();
11843 TemplateName SecondTN = SecondTA.getAsTemplate();
11844 if (FirstTN.getKind() == TemplateName::Template &&
11845 SecondTN.getKind() == TemplateName::Template) {
11846 if (FirstTN.getAsTemplateDecl()->getName() ==
11847 SecondTN.getAsTemplateDecl()->getName()) {
11848 // FIXME: This fixes a bad diagnostic where both templates are named
11849 // the same. This particular case is a bit difficult since:
11850 // 1) It is passed as a string to the diagnostic printer.
11851 // 2) The diagnostic printer only attempts to find a better
11852 // name for types, not decls.
11853 // Ideally, this should folded into the diagnostic printer.
11854 S.Diag(Templated->getLocation(),
11855 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11856 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11857 return;
11858 }
11859 }
11860 }
11861
11862 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11863 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11864 return;
11865
11866 // FIXME: For generic lambda parameters, check if the function is a lambda
11867 // call operator, and if so, emit a prettier and more informative
11868 // diagnostic that mentions 'auto' and lambda in addition to
11869 // (or instead of?) the canonical template type parameters.
11870 S.Diag(Templated->getLocation(),
11871 diag::note_ovl_candidate_non_deduced_mismatch)
11872 << FirstTA << SecondTA;
11873 return;
11874 }
11875 // TODO: diagnose these individually, then kill off
11876 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11878 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11879 MaybeEmitInheritedConstructorNote(S, Found);
11880 return;
11882 S.Diag(Templated->getLocation(),
11883 diag::note_cuda_ovl_candidate_target_mismatch);
11884 return;
11885 }
11886}
11887
11888/// Diagnose a failed template-argument deduction, for function calls.
11890 unsigned NumArgs,
11891 bool TakingCandidateAddress) {
11895 if (CheckArityMismatch(S, Cand, NumArgs))
11896 return;
11897 }
11898 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11899 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11900}
11901
11902/// CUDA: diagnose an invalid call across targets.
11904 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11905 FunctionDecl *Callee = Cand->Function;
11906
11907 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11908 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11909
11910 std::string FnDesc;
11911 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11912 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11913 Cand->getRewriteKind(), FnDesc);
11914
11915 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11916 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11917 << FnDesc /* Ignored */
11918 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11919
11920 // This could be an implicit constructor for which we could not infer the
11921 // target due to a collsion. Diagnose that case.
11922 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11923 if (Meth != nullptr && Meth->isImplicit()) {
11924 CXXRecordDecl *ParentClass = Meth->getParent();
11926
11927 switch (FnKindPair.first) {
11928 default:
11929 return;
11930 case oc_implicit_default_constructor:
11932 break;
11933 case oc_implicit_copy_constructor:
11935 break;
11936 case oc_implicit_move_constructor:
11938 break;
11939 case oc_implicit_copy_assignment:
11941 break;
11942 case oc_implicit_move_assignment:
11944 break;
11945 };
11946
11947 bool ConstRHS = false;
11948 if (Meth->getNumParams()) {
11949 if (const ReferenceType *RT =
11950 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11951 ConstRHS = RT->getPointeeType().isConstQualified();
11952 }
11953 }
11954
11955 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11956 /* ConstRHS */ ConstRHS,
11957 /* Diagnose */ true);
11958 }
11959}
11960
11962 FunctionDecl *Callee = Cand->Function;
11963 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11964
11965 S.Diag(Callee->getLocation(),
11966 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11967 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11968}
11969
11972 assert(ES.isExplicit() && "not an explicit candidate");
11973
11974 unsigned Kind;
11975 switch (Cand->Function->getDeclKind()) {
11976 case Decl::Kind::CXXConstructor:
11977 Kind = 0;
11978 break;
11979 case Decl::Kind::CXXConversion:
11980 Kind = 1;
11981 break;
11982 case Decl::Kind::CXXDeductionGuide:
11983 Kind = Cand->Function->isImplicit() ? 0 : 2;
11984 break;
11985 default:
11986 llvm_unreachable("invalid Decl");
11987 }
11988
11989 // Note the location of the first (in-class) declaration; a redeclaration
11990 // (particularly an out-of-class definition) will typically lack the
11991 // 'explicit' specifier.
11992 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11994 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11995 First = Pattern->getFirstDecl();
11996
11997 S.Diag(First->getLocation(),
11998 diag::note_ovl_candidate_explicit)
11999 << Kind << (ES.getExpr() ? 1 : 0)
12000 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12001}
12002
12003/// Generates a 'note' diagnostic for an overload candidate. We've
12004/// already generated a primary error at the call site.
12005///
12006/// It really does need to be a single diagnostic with its caret
12007/// pointed at the candidate declaration. Yes, this creates some
12008/// major challenges of technical writing. Yes, this makes pointing
12009/// out problems with specific arguments quite awkward. It's still
12010/// better than generating twenty screens of text for every failed
12011/// overload.
12012///
12013/// It would be great to be able to express per-candidate problems
12014/// more richly for those diagnostic clients that cared, but we'd
12015/// still have to be just as careful with the default diagnostics.
12016/// \param CtorDestAS Addr space of object being constructed (for ctor
12017/// candidates only).
12019 unsigned NumArgs,
12020 bool TakingCandidateAddress,
12021 LangAS CtorDestAS = LangAS::Default) {
12022 FunctionDecl *Fn = Cand->Function;
12024 return;
12025
12026 // There is no physical candidate declaration to point to for OpenCL builtins.
12027 // Except for failed conversions, the notes are identical for each candidate,
12028 // so do not generate such notes.
12029 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12031 return;
12032
12033 // Note deleted candidates, but only if they're viable.
12034 if (Cand->Viable) {
12035 if (Fn->isDeleted()) {
12036 std::string FnDesc;
12037 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12038 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12039 Cand->getRewriteKind(), FnDesc);
12040
12041 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12042 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12043 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12044 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12045 return;
12046 }
12047
12048 // We don't really have anything else to say about viable candidates.
12049 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12050 return;
12051 }
12052
12053 switch (Cand->FailureKind) {
12056 return DiagnoseArityMismatch(S, Cand, NumArgs);
12057
12059 return DiagnoseBadDeduction(S, Cand, NumArgs,
12060 TakingCandidateAddress);
12061
12063 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12064 << (Fn->getPrimaryTemplate() ? 1 : 0);
12065 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12066 return;
12067 }
12068
12070 Qualifiers QualsForPrinting;
12071 QualsForPrinting.setAddressSpace(CtorDestAS);
12072 S.Diag(Fn->getLocation(),
12073 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12074 << QualsForPrinting;
12075 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12076 return;
12077 }
12078
12082 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12083
12085 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12086 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12087 if (Cand->Conversions[I].isBad())
12088 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12089
12090 // FIXME: this currently happens when we're called from SemaInit
12091 // when user-conversion overload fails. Figure out how to handle
12092 // those conditions and diagnose them well.
12093 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12094 }
12095
12097 return DiagnoseBadTarget(S, Cand);
12098
12099 case ovl_fail_enable_if:
12100 return DiagnoseFailedEnableIfAttr(S, Cand);
12101
12102 case ovl_fail_explicit:
12103 return DiagnoseFailedExplicitSpec(S, Cand);
12104
12106 // It's generally not interesting to note copy/move constructors here.
12107 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12108 return;
12109 S.Diag(Fn->getLocation(),
12110 diag::note_ovl_candidate_inherited_constructor_slice)
12111 << (Fn->getPrimaryTemplate() ? 1 : 0)
12113 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12114 return;
12115
12117 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
12118 (void)Available;
12119 assert(!Available);
12120 break;
12121 }
12123 // Do nothing, these should simply be ignored.
12124 break;
12125
12127 std::string FnDesc;
12128 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12129 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12130 Cand->getRewriteKind(), FnDesc);
12131
12132 S.Diag(Fn->getLocation(),
12133 diag::note_ovl_candidate_constraints_not_satisfied)
12134 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12135 << FnDesc /* Ignored */;
12136 ConstraintSatisfaction Satisfaction;
12137 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12138 break;
12139 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12140 }
12141 }
12142}
12143
12146 return;
12147
12148 // Desugar the type of the surrogate down to a function type,
12149 // retaining as many typedefs as possible while still showing
12150 // the function type (and, therefore, its parameter types).
12151 QualType FnType = Cand->Surrogate->getConversionType();
12152 bool isLValueReference = false;
12153 bool isRValueReference = false;
12154 bool isPointer = false;
12155 if (const LValueReferenceType *FnTypeRef =
12156 FnType->getAs<LValueReferenceType>()) {
12157 FnType = FnTypeRef->getPointeeType();
12158 isLValueReference = true;
12159 } else if (const RValueReferenceType *FnTypeRef =
12160 FnType->getAs<RValueReferenceType>()) {
12161 FnType = FnTypeRef->getPointeeType();
12162 isRValueReference = true;
12163 }
12164 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12165 FnType = FnTypePtr->getPointeeType();
12166 isPointer = true;
12167 }
12168 // Desugar down to a function type.
12169 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12170 // Reconstruct the pointer/reference as appropriate.
12171 if (isPointer) FnType = S.Context.getPointerType(FnType);
12172 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12173 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12174
12175 if (!Cand->Viable &&
12177 S.Diag(Cand->Surrogate->getLocation(),
12178 diag::note_ovl_surrogate_constraints_not_satisfied)
12179 << Cand->Surrogate;
12180 ConstraintSatisfaction Satisfaction;
12181 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12182 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12183 } else {
12184 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12185 << FnType;
12186 }
12187}
12188
12189static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12190 SourceLocation OpLoc,
12191 OverloadCandidate *Cand) {
12192 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12193 std::string TypeStr("operator");
12194 TypeStr += Opc;
12195 TypeStr += "(";
12196 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12197 if (Cand->Conversions.size() == 1) {
12198 TypeStr += ")";
12199 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12200 } else {
12201 TypeStr += ", ";
12202 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12203 TypeStr += ")";
12204 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12205 }
12206}
12207
12209 OverloadCandidate *Cand) {
12210 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12211 if (ICS.isBad()) break; // all meaningless after first invalid
12212 if (!ICS.isAmbiguous()) continue;
12213
12215 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12216 }
12217}
12218
12220 if (Cand->Function)
12221 return Cand->Function->getLocation();
12222 if (Cand->IsSurrogate)
12223 return Cand->Surrogate->getLocation();
12224 return SourceLocation();
12225}
12226
12227static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12228 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12232 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12233
12237 return 1;
12238
12241 return 2;
12242
12250 return 3;
12251
12253 return 4;
12254
12256 return 5;
12257
12260 return 6;
12261 }
12262 llvm_unreachable("Unhandled deduction result");
12263}
12264
12265namespace {
12266
12267struct CompareOverloadCandidatesForDisplay {
12268 Sema &S;
12270 size_t NumArgs;
12272
12273 CompareOverloadCandidatesForDisplay(
12274 Sema &S, SourceLocation Loc, size_t NArgs,
12276 : S(S), NumArgs(NArgs), CSK(CSK) {}
12277
12278 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12279 // If there are too many or too few arguments, that's the high-order bit we
12280 // want to sort by, even if the immediate failure kind was something else.
12281 if (C->FailureKind == ovl_fail_too_many_arguments ||
12282 C->FailureKind == ovl_fail_too_few_arguments)
12283 return static_cast<OverloadFailureKind>(C->FailureKind);
12284
12285 if (C->Function) {
12286 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12288 if (NumArgs < C->Function->getMinRequiredArguments())
12290 }
12291
12292 return static_cast<OverloadFailureKind>(C->FailureKind);
12293 }
12294
12295 bool operator()(const OverloadCandidate *L,
12296 const OverloadCandidate *R) {
12297 // Fast-path this check.
12298 if (L == R) return false;
12299
12300 // Order first by viability.
12301 if (L->Viable) {
12302 if (!R->Viable) return true;
12303
12304 if (int Ord = CompareConversions(*L, *R))
12305 return Ord < 0;
12306 // Use other tie breakers.
12307 } else if (R->Viable)
12308 return false;
12309
12310 assert(L->Viable == R->Viable);
12311
12312 // Criteria by which we can sort non-viable candidates:
12313 if (!L->Viable) {
12314 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12315 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12316
12317 // 1. Arity mismatches come after other candidates.
12318 if (LFailureKind == ovl_fail_too_many_arguments ||
12319 LFailureKind == ovl_fail_too_few_arguments) {
12320 if (RFailureKind == ovl_fail_too_many_arguments ||
12321 RFailureKind == ovl_fail_too_few_arguments) {
12322 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12323 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12324 if (LDist == RDist) {
12325 if (LFailureKind == RFailureKind)
12326 // Sort non-surrogates before surrogates.
12327 return !L->IsSurrogate && R->IsSurrogate;
12328 // Sort candidates requiring fewer parameters than there were
12329 // arguments given after candidates requiring more parameters
12330 // than there were arguments given.
12331 return LFailureKind == ovl_fail_too_many_arguments;
12332 }
12333 return LDist < RDist;
12334 }
12335 return false;
12336 }
12337 if (RFailureKind == ovl_fail_too_many_arguments ||
12338 RFailureKind == ovl_fail_too_few_arguments)
12339 return true;
12340
12341 // 2. Bad conversions come first and are ordered by the number
12342 // of bad conversions and quality of good conversions.
12343 if (LFailureKind == ovl_fail_bad_conversion) {
12344 if (RFailureKind != ovl_fail_bad_conversion)
12345 return true;
12346
12347 // The conversion that can be fixed with a smaller number of changes,
12348 // comes first.
12349 unsigned numLFixes = L->Fix.NumConversionsFixed;
12350 unsigned numRFixes = R->Fix.NumConversionsFixed;
12351 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12352 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12353 if (numLFixes != numRFixes) {
12354 return numLFixes < numRFixes;
12355 }
12356
12357 // If there's any ordering between the defined conversions...
12358 if (int Ord = CompareConversions(*L, *R))
12359 return Ord < 0;
12360 } else if (RFailureKind == ovl_fail_bad_conversion)
12361 return false;
12362
12363 if (LFailureKind == ovl_fail_bad_deduction) {
12364 if (RFailureKind != ovl_fail_bad_deduction)
12365 return true;
12366
12368 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12369 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12370 if (LRank != RRank)
12371 return LRank < RRank;
12372 }
12373 } else if (RFailureKind == ovl_fail_bad_deduction)
12374 return false;
12375
12376 // TODO: others?
12377 }
12378
12379 // Sort everything else by location.
12382
12383 // Put candidates without locations (e.g. builtins) at the end.
12384 if (LLoc.isValid() && RLoc.isValid())
12385 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12386 if (LLoc.isValid() && !RLoc.isValid())
12387 return true;
12388 if (RLoc.isValid() && !LLoc.isValid())
12389 return false;
12390 assert(!LLoc.isValid() && !RLoc.isValid());
12391 // For builtins and other functions without locations, fallback to the order
12392 // in which they were added into the candidate set.
12393 return L < R;
12394 }
12395
12396private:
12397 struct ConversionSignals {
12398 unsigned KindRank = 0;
12400
12401 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12402 ConversionSignals Sig;
12403 Sig.KindRank = Seq.getKindRank();
12404 if (Seq.isStandard())
12405 Sig.Rank = Seq.Standard.getRank();
12406 else if (Seq.isUserDefined())
12407 Sig.Rank = Seq.UserDefined.After.getRank();
12408 // We intend StaticObjectArgumentConversion to compare the same as
12409 // StandardConversion with ICR_ExactMatch rank.
12410 return Sig;
12411 }
12412
12413 static ConversionSignals ForObjectArgument() {
12414 // We intend StaticObjectArgumentConversion to compare the same as
12415 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12416 return {};
12417 }
12418 };
12419
12420 // Returns -1 if conversions in L are considered better.
12421 // 0 if they are considered indistinguishable.
12422 // 1 if conversions in R are better.
12423 int CompareConversions(const OverloadCandidate &L,
12424 const OverloadCandidate &R) {
12425 // We cannot use `isBetterOverloadCandidate` because it is defined
12426 // according to the C++ standard and provides a partial order, but we need
12427 // a total order as this function is used in sort.
12428 assert(L.Conversions.size() == R.Conversions.size());
12429 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12430 auto LS = L.IgnoreObjectArgument && I == 0
12431 ? ConversionSignals::ForObjectArgument()
12432 : ConversionSignals::ForSequence(L.Conversions[I]);
12433 auto RS = R.IgnoreObjectArgument
12434 ? ConversionSignals::ForObjectArgument()
12435 : ConversionSignals::ForSequence(R.Conversions[I]);
12436 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12437 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12438 ? -1
12439 : 1;
12440 }
12441 // FIXME: find a way to compare templates for being more or less
12442 // specialized that provides a strict weak ordering.
12443 return 0;
12444 }
12445};
12446}
12447
12448/// CompleteNonViableCandidate - Normally, overload resolution only
12449/// computes up to the first bad conversion. Produces the FixIt set if
12450/// possible.
12451static void
12453 ArrayRef<Expr *> Args,
12455 assert(!Cand->Viable);
12456
12457 // Don't do anything on failures other than bad conversion.
12459 return;
12460
12461 // We only want the FixIts if all the arguments can be corrected.
12462 bool Unfixable = false;
12463 // Use a implicit copy initialization to check conversion fixes.
12465
12466 // Attempt to fix the bad conversion.
12467 unsigned ConvCount = Cand->Conversions.size();
12468 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12469 ++ConvIdx) {
12470 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12471 if (Cand->Conversions[ConvIdx].isInitialized() &&
12472 Cand->Conversions[ConvIdx].isBad()) {
12473 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12474 break;
12475 }
12476 }
12477
12478 // FIXME: this should probably be preserved from the overload
12479 // operation somehow.
12480 bool SuppressUserConversions = false;
12481
12482 unsigned ConvIdx = 0;
12483 unsigned ArgIdx = 0;
12484 ArrayRef<QualType> ParamTypes;
12485 bool Reversed = Cand->isReversed();
12486
12487 if (Cand->IsSurrogate) {
12488 QualType ConvType
12490 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12491 ConvType = ConvPtrType->getPointeeType();
12492 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12493 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12494 ConvIdx = 1;
12495 } else if (Cand->Function) {
12496 ParamTypes =
12497 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12498 if (isa<CXXMethodDecl>(Cand->Function) &&
12499 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12500 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12501 ConvIdx = 1;
12503 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12505 OO_Subscript)
12506 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12507 ArgIdx = 1;
12508 }
12509 } else {
12510 // Builtin operator.
12511 assert(ConvCount <= 3);
12512 ParamTypes = Cand->BuiltinParamTypes;
12513 }
12514
12515 // Fill in the rest of the conversions.
12516 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12517 ConvIdx != ConvCount;
12518 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12519 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12520 if (Cand->Conversions[ConvIdx].isInitialized()) {
12521 // We've already checked this conversion.
12522 } else if (ParamIdx < ParamTypes.size()) {
12523 if (ParamTypes[ParamIdx]->isDependentType())
12524 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12525 Args[ArgIdx]->getType());
12526 else {
12527 Cand->Conversions[ConvIdx] =
12528 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12529 SuppressUserConversions,
12530 /*InOverloadResolution=*/true,
12531 /*AllowObjCWritebackConversion=*/
12532 S.getLangOpts().ObjCAutoRefCount);
12533 // Store the FixIt in the candidate if it exists.
12534 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12535 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12536 }
12537 } else
12538 Cand->Conversions[ConvIdx].setEllipsis();
12539 }
12540}
12541
12544 SourceLocation OpLoc,
12545 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12546 // Sort the candidates by viability and position. Sorting directly would
12547 // be prohibitive, so we make a set of pointers and sort those.
12549 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12550 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12551 if (!Filter(*Cand))
12552 continue;
12553 switch (OCD) {
12554 case OCD_AllCandidates:
12555 if (!Cand->Viable) {
12556 if (!Cand->Function && !Cand->IsSurrogate) {
12557 // This a non-viable builtin candidate. We do not, in general,
12558 // want to list every possible builtin candidate.
12559 continue;
12560 }
12561 CompleteNonViableCandidate(S, Cand, Args, Kind);
12562 }
12563 break;
12564
12566 if (!Cand->Viable)
12567 continue;
12568 break;
12569
12571 if (!Cand->Best)
12572 continue;
12573 break;
12574 }
12575
12576 Cands.push_back(Cand);
12577 }
12578
12579 llvm::stable_sort(
12580 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12581
12582 return Cands;
12583}
12584
12586 SourceLocation OpLoc) {
12587 bool DeferHint = false;
12588 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12589 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12590 // host device candidates.
12591 auto WrongSidedCands =
12592 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12593 return (Cand.Viable == false &&
12594 Cand.FailureKind == ovl_fail_bad_target) ||
12595 (Cand.Function &&
12596 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12597 Cand.Function->template hasAttr<CUDADeviceAttr>());
12598 });
12599 DeferHint = !WrongSidedCands.empty();
12600 }
12601 return DeferHint;
12602}
12603
12604/// When overload resolution fails, prints diagnostic messages containing the
12605/// candidates in the candidate set.
12608 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12609 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12610
12611 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12612
12613 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12614
12615 // In WebAssembly we don't want to emit further diagnostics if a table is
12616 // passed as an argument to a function.
12617 bool NoteCands = true;
12618 for (const Expr *Arg : Args) {
12619 if (Arg->getType()->isWebAssemblyTableType())
12620 NoteCands = false;
12621 }
12622
12623 if (NoteCands)
12624 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12625
12626 if (OCD == OCD_AmbiguousCandidates)
12628}
12629
12632 StringRef Opc, SourceLocation OpLoc) {
12633 bool ReportedAmbiguousConversions = false;
12634
12635 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12636 unsigned CandsShown = 0;
12637 auto I = Cands.begin(), E = Cands.end();
12638 for (; I != E; ++I) {
12639 OverloadCandidate *Cand = *I;
12640
12641 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12642 ShowOverloads == Ovl_Best) {
12643 break;
12644 }
12645 ++CandsShown;
12646
12647 if (Cand->Function)
12648 NoteFunctionCandidate(S, Cand, Args.size(),
12649 /*TakingCandidateAddress=*/false, DestAS);
12650 else if (Cand->IsSurrogate)
12651 NoteSurrogateCandidate(S, Cand);
12652 else {
12653 assert(Cand->Viable &&
12654 "Non-viable built-in candidates are not added to Cands.");
12655 // Generally we only see ambiguities including viable builtin
12656 // operators if overload resolution got screwed up by an
12657 // ambiguous user-defined conversion.
12658 //
12659 // FIXME: It's quite possible for different conversions to see
12660 // different ambiguities, though.
12661 if (!ReportedAmbiguousConversions) {
12662 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12663 ReportedAmbiguousConversions = true;
12664 }
12665
12666 // If this is a viable builtin, print it.
12667 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12668 }
12669 }
12670
12671 // Inform S.Diags that we've shown an overload set with N elements. This may
12672 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12673 S.Diags.overloadCandidatesShown(CandsShown);
12674
12675 if (I != E)
12676 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12677 shouldDeferDiags(S, Args, OpLoc))
12678 << int(E - I);
12679}
12680
12681static SourceLocation
12683 return Cand->Specialization ? Cand->Specialization->getLocation()
12684 : SourceLocation();
12685}
12686
12687namespace {
12688struct CompareTemplateSpecCandidatesForDisplay {
12689 Sema &S;
12690 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12691
12692 bool operator()(const TemplateSpecCandidate *L,
12693 const TemplateSpecCandidate *R) {
12694 // Fast-path this check.
12695 if (L == R)
12696 return false;
12697
12698 // Assuming that both candidates are not matches...
12699
12700 // Sort by the ranking of deduction failures.
12704
12705 // Sort everything else by location.
12708
12709 // Put candidates without locations (e.g. builtins) at the end.
12710 if (LLoc.isInvalid())
12711 return false;
12712 if (RLoc.isInvalid())
12713 return true;
12714
12715 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12716 }
12717};
12718}
12719
12720/// Diagnose a template argument deduction failure.
12721/// We are treating these failures as overload failures due to bad
12722/// deductions.
12724 bool ForTakingAddress) {
12725 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12726 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12727}
12728
12729void TemplateSpecCandidateSet::destroyCandidates() {
12730 for (iterator i = begin(), e = end(); i != e; ++i) {
12731 i->DeductionFailure.Destroy();
12732 }
12733}
12734
12736 destroyCandidates();
12737 Candidates.clear();
12738}
12739
12740/// NoteCandidates - When no template specialization match is found, prints
12741/// diagnostic messages containing the non-matching specializations that form
12742/// the candidate set.
12743/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12744/// OCD == OCD_AllCandidates and Cand->Viable == false.
12746 // Sort the candidates by position (assuming no candidate is a match).
12747 // Sorting directly would be prohibitive, so we make a set of pointers
12748 // and sort those.
12750 Cands.reserve(size());
12751 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12752 if (Cand->Specialization)
12753 Cands.push_back(Cand);
12754 // Otherwise, this is a non-matching builtin candidate. We do not,
12755 // in general, want to list every possible builtin candidate.
12756 }
12757
12758 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12759
12760 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12761 // for generalization purposes (?).
12762 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12763
12765 unsigned CandsShown = 0;
12766 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12767 TemplateSpecCandidate *Cand = *I;
12768
12769 // Set an arbitrary limit on the number of candidates we'll spam
12770 // the user with. FIXME: This limit should depend on details of the
12771 // candidate list.
12772 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12773 break;
12774 ++CandsShown;
12775
12776 assert(Cand->Specialization &&
12777 "Non-matching built-in candidates are not added to Cands.");
12778 Cand->NoteDeductionFailure(S, ForTakingAddress);
12779 }
12780
12781 if (I != E)
12782 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12783}
12784
12785// [PossiblyAFunctionType] --> [Return]
12786// NonFunctionType --> NonFunctionType
12787// R (A) --> R(A)
12788// R (*)(A) --> R (A)
12789// R (&)(A) --> R (A)
12790// R (S::*)(A) --> R (A)
12792 QualType Ret = PossiblyAFunctionType;
12793 if (const PointerType *ToTypePtr =
12794 PossiblyAFunctionType->getAs<PointerType>())
12795 Ret = ToTypePtr->getPointeeType();
12796 else if (const ReferenceType *ToTypeRef =
12797 PossiblyAFunctionType->getAs<ReferenceType>())
12798 Ret = ToTypeRef->getPointeeType();
12799 else if (const MemberPointerType *MemTypePtr =
12800 PossiblyAFunctionType->getAs<MemberPointerType>())
12801 Ret = MemTypePtr->getPointeeType();
12802 Ret =
12803 Context.getCanonicalType(Ret).getUnqualifiedType();
12804 return Ret;
12805}
12806
12808 bool Complain = true) {
12809 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12810 S.DeduceReturnType(FD, Loc, Complain))
12811 return true;
12812
12813 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12814 if (S.getLangOpts().CPlusPlus17 &&
12815 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12816 !S.ResolveExceptionSpec(Loc, FPT))
12817 return true;
12818
12819 return false;
12820}
12821
12822namespace {
12823// A helper class to help with address of function resolution
12824// - allows us to avoid passing around all those ugly parameters
12825class AddressOfFunctionResolver {
12826 Sema& S;
12827 Expr* SourceExpr;
12828 const QualType& TargetType;
12829 QualType TargetFunctionType; // Extracted function type from target type
12830
12831 bool Complain;
12832 //DeclAccessPair& ResultFunctionAccessPair;
12833 ASTContext& Context;
12834
12835 bool TargetTypeIsNonStaticMemberFunction;
12836 bool FoundNonTemplateFunction;
12837 bool StaticMemberFunctionFromBoundPointer;
12838 bool HasComplained;
12839
12840 OverloadExpr::FindResult OvlExprInfo;
12841 OverloadExpr *OvlExpr;
12842 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12844 TemplateSpecCandidateSet FailedCandidates;
12845
12846public:
12847 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12848 const QualType &TargetType, bool Complain)
12849 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12850 Complain(Complain), Context(S.getASTContext()),
12851 TargetTypeIsNonStaticMemberFunction(
12852 !!TargetType->getAs<MemberPointerType>()),
12853 FoundNonTemplateFunction(false),
12854 StaticMemberFunctionFromBoundPointer(false),
12855 HasComplained(false),
12856 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12857 OvlExpr(OvlExprInfo.Expression),
12858 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12859 ExtractUnqualifiedFunctionTypeFromTargetType();
12860
12861 if (TargetFunctionType->isFunctionType()) {
12862 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12863 if (!UME->isImplicitAccess() &&
12865 StaticMemberFunctionFromBoundPointer = true;
12866 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12867 DeclAccessPair dap;
12869 OvlExpr, false, &dap)) {
12870 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12871 if (!Method->isStatic()) {
12872 // If the target type is a non-function type and the function found
12873 // is a non-static member function, pretend as if that was the
12874 // target, it's the only possible type to end up with.
12875 TargetTypeIsNonStaticMemberFunction = true;
12876
12877 // And skip adding the function if its not in the proper form.
12878 // We'll diagnose this due to an empty set of functions.
12879 if (!OvlExprInfo.HasFormOfMemberPointer)
12880 return;
12881 }
12882
12883 Matches.push_back(std::make_pair(dap, Fn));
12884 }
12885 return;
12886 }
12887
12888 if (OvlExpr->hasExplicitTemplateArgs())
12889 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12890
12891 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12892 // C++ [over.over]p4:
12893 // If more than one function is selected, [...]
12894 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12895 if (FoundNonTemplateFunction)
12896 EliminateAllTemplateMatches();
12897 else
12898 EliminateAllExceptMostSpecializedTemplate();
12899 }
12900 }
12901
12902 if (S.getLangOpts().CUDA && Matches.size() > 1)
12903 EliminateSuboptimalCudaMatches();
12904 }
12905
12906 bool hasComplained() const { return HasComplained; }
12907
12908private:
12909 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12910 QualType Discard;
12911 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12912 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12913 }
12914
12915 /// \return true if A is considered a better overload candidate for the
12916 /// desired type than B.
12917 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12918 // If A doesn't have exactly the correct type, we don't want to classify it
12919 // as "better" than anything else. This way, the user is required to
12920 // disambiguate for us if there are multiple candidates and no exact match.
12921 return candidateHasExactlyCorrectType(A) &&
12922 (!candidateHasExactlyCorrectType(B) ||
12923 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12924 }
12925
12926 /// \return true if we were able to eliminate all but one overload candidate,
12927 /// false otherwise.
12928 bool eliminiateSuboptimalOverloadCandidates() {
12929 // Same algorithm as overload resolution -- one pass to pick the "best",
12930 // another pass to be sure that nothing is better than the best.
12931 auto Best = Matches.begin();
12932 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12933 if (isBetterCandidate(I->second, Best->second))
12934 Best = I;
12935
12936 const FunctionDecl *BestFn = Best->second;
12937 auto IsBestOrInferiorToBest = [this, BestFn](
12938 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12939 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12940 };
12941
12942 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12943 // option, so we can potentially give the user a better error
12944 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12945 return false;
12946 Matches[0] = *Best;
12947 Matches.resize(1);
12948 return true;
12949 }
12950
12951 bool isTargetTypeAFunction() const {
12952 return TargetFunctionType->isFunctionType();
12953 }
12954
12955 // [ToType] [Return]
12956
12957 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12958 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12959 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12960 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12961 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12962 }
12963
12964 // return true if any matching specializations were found
12965 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12966 const DeclAccessPair& CurAccessFunPair) {
12967 if (CXXMethodDecl *Method
12968 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12969 // Skip non-static function templates when converting to pointer, and
12970 // static when converting to member pointer.
12971 bool CanConvertToFunctionPointer =
12972 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12973 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12974 return false;
12975 }
12976 else if (TargetTypeIsNonStaticMemberFunction)
12977 return false;
12978
12979 // C++ [over.over]p2:
12980 // If the name is a function template, template argument deduction is
12981 // done (14.8.2.2), and if the argument deduction succeeds, the
12982 // resulting template argument list is used to generate a single
12983 // function template specialization, which is added to the set of
12984 // overloaded functions considered.
12985 FunctionDecl *Specialization = nullptr;
12986 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12988 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
12989 Specialization, Info, /*IsAddressOfFunction*/ true);
12990 Result != TemplateDeductionResult::Success) {
12991 // Make a note of the failed deduction for diagnostics.
12992 FailedCandidates.addCandidate()
12993 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12994 MakeDeductionFailureInfo(Context, Result, Info));
12995 return false;
12996 }
12997
12998 // Template argument deduction ensures that we have an exact match or
12999 // compatible pointer-to-function arguments that would be adjusted by ICS.
13000 // This function template specicalization works.
13002 Context.getCanonicalType(Specialization->getType()),
13003 Context.getCanonicalType(TargetFunctionType)));
13004
13006 return false;
13007
13008 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13009 return true;
13010 }
13011
13012 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13013 const DeclAccessPair& CurAccessFunPair) {
13014 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13015 // Skip non-static functions when converting to pointer, and static
13016 // when converting to member pointer.
13017 bool CanConvertToFunctionPointer =
13018 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13019 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13020 return false;
13021 }
13022 else if (TargetTypeIsNonStaticMemberFunction)
13023 return false;
13024
13025 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13026 if (S.getLangOpts().CUDA) {
13027 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13028 if (!(Caller && Caller->isImplicit()) &&
13029 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13030 return false;
13031 }
13032 if (FunDecl->isMultiVersion()) {
13033 const auto *TA = FunDecl->getAttr<TargetAttr>();
13034 if (TA && !TA->isDefaultVersion())
13035 return false;
13036 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13037 if (TVA && !TVA->isDefaultVersion())
13038 return false;
13039 }
13040
13041 // If any candidate has a placeholder return type, trigger its deduction
13042 // now.
13043 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13044 Complain)) {
13045 HasComplained |= Complain;
13046 return false;
13047 }
13048
13049 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13050 return false;
13051
13052 // If we're in C, we need to support types that aren't exactly identical.
13053 if (!S.getLangOpts().CPlusPlus ||
13054 candidateHasExactlyCorrectType(FunDecl)) {
13055 Matches.push_back(std::make_pair(
13056 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13057 FoundNonTemplateFunction = true;
13058 return true;
13059 }
13060 }
13061
13062 return false;
13063 }
13064
13065 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13066 bool Ret = false;
13067
13068 // If the overload expression doesn't have the form of a pointer to
13069 // member, don't try to convert it to a pointer-to-member type.
13070 if (IsInvalidFormOfPointerToMemberFunction())
13071 return false;
13072
13073 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13074 E = OvlExpr->decls_end();
13075 I != E; ++I) {
13076 // Look through any using declarations to find the underlying function.
13077 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13078
13079 // C++ [over.over]p3:
13080 // Non-member functions and static member functions match
13081 // targets of type "pointer-to-function" or "reference-to-function."
13082 // Nonstatic member functions match targets of
13083 // type "pointer-to-member-function."
13084 // Note that according to DR 247, the containing class does not matter.
13085 if (FunctionTemplateDecl *FunctionTemplate
13086 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13087 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13088 Ret = true;
13089 }
13090 // If we have explicit template arguments supplied, skip non-templates.
13091 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13092 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13093 Ret = true;
13094 }
13095 assert(Ret || Matches.empty());
13096 return Ret;
13097 }
13098
13099 void EliminateAllExceptMostSpecializedTemplate() {
13100 // [...] and any given function template specialization F1 is
13101 // eliminated if the set contains a second function template
13102 // specialization whose function template is more specialized
13103 // than the function template of F1 according to the partial
13104 // ordering rules of 14.5.5.2.
13105
13106 // The algorithm specified above is quadratic. We instead use a
13107 // two-pass algorithm (similar to the one used to identify the
13108 // best viable function in an overload set) that identifies the
13109 // best function template (if it exists).
13110
13111 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13112 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13113 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13114
13115 // TODO: It looks like FailedCandidates does not serve much purpose
13116 // here, since the no_viable diagnostic has index 0.
13118 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13119 SourceExpr->getBeginLoc(), S.PDiag(),
13120 S.PDiag(diag::err_addr_ovl_ambiguous)
13121 << Matches[0].second->getDeclName(),
13122 S.PDiag(diag::note_ovl_candidate)
13123 << (unsigned)oc_function << (unsigned)ocs_described_template,
13124 Complain, TargetFunctionType);
13125
13126 if (Result != MatchesCopy.end()) {
13127 // Make it the first and only element
13128 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13129 Matches[0].second = cast<FunctionDecl>(*Result);
13130 Matches.resize(1);
13131 } else
13132 HasComplained |= Complain;
13133 }
13134
13135 void EliminateAllTemplateMatches() {
13136 // [...] any function template specializations in the set are
13137 // eliminated if the set also contains a non-template function, [...]
13138 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13139 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13140 ++I;
13141 else {
13142 Matches[I] = Matches[--N];
13143 Matches.resize(N);
13144 }
13145 }
13146 }
13147
13148 void EliminateSuboptimalCudaMatches() {
13149 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13150 Matches);
13151 }
13152
13153public:
13154 void ComplainNoMatchesFound() const {
13155 assert(Matches.empty());
13156 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13157 << OvlExpr->getName() << TargetFunctionType
13158 << OvlExpr->getSourceRange();
13159 if (FailedCandidates.empty())
13160 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13161 /*TakingAddress=*/true);
13162 else {
13163 // We have some deduction failure messages. Use them to diagnose
13164 // the function templates, and diagnose the non-template candidates
13165 // normally.
13166 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13167 IEnd = OvlExpr->decls_end();
13168 I != IEnd; ++I)
13169 if (FunctionDecl *Fun =
13170 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13172 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13173 /*TakingAddress=*/true);
13174 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13175 }
13176 }
13177
13178 bool IsInvalidFormOfPointerToMemberFunction() const {
13179 return TargetTypeIsNonStaticMemberFunction &&
13180 !OvlExprInfo.HasFormOfMemberPointer;
13181 }
13182
13183 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13184 // TODO: Should we condition this on whether any functions might
13185 // have matched, or is it more appropriate to do that in callers?
13186 // TODO: a fixit wouldn't hurt.
13187 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13188 << TargetType << OvlExpr->getSourceRange();
13189 }
13190
13191 bool IsStaticMemberFunctionFromBoundPointer() const {
13192 return StaticMemberFunctionFromBoundPointer;
13193 }
13194
13195 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13196 S.Diag(OvlExpr->getBeginLoc(),
13197 diag::err_invalid_form_pointer_member_function)
13198 << OvlExpr->getSourceRange();
13199 }
13200
13201 void ComplainOfInvalidConversion() const {
13202 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13203 << OvlExpr->getName() << TargetType;
13204 }
13205
13206 void ComplainMultipleMatchesFound() const {
13207 assert(Matches.size() > 1);
13208 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13209 << OvlExpr->getName() << OvlExpr->getSourceRange();
13210 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13211 /*TakingAddress=*/true);
13212 }
13213
13214 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13215
13216 int getNumMatches() const { return Matches.size(); }
13217
13218 FunctionDecl* getMatchingFunctionDecl() const {
13219 if (Matches.size() != 1) return nullptr;
13220 return Matches[0].second;
13221 }
13222
13223 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13224 if (Matches.size() != 1) return nullptr;
13225 return &Matches[0].first;
13226 }
13227};
13228}
13229
13230/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13231/// an overloaded function (C++ [over.over]), where @p From is an
13232/// expression with overloaded function type and @p ToType is the type
13233/// we're trying to resolve to. For example:
13234///
13235/// @code
13236/// int f(double);
13237/// int f(int);
13238///
13239/// int (*pfd)(double) = f; // selects f(double)
13240/// @endcode
13241///
13242/// This routine returns the resulting FunctionDecl if it could be
13243/// resolved, and NULL otherwise. When @p Complain is true, this
13244/// routine will emit diagnostics if there is an error.
13247 QualType TargetType,
13248 bool Complain,
13249 DeclAccessPair &FoundResult,
13250 bool *pHadMultipleCandidates) {
13251 assert(AddressOfExpr->getType() == Context.OverloadTy);
13252
13253 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13254 Complain);
13255 int NumMatches = Resolver.getNumMatches();
13256 FunctionDecl *Fn = nullptr;
13257 bool ShouldComplain = Complain && !Resolver.hasComplained();
13258 if (NumMatches == 0 && ShouldComplain) {
13259 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13260 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13261 else
13262 Resolver.ComplainNoMatchesFound();
13263 }
13264 else if (NumMatches > 1 && ShouldComplain)
13265 Resolver.ComplainMultipleMatchesFound();
13266 else if (NumMatches == 1) {
13267 Fn = Resolver.getMatchingFunctionDecl();
13268 assert(Fn);
13269 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13270 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13271 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13272 if (Complain) {
13273 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13274 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13275 else
13276 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13277 }
13278 }
13279
13280 if (pHadMultipleCandidates)
13281 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13282 return Fn;
13283}
13284
13285/// Given an expression that refers to an overloaded function, try to
13286/// resolve that function to a single function that can have its address taken.
13287/// This will modify `Pair` iff it returns non-null.
13288///
13289/// This routine can only succeed if from all of the candidates in the overload
13290/// set for SrcExpr that can have their addresses taken, there is one candidate
13291/// that is more constrained than the rest.
13295 OverloadExpr *Ovl = R.Expression;
13296 bool IsResultAmbiguous = false;
13297 FunctionDecl *Result = nullptr;
13298 DeclAccessPair DAP;
13299 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13300
13301 // Return positive for better, negative for worse, 0 for equal preference.
13302 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13303 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13304 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13305 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13306 };
13307
13308 // Don't use the AddressOfResolver because we're specifically looking for
13309 // cases where we have one overload candidate that lacks
13310 // enable_if/pass_object_size/...
13311 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13312 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13313 if (!FD)
13314 return nullptr;
13315
13317 continue;
13318
13319 // If we found a better result, update Result.
13320 auto FoundBetter = [&]() {
13321 IsResultAmbiguous = false;
13322 DAP = I.getPair();
13323 Result = FD;
13324 };
13325
13326 // We have more than one result - see if it is more constrained than the
13327 // previous one.
13328 if (Result) {
13329 // Check CUDA preference first. If the candidates have differennt CUDA
13330 // preference, choose the one with higher CUDA preference. Otherwise,
13331 // choose the one with more constraints.
13332 if (getLangOpts().CUDA) {
13333 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13334 // FD has different preference than Result.
13335 if (PreferenceByCUDA != 0) {
13336 // FD is more preferable than Result.
13337 if (PreferenceByCUDA > 0)
13338 FoundBetter();
13339 continue;
13340 }
13341 }
13342 // FD has the same CUDA prefernece than Result. Continue check
13343 // constraints.
13344 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13345 if (MoreConstrained != FD) {
13346 if (!MoreConstrained) {
13347 IsResultAmbiguous = true;
13348 AmbiguousDecls.push_back(FD);
13349 }
13350 continue;
13351 }
13352 // FD is more constrained - replace Result with it.
13353 }
13354 FoundBetter();
13355 }
13356
13357 if (IsResultAmbiguous)
13358 return nullptr;
13359
13360 if (Result) {
13362 // We skipped over some ambiguous declarations which might be ambiguous with
13363 // the selected result.
13364 for (FunctionDecl *Skipped : AmbiguousDecls) {
13365 // If skipped candidate has different CUDA preference than the result,
13366 // there is no ambiguity. Otherwise check whether they have different
13367 // constraints.
13368 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13369 continue;
13370 if (!getMoreConstrainedFunction(Skipped, Result))
13371 return nullptr;
13372 }
13373 Pair = DAP;
13374 }
13375 return Result;
13376}
13377
13378/// Given an overloaded function, tries to turn it into a non-overloaded
13379/// function reference using resolveAddressOfSingleOverloadCandidate. This
13380/// will perform access checks, diagnose the use of the resultant decl, and, if
13381/// requested, potentially perform a function-to-pointer decay.
13382///
13383/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13384/// Otherwise, returns true. This may emit diagnostics and return true.
13386 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13387 Expr *E = SrcExpr.get();
13388 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13389
13390 DeclAccessPair DAP;
13391 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13392 if (!Found || Found->isCPUDispatchMultiVersion() ||
13394 return false;
13395
13396 // Emitting multiple diagnostics for a function that is both inaccessible and
13397 // unavailable is consistent with our behavior elsewhere. So, always check
13398 // for both.
13399 DiagnoseUseOfDecl(Found, E->getExprLoc());
13400 CheckAddressOfMemberAccess(E, DAP);
13401 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13402 if (Res.isInvalid())
13403 return false;
13404 Expr *Fixed = Res.get();
13405 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13406 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13407 else
13408 SrcExpr = Fixed;
13409 return true;
13410}
13411
13412/// Given an expression that refers to an overloaded function, try to
13413/// resolve that overloaded function expression down to a single function.
13414///
13415/// This routine can only resolve template-ids that refer to a single function
13416/// template, where that template-id refers to a single template whose template
13417/// arguments are either provided by the template-id or have defaults,
13418/// as described in C++0x [temp.arg.explicit]p3.
13419///
13420/// If no template-ids are found, no diagnostics are emitted and NULL is
13421/// returned.
13423 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13424 TemplateSpecCandidateSet *FailedTSC) {
13425 // C++ [over.over]p1:
13426 // [...] [Note: any redundant set of parentheses surrounding the
13427 // overloaded function name is ignored (5.1). ]
13428 // C++ [over.over]p1:
13429 // [...] The overloaded function name can be preceded by the &
13430 // operator.
13431
13432 // If we didn't actually find any template-ids, we're done.
13433 if (!ovl->hasExplicitTemplateArgs())
13434 return nullptr;
13435
13436 TemplateArgumentListInfo ExplicitTemplateArgs;
13437 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13438
13439 // Look through all of the overloaded functions, searching for one
13440 // whose type matches exactly.
13441 FunctionDecl *Matched = nullptr;
13442 for (UnresolvedSetIterator I = ovl->decls_begin(),
13443 E = ovl->decls_end(); I != E; ++I) {
13444 // C++0x [temp.arg.explicit]p3:
13445 // [...] In contexts where deduction is done and fails, or in contexts
13446 // where deduction is not done, if a template argument list is
13447 // specified and it, along with any default template arguments,
13448 // identifies a single function template specialization, then the
13449 // template-id is an lvalue for the function template specialization.
13450 FunctionTemplateDecl *FunctionTemplate
13451 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13452
13453 // C++ [over.over]p2:
13454 // If the name is a function template, template argument deduction is
13455 // done (14.8.2.2), and if the argument deduction succeeds, the
13456 // resulting template argument list is used to generate a single
13457 // function template specialization, which is added to the set of
13458 // overloaded functions considered.
13459 FunctionDecl *Specialization = nullptr;
13460 TemplateDeductionInfo Info(ovl->getNameLoc());
13462 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13463 /*IsAddressOfFunction*/ true);
13465 // Make a note of the failed deduction for diagnostics.
13466 if (FailedTSC)
13467 FailedTSC->addCandidate().set(
13468 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13469 MakeDeductionFailureInfo(Context, Result, Info));
13470 continue;
13471 }
13472
13473 assert(Specialization && "no specialization and no error?");
13474
13475 // Multiple matches; we can't resolve to a single declaration.
13476 if (Matched) {
13477 if (Complain) {
13478 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13479 << ovl->getName();
13480 NoteAllOverloadCandidates(ovl);
13481 }
13482 return nullptr;
13483 }
13484
13485 Matched = Specialization;
13486 if (FoundResult) *FoundResult = I.getPair();
13487 }
13488
13489 if (Matched &&
13490 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13491 return nullptr;
13492
13493 return Matched;
13494}
13495
13496// Resolve and fix an overloaded expression that can be resolved
13497// because it identifies a single function template specialization.
13498//
13499// Last three arguments should only be supplied if Complain = true
13500//
13501// Return true if it was logically possible to so resolve the
13502// expression, regardless of whether or not it succeeded. Always
13503// returns true if 'complain' is set.
13505 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13506 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13507 unsigned DiagIDForComplaining) {
13508 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13509
13511
13512 DeclAccessPair found;
13513 ExprResult SingleFunctionExpression;
13514 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13515 ovl.Expression, /*complain*/ false, &found)) {
13516 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13517 SrcExpr = ExprError();
13518 return true;
13519 }
13520
13521 // It is only correct to resolve to an instance method if we're
13522 // resolving a form that's permitted to be a pointer to member.
13523 // Otherwise we'll end up making a bound member expression, which
13524 // is illegal in all the contexts we resolve like this.
13525 if (!ovl.HasFormOfMemberPointer &&
13526 isa<CXXMethodDecl>(fn) &&
13527 cast<CXXMethodDecl>(fn)->isInstance()) {
13528 if (!complain) return false;
13529
13530 Diag(ovl.Expression->getExprLoc(),
13531 diag::err_bound_member_function)
13532 << 0 << ovl.Expression->getSourceRange();
13533
13534 // TODO: I believe we only end up here if there's a mix of
13535 // static and non-static candidates (otherwise the expression
13536 // would have 'bound member' type, not 'overload' type).
13537 // Ideally we would note which candidate was chosen and why
13538 // the static candidates were rejected.
13539 SrcExpr = ExprError();
13540 return true;
13541 }
13542
13543 // Fix the expression to refer to 'fn'.
13544 SingleFunctionExpression =
13545 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13546
13547 // If desired, do function-to-pointer decay.
13548 if (doFunctionPointerConversion) {
13549 SingleFunctionExpression =
13550 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13551 if (SingleFunctionExpression.isInvalid()) {
13552 SrcExpr = ExprError();
13553 return true;
13554 }
13555 }
13556 }
13557
13558 if (!SingleFunctionExpression.isUsable()) {
13559 if (complain) {
13560 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13561 << ovl.Expression->getName()
13562 << DestTypeForComplaining
13563 << OpRangeForComplaining
13565 NoteAllOverloadCandidates(SrcExpr.get());
13566
13567 SrcExpr = ExprError();
13568 return true;
13569 }
13570
13571 return false;
13572 }
13573
13574 SrcExpr = SingleFunctionExpression;
13575 return true;
13576}
13577
13578/// Add a single candidate to the overload set.
13580 DeclAccessPair FoundDecl,
13581 TemplateArgumentListInfo *ExplicitTemplateArgs,
13582 ArrayRef<Expr *> Args,
13583 OverloadCandidateSet &CandidateSet,
13584 bool PartialOverloading,
13585 bool KnownValid) {
13586 NamedDecl *Callee = FoundDecl.getDecl();
13587 if (isa<UsingShadowDecl>(Callee))
13588 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13589
13590 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13591 if (ExplicitTemplateArgs) {
13592 assert(!KnownValid && "Explicit template arguments?");
13593 return;
13594 }
13595 // Prevent ill-formed function decls to be added as overload candidates.
13596 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13597 return;
13598
13599 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13600 /*SuppressUserConversions=*/false,
13601 PartialOverloading);
13602 return;
13603 }
13604
13605 if (FunctionTemplateDecl *FuncTemplate
13606 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13607 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13608 ExplicitTemplateArgs, Args, CandidateSet,
13609 /*SuppressUserConversions=*/false,
13610 PartialOverloading);
13611 return;
13612 }
13613
13614 assert(!KnownValid && "unhandled case in overloaded call candidate");
13615}
13616
13617/// Add the overload candidates named by callee and/or found by argument
13618/// dependent lookup to the given overload set.
13620 ArrayRef<Expr *> Args,
13621 OverloadCandidateSet &CandidateSet,
13622 bool PartialOverloading) {
13623
13624#ifndef NDEBUG
13625 // Verify that ArgumentDependentLookup is consistent with the rules
13626 // in C++0x [basic.lookup.argdep]p3:
13627 //
13628 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13629 // and let Y be the lookup set produced by argument dependent
13630 // lookup (defined as follows). If X contains
13631 //
13632 // -- a declaration of a class member, or
13633 //
13634 // -- a block-scope function declaration that is not a
13635 // using-declaration, or
13636 //
13637 // -- a declaration that is neither a function or a function
13638 // template
13639 //
13640 // then Y is empty.
13641
13642 if (ULE->requiresADL()) {
13644 E = ULE->decls_end(); I != E; ++I) {
13645 assert(!(*I)->getDeclContext()->isRecord());
13646 assert(isa<UsingShadowDecl>(*I) ||
13647 !(*I)->getDeclContext()->isFunctionOrMethod());
13648 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13649 }
13650 }
13651#endif
13652
13653 // It would be nice to avoid this copy.
13654 TemplateArgumentListInfo TABuffer;
13655 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13656 if (ULE->hasExplicitTemplateArgs()) {
13657 ULE->copyTemplateArgumentsInto(TABuffer);
13658 ExplicitTemplateArgs = &TABuffer;
13659 }
13660
13662 E = ULE->decls_end(); I != E; ++I)
13663 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13664 CandidateSet, PartialOverloading,
13665 /*KnownValid*/ true);
13666
13667 if (ULE->requiresADL())
13668 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13669 Args, ExplicitTemplateArgs,
13670 CandidateSet, PartialOverloading);
13671}
13672
13673/// Add the call candidates from the given set of lookup results to the given
13674/// overload set. Non-function lookup results are ignored.
13676 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13677 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13678 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13679 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13680 CandidateSet, false, /*KnownValid*/ false);
13681}
13682
13683/// Determine whether a declaration with the specified name could be moved into
13684/// a different namespace.
13686 switch (Name.getCXXOverloadedOperator()) {
13687 case OO_New: case OO_Array_New:
13688 case OO_Delete: case OO_Array_Delete:
13689 return false;
13690
13691 default:
13692 return true;
13693 }
13694}
13695
13696/// Attempt to recover from an ill-formed use of a non-dependent name in a
13697/// template, where the non-dependent name was declared after the template
13698/// was defined. This is common in code written for a compilers which do not
13699/// correctly implement two-stage name lookup.
13700///
13701/// Returns true if a viable candidate was found and a diagnostic was issued.
13703 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13705 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13706 CXXRecordDecl **FoundInClass = nullptr) {
13707 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13708 return false;
13709
13710 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13711 if (DC->isTransparentContext())
13712 continue;
13713
13714 SemaRef.LookupQualifiedName(R, DC);
13715
13716 if (!R.empty()) {
13718
13719 OverloadCandidateSet Candidates(FnLoc, CSK);
13720 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13721 Candidates);
13722
13725 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13726
13727 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13728 // We either found non-function declarations or a best viable function
13729 // at class scope. A class-scope lookup result disables ADL. Don't
13730 // look past this, but let the caller know that we found something that
13731 // either is, or might be, usable in this class.
13732 if (FoundInClass) {
13733 *FoundInClass = RD;
13734 if (OR == OR_Success) {
13735 R.clear();
13736 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13737 R.resolveKind();
13738 }
13739 }
13740 return false;
13741 }
13742
13743 if (OR != OR_Success) {
13744 // There wasn't a unique best function or function template.
13745 return false;
13746 }
13747
13748 // Find the namespaces where ADL would have looked, and suggest
13749 // declaring the function there instead.
13750 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13751 Sema::AssociatedClassSet AssociatedClasses;
13752 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13753 AssociatedNamespaces,
13754 AssociatedClasses);
13755 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13757 DeclContext *Std = SemaRef.getStdNamespace();
13758 for (Sema::AssociatedNamespaceSet::iterator
13759 it = AssociatedNamespaces.begin(),
13760 end = AssociatedNamespaces.end(); it != end; ++it) {
13761 // Never suggest declaring a function within namespace 'std'.
13762 if (Std && Std->Encloses(*it))
13763 continue;
13764
13765 // Never suggest declaring a function within a namespace with a
13766 // reserved name, like __gnu_cxx.
13767 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13768 if (NS &&
13769 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13770 continue;
13771
13772 SuggestedNamespaces.insert(*it);
13773 }
13774 }
13775
13776 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13777 << R.getLookupName();
13778 if (SuggestedNamespaces.empty()) {
13779 SemaRef.Diag(Best->Function->getLocation(),
13780 diag::note_not_found_by_two_phase_lookup)
13781 << R.getLookupName() << 0;
13782 } else if (SuggestedNamespaces.size() == 1) {
13783 SemaRef.Diag(Best->Function->getLocation(),
13784 diag::note_not_found_by_two_phase_lookup)
13785 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13786 } else {
13787 // FIXME: It would be useful to list the associated namespaces here,
13788 // but the diagnostics infrastructure doesn't provide a way to produce
13789 // a localized representation of a list of items.
13790 SemaRef.Diag(Best->Function->getLocation(),
13791 diag::note_not_found_by_two_phase_lookup)
13792 << R.getLookupName() << 2;
13793 }
13794
13795 // Try to recover by calling this function.
13796 return true;
13797 }
13798
13799 R.clear();
13800 }
13801
13802 return false;
13803}
13804
13805/// Attempt to recover from ill-formed use of a non-dependent operator in a
13806/// template, where the non-dependent operator was declared after the template
13807/// was defined.
13808///
13809/// Returns true if a viable candidate was found and a diagnostic was issued.
13810static bool
13812 SourceLocation OpLoc,
13813 ArrayRef<Expr *> Args) {
13814 DeclarationName OpName =
13816 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13817 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13819 /*ExplicitTemplateArgs=*/nullptr, Args);
13820}
13821
13822namespace {
13823class BuildRecoveryCallExprRAII {
13824 Sema &SemaRef;
13826
13827public:
13828 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13829 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13830 SemaRef.IsBuildingRecoveryCallExpr = true;
13831 }
13832
13833 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13834};
13835}
13836
13837/// Attempts to recover from a call where no functions were found.
13838///
13839/// This function will do one of three things:
13840/// * Diagnose, recover, and return a recovery expression.
13841/// * Diagnose, fail to recover, and return ExprError().
13842/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13843/// expected to diagnose as appropriate.
13844static ExprResult
13847 SourceLocation LParenLoc,
13849 SourceLocation RParenLoc,
13850 bool EmptyLookup, bool AllowTypoCorrection) {
13851 // Do not try to recover if it is already building a recovery call.
13852 // This stops infinite loops for template instantiations like
13853 //
13854 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13855 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13856 if (SemaRef.IsBuildingRecoveryCallExpr)
13857 return ExprResult();
13858 BuildRecoveryCallExprRAII RCE(SemaRef);
13859
13860 CXXScopeSpec SS;
13861 SS.Adopt(ULE->getQualifierLoc());
13862 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13863
13864 TemplateArgumentListInfo TABuffer;
13865 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13866 if (ULE->hasExplicitTemplateArgs()) {
13867 ULE->copyTemplateArgumentsInto(TABuffer);
13868 ExplicitTemplateArgs = &TABuffer;
13869 }
13870
13871 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13873 CXXRecordDecl *FoundInClass = nullptr;
13874 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13876 ExplicitTemplateArgs, Args, &FoundInClass)) {
13877 // OK, diagnosed a two-phase lookup issue.
13878 } else if (EmptyLookup) {
13879 // Try to recover from an empty lookup with typo correction.
13880 R.clear();
13881 NoTypoCorrectionCCC NoTypoValidator{};
13882 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13883 ExplicitTemplateArgs != nullptr,
13884 dyn_cast<MemberExpr>(Fn));
13885 CorrectionCandidateCallback &Validator =
13886 AllowTypoCorrection
13887 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13888 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13889 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13890 Args))
13891 return ExprError();
13892 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13893 // We found a usable declaration of the name in a dependent base of some
13894 // enclosing class.
13895 // FIXME: We should also explain why the candidates found by name lookup
13896 // were not viable.
13897 if (SemaRef.DiagnoseDependentMemberLookup(R))
13898 return ExprError();
13899 } else {
13900 // We had viable candidates and couldn't recover; let the caller diagnose
13901 // this.
13902 return ExprResult();
13903 }
13904
13905 // If we get here, we should have issued a diagnostic and formed a recovery
13906 // lookup result.
13907 assert(!R.empty() && "lookup results empty despite recovery");
13908
13909 // If recovery created an ambiguity, just bail out.
13910 if (R.isAmbiguous()) {
13912 return ExprError();
13913 }
13914
13915 // Build an implicit member call if appropriate. Just drop the
13916 // casts and such from the call, we don't really care.
13917 ExprResult NewFn = ExprError();
13918 if ((*R.begin())->isCXXClassMember())
13919 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13920 ExplicitTemplateArgs, S);
13921 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13922 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13923 ExplicitTemplateArgs);
13924 else
13925 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13926
13927 if (NewFn.isInvalid())
13928 return ExprError();
13929
13930 // This shouldn't cause an infinite loop because we're giving it
13931 // an expression with viable lookup results, which should never
13932 // end up here.
13933 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13934 MultiExprArg(Args.data(), Args.size()),
13935 RParenLoc);
13936}
13937
13938/// Constructs and populates an OverloadedCandidateSet from
13939/// the given function.
13940/// \returns true when an the ExprResult output parameter has been set.
13943 MultiExprArg Args,
13944 SourceLocation RParenLoc,
13945 OverloadCandidateSet *CandidateSet,
13946 ExprResult *Result) {
13947#ifndef NDEBUG
13948 if (ULE->requiresADL()) {
13949 // To do ADL, we must have found an unqualified name.
13950 assert(!ULE->getQualifier() && "qualified name with ADL");
13951
13952 // We don't perform ADL for implicit declarations of builtins.
13953 // Verify that this was correctly set up.
13954 FunctionDecl *F;
13955 if (ULE->decls_begin() != ULE->decls_end() &&
13956 ULE->decls_begin() + 1 == ULE->decls_end() &&
13957 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13958 F->getBuiltinID() && F->isImplicit())
13959 llvm_unreachable("performing ADL for builtin");
13960
13961 // We don't perform ADL in C.
13962 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13963 }
13964#endif
13965
13966 UnbridgedCastsSet UnbridgedCasts;
13967 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13968 *Result = ExprError();
13969 return true;
13970 }
13971
13972 // Add the functions denoted by the callee to the set of candidate
13973 // functions, including those from argument-dependent lookup.
13974 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13975
13976 if (getLangOpts().MSVCCompat &&
13977 CurContext->isDependentContext() && !isSFINAEContext() &&
13978 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13979
13981 if (CandidateSet->empty() ||
13982 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13984 // In Microsoft mode, if we are inside a template class member function
13985 // then create a type dependent CallExpr. The goal is to postpone name
13986 // lookup to instantiation time to be able to search into type dependent
13987 // base classes.
13988 CallExpr *CE =
13989 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13990 RParenLoc, CurFPFeatureOverrides());
13992 *Result = CE;
13993 return true;
13994 }
13995 }
13996
13997 if (CandidateSet->empty())
13998 return false;
13999
14000 UnbridgedCasts.restore();
14001 return false;
14002}
14003
14004// Guess at what the return type for an unresolvable overload should be.
14007 std::optional<QualType> Result;
14008 // Adjust Type after seeing a candidate.
14009 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14010 if (!Candidate.Function)
14011 return;
14012 if (Candidate.Function->isInvalidDecl())
14013 return;
14014 QualType T = Candidate.Function->getReturnType();
14015 if (T.isNull())
14016 return;
14017 if (!Result)
14018 Result = T;
14019 else if (Result != T)
14020 Result = QualType();
14021 };
14022
14023 // Look for an unambiguous type from a progressively larger subset.
14024 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14025 //
14026 // First, consider only the best candidate.
14027 if (Best && *Best != CS.end())
14028 ConsiderCandidate(**Best);
14029 // Next, consider only viable candidates.
14030 if (!Result)
14031 for (const auto &C : CS)
14032 if (C.Viable)
14033 ConsiderCandidate(C);
14034 // Finally, consider all candidates.
14035 if (!Result)
14036 for (const auto &C : CS)
14037 ConsiderCandidate(C);
14038
14039 if (!Result)
14040 return QualType();
14041 auto Value = *Result;
14042 if (Value.isNull() || Value->isUndeducedType())
14043 return QualType();
14044 return Value;
14045}
14046
14047/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14048/// the completed call expression. If overload resolution fails, emits
14049/// diagnostics and returns ExprError()
14052 SourceLocation LParenLoc,
14053 MultiExprArg Args,
14054 SourceLocation RParenLoc,
14055 Expr *ExecConfig,
14056 OverloadCandidateSet *CandidateSet,
14058 OverloadingResult OverloadResult,
14059 bool AllowTypoCorrection) {
14060 switch (OverloadResult) {
14061 case OR_Success: {
14062 FunctionDecl *FDecl = (*Best)->Function;
14063 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14064 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14065 return ExprError();
14066 ExprResult Res =
14067 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14068 if (Res.isInvalid())
14069 return ExprError();
14070 return SemaRef.BuildResolvedCallExpr(
14071 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14072 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14073 }
14074
14075 case OR_No_Viable_Function: {
14076 // Try to recover by looking for viable functions which the user might
14077 // have meant to call.
14078 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14079 Args, RParenLoc,
14080 CandidateSet->empty(),
14081 AllowTypoCorrection);
14082 if (Recovery.isInvalid() || Recovery.isUsable())
14083 return Recovery;
14084
14085 // If the user passes in a function that we can't take the address of, we
14086 // generally end up emitting really bad error messages. Here, we attempt to
14087 // emit better ones.
14088 for (const Expr *Arg : Args) {
14089 if (!Arg->getType()->isFunctionType())
14090 continue;
14091 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14092 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14093 if (FD &&
14094 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14095 Arg->getExprLoc()))
14096 return ExprError();
14097 }
14098 }
14099
14100 CandidateSet->NoteCandidates(
14102 Fn->getBeginLoc(),
14103 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14104 << ULE->getName() << Fn->getSourceRange()),
14105 SemaRef, OCD_AllCandidates, Args);
14106 break;
14107 }
14108
14109 case OR_Ambiguous:
14110 CandidateSet->NoteCandidates(
14112 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14113 << ULE->getName() << Fn->getSourceRange()),
14114 SemaRef, OCD_AmbiguousCandidates, Args);
14115 break;
14116
14117 case OR_Deleted: {
14118 FunctionDecl *FDecl = (*Best)->Function;
14120 Fn->getSourceRange(), ULE->getName(),
14121 *CandidateSet, FDecl, Args);
14122
14123 // We emitted an error for the unavailable/deleted function call but keep
14124 // the call in the AST.
14125 ExprResult Res =
14126 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14127 if (Res.isInvalid())
14128 return ExprError();
14129 return SemaRef.BuildResolvedCallExpr(
14130 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14131 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14132 }
14133 }
14134
14135 // Overload resolution failed, try to recover.
14136 SmallVector<Expr *, 8> SubExprs = {Fn};
14137 SubExprs.append(Args.begin(), Args.end());
14138 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14139 chooseRecoveryType(*CandidateSet, Best));
14140}
14141
14144 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14145 if (I->Viable &&
14146 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14147 I->Viable = false;
14148 I->FailureKind = ovl_fail_addr_not_available;
14149 }
14150 }
14151}
14152
14153/// BuildOverloadedCallExpr - Given the call expression that calls Fn
14154/// (which eventually refers to the declaration Func) and the call
14155/// arguments Args/NumArgs, attempt to resolve the function call down
14156/// to a specific function. If overload resolution succeeds, returns
14157/// the call expression produced by overload resolution.
14158/// Otherwise, emits diagnostics and returns ExprError.
14161 SourceLocation LParenLoc,
14162 MultiExprArg Args,
14163 SourceLocation RParenLoc,
14164 Expr *ExecConfig,
14165 bool AllowTypoCorrection,
14166 bool CalleesAddressIsTaken) {
14167 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
14169 ExprResult result;
14170
14171 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14172 &result))
14173 return result;
14174
14175 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14176 // functions that aren't addressible are considered unviable.
14177 if (CalleesAddressIsTaken)
14178 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14179
14181 OverloadingResult OverloadResult =
14182 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14183
14184 // Model the case with a call to a templated function whose definition
14185 // encloses the call and whose return type contains a placeholder type as if
14186 // the UnresolvedLookupExpr was type-dependent.
14187 if (OverloadResult == OR_Success) {
14188 const FunctionDecl *FDecl = Best->Function;
14189 if (FDecl && FDecl->isTemplateInstantiation() &&
14190 FDecl->getReturnType()->isUndeducedType()) {
14191 if (const auto *TP =
14192 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14193 TP && TP->willHaveBody()) {
14194 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14195 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14196 }
14197 }
14198 }
14199
14200 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14201 ExecConfig, &CandidateSet, &Best,
14202 OverloadResult, AllowTypoCorrection);
14203}
14204
14208 const UnresolvedSetImpl &Fns,
14209 bool PerformADL) {
14210 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14211 PerformADL, Fns.begin(), Fns.end(),
14212 /*KnownDependent=*/false);
14213}
14214
14216 CXXConversionDecl *Method,
14217 bool HadMultipleCandidates) {
14218 // Convert the expression to match the conversion function's implicit object
14219 // parameter.
14220 ExprResult Exp;
14221 if (Method->isExplicitObjectMemberFunction())
14222 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14223 else
14224 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14225 FoundDecl, Method);
14226 if (Exp.isInvalid())
14227 return true;
14228
14229 if (Method->getParent()->isLambda() &&
14231 // This is a lambda conversion to block pointer; check if the argument
14232 // was a LambdaExpr.
14233 Expr *SubE = E;
14234 auto *CE = dyn_cast<CastExpr>(SubE);
14235 if (CE && CE->getCastKind() == CK_NoOp)
14236 SubE = CE->getSubExpr();
14237 SubE = SubE->IgnoreParens();
14238 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14239 SubE = BE->getSubExpr();
14240 if (isa<LambdaExpr>(SubE)) {
14241 // For the conversion to block pointer on a lambda expression, we
14242 // construct a special BlockLiteral instead; this doesn't really make
14243 // a difference in ARC, but outside of ARC the resulting block literal
14244 // follows the normal lifetime rules for block literals instead of being
14245 // autoreleased.
14246 PushExpressionEvaluationContext(
14247 ExpressionEvaluationContext::PotentiallyEvaluated);
14248 ExprResult BlockExp = BuildBlockForLambdaConversion(
14249 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14250 PopExpressionEvaluationContext();
14251
14252 // FIXME: This note should be produced by a CodeSynthesisContext.
14253 if (BlockExp.isInvalid())
14254 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14255 return BlockExp;
14256 }
14257 }
14258 CallExpr *CE;
14259 QualType ResultType = Method->getReturnType();
14261 ResultType = ResultType.getNonLValueExprType(Context);
14262 if (Method->isExplicitObjectMemberFunction()) {
14263 ExprResult FnExpr =
14264 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14265 HadMultipleCandidates, E->getBeginLoc());
14266 if (FnExpr.isInvalid())
14267 return ExprError();
14268 Expr *ObjectParam = Exp.get();
14269 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14270 ResultType, VK, Exp.get()->getEndLoc(),
14271 CurFPFeatureOverrides());
14272 } else {
14273 MemberExpr *ME =
14274 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14276 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14277 HadMultipleCandidates, DeclarationNameInfo(),
14279
14280 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14281 Exp.get()->getEndLoc(),
14282 CurFPFeatureOverrides());
14283 }
14284
14285 if (CheckFunctionCall(Method, CE,
14286 Method->getType()->castAs<FunctionProtoType>()))
14287 return ExprError();
14288
14289 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14290}
14291
14292/// Create a unary operation that may resolve to an overloaded
14293/// operator.
14294///
14295/// \param OpLoc The location of the operator itself (e.g., '*').
14296///
14297/// \param Opc The UnaryOperatorKind that describes this operator.
14298///
14299/// \param Fns The set of non-member functions that will be
14300/// considered by overload resolution. The caller needs to build this
14301/// set based on the context using, e.g.,
14302/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14303/// set should not contain any member functions; those will be added
14304/// by CreateOverloadedUnaryOp().
14305///
14306/// \param Input The input argument.
14309 const UnresolvedSetImpl &Fns,
14310 Expr *Input, bool PerformADL) {
14312 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14314 // TODO: provide better source location info.
14315 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14316
14317 if (checkPlaceholderForOverload(*this, Input))
14318 return ExprError();
14319
14320 Expr *Args[2] = { Input, nullptr };
14321 unsigned NumArgs = 1;
14322
14323 // For post-increment and post-decrement, add the implicit '0' as
14324 // the second argument, so that we know this is a post-increment or
14325 // post-decrement.
14326 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14327 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14328 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14329 SourceLocation());
14330 NumArgs = 2;
14331 }
14332
14333 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14334
14335 if (Input->isTypeDependent()) {
14337 // [C++26][expr.unary.op][expr.pre.incr]
14338 // The * operator yields an lvalue of type
14339 // The pre/post increment operators yied an lvalue.
14340 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14341 VK = VK_LValue;
14342
14343 if (Fns.empty())
14344 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14345 OK_Ordinary, OpLoc, false,
14346 CurFPFeatureOverrides());
14347
14348 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14349 ExprResult Fn = CreateUnresolvedLookupExpr(
14350 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14351 if (Fn.isInvalid())
14352 return ExprError();
14353 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14354 Context.DependentTy, VK, OpLoc,
14355 CurFPFeatureOverrides());
14356 }
14357
14358 // Build an empty overload set.
14360
14361 // Add the candidates from the given function set.
14362 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14363
14364 // Add operator candidates that are member functions.
14365 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14366
14367 // Add candidates from ADL.
14368 if (PerformADL) {
14369 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14370 /*ExplicitTemplateArgs*/nullptr,
14371 CandidateSet);
14372 }
14373
14374 // Add builtin operator candidates.
14375 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14376
14377 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14378
14379 // Perform overload resolution.
14381 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14382 case OR_Success: {
14383 // We found a built-in operator or an overloaded operator.
14384 FunctionDecl *FnDecl = Best->Function;
14385
14386 if (FnDecl) {
14387 Expr *Base = nullptr;
14388 // We matched an overloaded operator. Build a call to that
14389 // operator.
14390
14391 // Convert the arguments.
14392 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14393 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14394
14395 ExprResult InputInit;
14396 if (Method->isExplicitObjectMemberFunction())
14397 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14398 else
14399 InputInit = PerformImplicitObjectArgumentInitialization(
14400 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14401 if (InputInit.isInvalid())
14402 return ExprError();
14403 Base = Input = InputInit.get();
14404 } else {
14405 // Convert the arguments.
14406 ExprResult InputInit
14407 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14408 Context,
14409 FnDecl->getParamDecl(0)),
14411 Input);
14412 if (InputInit.isInvalid())
14413 return ExprError();
14414 Input = InputInit.get();
14415 }
14416
14417 // Build the actual expression node.
14418 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14419 Base, HadMultipleCandidates,
14420 OpLoc);
14421 if (FnExpr.isInvalid())
14422 return ExprError();
14423
14424 // Determine the result type.
14425 QualType ResultTy = FnDecl->getReturnType();
14427 ResultTy = ResultTy.getNonLValueExprType(Context);
14428
14429 Args[0] = Input;
14431 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14432 CurFPFeatureOverrides(), Best->IsADLCandidate);
14433
14434 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14435 return ExprError();
14436
14437 if (CheckFunctionCall(FnDecl, TheCall,
14438 FnDecl->getType()->castAs<FunctionProtoType>()))
14439 return ExprError();
14440 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14441 } else {
14442 // We matched a built-in operator. Convert the arguments, then
14443 // break out so that we will build the appropriate built-in
14444 // operator node.
14445 ExprResult InputRes = PerformImplicitConversion(
14446 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14448 if (InputRes.isInvalid())
14449 return ExprError();
14450 Input = InputRes.get();
14451 break;
14452 }
14453 }
14454
14456 // This is an erroneous use of an operator which can be overloaded by
14457 // a non-member function. Check for non-member operators which were
14458 // defined too late to be candidates.
14459 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14460 // FIXME: Recover by calling the found function.
14461 return ExprError();
14462
14463 // No viable function; fall through to handling this as a
14464 // built-in operator, which will produce an error message for us.
14465 break;
14466
14467 case OR_Ambiguous:
14468 CandidateSet.NoteCandidates(
14469 PartialDiagnosticAt(OpLoc,
14470 PDiag(diag::err_ovl_ambiguous_oper_unary)
14472 << Input->getType() << Input->getSourceRange()),
14473 *this, OCD_AmbiguousCandidates, ArgsArray,
14474 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14475 return ExprError();
14476
14477 case OR_Deleted: {
14478 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14479 // object whose method was called. Later in NoteCandidates size of ArgsArray
14480 // is passed further and it eventually ends up compared to number of
14481 // function candidate parameters which never includes the object parameter,
14482 // so slice ArgsArray to make sure apples are compared to apples.
14483 StringLiteral *Msg = Best->Function->getDeletedMessage();
14484 CandidateSet.NoteCandidates(
14485 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14487 << (Msg != nullptr)
14488 << (Msg ? Msg->getString() : StringRef())
14489 << Input->getSourceRange()),
14490 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14491 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14492 return ExprError();
14493 }
14494 }
14495
14496 // Either we found no viable overloaded operator or we matched a
14497 // built-in operator. In either case, fall through to trying to
14498 // build a built-in operation.
14499 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14500}
14501
14502/// Perform lookup for an overloaded binary operator.
14505 const UnresolvedSetImpl &Fns,
14506 ArrayRef<Expr *> Args, bool PerformADL) {
14507 SourceLocation OpLoc = CandidateSet.getLocation();
14508
14509 OverloadedOperatorKind ExtraOp =
14512 : OO_None;
14513
14514 // Add the candidates from the given function set. This also adds the
14515 // rewritten candidates using these functions if necessary.
14516 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14517
14518 // Add operator candidates that are member functions.
14519 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14520 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14521 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14523
14524 // In C++20, also add any rewritten member candidates.
14525 if (ExtraOp) {
14526 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14527 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14528 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14529 CandidateSet,
14531 }
14532
14533 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14534 // performed for an assignment operator (nor for operator[] nor operator->,
14535 // which don't get here).
14536 if (Op != OO_Equal && PerformADL) {
14538 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14539 /*ExplicitTemplateArgs*/ nullptr,
14540 CandidateSet);
14541 if (ExtraOp) {
14542 DeclarationName ExtraOpName =
14543 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14544 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14545 /*ExplicitTemplateArgs*/ nullptr,
14546 CandidateSet);
14547 }
14548 }
14549
14550 // Add builtin operator candidates.
14551 //
14552 // FIXME: We don't add any rewritten candidates here. This is strictly
14553 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14554 // resulting in our selecting a rewritten builtin candidate. For example:
14555 //
14556 // enum class E { e };
14557 // bool operator!=(E, E) requires false;
14558 // bool k = E::e != E::e;
14559 //
14560 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14561 // it seems unreasonable to consider rewritten builtin candidates. A core
14562 // issue has been filed proposing to removed this requirement.
14563 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14564}
14565
14566/// Create a binary operation that may resolve to an overloaded
14567/// operator.
14568///
14569/// \param OpLoc The location of the operator itself (e.g., '+').
14570///
14571/// \param Opc The BinaryOperatorKind that describes this operator.
14572///
14573/// \param Fns The set of non-member functions that will be
14574/// considered by overload resolution. The caller needs to build this
14575/// set based on the context using, e.g.,
14576/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14577/// set should not contain any member functions; those will be added
14578/// by CreateOverloadedBinOp().
14579///
14580/// \param LHS Left-hand argument.
14581/// \param RHS Right-hand argument.
14582/// \param PerformADL Whether to consider operator candidates found by ADL.
14583/// \param AllowRewrittenCandidates Whether to consider candidates found by
14584/// C++20 operator rewrites.
14585/// \param DefaultedFn If we are synthesizing a defaulted operator function,
14586/// the function in question. Such a function is never a candidate in
14587/// our overload resolution. This also enables synthesizing a three-way
14588/// comparison from < and == as described in C++20 [class.spaceship]p1.
14591 const UnresolvedSetImpl &Fns, Expr *LHS,
14592 Expr *RHS, bool PerformADL,
14593 bool AllowRewrittenCandidates,
14594 FunctionDecl *DefaultedFn) {
14595 Expr *Args[2] = { LHS, RHS };
14596 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14597
14598 if (!getLangOpts().CPlusPlus20)
14599 AllowRewrittenCandidates = false;
14600
14602
14603 // If either side is type-dependent, create an appropriate dependent
14604 // expression.
14605 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14606 if (Fns.empty()) {
14607 // If there are no functions to store, just build a dependent
14608 // BinaryOperator or CompoundAssignment.
14611 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14612 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14613 Context.DependentTy);
14615 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14616 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14617 }
14618
14619 // FIXME: save results of ADL from here?
14620 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14621 // TODO: provide better source location info in DNLoc component.
14623 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14624 ExprResult Fn = CreateUnresolvedLookupExpr(
14625 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14626 if (Fn.isInvalid())
14627 return ExprError();
14628 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14629 Context.DependentTy, VK_PRValue, OpLoc,
14630 CurFPFeatureOverrides());
14631 }
14632
14633 // If this is the .* operator, which is not overloadable, just
14634 // create a built-in binary operator.
14635 if (Opc == BO_PtrMemD) {
14636 auto CheckPlaceholder = [&](Expr *&Arg) {
14637 ExprResult Res = CheckPlaceholderExpr(Arg);
14638 if (Res.isUsable())
14639 Arg = Res.get();
14640 return !Res.isUsable();
14641 };
14642
14643 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14644 // expression that contains placeholders (in either the LHS or RHS).
14645 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14646 return ExprError();
14647 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14648 }
14649
14650 // Always do placeholder-like conversions on the RHS.
14651 if (checkPlaceholderForOverload(*this, Args[1]))
14652 return ExprError();
14653
14654 // Do placeholder-like conversion on the LHS; note that we should
14655 // not get here with a PseudoObject LHS.
14656 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14657 if (checkPlaceholderForOverload(*this, Args[0]))
14658 return ExprError();
14659
14660 // If this is the assignment operator, we only perform overload resolution
14661 // if the left-hand side is a class or enumeration type. This is actually
14662 // a hack. The standard requires that we do overload resolution between the
14663 // various built-in candidates, but as DR507 points out, this can lead to
14664 // problems. So we do it this way, which pretty much follows what GCC does.
14665 // Note that we go the traditional code path for compound assignment forms.
14666 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14667 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14668
14669 // Build the overload set.
14672 Op, OpLoc, AllowRewrittenCandidates));
14673 if (DefaultedFn)
14674 CandidateSet.exclude(DefaultedFn);
14675 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14676
14677 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14678
14679 // Perform overload resolution.
14681 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14682 case OR_Success: {
14683 // We found a built-in operator or an overloaded operator.
14684 FunctionDecl *FnDecl = Best->Function;
14685
14686 bool IsReversed = Best->isReversed();
14687 if (IsReversed)
14688 std::swap(Args[0], Args[1]);
14689
14690 if (FnDecl) {
14691
14692 if (FnDecl->isInvalidDecl())
14693 return ExprError();
14694
14695 Expr *Base = nullptr;
14696 // We matched an overloaded operator. Build a call to that
14697 // operator.
14698
14699 OverloadedOperatorKind ChosenOp =
14701
14702 // C++2a [over.match.oper]p9:
14703 // If a rewritten operator== candidate is selected by overload
14704 // resolution for an operator@, its return type shall be cv bool
14705 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14706 !FnDecl->getReturnType()->isBooleanType()) {
14707 bool IsExtension =
14709 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14710 : diag::err_ovl_rewrite_equalequal_not_bool)
14711 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14712 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14713 Diag(FnDecl->getLocation(), diag::note_declared_at);
14714 if (!IsExtension)
14715 return ExprError();
14716 }
14717
14718 if (AllowRewrittenCandidates && !IsReversed &&
14719 CandidateSet.getRewriteInfo().isReversible()) {
14720 // We could have reversed this operator, but didn't. Check if some
14721 // reversed form was a viable candidate, and if so, if it had a
14722 // better conversion for either parameter. If so, this call is
14723 // formally ambiguous, and allowing it is an extension.
14725 for (OverloadCandidate &Cand : CandidateSet) {
14726 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14727 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14728 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14730 *this, OpLoc, Cand.Conversions[ArgIdx],
14731 Best->Conversions[ArgIdx]) ==
14733 AmbiguousWith.push_back(Cand.Function);
14734 break;
14735 }
14736 }
14737 }
14738 }
14739
14740 if (!AmbiguousWith.empty()) {
14741 bool AmbiguousWithSelf =
14742 AmbiguousWith.size() == 1 &&
14743 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14744 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14746 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14747 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14748 if (AmbiguousWithSelf) {
14749 Diag(FnDecl->getLocation(),
14750 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14751 // Mark member== const or provide matching != to disallow reversed
14752 // args. Eg.
14753 // struct S { bool operator==(const S&); };
14754 // S()==S();
14755 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14756 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14757 !MD->isConst() &&
14758 !MD->hasCXXExplicitFunctionObjectParameter() &&
14759 Context.hasSameUnqualifiedType(
14760 MD->getFunctionObjectParameterType(),
14761 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14762 Context.hasSameUnqualifiedType(
14763 MD->getFunctionObjectParameterType(),
14764 Args[0]->getType()) &&
14765 Context.hasSameUnqualifiedType(
14766 MD->getFunctionObjectParameterType(),
14767 Args[1]->getType()))
14768 Diag(FnDecl->getLocation(),
14769 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14770 } else {
14771 Diag(FnDecl->getLocation(),
14772 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14773 for (auto *F : AmbiguousWith)
14774 Diag(F->getLocation(),
14775 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14776 }
14777 }
14778 }
14779
14780 // Check for nonnull = nullable.
14781 // This won't be caught in the arg's initialization: the parameter to
14782 // the assignment operator is not marked nonnull.
14783 if (Op == OO_Equal)
14784 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14785 Args[1]->getType(), OpLoc);
14786
14787 // Convert the arguments.
14788 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14789 // Best->Access is only meaningful for class members.
14790 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14791
14792 ExprResult Arg0, Arg1;
14793 unsigned ParamIdx = 0;
14794 if (Method->isExplicitObjectMemberFunction()) {
14795 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14796 ParamIdx = 1;
14797 } else {
14798 Arg0 = PerformImplicitObjectArgumentInitialization(
14799 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14800 }
14801 Arg1 = PerformCopyInitialization(
14803 Context, FnDecl->getParamDecl(ParamIdx)),
14804 SourceLocation(), Args[1]);
14805 if (Arg0.isInvalid() || Arg1.isInvalid())
14806 return ExprError();
14807
14808 Base = Args[0] = Arg0.getAs<Expr>();
14809 Args[1] = RHS = Arg1.getAs<Expr>();
14810 } else {
14811 // Convert the arguments.
14812 ExprResult Arg0 = PerformCopyInitialization(
14814 FnDecl->getParamDecl(0)),
14815 SourceLocation(), Args[0]);
14816 if (Arg0.isInvalid())
14817 return ExprError();
14818
14819 ExprResult Arg1 =
14820 PerformCopyInitialization(
14822 FnDecl->getParamDecl(1)),
14823 SourceLocation(), Args[1]);
14824 if (Arg1.isInvalid())
14825 return ExprError();
14826 Args[0] = LHS = Arg0.getAs<Expr>();
14827 Args[1] = RHS = Arg1.getAs<Expr>();
14828 }
14829
14830 // Build the actual expression node.
14831 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14832 Best->FoundDecl, Base,
14833 HadMultipleCandidates, OpLoc);
14834 if (FnExpr.isInvalid())
14835 return ExprError();
14836
14837 // Determine the result type.
14838 QualType ResultTy = FnDecl->getReturnType();
14840 ResultTy = ResultTy.getNonLValueExprType(Context);
14841
14842 CallExpr *TheCall;
14843 ArrayRef<const Expr *> ArgsArray(Args, 2);
14844 const Expr *ImplicitThis = nullptr;
14845
14846 // We always create a CXXOperatorCallExpr, even for explicit object
14847 // members; CodeGen should take care not to emit the this pointer.
14849 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14850 CurFPFeatureOverrides(), Best->IsADLCandidate);
14851
14852 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14853 Method && Method->isImplicitObjectMemberFunction()) {
14854 // Cut off the implicit 'this'.
14855 ImplicitThis = ArgsArray[0];
14856 ArgsArray = ArgsArray.slice(1);
14857 }
14858
14859 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14860 FnDecl))
14861 return ExprError();
14862
14863 // Check for a self move.
14864 if (Op == OO_Equal)
14865 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14866
14867 if (ImplicitThis) {
14868 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14869 QualType ThisTypeFromDecl = Context.getPointerType(
14870 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14871
14872 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14873 ThisTypeFromDecl);
14874 }
14875
14876 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14877 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14878 VariadicDoesNotApply);
14879
14880 ExprResult R = MaybeBindToTemporary(TheCall);
14881 if (R.isInvalid())
14882 return ExprError();
14883
14884 R = CheckForImmediateInvocation(R, FnDecl);
14885 if (R.isInvalid())
14886 return ExprError();
14887
14888 // For a rewritten candidate, we've already reversed the arguments
14889 // if needed. Perform the rest of the rewrite now.
14890 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14891 (Op == OO_Spaceship && IsReversed)) {
14892 if (Op == OO_ExclaimEqual) {
14893 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14894 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14895 } else {
14896 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14897 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14898 Expr *ZeroLiteral =
14899 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14900
14903 Ctx.Entity = FnDecl;
14904 pushCodeSynthesisContext(Ctx);
14905
14906 R = CreateOverloadedBinOp(
14907 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14908 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14909 /*AllowRewrittenCandidates=*/false);
14910
14911 popCodeSynthesisContext();
14912 }
14913 if (R.isInvalid())
14914 return ExprError();
14915 } else {
14916 assert(ChosenOp == Op && "unexpected operator name");
14917 }
14918
14919 // Make a note in the AST if we did any rewriting.
14920 if (Best->RewriteKind != CRK_None)
14921 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14922
14923 return R;
14924 } else {
14925 // We matched a built-in operator. Convert the arguments, then
14926 // break out so that we will build the appropriate built-in
14927 // operator node.
14928 ExprResult ArgsRes0 = PerformImplicitConversion(
14929 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14931 if (ArgsRes0.isInvalid())
14932 return ExprError();
14933 Args[0] = ArgsRes0.get();
14934
14935 ExprResult ArgsRes1 = PerformImplicitConversion(
14936 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14938 if (ArgsRes1.isInvalid())
14939 return ExprError();
14940 Args[1] = ArgsRes1.get();
14941 break;
14942 }
14943 }
14944
14945 case OR_No_Viable_Function: {
14946 // C++ [over.match.oper]p9:
14947 // If the operator is the operator , [...] and there are no
14948 // viable functions, then the operator is assumed to be the
14949 // built-in operator and interpreted according to clause 5.
14950 if (Opc == BO_Comma)
14951 break;
14952
14953 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14954 // compare result using '==' and '<'.
14955 if (DefaultedFn && Opc == BO_Cmp) {
14956 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14957 Args[1], DefaultedFn);
14958 if (E.isInvalid() || E.isUsable())
14959 return E;
14960 }
14961
14962 // For class as left operand for assignment or compound assignment
14963 // operator do not fall through to handling in built-in, but report that
14964 // no overloaded assignment operator found
14966 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14967 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14968 Args, OpLoc);
14969 DeferDiagsRAII DDR(*this,
14970 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14971 if (Args[0]->getType()->isRecordType() &&
14972 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14973 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14975 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14976 if (Args[0]->getType()->isIncompleteType()) {
14977 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14978 << Args[0]->getType()
14979 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14980 }
14981 } else {
14982 // This is an erroneous use of an operator which can be overloaded by
14983 // a non-member function. Check for non-member operators which were
14984 // defined too late to be candidates.
14985 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14986 // FIXME: Recover by calling the found function.
14987 return ExprError();
14988
14989 // No viable function; try to create a built-in operation, which will
14990 // produce an error. Then, show the non-viable candidates.
14991 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14992 }
14993 assert(Result.isInvalid() &&
14994 "C++ binary operator overloading is missing candidates!");
14995 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14996 return Result;
14997 }
14998
14999 case OR_Ambiguous:
15000 CandidateSet.NoteCandidates(
15001 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15003 << Args[0]->getType()
15004 << Args[1]->getType()
15005 << Args[0]->getSourceRange()
15006 << Args[1]->getSourceRange()),
15008 OpLoc);
15009 return ExprError();
15010
15011 case OR_Deleted: {
15012 if (isImplicitlyDeleted(Best->Function)) {
15013 FunctionDecl *DeletedFD = Best->Function;
15014 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15015 if (DFK.isSpecialMember()) {
15016 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15017 << Args[0]->getType()
15018 << llvm::to_underlying(DFK.asSpecialMember());
15019 } else {
15020 assert(DFK.isComparison());
15021 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15022 << Args[0]->getType() << DeletedFD;
15023 }
15024
15025 // The user probably meant to call this special member. Just
15026 // explain why it's deleted.
15027 NoteDeletedFunction(DeletedFD);
15028 return ExprError();
15029 }
15030
15031 StringLiteral *Msg = Best->Function->getDeletedMessage();
15032 CandidateSet.NoteCandidates(
15034 OpLoc,
15035 PDiag(diag::err_ovl_deleted_oper)
15036 << getOperatorSpelling(Best->Function->getDeclName()
15037 .getCXXOverloadedOperator())
15038 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15039 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15041 OpLoc);
15042 return ExprError();
15043 }
15044 }
15045
15046 // We matched a built-in operator; build it.
15047 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15048}
15049
15051 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15052 FunctionDecl *DefaultedFn) {
15053 const ComparisonCategoryInfo *Info =
15054 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15055 // If we're not producing a known comparison category type, we can't
15056 // synthesize a three-way comparison. Let the caller diagnose this.
15057 if (!Info)
15058 return ExprResult((Expr*)nullptr);
15059
15060 // If we ever want to perform this synthesis more generally, we will need to
15061 // apply the temporary materialization conversion to the operands.
15062 assert(LHS->isGLValue() && RHS->isGLValue() &&
15063 "cannot use prvalue expressions more than once");
15064 Expr *OrigLHS = LHS;
15065 Expr *OrigRHS = RHS;
15066
15067 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15068 // each of them multiple times below.
15069 LHS = new (Context)
15070 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15071 LHS->getObjectKind(), LHS);
15072 RHS = new (Context)
15073 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15074 RHS->getObjectKind(), RHS);
15075
15076 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15077 DefaultedFn);
15078 if (Eq.isInvalid())
15079 return ExprError();
15080
15081 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15082 true, DefaultedFn);
15083 if (Less.isInvalid())
15084 return ExprError();
15085
15087 if (Info->isPartial()) {
15088 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15089 DefaultedFn);
15090 if (Greater.isInvalid())
15091 return ExprError();
15092 }
15093
15094 // Form the list of comparisons we're going to perform.
15095 struct Comparison {
15096 ExprResult Cmp;
15098 } Comparisons[4] =
15104 };
15105
15106 int I = Info->isPartial() ? 3 : 2;
15107
15108 // Combine the comparisons with suitable conditional expressions.
15110 for (; I >= 0; --I) {
15111 // Build a reference to the comparison category constant.
15112 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15113 // FIXME: Missing a constant for a comparison category. Diagnose this?
15114 if (!VI)
15115 return ExprResult((Expr*)nullptr);
15116 ExprResult ThisResult =
15117 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15118 if (ThisResult.isInvalid())
15119 return ExprError();
15120
15121 // Build a conditional unless this is the final case.
15122 if (Result.get()) {
15123 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15124 ThisResult.get(), Result.get());
15125 if (Result.isInvalid())
15126 return ExprError();
15127 } else {
15128 Result = ThisResult;
15129 }
15130 }
15131
15132 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15133 // bind the OpaqueValueExprs before they're (repeatedly) used.
15134 Expr *SyntacticForm = BinaryOperator::Create(
15135 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15136 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15137 CurFPFeatureOverrides());
15138 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15139 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15140}
15141
15143 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15144 MultiExprArg Args, SourceLocation LParenLoc) {
15145
15146 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15147 unsigned NumParams = Proto->getNumParams();
15148 unsigned NumArgsSlots =
15149 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15150 // Build the full argument list for the method call (the implicit object
15151 // parameter is placed at the beginning of the list).
15152 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15153 bool IsError = false;
15154 // Initialize the implicit object parameter.
15155 // Check the argument types.
15156 for (unsigned i = 0; i != NumParams; i++) {
15157 Expr *Arg;
15158 if (i < Args.size()) {
15159 Arg = Args[i];
15160 ExprResult InputInit =
15162 S.Context, Method->getParamDecl(i)),
15163 SourceLocation(), Arg);
15164 IsError |= InputInit.isInvalid();
15165 Arg = InputInit.getAs<Expr>();
15166 } else {
15167 ExprResult DefArg =
15168 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15169 if (DefArg.isInvalid()) {
15170 IsError = true;
15171 break;
15172 }
15173 Arg = DefArg.getAs<Expr>();
15174 }
15175
15176 MethodArgs.push_back(Arg);
15177 }
15178 return IsError;
15179}
15180
15182 SourceLocation RLoc,
15183 Expr *Base,
15184 MultiExprArg ArgExpr) {
15186 Args.push_back(Base);
15187 for (auto *e : ArgExpr) {
15188 Args.push_back(e);
15189 }
15190 DeclarationName OpName =
15191 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15192
15193 SourceRange Range = ArgExpr.empty()
15194 ? SourceRange{}
15195 : SourceRange(ArgExpr.front()->getBeginLoc(),
15196 ArgExpr.back()->getEndLoc());
15197
15198 // If either side is type-dependent, create an appropriate dependent
15199 // expression.
15201
15202 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15203 // CHECKME: no 'operator' keyword?
15204 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15205 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15206 ExprResult Fn = CreateUnresolvedLookupExpr(
15207 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15208 if (Fn.isInvalid())
15209 return ExprError();
15210 // Can't add any actual overloads yet
15211
15212 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15213 Context.DependentTy, VK_PRValue, RLoc,
15214 CurFPFeatureOverrides());
15215 }
15216
15217 // Handle placeholders
15218 UnbridgedCastsSet UnbridgedCasts;
15219 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15220 return ExprError();
15221 }
15222 // Build an empty overload set.
15224
15225 // Subscript can only be overloaded as a member function.
15226
15227 // Add operator candidates that are member functions.
15228 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15229
15230 // Add builtin operator candidates.
15231 if (Args.size() == 2)
15232 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15233
15234 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15235
15236 // Perform overload resolution.
15238 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15239 case OR_Success: {
15240 // We found a built-in operator or an overloaded operator.
15241 FunctionDecl *FnDecl = Best->Function;
15242
15243 if (FnDecl) {
15244 // We matched an overloaded operator. Build a call to that
15245 // operator.
15246
15247 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15248
15249 // Convert the arguments.
15250 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15251 SmallVector<Expr *, 2> MethodArgs;
15252
15253 // Initialize the object parameter.
15254 if (Method->isExplicitObjectMemberFunction()) {
15255 ExprResult Res =
15256 InitializeExplicitObjectArgument(*this, Args[0], Method);
15257 if (Res.isInvalid())
15258 return ExprError();
15259 Args[0] = Res.get();
15260 ArgExpr = Args;
15261 } else {
15262 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15263 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15264 if (Arg0.isInvalid())
15265 return ExprError();
15266
15267 MethodArgs.push_back(Arg0.get());
15268 }
15269
15271 *this, MethodArgs, Method, ArgExpr, LLoc);
15272 if (IsError)
15273 return ExprError();
15274
15275 // Build the actual expression node.
15276 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15277 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15279 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15280 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15281 if (FnExpr.isInvalid())
15282 return ExprError();
15283
15284 // Determine the result type
15285 QualType ResultTy = FnDecl->getReturnType();
15287 ResultTy = ResultTy.getNonLValueExprType(Context);
15288
15290 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15291 CurFPFeatureOverrides());
15292
15293 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15294 return ExprError();
15295
15296 if (CheckFunctionCall(Method, TheCall,
15297 Method->getType()->castAs<FunctionProtoType>()))
15298 return ExprError();
15299
15300 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15301 FnDecl);
15302 } else {
15303 // We matched a built-in operator. Convert the arguments, then
15304 // break out so that we will build the appropriate built-in
15305 // operator node.
15306 ExprResult ArgsRes0 = PerformImplicitConversion(
15307 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15309 if (ArgsRes0.isInvalid())
15310 return ExprError();
15311 Args[0] = ArgsRes0.get();
15312
15313 ExprResult ArgsRes1 = PerformImplicitConversion(
15314 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15316 if (ArgsRes1.isInvalid())
15317 return ExprError();
15318 Args[1] = ArgsRes1.get();
15319
15320 break;
15321 }
15322 }
15323
15324 case OR_No_Viable_Function: {
15326 CandidateSet.empty()
15327 ? (PDiag(diag::err_ovl_no_oper)
15328 << Args[0]->getType() << /*subscript*/ 0
15329 << Args[0]->getSourceRange() << Range)
15330 : (PDiag(diag::err_ovl_no_viable_subscript)
15331 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15332 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15333 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15334 return ExprError();
15335 }
15336
15337 case OR_Ambiguous:
15338 if (Args.size() == 2) {
15339 CandidateSet.NoteCandidates(
15341 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15342 << "[]" << Args[0]->getType() << Args[1]->getType()
15343 << Args[0]->getSourceRange() << Range),
15344 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15345 } else {
15346 CandidateSet.NoteCandidates(
15348 PDiag(diag::err_ovl_ambiguous_subscript_call)
15349 << Args[0]->getType()
15350 << Args[0]->getSourceRange() << Range),
15351 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15352 }
15353 return ExprError();
15354
15355 case OR_Deleted: {
15356 StringLiteral *Msg = Best->Function->getDeletedMessage();
15357 CandidateSet.NoteCandidates(
15359 PDiag(diag::err_ovl_deleted_oper)
15360 << "[]" << (Msg != nullptr)
15361 << (Msg ? Msg->getString() : StringRef())
15362 << Args[0]->getSourceRange() << Range),
15363 *this, OCD_AllCandidates, Args, "[]", LLoc);
15364 return ExprError();
15365 }
15366 }
15367
15368 // We matched a built-in operator; build it.
15369 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15370}
15371
15372/// BuildCallToMemberFunction - Build a call to a member
15373/// function. MemExpr is the expression that refers to the member
15374/// function (and includes the object parameter), Args/NumArgs are the
15375/// arguments to the function call (not including the object
15376/// parameter). The caller needs to validate that the member
15377/// expression refers to a non-static member function or an overloaded
15378/// member function.
15380 SourceLocation LParenLoc,
15381 MultiExprArg Args,
15382 SourceLocation RParenLoc,
15383 Expr *ExecConfig, bool IsExecConfig,
15384 bool AllowRecovery) {
15385 assert(MemExprE->getType() == Context.BoundMemberTy ||
15386 MemExprE->getType() == Context.OverloadTy);
15387
15388 // Dig out the member expression. This holds both the object
15389 // argument and the member function we're referring to.
15390 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15391
15392 // Determine whether this is a call to a pointer-to-member function.
15393 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15394 assert(op->getType() == Context.BoundMemberTy);
15395 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15396
15397 QualType fnType =
15398 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15399
15400 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15401 QualType resultType = proto->getCallResultType(Context);
15403
15404 // Check that the object type isn't more qualified than the
15405 // member function we're calling.
15406 Qualifiers funcQuals = proto->getMethodQuals();
15407
15408 QualType objectType = op->getLHS()->getType();
15409 if (op->getOpcode() == BO_PtrMemI)
15410 objectType = objectType->castAs<PointerType>()->getPointeeType();
15411 Qualifiers objectQuals = objectType.getQualifiers();
15412
15413 Qualifiers difference = objectQuals - funcQuals;
15414 difference.removeObjCGCAttr();
15415 difference.removeAddressSpace();
15416 if (difference) {
15417 std::string qualsString = difference.getAsString();
15418 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15419 << fnType.getUnqualifiedType()
15420 << qualsString
15421 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15422 }
15423
15425 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15426 CurFPFeatureOverrides(), proto->getNumParams());
15427
15428 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15429 call, nullptr))
15430 return ExprError();
15431
15432 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15433 return ExprError();
15434
15435 if (CheckOtherCall(call, proto))
15436 return ExprError();
15437
15438 return MaybeBindToTemporary(call);
15439 }
15440
15441 // We only try to build a recovery expr at this level if we can preserve
15442 // the return type, otherwise we return ExprError() and let the caller
15443 // recover.
15444 auto BuildRecoveryExpr = [&](QualType Type) {
15445 if (!AllowRecovery)
15446 return ExprError();
15447 std::vector<Expr *> SubExprs = {MemExprE};
15448 llvm::append_range(SubExprs, Args);
15449 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15450 Type);
15451 };
15452 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15453 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15454 RParenLoc, CurFPFeatureOverrides());
15455
15456 UnbridgedCastsSet UnbridgedCasts;
15457 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15458 return ExprError();
15459
15460 MemberExpr *MemExpr;
15461 CXXMethodDecl *Method = nullptr;
15462 bool HadMultipleCandidates = false;
15463 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15464 NestedNameSpecifier *Qualifier = nullptr;
15465 if (isa<MemberExpr>(NakedMemExpr)) {
15466 MemExpr = cast<MemberExpr>(NakedMemExpr);
15467 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15468 FoundDecl = MemExpr->getFoundDecl();
15469 Qualifier = MemExpr->getQualifier();
15470 UnbridgedCasts.restore();
15471 } else {
15472 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15473 Qualifier = UnresExpr->getQualifier();
15474
15475 QualType ObjectType = UnresExpr->getBaseType();
15476 Expr::Classification ObjectClassification
15478 : UnresExpr->getBase()->Classify(Context);
15479
15480 // Add overload candidates
15481 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15483
15484 // FIXME: avoid copy.
15485 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15486 if (UnresExpr->hasExplicitTemplateArgs()) {
15487 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15488 TemplateArgs = &TemplateArgsBuffer;
15489 }
15490
15492 E = UnresExpr->decls_end(); I != E; ++I) {
15493
15494 QualType ExplicitObjectType = ObjectType;
15495
15496 NamedDecl *Func = *I;
15497 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15498 if (isa<UsingShadowDecl>(Func))
15499 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15500
15501 bool HasExplicitParameter = false;
15502 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15503 M && M->hasCXXExplicitFunctionObjectParameter())
15504 HasExplicitParameter = true;
15505 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15506 M &&
15507 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15508 HasExplicitParameter = true;
15509
15510 if (HasExplicitParameter)
15511 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15512
15513 // Microsoft supports direct constructor calls.
15514 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15515 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15516 CandidateSet,
15517 /*SuppressUserConversions*/ false);
15518 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15519 // If explicit template arguments were provided, we can't call a
15520 // non-template member function.
15521 if (TemplateArgs)
15522 continue;
15523
15524 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15525 ObjectClassification, Args, CandidateSet,
15526 /*SuppressUserConversions=*/false);
15527 } else {
15528 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15529 I.getPair(), ActingDC, TemplateArgs,
15530 ExplicitObjectType, ObjectClassification,
15531 Args, CandidateSet,
15532 /*SuppressUserConversions=*/false);
15533 }
15534 }
15535
15536 HadMultipleCandidates = (CandidateSet.size() > 1);
15537
15538 DeclarationName DeclName = UnresExpr->getMemberName();
15539
15540 UnbridgedCasts.restore();
15541
15543 bool Succeeded = false;
15544 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15545 Best)) {
15546 case OR_Success:
15547 Method = cast<CXXMethodDecl>(Best->Function);
15548 FoundDecl = Best->FoundDecl;
15549 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15550 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15551 break;
15552 // If FoundDecl is different from Method (such as if one is a template
15553 // and the other a specialization), make sure DiagnoseUseOfDecl is
15554 // called on both.
15555 // FIXME: This would be more comprehensively addressed by modifying
15556 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15557 // being used.
15558 if (Method != FoundDecl.getDecl() &&
15559 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15560 break;
15561 Succeeded = true;
15562 break;
15563
15565 CandidateSet.NoteCandidates(
15567 UnresExpr->getMemberLoc(),
15568 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15569 << DeclName << MemExprE->getSourceRange()),
15570 *this, OCD_AllCandidates, Args);
15571 break;
15572 case OR_Ambiguous:
15573 CandidateSet.NoteCandidates(
15574 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15575 PDiag(diag::err_ovl_ambiguous_member_call)
15576 << DeclName << MemExprE->getSourceRange()),
15577 *this, OCD_AmbiguousCandidates, Args);
15578 break;
15579 case OR_Deleted:
15580 DiagnoseUseOfDeletedFunction(
15581 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15582 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15583 break;
15584 }
15585 // Overload resolution fails, try to recover.
15586 if (!Succeeded)
15587 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15588
15589 ExprResult Res =
15590 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15591 if (Res.isInvalid())
15592 return ExprError();
15593 MemExprE = Res.get();
15594
15595 // If overload resolution picked a static member
15596 // build a non-member call based on that function.
15597 if (Method->isStatic()) {
15598 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15599 ExecConfig, IsExecConfig);
15600 }
15601
15602 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15603 }
15604
15605 QualType ResultType = Method->getReturnType();
15607 ResultType = ResultType.getNonLValueExprType(Context);
15608
15609 assert(Method && "Member call to something that isn't a method?");
15610 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15611
15612 CallExpr *TheCall = nullptr;
15614 if (Method->isExplicitObjectMemberFunction()) {
15615 PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15616 NewArgs);
15617 // Build the actual expression node.
15618 ExprResult FnExpr =
15619 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15620 HadMultipleCandidates, MemExpr->getExprLoc());
15621 if (FnExpr.isInvalid())
15622 return ExprError();
15623
15624 TheCall =
15625 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15626 CurFPFeatureOverrides(), Proto->getNumParams());
15627 } else {
15628 // Convert the object argument (for a non-static member function call).
15629 // We only need to do this if there was actually an overload; otherwise
15630 // it was done at lookup.
15631 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15632 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15633 if (ObjectArg.isInvalid())
15634 return ExprError();
15635 MemExpr->setBase(ObjectArg.get());
15636 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15637 RParenLoc, CurFPFeatureOverrides(),
15638 Proto->getNumParams());
15639 }
15640
15641 // Check for a valid return type.
15642 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15643 TheCall, Method))
15644 return BuildRecoveryExpr(ResultType);
15645
15646 // Convert the rest of the arguments
15647 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15648 RParenLoc))
15649 return BuildRecoveryExpr(ResultType);
15650
15651 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15652
15653 if (CheckFunctionCall(Method, TheCall, Proto))
15654 return ExprError();
15655
15656 // In the case the method to call was not selected by the overloading
15657 // resolution process, we still need to handle the enable_if attribute. Do
15658 // that here, so it will not hide previous -- and more relevant -- errors.
15659 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15660 if (const EnableIfAttr *Attr =
15661 CheckEnableIf(Method, LParenLoc, Args, true)) {
15662 Diag(MemE->getMemberLoc(),
15663 diag::err_ovl_no_viable_member_function_in_call)
15664 << Method << Method->getSourceRange();
15665 Diag(Method->getLocation(),
15666 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15667 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15668 return ExprError();
15669 }
15670 }
15671
15672 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15673 TheCall->getDirectCallee()->isPureVirtual()) {
15674 const FunctionDecl *MD = TheCall->getDirectCallee();
15675
15676 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15677 MemExpr->performsVirtualDispatch(getLangOpts())) {
15678 Diag(MemExpr->getBeginLoc(),
15679 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15680 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15681 << MD->getParent();
15682
15683 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15684 if (getLangOpts().AppleKext)
15685 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15686 << MD->getParent() << MD->getDeclName();
15687 }
15688 }
15689
15690 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15691 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15692 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15693 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15694 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15695 MemExpr->getMemberLoc());
15696 }
15697
15698 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15699 TheCall->getDirectCallee());
15700}
15701
15702/// BuildCallToObjectOfClassType - Build a call to an object of class
15703/// type (C++ [over.call.object]), which can end up invoking an
15704/// overloaded function call operator (@c operator()) or performing a
15705/// user-defined conversion on the object argument.
15708 SourceLocation LParenLoc,
15709 MultiExprArg Args,
15710 SourceLocation RParenLoc) {
15711 if (checkPlaceholderForOverload(*this, Obj))
15712 return ExprError();
15713 ExprResult Object = Obj;
15714
15715 UnbridgedCastsSet UnbridgedCasts;
15716 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15717 return ExprError();
15718
15719 assert(Object.get()->getType()->isRecordType() &&
15720 "Requires object type argument");
15721
15722 // C++ [over.call.object]p1:
15723 // If the primary-expression E in the function call syntax
15724 // evaluates to a class object of type "cv T", then the set of
15725 // candidate functions includes at least the function call
15726 // operators of T. The function call operators of T are obtained by
15727 // ordinary lookup of the name operator() in the context of
15728 // (E).operator().
15729 OverloadCandidateSet CandidateSet(LParenLoc,
15731 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15732
15733 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15734 diag::err_incomplete_object_call, Object.get()))
15735 return true;
15736
15737 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15738 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15739 LookupQualifiedName(R, Record->getDecl());
15740 R.suppressAccessDiagnostics();
15741
15742 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15743 Oper != OperEnd; ++Oper) {
15744 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15745 Object.get()->Classify(Context), Args, CandidateSet,
15746 /*SuppressUserConversion=*/false);
15747 }
15748
15749 // When calling a lambda, both the call operator, and
15750 // the conversion operator to function pointer
15751 // are considered. But when constraint checking
15752 // on the call operator fails, it will also fail on the
15753 // conversion operator as the constraints are always the same.
15754 // As the user probably does not intend to perform a surrogate call,
15755 // we filter them out to produce better error diagnostics, ie to avoid
15756 // showing 2 failed overloads instead of one.
15757 bool IgnoreSurrogateFunctions = false;
15758 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15759 const OverloadCandidate &Candidate = *CandidateSet.begin();
15760 if (!Candidate.Viable &&
15762 IgnoreSurrogateFunctions = true;
15763 }
15764
15765 // C++ [over.call.object]p2:
15766 // In addition, for each (non-explicit in C++0x) conversion function
15767 // declared in T of the form
15768 //
15769 // operator conversion-type-id () cv-qualifier;
15770 //
15771 // where cv-qualifier is the same cv-qualification as, or a
15772 // greater cv-qualification than, cv, and where conversion-type-id
15773 // denotes the type "pointer to function of (P1,...,Pn) returning
15774 // R", or the type "reference to pointer to function of
15775 // (P1,...,Pn) returning R", or the type "reference to function
15776 // of (P1,...,Pn) returning R", a surrogate call function [...]
15777 // is also considered as a candidate function. Similarly,
15778 // surrogate call functions are added to the set of candidate
15779 // functions for each conversion function declared in an
15780 // accessible base class provided the function is not hidden
15781 // within T by another intervening declaration.
15782 const auto &Conversions =
15783 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15784 for (auto I = Conversions.begin(), E = Conversions.end();
15785 !IgnoreSurrogateFunctions && I != E; ++I) {
15786 NamedDecl *D = *I;
15787 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15788 if (isa<UsingShadowDecl>(D))
15789 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15790
15791 // Skip over templated conversion functions; they aren't
15792 // surrogates.
15793 if (isa<FunctionTemplateDecl>(D))
15794 continue;
15795
15796 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15797 if (!Conv->isExplicit()) {
15798 // Strip the reference type (if any) and then the pointer type (if
15799 // any) to get down to what might be a function type.
15800 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15801 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15802 ConvType = ConvPtrType->getPointeeType();
15803
15804 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15805 {
15806 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15807 Object.get(), Args, CandidateSet);
15808 }
15809 }
15810 }
15811
15812 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15813
15814 // Perform overload resolution.
15816 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15817 Best)) {
15818 case OR_Success:
15819 // Overload resolution succeeded; we'll build the appropriate call
15820 // below.
15821 break;
15822
15823 case OR_No_Viable_Function: {
15825 CandidateSet.empty()
15826 ? (PDiag(diag::err_ovl_no_oper)
15827 << Object.get()->getType() << /*call*/ 1
15828 << Object.get()->getSourceRange())
15829 : (PDiag(diag::err_ovl_no_viable_object_call)
15830 << Object.get()->getType() << Object.get()->getSourceRange());
15831 CandidateSet.NoteCandidates(
15832 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15833 OCD_AllCandidates, Args);
15834 break;
15835 }
15836 case OR_Ambiguous:
15837 if (!R.isAmbiguous())
15838 CandidateSet.NoteCandidates(
15839 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15840 PDiag(diag::err_ovl_ambiguous_object_call)
15841 << Object.get()->getType()
15842 << Object.get()->getSourceRange()),
15843 *this, OCD_AmbiguousCandidates, Args);
15844 break;
15845
15846 case OR_Deleted: {
15847 // FIXME: Is this diagnostic here really necessary? It seems that
15848 // 1. we don't have any tests for this diagnostic, and
15849 // 2. we already issue err_deleted_function_use for this later on anyway.
15850 StringLiteral *Msg = Best->Function->getDeletedMessage();
15851 CandidateSet.NoteCandidates(
15852 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15853 PDiag(diag::err_ovl_deleted_object_call)
15854 << Object.get()->getType() << (Msg != nullptr)
15855 << (Msg ? Msg->getString() : StringRef())
15856 << Object.get()->getSourceRange()),
15857 *this, OCD_AllCandidates, Args);
15858 break;
15859 }
15860 }
15861
15862 if (Best == CandidateSet.end())
15863 return true;
15864
15865 UnbridgedCasts.restore();
15866
15867 if (Best->Function == nullptr) {
15868 // Since there is no function declaration, this is one of the
15869 // surrogate candidates. Dig out the conversion function.
15870 CXXConversionDecl *Conv
15871 = cast<CXXConversionDecl>(
15872 Best->Conversions[0].UserDefined.ConversionFunction);
15873
15874 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15875 Best->FoundDecl);
15876 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15877 return ExprError();
15878 assert(Conv == Best->FoundDecl.getDecl() &&
15879 "Found Decl & conversion-to-functionptr should be same, right?!");
15880 // We selected one of the surrogate functions that converts the
15881 // object parameter to a function pointer. Perform the conversion
15882 // on the object argument, then let BuildCallExpr finish the job.
15883
15884 // Create an implicit member expr to refer to the conversion operator.
15885 // and then call it.
15886 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15887 Conv, HadMultipleCandidates);
15888 if (Call.isInvalid())
15889 return ExprError();
15890 // Record usage of conversion in an implicit cast.
15892 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15893 nullptr, VK_PRValue, CurFPFeatureOverrides());
15894
15895 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15896 }
15897
15898 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15899
15900 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15901 // that calls this method, using Object for the implicit object
15902 // parameter and passing along the remaining arguments.
15903 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15904
15905 // An error diagnostic has already been printed when parsing the declaration.
15906 if (Method->isInvalidDecl())
15907 return ExprError();
15908
15909 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15910 unsigned NumParams = Proto->getNumParams();
15911
15912 DeclarationNameInfo OpLocInfo(
15913 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15914 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15915 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15916 Obj, HadMultipleCandidates,
15917 OpLocInfo.getLoc(),
15918 OpLocInfo.getInfo());
15919 if (NewFn.isInvalid())
15920 return true;
15921
15922 SmallVector<Expr *, 8> MethodArgs;
15923 MethodArgs.reserve(NumParams + 1);
15924
15925 bool IsError = false;
15926
15927 // Initialize the object parameter.
15929 if (Method->isExplicitObjectMemberFunction()) {
15930 // FIXME: we should do that during the definition of the lambda when we can.
15931 DiagnoseInvalidExplicitObjectParameterInLambda(Method);
15932 PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15933 } else {
15934 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15935 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15936 if (ObjRes.isInvalid())
15937 IsError = true;
15938 else
15939 Object = ObjRes;
15940 MethodArgs.push_back(Object.get());
15941 }
15942
15944 *this, MethodArgs, Method, Args, LParenLoc);
15945
15946 // If this is a variadic call, handle args passed through "...".
15947 if (Proto->isVariadic()) {
15948 // Promote the arguments (C99 6.5.2.2p7).
15949 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15950 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15951 nullptr);
15952 IsError |= Arg.isInvalid();
15953 MethodArgs.push_back(Arg.get());
15954 }
15955 }
15956
15957 if (IsError)
15958 return true;
15959
15960 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15961
15962 // Once we've built TheCall, all of the expressions are properly owned.
15963 QualType ResultTy = Method->getReturnType();
15965 ResultTy = ResultTy.getNonLValueExprType(Context);
15966
15968 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15969 CurFPFeatureOverrides());
15970
15971 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15972 return true;
15973
15974 if (CheckFunctionCall(Method, TheCall, Proto))
15975 return true;
15976
15977 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15978}
15979
15980/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15981/// (if one exists), where @c Base is an expression of class type and
15982/// @c Member is the name of the member we're trying to find.
15985 bool *NoArrowOperatorFound) {
15986 assert(Base->getType()->isRecordType() &&
15987 "left-hand side must have class type");
15988
15990 return ExprError();
15991
15992 SourceLocation Loc = Base->getExprLoc();
15993
15994 // C++ [over.ref]p1:
15995 //
15996 // [...] An expression x->m is interpreted as (x.operator->())->m
15997 // for a class object x of type T if T::operator->() exists and if
15998 // the operator is selected as the best match function by the
15999 // overload resolution mechanism (13.3).
16000 DeclarationName OpName =
16001 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16003
16004 if (RequireCompleteType(Loc, Base->getType(),
16005 diag::err_typecheck_incomplete_tag, Base))
16006 return ExprError();
16007
16008 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16009 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16011
16012 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16013 Oper != OperEnd; ++Oper) {
16014 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16015 std::nullopt, CandidateSet,
16016 /*SuppressUserConversion=*/false);
16017 }
16018
16019 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16020
16021 // Perform overload resolution.
16023 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16024 case OR_Success:
16025 // Overload resolution succeeded; we'll build the call below.
16026 break;
16027
16028 case OR_No_Viable_Function: {
16029 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16030 if (CandidateSet.empty()) {
16031 QualType BaseType = Base->getType();
16032 if (NoArrowOperatorFound) {
16033 // Report this specific error to the caller instead of emitting a
16034 // diagnostic, as requested.
16035 *NoArrowOperatorFound = true;
16036 return ExprError();
16037 }
16038 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16039 << BaseType << Base->getSourceRange();
16040 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16041 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16042 << FixItHint::CreateReplacement(OpLoc, ".");
16043 }
16044 } else
16045 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16046 << "operator->" << Base->getSourceRange();
16047 CandidateSet.NoteCandidates(*this, Base, Cands);
16048 return ExprError();
16049 }
16050 case OR_Ambiguous:
16051 if (!R.isAmbiguous())
16052 CandidateSet.NoteCandidates(
16053 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16054 << "->" << Base->getType()
16055 << Base->getSourceRange()),
16057 return ExprError();
16058
16059 case OR_Deleted: {
16060 StringLiteral *Msg = Best->Function->getDeletedMessage();
16061 CandidateSet.NoteCandidates(
16062 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16063 << "->" << (Msg != nullptr)
16064 << (Msg ? Msg->getString() : StringRef())
16065 << Base->getSourceRange()),
16066 *this, OCD_AllCandidates, Base);
16067 return ExprError();
16068 }
16069 }
16070
16071 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16072
16073 // Convert the object parameter.
16074 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16075
16076 if (Method->isExplicitObjectMemberFunction()) {
16077 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16078 if (R.isInvalid())
16079 return ExprError();
16080 Base = R.get();
16081 } else {
16082 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16083 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16084 if (BaseResult.isInvalid())
16085 return ExprError();
16086 Base = BaseResult.get();
16087 }
16088
16089 // Build the operator call.
16090 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16091 Base, HadMultipleCandidates, OpLoc);
16092 if (FnExpr.isInvalid())
16093 return ExprError();
16094
16095 QualType ResultTy = Method->getReturnType();
16097 ResultTy = ResultTy.getNonLValueExprType(Context);
16098
16099 CallExpr *TheCall =
16100 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16101 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16102
16103 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16104 return ExprError();
16105
16106 if (CheckFunctionCall(Method, TheCall,
16107 Method->getType()->castAs<FunctionProtoType>()))
16108 return ExprError();
16109
16110 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16111}
16112
16113/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
16114/// a literal operator described by the provided lookup results.
16116 DeclarationNameInfo &SuffixInfo,
16117 ArrayRef<Expr*> Args,
16118 SourceLocation LitEndLoc,
16119 TemplateArgumentListInfo *TemplateArgs) {
16120 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16121
16122 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16124 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16125 TemplateArgs);
16126
16127 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16128
16129 // Perform overload resolution. This will usually be trivial, but might need
16130 // to perform substitutions for a literal operator template.
16132 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16133 case OR_Success:
16134 case OR_Deleted:
16135 break;
16136
16138 CandidateSet.NoteCandidates(
16139 PartialDiagnosticAt(UDSuffixLoc,
16140 PDiag(diag::err_ovl_no_viable_function_in_call)
16141 << R.getLookupName()),
16142 *this, OCD_AllCandidates, Args);
16143 return ExprError();
16144
16145 case OR_Ambiguous:
16146 CandidateSet.NoteCandidates(
16147 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16148 << R.getLookupName()),
16149 *this, OCD_AmbiguousCandidates, Args);
16150 return ExprError();
16151 }
16152
16153 FunctionDecl *FD = Best->Function;
16154 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16155 nullptr, HadMultipleCandidates,
16156 SuffixInfo.getLoc(),
16157 SuffixInfo.getInfo());
16158 if (Fn.isInvalid())
16159 return true;
16160
16161 // Check the argument types. This should almost always be a no-op, except
16162 // that array-to-pointer decay is applied to string literals.
16163 Expr *ConvArgs[2];
16164 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16165 ExprResult InputInit = PerformCopyInitialization(
16167 SourceLocation(), Args[ArgIdx]);
16168 if (InputInit.isInvalid())
16169 return true;
16170 ConvArgs[ArgIdx] = InputInit.get();
16171 }
16172
16173 QualType ResultTy = FD->getReturnType();
16175 ResultTy = ResultTy.getNonLValueExprType(Context);
16176
16178 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16179 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16180
16181 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16182 return ExprError();
16183
16184 if (CheckFunctionCall(FD, UDL, nullptr))
16185 return ExprError();
16186
16187 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16188}
16189
16190/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
16191/// given LookupResult is non-empty, it is assumed to describe a member which
16192/// will be invoked. Otherwise, the function will be found via argument
16193/// dependent lookup.
16194/// CallExpr is set to a valid expression and FRS_Success returned on success,
16195/// otherwise CallExpr is set to ExprError() and some non-success value
16196/// is returned.
16199 SourceLocation RangeLoc,
16200 const DeclarationNameInfo &NameInfo,
16201 LookupResult &MemberLookup,
16202 OverloadCandidateSet *CandidateSet,
16204 Scope *S = nullptr;
16205
16207 if (!MemberLookup.empty()) {
16208 ExprResult MemberRef =
16209 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16210 /*IsPtr=*/false, CXXScopeSpec(),
16211 /*TemplateKWLoc=*/SourceLocation(),
16212 /*FirstQualifierInScope=*/nullptr,
16213 MemberLookup,
16214 /*TemplateArgs=*/nullptr, S);
16215 if (MemberRef.isInvalid()) {
16216 *CallExpr = ExprError();
16217 return FRS_DiagnosticIssued;
16218 }
16219 *CallExpr =
16220 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16221 if (CallExpr->isInvalid()) {
16222 *CallExpr = ExprError();
16223 return FRS_DiagnosticIssued;
16224 }
16225 } else {
16226 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16228 NameInfo, UnresolvedSet<0>());
16229 if (FnR.isInvalid())
16230 return FRS_DiagnosticIssued;
16231 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16232
16233 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16234 CandidateSet, CallExpr);
16235 if (CandidateSet->empty() || CandidateSetError) {
16236 *CallExpr = ExprError();
16237 return FRS_NoViableFunction;
16238 }
16240 OverloadingResult OverloadResult =
16241 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16242
16243 if (OverloadResult == OR_No_Viable_Function) {
16244 *CallExpr = ExprError();
16245 return FRS_NoViableFunction;
16246 }
16247 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16248 Loc, nullptr, CandidateSet, &Best,
16249 OverloadResult,
16250 /*AllowTypoCorrection=*/false);
16251 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16252 *CallExpr = ExprError();
16253 return FRS_DiagnosticIssued;
16254 }
16255 }
16256 return FRS_Success;
16257}
16258
16259
16260/// FixOverloadedFunctionReference - E is an expression that refers to
16261/// a C++ overloaded function (possibly with some parentheses and
16262/// perhaps a '&' around it). We have resolved the overloaded function
16263/// to the function declaration Fn, so patch up the expression E to
16264/// refer (possibly indirectly) to Fn. Returns the new expr.
16266 FunctionDecl *Fn) {
16267 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16268 ExprResult SubExpr =
16269 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16270 if (SubExpr.isInvalid())
16271 return ExprError();
16272 if (SubExpr.get() == PE->getSubExpr())
16273 return PE;
16274
16275 return new (Context)
16276 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16277 }
16278
16279 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16280 ExprResult SubExpr =
16281 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16282 if (SubExpr.isInvalid())
16283 return ExprError();
16284 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16285 SubExpr.get()->getType()) &&
16286 "Implicit cast type cannot be determined from overload");
16287 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16288 if (SubExpr.get() == ICE->getSubExpr())
16289 return ICE;
16290
16291 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16292 SubExpr.get(), nullptr, ICE->getValueKind(),
16293 CurFPFeatureOverrides());
16294 }
16295
16296 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16297 if (!GSE->isResultDependent()) {
16298 ExprResult SubExpr =
16299 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16300 if (SubExpr.isInvalid())
16301 return ExprError();
16302 if (SubExpr.get() == GSE->getResultExpr())
16303 return GSE;
16304
16305 // Replace the resulting type information before rebuilding the generic
16306 // selection expression.
16307 ArrayRef<Expr *> A = GSE->getAssocExprs();
16308 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16309 unsigned ResultIdx = GSE->getResultIndex();
16310 AssocExprs[ResultIdx] = SubExpr.get();
16311
16312 if (GSE->isExprPredicate())
16314 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16315 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16316 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16317 ResultIdx);
16319 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16320 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16321 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16322 ResultIdx);
16323 }
16324 // Rather than fall through to the unreachable, return the original generic
16325 // selection expression.
16326 return GSE;
16327 }
16328
16329 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16330 assert(UnOp->getOpcode() == UO_AddrOf &&
16331 "Can only take the address of an overloaded function");
16332 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16333 if (Method->isStatic()) {
16334 // Do nothing: static member functions aren't any different
16335 // from non-member functions.
16336 } else {
16337 // Fix the subexpression, which really has to be an
16338 // UnresolvedLookupExpr holding an overloaded member function
16339 // or template.
16340 ExprResult SubExpr =
16341 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16342 if (SubExpr.isInvalid())
16343 return ExprError();
16344 if (SubExpr.get() == UnOp->getSubExpr())
16345 return UnOp;
16346
16347 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16348 SubExpr.get(), Method))
16349 return ExprError();
16350
16351 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16352 "fixed to something other than a decl ref");
16353 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16354 "fixed to a member ref with no nested name qualifier");
16355
16356 // We have taken the address of a pointer to member
16357 // function. Perform the computation here so that we get the
16358 // appropriate pointer to member type.
16359 QualType ClassType
16360 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16361 QualType MemPtrType
16362 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16363 // Under the MS ABI, lock down the inheritance model now.
16364 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16365 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16366
16367 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16368 MemPtrType, VK_PRValue, OK_Ordinary,
16369 UnOp->getOperatorLoc(), false,
16370 CurFPFeatureOverrides());
16371 }
16372 }
16373 ExprResult SubExpr =
16374 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16375 if (SubExpr.isInvalid())
16376 return ExprError();
16377 if (SubExpr.get() == UnOp->getSubExpr())
16378 return UnOp;
16379
16380 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16381 SubExpr.get());
16382 }
16383
16384 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16385 // FIXME: avoid copy.
16386 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16387 if (ULE->hasExplicitTemplateArgs()) {
16388 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16389 TemplateArgs = &TemplateArgsBuffer;
16390 }
16391
16392 QualType Type = Fn->getType();
16393 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16394
16395 // FIXME: Duplicated from BuildDeclarationNameExpr.
16396 if (unsigned BID = Fn->getBuiltinID()) {
16397 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16398 Type = Context.BuiltinFnTy;
16399 ValueKind = VK_PRValue;
16400 }
16401 }
16402
16403 DeclRefExpr *DRE = BuildDeclRefExpr(
16404 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16405 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16406 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16407 return DRE;
16408 }
16409
16410 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16411 // FIXME: avoid copy.
16412 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16413 if (MemExpr->hasExplicitTemplateArgs()) {
16414 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16415 TemplateArgs = &TemplateArgsBuffer;
16416 }
16417
16418 Expr *Base;
16419
16420 // If we're filling in a static method where we used to have an
16421 // implicit member access, rewrite to a simple decl ref.
16422 if (MemExpr->isImplicitAccess()) {
16423 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16424 DeclRefExpr *DRE = BuildDeclRefExpr(
16425 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16426 MemExpr->getQualifierLoc(), Found.getDecl(),
16427 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16428 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16429 return DRE;
16430 } else {
16431 SourceLocation Loc = MemExpr->getMemberLoc();
16432 if (MemExpr->getQualifier())
16433 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16434 Base =
16435 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16436 }
16437 } else
16438 Base = MemExpr->getBase();
16439
16440 ExprValueKind valueKind;
16441 QualType type;
16442 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16443 valueKind = VK_LValue;
16444 type = Fn->getType();
16445 } else {
16446 valueKind = VK_PRValue;
16447 type = Context.BoundMemberTy;
16448 }
16449
16450 return BuildMemberExpr(
16451 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16452 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16453 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16454 type, valueKind, OK_Ordinary, TemplateArgs);
16455 }
16456
16457 llvm_unreachable("Invalid reference to overloaded function");
16458}
16459
16461 DeclAccessPair Found,
16462 FunctionDecl *Fn) {
16463 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16464}
16465
16466bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16468 if (!PartialOverloading || !Function)
16469 return true;
16470 if (Function->isVariadic())
16471 return false;
16472 if (const auto *Proto =
16473 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16474 if (Proto->isTemplateVariadic())
16475 return false;
16476 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16477 if (const auto *Proto =
16478 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16479 if (Proto->isTemplateVariadic())
16480 return false;
16481 return true;
16482}
16483
16485 DeclarationName Name,
16486 OverloadCandidateSet &CandidateSet,
16487 FunctionDecl *Fn, MultiExprArg Args,
16488 bool IsMember) {
16489 StringLiteral *Msg = Fn->getDeletedMessage();
16490 CandidateSet.NoteCandidates(
16491 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16492 << IsMember << Name << (Msg != nullptr)
16493 << (Msg ? Msg->getString() : StringRef())
16494 << Range),
16495 *this, OCD_AllCandidates, Args);
16496}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3285
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
LangStandard::Kind Std
#define X(type, name)
Definition: Value.h:143
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static std::string getName(const CallEvent &Call)
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:5704
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static ExprResult 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)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs)
General arity mismatch diagnosis over a candidate in a candidate set.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static ImplicitConversionSequence::CompareKind HLSLCompareFloatingRank(QualType LHS, QualType RHS)
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs)
Additional arity mismatch diagnosis specific to a function overload candidates.
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, PackFold PackFold=PackFold::ParameterToArgument)
Defines the SourceManager interface.
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
__device__ __2f16 b
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:869
iterator end()
Definition: Lookup.h:893
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:885
iterator begin()
Definition: Lookup.h:892
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:890
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:397
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
APFloat & getFloat()
Definition: APValue.h:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2768
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
Definition: ASTContext.h:1100
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1103
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
CanQualType DoubleTy
Definition: ASTContext.h:1103
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1591
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
bool canBindObjCObjectType(QualType To, QualType From)
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType Ibm128Ty
Definition: ASTContext.h:1103
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2272
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1092
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:758
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1279
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1119
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
CanQualType SignedCharTy
Definition: ASTContext.h:1100
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1119
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2064
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2341
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1102
CanQualType BuiltinFnTy
Definition: ASTContext.h:1121
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1288
CanQualType UnknownAnyTy
Definition: ASTContext.h:1120
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1569
CanQualType ShortTy
Definition: ASTContext.h:1100
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
CanQualType Char32Ty
Definition: ASTContext.h:1099
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2152
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1100
CanQualType WCharTy
Definition: ASTContext.h:1094
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1097
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3518
QualType getElementType() const
Definition: Type.h:3530
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7189
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2181
StringRef getOpcodeStr() const
Definition: Expr.h:3905
bool isCompoundAssignmentOp() const
Definition: Expr.h:3983
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4786
Pointer to a block type.
Definition: Type.h:3349
This class is used for builtin types like 'int'.
Definition: Type.h:2981
Kind getKind() const
Definition: Type.h:3023
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2898
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:626
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2455
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2462
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2214
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2576
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2565
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isStatic() const
Definition: DeclCXX.cpp:2186
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:562
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1833
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1494
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3142
static CallExpr * CreateTemporary(void *Mem, Expr *Fn, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, ADLCallKind UsesADL=NotADL)
Create a temporary call expression with no arguments in the memory pointed to by Mem.
Definition: Expr.cpp:1508
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isAtLeastAsQualifiedAs(CanQual< T > Other) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
bool isVolatileQualified() const
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition: Type.h:3086
QualType getElementType() const
Definition: Type.h:3096
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4808
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3556
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1956
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2059
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition: Expr.h:1447
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:239
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:235
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1132
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isInvalidDecl() const
Definition: DeclBase.h:594
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:575
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:570
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:583
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:746
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:731
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:722
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3867
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4072
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
EnumDecl * getDecl() const
Definition: Type.h:5582
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1921
const Expr * getExpr() const
Definition: DeclCXX.h:1906
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2144
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
bool isPRValue() const
Definition: Expr.h:383
bool isXValue() const
Definition: Expr.h:381
static Classification makeSimpleLValue()
Create a simple, modifiably lvalue.
Definition: Expr.h:388
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool isPRValue() const
Definition: Expr.h:278
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3279
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4084
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3923
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3057
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
Represents a function declaration or definition.
Definition: Decl.h:1971
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2599
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
param_iterator param_end()
Definition: Decl.h:2696
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2667
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3536
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
QualType getReturnType() const
Definition: Decl.h:2754
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3576
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4113
unsigned getMinRequiredExplicitArguments() const
Returns the minimum number of non-object arguments needed to call this function.
Definition: Decl.cpp:3740
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
param_iterator param_begin()
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4237
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2502
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3314
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4106
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3735
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2432
bool isDeletedAsWritten() const
Definition: Decl.h:2506
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3306
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3572
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2347
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4395
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4266
bool isConsteval() const
Definition: Decl.h:2444
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3580
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2771
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition: Decl.cpp:3585
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3889
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2595
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
unsigned getNumParams() const
Definition: Type.h:4889
Qualifiers getMethodQuals() const
Definition: Type.h:5030
QualType getParamType(unsigned i) const
Definition: Type.h:4891
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
ArrayRef< QualType > param_types() const
Definition: Type.h:5044
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4367
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4441
bool getNoReturn() const
Definition: Type.h:4415
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
ExtInfo getExtInfo() const
Definition: Type.h:4585
CallingConv getCallConv() const
Definition: Type.h:4584
QualType getReturnType() const
Definition: Type.h:4573
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4597
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition: Expr.cpp:4475
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:594
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:691
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:598
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition: Overload.h:742
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:602
bool hasInitializerListContainerType() const
Definition: Overload.h:724
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:655
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:731
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:606
QualType getInitializerListContainerType() const
Definition: Overload.h:734
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:4847
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4954
unsigned getNumInits() const
Definition: Expr.h:4877
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2466
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4893
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2484
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3424
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
Represents the results of name lookup.
Definition: Lookup.h:46
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
bool isAmbiguous() const
Definition: Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition: Lookup.h:641
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3361
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3269
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3390
Expr * getBase() const
Definition: Expr.h:3249
void setBase(Expr *E)
Definition: Expr.h:3248
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3283
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1798
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3367
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3259
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
QualType getPointeeType() const
Definition: Type.h:3476
const Type * getClass() const
Definition: Type.h:3490
Describes a module or submodule.
Definition: Module.h:105
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6952
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
unsigned param_size() const
Definition: DeclObjC.h:347
bool isVariadic() const
Definition: DeclObjC.h:431
Represents a pointer to an Objective C object.
Definition: Type.h:7008
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7097
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7066
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7020
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7060
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1788
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7072
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition: Overload.h:1137
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1164
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions=std::nullopt)
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1178
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1130
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1001
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:996
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition: Overload.h:1145
SourceLocation getLocation() const
Definition: Overload.h:1128
CandidateSetKind getKind() const
Definition: Overload.h:1129
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2978
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3093
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3129
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3038
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3090
decls_iterator decls_begin() const
Definition: ExprCXX.h:3070
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3081
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3103
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3099
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3149
decls_iterator decls_end() const
Definition: ExprCXX.h:3073
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3087
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2938
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
QualType getPointeeType() const
Definition: Type.h:3149
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4880
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7437
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7448
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3477
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7541
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7485
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7560
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1092
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7531
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7480
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7405
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7391
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7299
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7306
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4295
bool hasAtomic() const
Definition: Type.h:844
bool hasRestrict() const
Definition: Type.h:843
QualifiersAndAtomic withVolatile()
Definition: Type.h:856
QualifiersAndAtomic withAtomic()
Definition: Type.h:863
bool hasVolatile() const
Definition: Type.h:841
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
GC getObjCGCAttr() const
Definition: Type.h:505
bool hasOnlyConst() const
Definition: Type.h:444
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
void removeObjCLifetime()
Definition: Type.h:537
bool hasConst() const
Definition: Type.h:443
void addRestrict()
Definition: Type.h:466
bool hasRestrict() const
Definition: Type.h:463
void removeObjCGCAttr()
Definition: Type.h:509
void removeUnaligned()
Definition: Type.h:501
void removeAddressSpace()
Definition: Type.h:582
void addConst()
Definition: Type.h:446
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
bool hasVolatile() const
Definition: Type.h:453
bool hasObjCGCAttr() const
Definition: Type.h:504
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
std::string getAsString() const
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:754
void addVolatile()
Definition: Type.h:456
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3442
Represents a struct/union/class.
Definition: Decl.h:4168
field_range fields() const
Definition: Decl.h:4374
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3380
QualType getPointeeType() const
Definition: Type.h:3398
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition: SemaCUDA.h:176
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:372
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:314
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition: SemaCUDA.cpp:320
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:227
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Definition: SemaObjC.cpp:1314
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:7976
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4642
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4671
RAII class to control scope of DeferDiags.
Definition: Sema.h:7827
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9409
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9439
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2478
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:7843
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7287
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:7299
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7295
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:168
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
SemaCUDA & CUDA()
Definition: Sema.h:993
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition: Sema.h:8059
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8062
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8068
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8066
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1422
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1499
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:848
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition: Sema.h:1003
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
ASTContext & getASTContext() const
Definition: Sema.h:517
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:645
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ForRangeStatus
Definition: Sema.h:8276
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AllowedExplicit
Definition: Sema.h:7869
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:765
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9167
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:65
const LangOptions & getLangOpts() const
Definition: Sema.h:510
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6464
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
const LangOptions & LangOpts
Definition: Sema.h:846
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:6732
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9682
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:652
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3232
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11608
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8545
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6018
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6057
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6036
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6020
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6053
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19837
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20806
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10401
AssignmentAction
Definition: Sema.h:5157
@ AA_Converting
Definition: Sema.h:5161
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5526
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7599
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7645
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:228
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11583
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3335
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
CCEKind
Contexts in which a converted constant expression is required.
Definition: Sema.h:7946
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:7951
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:7952
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:7950
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:7949
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
OverloadKind
Definition: Sema.h:7845
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:851
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2416
DiagnosticsEngine & Diags
Definition: Sema.h:850
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10684
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20999
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:10669
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6650
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:267
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:357
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:355
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:327
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
QualType getFromType() const
Definition: Overload.h:370
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:272
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:332
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:294
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:354
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:304
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:337
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:288
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:299
ImplicitConversionKind Element
Element - Between the second and third conversion a vector or matrix element conversion may occur.
Definition: Overload.h:284
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition: Overload.h:347
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition: Overload.h:319
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:323
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:314
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
void setAllToTypes(QualType T)
Definition: Overload.h:364
QualType getToType(unsigned Idx) const
Definition: Overload.h:374
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
StringRef getString() const
Definition: Expr.h:1850
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:655
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:708
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:693
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:244
Represents a template argument.
Definition: TemplateBase.h:61
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
Definition: TemplateName.h:219
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6089
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3414
The base class of the type hierarchy.
Definition: Type.h:1813
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2400
bool isBlockPointerType() const
Definition: Type.h:7620
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
bool isObjCBuiltinType() const
Definition: Type.h:7795
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2156
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1888
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:730
bool isIncompleteArrayType() const
Definition: Type.h:7686
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2135
bool isFloat16Type() const
Definition: Type.h:7914
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:667
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2060
bool isRValueReferenceType() const
Definition: Type.h:7632
bool isConstantArrayType() const
Definition: Type.h:7682
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8063
bool isArrayType() const
Definition: Type.h:7678
bool isCharType() const
Definition: Type.cpp:2078
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:7970
bool isArithmeticType() const
Definition: Type.cpp:2270
bool isPointerType() const
Definition: Type.h:7612
bool isArrayParameterType() const
Definition: Type.h:7694
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2469
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2047
bool isObjCQualifiedIdType() const
Definition: Type.h:7765
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
bool isExtVectorType() const
Definition: Type.h:7722
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2114
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7752
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2661
bool isLValueReferenceType() const
Definition: Type.h:7628
bool isBitIntType() const
Definition: Type.h:7840
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2327
bool isAnyComplexType() const
Definition: Type.h:7714
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7958
bool isHalfType() const
Definition: Type.h:7909
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7887
bool isQueueT() const
Definition: Type.h:7821
bool isMemberPointerType() const
Definition: Type.h:7660
bool isObjCIdType() const
Definition: Type.h:7777
bool isMatrixType() const
Definition: Type.h:7732
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8039
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2405
bool isEventT() const
Definition: Type.h:7813
bool isBFloat16Type() const
Definition: Type.h:7926
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isFunctionType() const
Definition: Type.h:7608
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool isVectorType() const
Definition: Type.h:7718
bool isObjCClassType() const
Definition: Type.h:7783
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2255
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2483
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2185
bool isAnyPointerType() const
Definition: Type.h:7616
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isSamplerT() const
Definition: Type.h:7809
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isNullPtrType() const
Definition: Type.h:7938
bool isRecordType() const
Definition: Type.h:7706
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1429
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4843
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1405
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3197
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:3273
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3265
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3936
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4044
QualType getBaseType() const
Definition: ExprCXX.h:4018
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4028
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4009
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4054
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4048
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
unsigned size() const
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition: ExprCXX.h:637
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition: ExprCXX.cpp:900
QualType getType() const
Definition: Decl.h:717
Represents a GCC generic vector type.
Definition: Type.h:3969
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:33
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:217
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
CUDAFunctionTarget
Definition: Cuda.h:132
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:774
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:802
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:811
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:794
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:798
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition: Overload.h:839
@ ovl_fail_too_few_arguments
Definition: Overload.h:776
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:818
@ ovl_fail_too_many_arguments
Definition: Overload.h:775
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:826
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:835
@ ovl_fail_bad_conversion
Definition: Overload.h:777
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:807
@ ovl_fail_bad_deduction
Definition: Overload.h:778
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:822
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:831
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:815
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:783
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1762
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1765
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:212
@ ICR_Conversion
Conversion.
Definition: Overload.h:220
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:229
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:232
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:223
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:226
@ ICR_Promotion
Promotion.
Definition: Overload.h:217
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:214
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:236
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition: Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition: Overload.h:84
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition: Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition: Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition: Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition: Overload.h:94
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition: Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition: Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition: Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition: Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition: Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition: Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition: Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition: Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition: Overload.h:205
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition: Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition: Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition: Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition: Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition: Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition: Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:425
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
const FunctionProtoType * T
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition: Overload.h:243
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1241
@ None
The alignment was not explicit in code.
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:443
ConversionSet::const_iterator const_iterator
Definition: Overload.h:479
ConversionSet & conversions()
Definition: Overload.h:462
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:470
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:445
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:528
QualType getFromType() const
Definition: Overload.h:527
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
std::optional< unsigned > getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Extra information about a function prototype.
Definition: Type.h:4735
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4743
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1006
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition: Overload.h:1019
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1055
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1028
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1045
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:848
CallExpr::ADLCallKind IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:903
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:945
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:933
bool IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:891
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:862
bool IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:900
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:858
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:853
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:877
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:907
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:874
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:924
unsigned getNumParams() const
Definition: Overload.h:958
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:915
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:911
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:871
DeductionFailureInfo DeductionFailure
Definition: Overload.h:918
bool Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:886
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:866
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:929
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9719
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:9807
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9839
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8076
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6303
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition: Overload.h:398
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:410
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:432
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:423
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:427
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:418
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:437
void dump() const
dump - Print this user-defined conversion sequence to standard error.