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/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/SmallVector.h"
44#include "llvm/Support/Casting.h"
45#include <algorithm>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
174 static const char *const Name[] = {
175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
179 "Function pointer conversion",
180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
183 "Complex promotion",
184 "Integral conversion",
185 "Floating conversion",
186 "Complex conversion",
187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
190 "Boolean conversion",
191 "Compatible-types conversion",
192 "Derived-to-base conversion",
193 "Vector conversion",
194 "SVE Vector conversion",
195 "RVV Vector conversion",
196 "Vector splat",
197 "Complex-real conversion",
198 "Block Pointer conversion",
199 "Transparent Union Conversion",
200 "Writeback conversion",
201 "OpenCL Zero Event Conversion",
202 "OpenCL Zero Queue Conversion",
203 "C specific type conversion",
204 "Incompatible pointer conversion",
205 "Fixed point conversion",
206 "HLSL vector truncation",
207 "Non-decaying array conversion",
208 };
209 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
210 return Name[Kind];
211}
212
213/// StandardConversionSequence - Set the standard conversion
214/// sequence to the identity conversion.
222 ReferenceBinding = false;
223 DirectBinding = false;
224 IsLvalueReference = true;
225 BindsToFunctionLvalue = false;
226 BindsToRvalue = false;
229 CopyConstructor = nullptr;
230}
231
232/// getRank - Retrieve the rank of this standard conversion sequence
233/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
234/// implicit conversions.
237 if (GetConversionRank(First) > Rank)
238 Rank = GetConversionRank(First);
239 if (GetConversionRank(Second) > Rank)
241 if (GetConversionRank(Element) > Rank)
243 if (GetConversionRank(Third) > Rank)
244 Rank = GetConversionRank(Third);
245 return Rank;
246}
247
248/// isPointerConversionToBool - Determines whether this conversion is
249/// a conversion of a pointer or pointer-to-member to bool. This is
250/// used as part of the ranking of standard conversion sequences
251/// (C++ 13.3.3.2p4).
253 // Note that FromType has not necessarily been transformed by the
254 // array-to-pointer or function-to-pointer implicit conversions, so
255 // check for their presence as well as checking whether FromType is
256 // a pointer.
257 if (getToType(1)->isBooleanType() &&
258 (getFromType()->isPointerType() ||
259 getFromType()->isMemberPointerType() ||
260 getFromType()->isObjCObjectPointerType() ||
261 getFromType()->isBlockPointerType() ||
263 return true;
264
265 return false;
266}
267
268/// isPointerConversionToVoidPointer - Determines whether this
269/// conversion is a conversion of a pointer to a void pointer. This is
270/// used as part of the ranking of standard conversion sequences (C++
271/// 13.3.3.2p4).
272bool
275 QualType FromType = getFromType();
276 QualType ToType = getToType(1);
277
278 // Note that FromType has not necessarily been transformed by the
279 // array-to-pointer implicit conversion, so check for its presence
280 // and redo the conversion to get a pointer.
282 FromType = Context.getArrayDecayedType(FromType);
283
284 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
285 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
286 return ToPtrType->getPointeeType()->isVoidType();
287
288 return false;
289}
290
291/// Skip any implicit casts which could be either part of a narrowing conversion
292/// or after one in an implicit conversion.
294 const Expr *Converted) {
295 // We can have cleanups wrapping the converted expression; these need to be
296 // preserved so that destructors run if necessary.
297 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
298 Expr *Inner =
299 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
300 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
301 EWC->getObjects());
302 }
303
304 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
305 switch (ICE->getCastKind()) {
306 case CK_NoOp:
307 case CK_IntegralCast:
308 case CK_IntegralToBoolean:
309 case CK_IntegralToFloating:
310 case CK_BooleanToSignedIntegral:
311 case CK_FloatingToIntegral:
312 case CK_FloatingToBoolean:
313 case CK_FloatingCast:
314 Converted = ICE->getSubExpr();
315 continue;
316
317 default:
318 return Converted;
319 }
320 }
321
322 return Converted;
323}
324
325/// Check if this standard conversion sequence represents a narrowing
326/// conversion, according to C++11 [dcl.init.list]p7.
327///
328/// \param Ctx The AST context.
329/// \param Converted The result of applying this standard conversion sequence.
330/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
331/// value of the expression prior to the narrowing conversion.
332/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
333/// type of the expression prior to the narrowing conversion.
334/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
335/// from floating point types to integral types should be ignored.
337 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
338 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
339 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
340 "narrowing check outside C++");
341
342 // C++11 [dcl.init.list]p7:
343 // A narrowing conversion is an implicit conversion ...
344 QualType FromType = getToType(0);
345 QualType ToType = getToType(1);
346
347 // A conversion to an enumeration type is narrowing if the conversion to
348 // the underlying type is narrowing. This only arises for expressions of
349 // the form 'Enum{init}'.
350 if (auto *ET = ToType->getAs<EnumType>())
351 ToType = ET->getDecl()->getIntegerType();
352
353 switch (Second) {
354 // 'bool' is an integral type; dispatch to the right place to handle it.
356 if (FromType->isRealFloatingType())
357 goto FloatingIntegralConversion;
359 goto IntegralConversion;
360 // -- from a pointer type or pointer-to-member type to bool, or
361 return NK_Type_Narrowing;
362
363 // -- from a floating-point type to an integer type, or
364 //
365 // -- from an integer type or unscoped enumeration type to a floating-point
366 // type, except where the source is a constant expression and the actual
367 // value after conversion will fit into the target type and will produce
368 // the original value when converted back to the original type, or
370 FloatingIntegralConversion:
371 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
372 return NK_Type_Narrowing;
373 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
374 ToType->isRealFloatingType()) {
375 if (IgnoreFloatToIntegralConversion)
376 return NK_Not_Narrowing;
377 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
378 assert(Initializer && "Unknown conversion expression");
379
380 // If it's value-dependent, we can't tell whether it's narrowing.
381 if (Initializer->isValueDependent())
383
384 if (std::optional<llvm::APSInt> IntConstantValue =
385 Initializer->getIntegerConstantExpr(Ctx)) {
386 // Convert the integer to the floating type.
387 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
388 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
389 llvm::APFloat::rmNearestTiesToEven);
390 // And back.
391 llvm::APSInt ConvertedValue = *IntConstantValue;
392 bool ignored;
393 Result.convertToInteger(ConvertedValue,
394 llvm::APFloat::rmTowardZero, &ignored);
395 // If the resulting value is different, this was a narrowing conversion.
396 if (*IntConstantValue != ConvertedValue) {
397 ConstantValue = APValue(*IntConstantValue);
398 ConstantType = Initializer->getType();
400 }
401 } else {
402 // Variables are always narrowings.
404 }
405 }
406 return NK_Not_Narrowing;
407
408 // -- from long double to double or float, or from double to float, except
409 // where the source is a constant expression and the actual value after
410 // conversion is within the range of values that can be represented (even
411 // if it cannot be represented exactly), or
413 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
414 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
415 // FromType is larger than ToType.
416 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
421
423 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
424 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
425 // Constant!
426 if (Ctx.getLangOpts().C23)
427 ConstantValue = R.Val;
428 assert(ConstantValue.isFloat());
429 llvm::APFloat FloatVal = ConstantValue.getFloat();
430 // Convert the source value into the target type.
431 bool ignored;
432 llvm::APFloat Converted = FloatVal;
433 llvm::APFloat::opStatus ConvertStatus =
434 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
435 llvm::APFloat::rmNearestTiesToEven, &ignored);
436 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
437 llvm::APFloat::rmNearestTiesToEven, &ignored);
438 if (Ctx.getLangOpts().C23) {
439 if (FloatVal.isNaN() && Converted.isNaN() &&
440 !FloatVal.isSignaling() && !Converted.isSignaling()) {
441 // Quiet NaNs are considered the same value, regardless of
442 // payloads.
443 return NK_Not_Narrowing;
444 }
445 // For normal values, check exact equality.
446 if (!Converted.bitwiseIsEqual(FloatVal)) {
447 ConstantType = Initializer->getType();
449 }
450 } else {
451 // If there was no overflow, the source value is within the range of
452 // values that can be represented.
453 if (ConvertStatus & llvm::APFloat::opOverflow) {
454 ConstantType = Initializer->getType();
456 }
457 }
458 } else {
460 }
461 }
462 return NK_Not_Narrowing;
463
464 // -- from an integer type or unscoped enumeration type to an integer type
465 // that cannot represent all the values of the original type, except where
466 // the source is a constant expression and the actual value after
467 // conversion will fit into the target type and will produce the original
468 // value when converted back to the original type.
470 IntegralConversion: {
471 assert(FromType->isIntegralOrUnscopedEnumerationType());
472 assert(ToType->isIntegralOrUnscopedEnumerationType());
473 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
474 const unsigned FromWidth = Ctx.getIntWidth(FromType);
475 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
476 const unsigned ToWidth = Ctx.getIntWidth(ToType);
477
478 if (FromWidth > ToWidth ||
479 (FromWidth == ToWidth && FromSigned != ToSigned) ||
480 (FromSigned && !ToSigned)) {
481 // Not all values of FromType can be represented in ToType.
482 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
483
484 // If it's value-dependent, we can't tell whether it's narrowing.
485 if (Initializer->isValueDependent())
487
488 std::optional<llvm::APSInt> OptInitializerValue;
489 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
490 // Such conversions on variables are always narrowing.
492 }
493 llvm::APSInt &InitializerValue = *OptInitializerValue;
494 bool Narrowing = false;
495 if (FromWidth < ToWidth) {
496 // Negative -> unsigned is narrowing. Otherwise, more bits is never
497 // narrowing.
498 if (InitializerValue.isSigned() && InitializerValue.isNegative())
499 Narrowing = true;
500 } else {
501 // Add a bit to the InitializerValue so we don't have to worry about
502 // signed vs. unsigned comparisons.
503 InitializerValue = InitializerValue.extend(
504 InitializerValue.getBitWidth() + 1);
505 // Convert the initializer to and from the target width and signed-ness.
506 llvm::APSInt ConvertedValue = InitializerValue;
507 ConvertedValue = ConvertedValue.trunc(ToWidth);
508 ConvertedValue.setIsSigned(ToSigned);
509 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
510 ConvertedValue.setIsSigned(InitializerValue.isSigned());
511 // If the result is different, this was a narrowing conversion.
512 if (ConvertedValue != InitializerValue)
513 Narrowing = true;
514 }
515 if (Narrowing) {
516 ConstantType = Initializer->getType();
517 ConstantValue = APValue(InitializerValue);
519 }
520 }
521 return NK_Not_Narrowing;
522 }
523 case ICK_Complex_Real:
524 if (FromType->isComplexType() && !ToType->isComplexType())
525 return NK_Type_Narrowing;
526 return NK_Not_Narrowing;
527
529 if (Ctx.getLangOpts().C23) {
530 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
532 if (Initializer->EvaluateAsRValue(R, Ctx)) {
533 ConstantValue = R.Val;
534 assert(ConstantValue.isFloat());
535 llvm::APFloat FloatVal = ConstantValue.getFloat();
536 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
537 // value, the unqualified versions of the type of the initializer and
538 // the corresponding real type of the object declared shall be
539 // compatible.
540 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
541 ConstantType = Initializer->getType();
543 }
544 }
545 }
546 return NK_Not_Narrowing;
547 default:
548 // Other kinds of conversions are not narrowings.
549 return NK_Not_Narrowing;
550 }
551}
552
553/// dump - Print this standard conversion sequence to standard
554/// error. Useful for debugging overloading issues.
555LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
556 raw_ostream &OS = llvm::errs();
557 bool PrintedSomething = false;
558 if (First != ICK_Identity) {
560 PrintedSomething = true;
561 }
562
563 if (Second != ICK_Identity) {
564 if (PrintedSomething) {
565 OS << " -> ";
566 }
568
569 if (CopyConstructor) {
570 OS << " (by copy constructor)";
571 } else if (DirectBinding) {
572 OS << " (direct reference binding)";
573 } else if (ReferenceBinding) {
574 OS << " (reference binding)";
575 }
576 PrintedSomething = true;
577 }
578
579 if (Third != ICK_Identity) {
580 if (PrintedSomething) {
581 OS << " -> ";
582 }
584 PrintedSomething = true;
585 }
586
587 if (!PrintedSomething) {
588 OS << "No conversions required";
589 }
590}
591
592/// dump - Print this user-defined conversion sequence to standard
593/// error. Useful for debugging overloading issues.
595 raw_ostream &OS = llvm::errs();
596 if (Before.First || Before.Second || Before.Third) {
597 Before.dump();
598 OS << " -> ";
599 }
601 OS << '\'' << *ConversionFunction << '\'';
602 else
603 OS << "aggregate initialization";
604 if (After.First || After.Second || After.Third) {
605 OS << " -> ";
606 After.dump();
607 }
608}
609
610/// dump - Print this implicit conversion sequence to standard
611/// error. Useful for debugging overloading issues.
613 raw_ostream &OS = llvm::errs();
615 OS << "Worst list element conversion: ";
616 switch (ConversionKind) {
618 OS << "Standard conversion: ";
619 Standard.dump();
620 break;
622 OS << "User-defined conversion: ";
624 break;
626 OS << "Ellipsis conversion";
627 break;
629 OS << "Ambiguous conversion";
630 break;
631 case BadConversion:
632 OS << "Bad conversion";
633 break;
634 }
635
636 OS << "\n";
637}
638
640 new (&conversions()) ConversionSet();
641}
642
644 conversions().~ConversionSet();
645}
646
647void
652}
653
654namespace {
655 // Structure used by DeductionFailureInfo to store
656 // template argument information.
657 struct DFIArguments {
658 TemplateArgument FirstArg;
659 TemplateArgument SecondArg;
660 };
661 // Structure used by DeductionFailureInfo to store
662 // template parameter and template argument information.
663 struct DFIParamWithArguments : DFIArguments {
664 TemplateParameter Param;
665 };
666 // Structure used by DeductionFailureInfo to store template argument
667 // information and the index of the problematic call argument.
668 struct DFIDeducedMismatchArgs : DFIArguments {
669 TemplateArgumentList *TemplateArgs;
670 unsigned CallArgIndex;
671 };
672 // Structure used by DeductionFailureInfo to store information about
673 // unsatisfied constraints.
674 struct CNSInfo {
675 TemplateArgumentList *TemplateArgs;
676 ConstraintSatisfaction Satisfaction;
677 };
678}
679
680/// Convert from Sema's representation of template deduction information
681/// to the form used in overload-candidate information.
685 TemplateDeductionInfo &Info) {
687 Result.Result = static_cast<unsigned>(TDK);
688 Result.HasDiagnostic = false;
689 switch (TDK) {
696 Result.Data = nullptr;
697 break;
698
701 Result.Data = Info.Param.getOpaqueValue();
702 break;
703
706 // FIXME: Should allocate from normal heap so that we can free this later.
707 auto *Saved = new (Context) DFIDeducedMismatchArgs;
708 Saved->FirstArg = Info.FirstArg;
709 Saved->SecondArg = Info.SecondArg;
710 Saved->TemplateArgs = Info.takeSugared();
711 Saved->CallArgIndex = Info.CallArgIndex;
712 Result.Data = Saved;
713 break;
714 }
715
717 // FIXME: Should allocate from normal heap so that we can free this later.
718 DFIArguments *Saved = new (Context) DFIArguments;
719 Saved->FirstArg = Info.FirstArg;
720 Saved->SecondArg = Info.SecondArg;
721 Result.Data = Saved;
722 break;
723 }
724
726 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
729 // FIXME: Should allocate from normal heap so that we can free this later.
730 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
731 Saved->Param = Info.Param;
732 Saved->FirstArg = Info.FirstArg;
733 Saved->SecondArg = Info.SecondArg;
734 Result.Data = Saved;
735 break;
736 }
737
739 Result.Data = Info.takeSugared();
740 if (Info.hasSFINAEDiagnostic()) {
744 Result.HasDiagnostic = true;
745 }
746 break;
747
749 CNSInfo *Saved = new (Context) CNSInfo;
750 Saved->TemplateArgs = Info.takeSugared();
751 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
752 Result.Data = Saved;
753 break;
754 }
755
759 llvm_unreachable("not a deduction failure");
760 }
761
762 return Result;
763}
764
766 switch (static_cast<TemplateDeductionResult>(Result)) {
776 break;
777
784 // FIXME: Destroy the data?
785 Data = nullptr;
786 break;
787
789 // FIXME: Destroy the template argument list?
790 Data = nullptr;
792 Diag->~PartialDiagnosticAt();
793 HasDiagnostic = false;
794 }
795 break;
796
798 // FIXME: Destroy the template argument list?
799 Data = nullptr;
801 Diag->~PartialDiagnosticAt();
802 HasDiagnostic = false;
803 }
804 break;
805
806 // Unhandled
809 break;
810 }
811}
812
814 if (HasDiagnostic)
815 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
816 return nullptr;
817}
818
820 switch (static_cast<TemplateDeductionResult>(Result)) {
833 return TemplateParameter();
834
837 return TemplateParameter::getFromOpaqueValue(Data);
838
842 return static_cast<DFIParamWithArguments*>(Data)->Param;
843
844 // Unhandled
847 break;
848 }
849
850 return TemplateParameter();
851}
852
854 switch (static_cast<TemplateDeductionResult>(Result)) {
868 return nullptr;
869
872 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
873
875 return static_cast<TemplateArgumentList*>(Data);
876
878 return static_cast<CNSInfo*>(Data)->TemplateArgs;
879
880 // Unhandled
883 break;
884 }
885
886 return nullptr;
887}
888
890 switch (static_cast<TemplateDeductionResult>(Result)) {
902 return nullptr;
903
910 return &static_cast<DFIArguments*>(Data)->FirstArg;
911
912 // Unhandled
915 break;
916 }
917
918 return nullptr;
919}
920
922 switch (static_cast<TemplateDeductionResult>(Result)) {
935 return nullptr;
936
942 return &static_cast<DFIArguments*>(Data)->SecondArg;
943
944 // Unhandled
947 break;
948 }
949
950 return nullptr;
951}
952
953std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
954 switch (static_cast<TemplateDeductionResult>(Result)) {
957 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
958
959 default:
960 return std::nullopt;
961 }
962}
963
965 const FunctionDecl *Y) {
966 if (!X || !Y)
967 return false;
968 if (X->getNumParams() != Y->getNumParams())
969 return false;
970 // FIXME: when do rewritten comparison operators
971 // with explicit object parameters correspond?
972 // https://cplusplus.github.io/CWG/issues/2797.html
973 for (unsigned I = 0; I < X->getNumParams(); ++I)
974 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
975 Y->getParamDecl(I)->getType()))
976 return false;
977 if (auto *FTX = X->getDescribedFunctionTemplate()) {
978 auto *FTY = Y->getDescribedFunctionTemplate();
979 if (!FTY)
980 return false;
981 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
982 FTY->getTemplateParameters()))
983 return false;
984 }
985 return true;
986}
987
989 Expr *FirstOperand, FunctionDecl *EqFD) {
990 assert(EqFD->getOverloadedOperator() ==
991 OverloadedOperatorKind::OO_EqualEqual);
992 // C++2a [over.match.oper]p4:
993 // A non-template function or function template F named operator== is a
994 // rewrite target with first operand o unless a search for the name operator!=
995 // in the scope S from the instantiation context of the operator expression
996 // finds a function or function template that would correspond
997 // ([basic.scope.scope]) to F if its name were operator==, where S is the
998 // scope of the class type of o if F is a class member, and the namespace
999 // scope of which F is a member otherwise. A function template specialization
1000 // named operator== is a rewrite target if its function template is a rewrite
1001 // target.
1003 OverloadedOperatorKind::OO_ExclaimEqual);
1004 if (isa<CXXMethodDecl>(EqFD)) {
1005 // If F is a class member, search scope is class type of first operand.
1006 QualType RHS = FirstOperand->getType();
1007 auto *RHSRec = RHS->getAs<RecordType>();
1008 if (!RHSRec)
1009 return true;
1010 LookupResult Members(S, NotEqOp, OpLoc,
1012 S.LookupQualifiedName(Members, RHSRec->getDecl());
1013 Members.suppressAccessDiagnostics();
1014 for (NamedDecl *Op : Members)
1015 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1016 return false;
1017 return true;
1018 }
1019 // Otherwise the search scope is the namespace scope of which F is a member.
1020 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1021 auto *NotEqFD = Op->getAsFunction();
1022 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1023 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1024 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1026 cast<Decl>(Op->getLexicalDeclContext())))
1027 return false;
1028 }
1029 return true;
1030}
1031
1035 return false;
1036 return Op == OO_EqualEqual || Op == OO_Spaceship;
1037}
1038
1040 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1041 auto Op = FD->getOverloadedOperator();
1042 if (!allowsReversed(Op))
1043 return false;
1044 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1045 assert(OriginalArgs.size() == 2);
1047 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1048 return false;
1049 }
1050 // Don't bother adding a reversed candidate that can never be a better
1051 // match than the non-reversed version.
1052 return FD->getNumNonObjectParams() != 2 ||
1054 FD->getParamDecl(1)->getType()) ||
1055 FD->hasAttr<EnableIfAttr>();
1056}
1057
1058void OverloadCandidateSet::destroyCandidates() {
1059 for (iterator i = begin(), e = end(); i != e; ++i) {
1060 for (auto &C : i->Conversions)
1061 C.~ImplicitConversionSequence();
1062 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1063 i->DeductionFailure.Destroy();
1064 }
1065}
1066
1068 destroyCandidates();
1069 SlabAllocator.Reset();
1070 NumInlineBytesUsed = 0;
1071 Candidates.clear();
1072 Functions.clear();
1073 Kind = CSK;
1074}
1075
1076namespace {
1077 class UnbridgedCastsSet {
1078 struct Entry {
1079 Expr **Addr;
1080 Expr *Saved;
1081 };
1082 SmallVector<Entry, 2> Entries;
1083
1084 public:
1085 void save(Sema &S, Expr *&E) {
1086 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1087 Entry entry = { &E, E };
1088 Entries.push_back(entry);
1089 E = S.stripARCUnbridgedCast(E);
1090 }
1091
1092 void restore() {
1094 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1095 *i->Addr = i->Saved;
1096 }
1097 };
1098}
1099
1100/// checkPlaceholderForOverload - Do any interesting placeholder-like
1101/// preprocessing on the given expression.
1102///
1103/// \param unbridgedCasts a collection to which to add unbridged casts;
1104/// without this, they will be immediately diagnosed as errors
1105///
1106/// Return true on unrecoverable error.
1107static bool
1109 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1110 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1111 // We can't handle overloaded expressions here because overload
1112 // resolution might reasonably tweak them.
1113 if (placeholder->getKind() == BuiltinType::Overload) return false;
1114
1115 // If the context potentially accepts unbridged ARC casts, strip
1116 // the unbridged cast and add it to the collection for later restoration.
1117 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1118 unbridgedCasts) {
1119 unbridgedCasts->save(S, E);
1120 return false;
1121 }
1122
1123 // Go ahead and check everything else.
1124 ExprResult result = S.CheckPlaceholderExpr(E);
1125 if (result.isInvalid())
1126 return true;
1127
1128 E = result.get();
1129 return false;
1130 }
1131
1132 // Nothing to do.
1133 return false;
1134}
1135
1136/// checkArgPlaceholdersForOverload - Check a set of call operands for
1137/// placeholders.
1139 UnbridgedCastsSet &unbridged) {
1140 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1141 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1142 return true;
1143
1144 return false;
1145}
1146
1147/// Determine whether the given New declaration is an overload of the
1148/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1149/// New and Old cannot be overloaded, e.g., if New has the same signature as
1150/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1151/// functions (or function templates) at all. When it does return Ovl_Match or
1152/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1153/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1154/// declaration.
1155///
1156/// Example: Given the following input:
1157///
1158/// void f(int, float); // #1
1159/// void f(int, int); // #2
1160/// int f(int, int); // #3
1161///
1162/// When we process #1, there is no previous declaration of "f", so IsOverload
1163/// will not be used.
1164///
1165/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1166/// the parameter types, we see that #1 and #2 are overloaded (since they have
1167/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1168/// unchanged.
1169///
1170/// When we process #3, Old is an overload set containing #1 and #2. We compare
1171/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1172/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1173/// functions are not part of the signature), IsOverload returns Ovl_Match and
1174/// MatchedDecl will be set to point to the FunctionDecl for #2.
1175///
1176/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1177/// by a using declaration. The rules for whether to hide shadow declarations
1178/// ignore some properties which otherwise figure into a function template's
1179/// signature.
1182 NamedDecl *&Match, bool NewIsUsingDecl) {
1183 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1184 I != E; ++I) {
1185 NamedDecl *OldD = *I;
1186
1187 bool OldIsUsingDecl = false;
1188 if (isa<UsingShadowDecl>(OldD)) {
1189 OldIsUsingDecl = true;
1190
1191 // We can always introduce two using declarations into the same
1192 // context, even if they have identical signatures.
1193 if (NewIsUsingDecl) continue;
1194
1195 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1196 }
1197
1198 // A using-declaration does not conflict with another declaration
1199 // if one of them is hidden.
1200 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1201 continue;
1202
1203 // If either declaration was introduced by a using declaration,
1204 // we'll need to use slightly different rules for matching.
1205 // Essentially, these rules are the normal rules, except that
1206 // function templates hide function templates with different
1207 // return types or template parameter lists.
1208 bool UseMemberUsingDeclRules =
1209 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1210 !New->getFriendObjectKind();
1211
1212 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1213 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1214 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1215 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1216 continue;
1217 }
1218
1219 if (!isa<FunctionTemplateDecl>(OldD) &&
1220 !shouldLinkPossiblyHiddenDecl(*I, New))
1221 continue;
1222
1223 Match = *I;
1224 return Ovl_Match;
1225 }
1226
1227 // Builtins that have custom typechecking or have a reference should
1228 // not be overloadable or redeclarable.
1229 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1230 Match = *I;
1231 return Ovl_NonFunction;
1232 }
1233 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1234 // We can overload with these, which can show up when doing
1235 // redeclaration checks for UsingDecls.
1236 assert(Old.getLookupKind() == LookupUsingDeclName);
1237 } else if (isa<TagDecl>(OldD)) {
1238 // We can always overload with tags by hiding them.
1239 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1240 // Optimistically assume that an unresolved using decl will
1241 // overload; if it doesn't, we'll have to diagnose during
1242 // template instantiation.
1243 //
1244 // Exception: if the scope is dependent and this is not a class
1245 // member, the using declaration can only introduce an enumerator.
1246 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1247 Match = *I;
1248 return Ovl_NonFunction;
1249 }
1250 } else {
1251 // (C++ 13p1):
1252 // Only function declarations can be overloaded; object and type
1253 // declarations cannot be overloaded.
1254 Match = *I;
1255 return Ovl_NonFunction;
1256 }
1257 }
1258
1259 // C++ [temp.friend]p1:
1260 // For a friend function declaration that is not a template declaration:
1261 // -- if the name of the friend is a qualified or unqualified template-id,
1262 // [...], otherwise
1263 // -- if the name of the friend is a qualified-id and a matching
1264 // non-template function is found in the specified class or namespace,
1265 // the friend declaration refers to that function, otherwise,
1266 // -- if the name of the friend is a qualified-id and a matching function
1267 // template is found in the specified class or namespace, the friend
1268 // declaration refers to the deduced specialization of that function
1269 // template, otherwise
1270 // -- the name shall be an unqualified-id [...]
1271 // If we get here for a qualified friend declaration, we've just reached the
1272 // third bullet. If the type of the friend is dependent, skip this lookup
1273 // until instantiation.
1274 if (New->getFriendObjectKind() && New->getQualifier() &&
1277 !New->getType()->isDependentType()) {
1278 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1279 TemplateSpecResult.addAllDecls(Old);
1280 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1281 /*QualifiedFriend*/true)) {
1282 New->setInvalidDecl();
1283 return Ovl_Overload;
1284 }
1285
1286 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1287 return Ovl_Match;
1288 }
1289
1290 return Ovl_Overload;
1291}
1292
1293static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1294 FunctionDecl *Old,
1295 bool UseMemberUsingDeclRules,
1296 bool ConsiderCudaAttrs,
1297 bool UseOverrideRules = false) {
1298 // C++ [basic.start.main]p2: This function shall not be overloaded.
1299 if (New->isMain())
1300 return false;
1301
1302 // MSVCRT user defined entry points cannot be overloaded.
1303 if (New->isMSVCRTEntryPoint())
1304 return false;
1305
1308
1309 // C++ [temp.fct]p2:
1310 // A function template can be overloaded with other function templates
1311 // and with normal (non-template) functions.
1312 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1313 return true;
1314
1315 // Is the function New an overload of the function Old?
1316 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1317 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1318
1319 // Compare the signatures (C++ 1.3.10) of the two functions to
1320 // determine whether they are overloads. If we find any mismatch
1321 // in the signature, they are overloads.
1322
1323 // If either of these functions is a K&R-style function (no
1324 // prototype), then we consider them to have matching signatures.
1325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1327 return false;
1328
1329 const auto *OldType = cast<FunctionProtoType>(OldQType);
1330 const auto *NewType = cast<FunctionProtoType>(NewQType);
1331
1332 // The signature of a function includes the types of its
1333 // parameters (C++ 1.3.10), which includes the presence or absence
1334 // of the ellipsis; see C++ DR 357).
1335 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1336 return true;
1337
1338 // For member-like friends, the enclosing class is part of the signature.
1339 if ((New->isMemberLikeConstrainedFriend() ||
1342 return true;
1343
1344 // Compare the parameter lists.
1345 // This can only be done once we have establish that friend functions
1346 // inhabit the same context, otherwise we might tried to instantiate
1347 // references to non-instantiated entities during constraint substitution.
1348 // GH78101.
1349 if (NewTemplate) {
1350 // C++ [temp.over.link]p4:
1351 // The signature of a function template consists of its function
1352 // signature, its return type and its template parameter list. The names
1353 // of the template parameters are significant only for establishing the
1354 // relationship between the template parameters and the rest of the
1355 // signature.
1356 //
1357 // We check the return type and template parameter lists for function
1358 // templates first; the remaining checks follow.
1359 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1360 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1361 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1362 bool SameReturnType = SemaRef.Context.hasSameType(
1364 // FIXME(GH58571): Match template parameter list even for non-constrained
1365 // template heads. This currently ensures that the code prior to C++20 is
1366 // not newly broken.
1367 bool ConstraintsInTemplateHead =
1370 // C++ [namespace.udecl]p11:
1371 // The set of declarations named by a using-declarator that inhabits a
1372 // class C does not include member functions and member function
1373 // templates of a base class that "correspond" to (and thus would
1374 // conflict with) a declaration of a function or function template in
1375 // C.
1376 // Comparing return types is not required for the "correspond" check to
1377 // decide whether a member introduced by a shadow declaration is hidden.
1378 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1379 !SameTemplateParameterList)
1380 return true;
1381 if (!UseMemberUsingDeclRules &&
1382 (!SameTemplateParameterList || !SameReturnType))
1383 return true;
1384 }
1385
1386 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1387 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1388
1389 int OldParamsOffset = 0;
1390 int NewParamsOffset = 0;
1391
1392 // When determining if a method is an overload from a base class, act as if
1393 // the implicit object parameter are of the same type.
1394
1395 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1397 return Q;
1398
1399 // We do not allow overloading based off of '__restrict'.
1400 Q.removeRestrict();
1401
1402 // We may not have applied the implicit const for a constexpr member
1403 // function yet (because we haven't yet resolved whether this is a static
1404 // or non-static member function). Add it now, on the assumption that this
1405 // is a redeclaration of OldMethod.
1406 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1407 (M->isConstexpr() || M->isConsteval()) &&
1408 !isa<CXXConstructorDecl>(NewMethod))
1409 Q.addConst();
1410 return Q;
1411 };
1412
1413 auto CompareType = [&](QualType Base, QualType D) {
1414 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1415 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1416
1417 auto DS = D.getNonReferenceType().getCanonicalType().split();
1418 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1419
1420 if (BS.Quals != DS.Quals)
1421 return false;
1422
1423 if (OldMethod->isImplicitObjectMemberFunction() &&
1424 OldMethod->getParent() != NewMethod->getParent()) {
1425 QualType ParentType =
1426 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1428 if (ParentType.getTypePtr() != BS.Ty)
1429 return false;
1430 BS.Ty = DS.Ty;
1431 }
1432
1433 // FIXME: should we ignore some type attributes here?
1434 if (BS.Ty != DS.Ty)
1435 return false;
1436
1437 if (Base->isLValueReferenceType())
1438 return D->isLValueReferenceType();
1439 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1440 };
1441
1442 // If the function is a class member, its signature includes the
1443 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1444 auto DiagnoseInconsistentRefQualifiers = [&]() {
1445 if (SemaRef.LangOpts.CPlusPlus23)
1446 return false;
1447 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1448 return false;
1449 if (OldMethod->isExplicitObjectMemberFunction() ||
1450 NewMethod->isExplicitObjectMemberFunction())
1451 return false;
1452 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1453 NewMethod->getRefQualifier() == RQ_None)) {
1454 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1455 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1456 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1457 return true;
1458 }
1459 return false;
1460 };
1461
1462 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1463 OldParamsOffset++;
1464 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1465 NewParamsOffset++;
1466
1467 if (OldType->getNumParams() - OldParamsOffset !=
1468 NewType->getNumParams() - NewParamsOffset ||
1470 {OldType->param_type_begin() + OldParamsOffset,
1471 OldType->param_type_end()},
1472 {NewType->param_type_begin() + NewParamsOffset,
1473 NewType->param_type_end()},
1474 nullptr)) {
1475 return true;
1476 }
1477
1478 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1479 !OldMethod->isStatic()) {
1480 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1481 const CXXMethodDecl *New) {
1482 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1483 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1484
1485 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1486 return F->getRefQualifier() == RQ_None &&
1487 !F->isExplicitObjectMemberFunction();
1488 };
1489
1490 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1491 CompareType(OldObjectType.getNonReferenceType(),
1492 NewObjectType.getNonReferenceType()))
1493 return true;
1494 return CompareType(OldObjectType, NewObjectType);
1495 }(OldMethod, NewMethod);
1496
1497 if (!HaveCorrespondingObjectParameters) {
1498 if (DiagnoseInconsistentRefQualifiers())
1499 return true;
1500 // CWG2554
1501 // and, if at least one is an explicit object member function, ignoring
1502 // object parameters
1503 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1504 !OldMethod->isExplicitObjectMemberFunction()))
1505 return true;
1506 }
1507 }
1508
1509 if (!UseOverrideRules) {
1510 Expr *NewRC = New->getTrailingRequiresClause(),
1511 *OldRC = Old->getTrailingRequiresClause();
1512 if ((NewRC != nullptr) != (OldRC != nullptr))
1513 return true;
1514
1515 if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1516 return true;
1517 }
1518
1519 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1520 NewMethod->isImplicitObjectMemberFunction()) {
1521 if (DiagnoseInconsistentRefQualifiers())
1522 return true;
1523 }
1524
1525 // Though pass_object_size is placed on parameters and takes an argument, we
1526 // consider it to be a function-level modifier for the sake of function
1527 // identity. Either the function has one or more parameters with
1528 // pass_object_size or it doesn't.
1531 return true;
1532
1533 // enable_if attributes are an order-sensitive part of the signature.
1535 NewI = New->specific_attr_begin<EnableIfAttr>(),
1536 NewE = New->specific_attr_end<EnableIfAttr>(),
1537 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1538 OldE = Old->specific_attr_end<EnableIfAttr>();
1539 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1540 if (NewI == NewE || OldI == OldE)
1541 return true;
1542 llvm::FoldingSetNodeID NewID, OldID;
1543 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1544 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1545 if (NewID != OldID)
1546 return true;
1547 }
1548
1549 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1550 // Don't allow overloading of destructors. (In theory we could, but it
1551 // would be a giant change to clang.)
1552 if (!isa<CXXDestructorDecl>(New)) {
1553 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1554 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1555 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1556 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1557 "Unexpected invalid target.");
1558
1559 // Allow overloading of functions with same signature and different CUDA
1560 // target attributes.
1561 if (NewTarget != OldTarget)
1562 return true;
1563 }
1564 }
1565 }
1566
1567 // The signatures match; this is not an overload.
1568 return false;
1569}
1570
1572 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1573 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1574 ConsiderCudaAttrs);
1575}
1576
1578 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1579 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1580 /*UseMemberUsingDeclRules=*/false,
1581 /*ConsiderCudaAttrs=*/true,
1582 /*UseOverrideRules=*/true);
1583}
1584
1585/// Tries a user-defined conversion from From to ToType.
1586///
1587/// Produces an implicit conversion sequence for when a standard conversion
1588/// is not an option. See TryImplicitConversion for more information.
1591 bool SuppressUserConversions,
1592 AllowedExplicit AllowExplicit,
1593 bool InOverloadResolution,
1594 bool CStyle,
1595 bool AllowObjCWritebackConversion,
1596 bool AllowObjCConversionOnExplicit) {
1598
1599 if (SuppressUserConversions) {
1600 // We're not in the case above, so there is no conversion that
1601 // we can perform.
1603 return ICS;
1604 }
1605
1606 // Attempt user-defined conversion.
1607 OverloadCandidateSet Conversions(From->getExprLoc(),
1609 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1610 Conversions, AllowExplicit,
1611 AllowObjCConversionOnExplicit)) {
1612 case OR_Success:
1613 case OR_Deleted:
1614 ICS.setUserDefined();
1615 // C++ [over.ics.user]p4:
1616 // A conversion of an expression of class type to the same class
1617 // type is given Exact Match rank, and a conversion of an
1618 // expression of class type to a base class of that type is
1619 // given Conversion rank, in spite of the fact that a copy
1620 // constructor (i.e., a user-defined conversion function) is
1621 // called for those cases.
1622 if (CXXConstructorDecl *Constructor
1623 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1624 QualType FromCanon
1626 QualType ToCanon
1628 if (Constructor->isCopyConstructor() &&
1629 (FromCanon == ToCanon ||
1630 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1631 // Turn this into a "standard" conversion sequence, so that it
1632 // gets ranked with standard conversion sequences.
1634 ICS.setStandard();
1636 ICS.Standard.setFromType(From->getType());
1637 ICS.Standard.setAllToTypes(ToType);
1638 ICS.Standard.CopyConstructor = Constructor;
1639 ICS.Standard.FoundCopyConstructor = Found;
1640 if (ToCanon != FromCanon)
1642 }
1643 }
1644 break;
1645
1646 case OR_Ambiguous:
1647 ICS.setAmbiguous();
1648 ICS.Ambiguous.setFromType(From->getType());
1649 ICS.Ambiguous.setToType(ToType);
1650 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1651 Cand != Conversions.end(); ++Cand)
1652 if (Cand->Best)
1653 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1654 break;
1655
1656 // Fall through.
1659 break;
1660 }
1661
1662 return ICS;
1663}
1664
1665/// TryImplicitConversion - Attempt to perform an implicit conversion
1666/// from the given expression (Expr) to the given type (ToType). This
1667/// function returns an implicit conversion sequence that can be used
1668/// to perform the initialization. Given
1669///
1670/// void f(float f);
1671/// void g(int i) { f(i); }
1672///
1673/// this routine would produce an implicit conversion sequence to
1674/// describe the initialization of f from i, which will be a standard
1675/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1676/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1677//
1678/// Note that this routine only determines how the conversion can be
1679/// performed; it does not actually perform the conversion. As such,
1680/// it will not produce any diagnostics if no conversion is available,
1681/// but will instead return an implicit conversion sequence of kind
1682/// "BadConversion".
1683///
1684/// If @p SuppressUserConversions, then user-defined conversions are
1685/// not permitted.
1686/// If @p AllowExplicit, then explicit user-defined conversions are
1687/// permitted.
1688///
1689/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1690/// writeback conversion, which allows __autoreleasing id* parameters to
1691/// be initialized with __strong id* or __weak id* arguments.
1694 bool SuppressUserConversions,
1695 AllowedExplicit AllowExplicit,
1696 bool InOverloadResolution,
1697 bool CStyle,
1698 bool AllowObjCWritebackConversion,
1699 bool AllowObjCConversionOnExplicit) {
1701 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1702 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1703 ICS.setStandard();
1704 return ICS;
1705 }
1706
1707 if (!S.getLangOpts().CPlusPlus) {
1709 return ICS;
1710 }
1711
1712 // C++ [over.ics.user]p4:
1713 // A conversion of an expression of class type to the same class
1714 // type is given Exact Match rank, and a conversion of an
1715 // expression of class type to a base class of that type is
1716 // given Conversion rank, in spite of the fact that a copy/move
1717 // constructor (i.e., a user-defined conversion function) is
1718 // called for those cases.
1719 QualType FromType = From->getType();
1720 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1721 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1722 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1723 ICS.setStandard();
1725 ICS.Standard.setFromType(FromType);
1726 ICS.Standard.setAllToTypes(ToType);
1727
1728 // We don't actually check at this point whether there is a valid
1729 // copy/move constructor, since overloading just assumes that it
1730 // exists. When we actually perform initialization, we'll find the
1731 // appropriate constructor to copy the returned object, if needed.
1732 ICS.Standard.CopyConstructor = nullptr;
1733
1734 // Determine whether this is considered a derived-to-base conversion.
1735 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1737
1738 return ICS;
1739 }
1740
1741 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1742 AllowExplicit, InOverloadResolution, CStyle,
1743 AllowObjCWritebackConversion,
1744 AllowObjCConversionOnExplicit);
1745}
1746
1749 bool SuppressUserConversions,
1750 AllowedExplicit AllowExplicit,
1751 bool InOverloadResolution,
1752 bool CStyle,
1753 bool AllowObjCWritebackConversion) {
1754 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1755 AllowExplicit, InOverloadResolution, CStyle,
1756 AllowObjCWritebackConversion,
1757 /*AllowObjCConversionOnExplicit=*/false);
1758}
1759
1760/// PerformImplicitConversion - Perform an implicit conversion of the
1761/// expression From to the type ToType. Returns the
1762/// converted expression. Flavor is the kind of conversion we're
1763/// performing, used in the error message. If @p AllowExplicit,
1764/// explicit user-defined conversions are permitted.
1766 AssignmentAction Action,
1767 bool AllowExplicit) {
1768 if (checkPlaceholderForOverload(*this, From))
1769 return ExprError();
1770
1771 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1772 bool AllowObjCWritebackConversion
1773 = getLangOpts().ObjCAutoRefCount &&
1774 (Action == AA_Passing || Action == AA_Sending);
1775 if (getLangOpts().ObjC)
1776 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1777 From->getType(), From);
1779 *this, From, ToType,
1780 /*SuppressUserConversions=*/false,
1781 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1782 /*InOverloadResolution=*/false,
1783 /*CStyle=*/false, AllowObjCWritebackConversion,
1784 /*AllowObjCConversionOnExplicit=*/false);
1785 return PerformImplicitConversion(From, ToType, ICS, Action);
1786}
1787
1788/// Determine whether the conversion from FromType to ToType is a valid
1789/// conversion that strips "noexcept" or "noreturn" off the nested function
1790/// type.
1792 QualType &ResultTy) {
1793 if (Context.hasSameUnqualifiedType(FromType, ToType))
1794 return false;
1795
1796 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1797 // or F(t noexcept) -> F(t)
1798 // where F adds one of the following at most once:
1799 // - a pointer
1800 // - a member pointer
1801 // - a block pointer
1802 // Changes here need matching changes in FindCompositePointerType.
1803 CanQualType CanTo = Context.getCanonicalType(ToType);
1804 CanQualType CanFrom = Context.getCanonicalType(FromType);
1805 Type::TypeClass TyClass = CanTo->getTypeClass();
1806 if (TyClass != CanFrom->getTypeClass()) return false;
1807 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1808 if (TyClass == Type::Pointer) {
1809 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1810 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1811 } else if (TyClass == Type::BlockPointer) {
1812 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1813 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1814 } else if (TyClass == Type::MemberPointer) {
1815 auto ToMPT = CanTo.castAs<MemberPointerType>();
1816 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1817 // A function pointer conversion cannot change the class of the function.
1818 if (ToMPT->getClass() != FromMPT->getClass())
1819 return false;
1820 CanTo = ToMPT->getPointeeType();
1821 CanFrom = FromMPT->getPointeeType();
1822 } else {
1823 return false;
1824 }
1825
1826 TyClass = CanTo->getTypeClass();
1827 if (TyClass != CanFrom->getTypeClass()) return false;
1828 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1829 return false;
1830 }
1831
1832 const auto *FromFn = cast<FunctionType>(CanFrom);
1833 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1834
1835 const auto *ToFn = cast<FunctionType>(CanTo);
1836 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1837
1838 bool Changed = false;
1839
1840 // Drop 'noreturn' if not present in target type.
1841 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1842 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1843 Changed = true;
1844 }
1845
1846 // Drop 'noexcept' if not present in target type.
1847 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1848 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1849 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1850 FromFn = cast<FunctionType>(
1851 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1852 EST_None)
1853 .getTypePtr());
1854 Changed = true;
1855 }
1856
1857 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1858 // only if the ExtParameterInfo lists of the two function prototypes can be
1859 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1861 bool CanUseToFPT, CanUseFromFPT;
1862 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1863 CanUseFromFPT, NewParamInfos) &&
1864 CanUseToFPT && !CanUseFromFPT) {
1865 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1866 ExtInfo.ExtParameterInfos =
1867 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1868 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1869 FromFPT->getParamTypes(), ExtInfo);
1870 FromFn = QT->getAs<FunctionType>();
1871 Changed = true;
1872 }
1873 }
1874
1875 if (!Changed)
1876 return false;
1877
1878 assert(QualType(FromFn, 0).isCanonical());
1879 if (QualType(FromFn, 0) != CanTo) return false;
1880
1881 ResultTy = ToType;
1882 return true;
1883}
1884
1885/// Determine whether the conversion from FromType to ToType is a valid
1886/// floating point conversion.
1887///
1888static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1889 QualType ToType) {
1890 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1891 return false;
1892 // FIXME: disable conversions between long double, __ibm128 and __float128
1893 // if their representation is different until there is back end support
1894 // We of course allow this conversion if long double is really double.
1895
1896 // Conversions between bfloat16 and float16 are currently not supported.
1897 if ((FromType->isBFloat16Type() &&
1898 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1899 (ToType->isBFloat16Type() &&
1900 (FromType->isFloat16Type() || FromType->isHalfType())))
1901 return false;
1902
1903 // Conversions between IEEE-quad and IBM-extended semantics are not
1904 // permitted.
1905 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1906 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1907 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1908 &ToSem == &llvm::APFloat::IEEEquad()) ||
1909 (&FromSem == &llvm::APFloat::IEEEquad() &&
1910 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1911 return false;
1912 return true;
1913}
1914
1915static bool IsVectorElementConversion(Sema &S, QualType FromType,
1916 QualType ToType,
1917 ImplicitConversionKind &ICK, Expr *From) {
1918 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1919 return true;
1920
1921 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1923 return true;
1924 }
1925
1926 if (IsFloatingPointConversion(S, FromType, ToType)) {
1928 return true;
1929 }
1930
1931 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1933 return true;
1934 }
1935
1936 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1938 ToType->isRealFloatingType())) {
1940 return true;
1941 }
1942
1943 if (S.IsIntegralPromotion(From, FromType, ToType)) {
1945 return true;
1946 }
1947
1948 if (FromType->isIntegralOrUnscopedEnumerationType() &&
1949 ToType->isIntegralType(S.Context)) {
1951 return true;
1952 }
1953
1954 return false;
1955}
1956
1957/// Determine whether the conversion from FromType to ToType is a valid
1958/// vector conversion.
1959///
1960/// \param ICK Will be set to the vector conversion kind, if this is a vector
1961/// conversion.
1962static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1964 ImplicitConversionKind &ElConv, Expr *From,
1965 bool InOverloadResolution, bool CStyle) {
1966 // We need at least one of these types to be a vector type to have a vector
1967 // conversion.
1968 if (!ToType->isVectorType() && !FromType->isVectorType())
1969 return false;
1970
1971 // Identical types require no conversions.
1972 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1973 return false;
1974
1975 // There are no conversions between extended vector types, only identity.
1976 if (ToType->isExtVectorType()) {
1977 if (FromType->isExtVectorType()) {
1978 // HLSL allows implicit truncation of vector types.
1979 if (S.getLangOpts().HLSL) {
1980 unsigned FromElts = FromType->getAs<VectorType>()->getNumElements();
1981 unsigned ToElts = ToType->getAs<VectorType>()->getNumElements();
1982 if (FromElts < ToElts)
1983 return false;
1984 if (FromElts == ToElts)
1985 ICK = ICK_Identity;
1986 else
1988
1989 QualType FromElTy = FromType->getAs<VectorType>()->getElementType();
1990 QualType ToElTy = ToType->getAs<VectorType>()->getElementType();
1991 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
1992 return true;
1993 return IsVectorElementConversion(S, FromElTy, ToElTy, ElConv, From);
1994 }
1995 // There are no conversions between extended vector types other than the
1996 // identity conversion.
1997 return false;
1998 }
1999
2000 // Vector splat from any arithmetic type to a vector.
2001 if (FromType->isArithmeticType()) {
2002 ICK = ICK_Vector_Splat;
2003 return true;
2004 }
2005 }
2006
2007 if (ToType->isSVESizelessBuiltinType() ||
2008 FromType->isSVESizelessBuiltinType())
2009 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2010 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2012 return true;
2013 }
2014
2015 if (ToType->isRVVSizelessBuiltinType() ||
2016 FromType->isRVVSizelessBuiltinType())
2017 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2018 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2020 return true;
2021 }
2022
2023 // We can perform the conversion between vector types in the following cases:
2024 // 1)vector types are equivalent AltiVec and GCC vector types
2025 // 2)lax vector conversions are permitted and the vector types are of the
2026 // same size
2027 // 3)the destination type does not have the ARM MVE strict-polymorphism
2028 // attribute, which inhibits lax vector conversion for overload resolution
2029 // only
2030 if (ToType->isVectorType() && FromType->isVectorType()) {
2031 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2032 (S.isLaxVectorConversion(FromType, ToType) &&
2033 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2034 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2035 S.isLaxVectorConversion(FromType, ToType) &&
2036 S.anyAltivecTypes(FromType, ToType) &&
2037 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2038 !InOverloadResolution && !CStyle) {
2039 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2040 << FromType << ToType;
2041 }
2043 return true;
2044 }
2045 }
2046
2047 return false;
2048}
2049
2050static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2051 bool InOverloadResolution,
2053 bool CStyle);
2054
2055/// IsStandardConversion - Determines whether there is a standard
2056/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2057/// expression From to the type ToType. Standard conversion sequences
2058/// only consider non-class types; for conversions that involve class
2059/// types, use TryImplicitConversion. If a conversion exists, SCS will
2060/// contain the standard conversion sequence required to perform this
2061/// conversion and this routine will return true. Otherwise, this
2062/// routine will return false and the value of SCS is unspecified.
2063static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2064 bool InOverloadResolution,
2066 bool CStyle,
2067 bool AllowObjCWritebackConversion) {
2068 QualType FromType = From->getType();
2069
2070 // Standard conversions (C++ [conv])
2072 SCS.IncompatibleObjC = false;
2073 SCS.setFromType(FromType);
2074 SCS.CopyConstructor = nullptr;
2075
2076 // There are no standard conversions for class types in C++, so
2077 // abort early. When overloading in C, however, we do permit them.
2078 if (S.getLangOpts().CPlusPlus &&
2079 (FromType->isRecordType() || ToType->isRecordType()))
2080 return false;
2081
2082 // The first conversion can be an lvalue-to-rvalue conversion,
2083 // array-to-pointer conversion, or function-to-pointer conversion
2084 // (C++ 4p1).
2085
2086 if (FromType == S.Context.OverloadTy) {
2087 DeclAccessPair AccessPair;
2088 if (FunctionDecl *Fn
2089 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2090 AccessPair)) {
2091 // We were able to resolve the address of the overloaded function,
2092 // so we can convert to the type of that function.
2093 FromType = Fn->getType();
2094 SCS.setFromType(FromType);
2095
2096 // we can sometimes resolve &foo<int> regardless of ToType, so check
2097 // if the type matches (identity) or we are converting to bool
2099 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2100 QualType resultTy;
2101 // if the function type matches except for [[noreturn]], it's ok
2102 if (!S.IsFunctionConversion(FromType,
2103 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2104 // otherwise, only a boolean conversion is standard
2105 if (!ToType->isBooleanType())
2106 return false;
2107 }
2108
2109 // Check if the "from" expression is taking the address of an overloaded
2110 // function and recompute the FromType accordingly. Take advantage of the
2111 // fact that non-static member functions *must* have such an address-of
2112 // expression.
2113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2114 if (Method && !Method->isStatic() &&
2115 !Method->isExplicitObjectMemberFunction()) {
2116 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2117 "Non-unary operator on non-static member address");
2118 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2119 == UO_AddrOf &&
2120 "Non-address-of operator on non-static member address");
2121 const Type *ClassType
2123 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2124 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2125 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2126 UO_AddrOf &&
2127 "Non-address-of operator for overloaded function expression");
2128 FromType = S.Context.getPointerType(FromType);
2129 }
2130 } else {
2131 return false;
2132 }
2133 }
2134 // Lvalue-to-rvalue conversion (C++11 4.1):
2135 // A glvalue (3.10) of a non-function, non-array type T can
2136 // be converted to a prvalue.
2137 bool argIsLValue = From->isGLValue();
2138 if (argIsLValue && !FromType->canDecayToPointerType() &&
2139 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2141
2142 // C11 6.3.2.1p2:
2143 // ... if the lvalue has atomic type, the value has the non-atomic version
2144 // of the type of the lvalue ...
2145 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2146 FromType = Atomic->getValueType();
2147
2148 // If T is a non-class type, the type of the rvalue is the
2149 // cv-unqualified version of T. Otherwise, the type of the rvalue
2150 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2151 // just strip the qualifiers because they don't matter.
2152 FromType = FromType.getUnqualifiedType();
2153 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2154 ToType->isArrayParameterType()) {
2155 // HLSL constant array parameters do not decay, so if the argument is a
2156 // constant array and the parameter is an ArrayParameterType we have special
2157 // handling here.
2158 FromType = S.Context.getArrayParameterType(FromType);
2159 if (S.Context.getCanonicalType(FromType) !=
2160 S.Context.getCanonicalType(ToType))
2161 return false;
2162
2164 SCS.setAllToTypes(ToType);
2165 return true;
2166 } else if (FromType->isArrayType()) {
2167 // Array-to-pointer conversion (C++ 4.2)
2169
2170 // An lvalue or rvalue of type "array of N T" or "array of unknown
2171 // bound of T" can be converted to an rvalue of type "pointer to
2172 // T" (C++ 4.2p1).
2173 FromType = S.Context.getArrayDecayedType(FromType);
2174
2175 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2176 // This conversion is deprecated in C++03 (D.4)
2178
2179 // For the purpose of ranking in overload resolution
2180 // (13.3.3.1.1), this conversion is considered an
2181 // array-to-pointer conversion followed by a qualification
2182 // conversion (4.4). (C++ 4.2p2)
2183 SCS.Second = ICK_Identity;
2186 SCS.setAllToTypes(FromType);
2187 return true;
2188 }
2189 } else if (FromType->isFunctionType() && argIsLValue) {
2190 // Function-to-pointer conversion (C++ 4.3).
2192
2193 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2194 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2196 return false;
2197
2198 // An lvalue of function type T can be converted to an rvalue of
2199 // type "pointer to T." The result is a pointer to the
2200 // function. (C++ 4.3p1).
2201 FromType = S.Context.getPointerType(FromType);
2202 } else {
2203 // We don't require any conversions for the first step.
2204 SCS.First = ICK_Identity;
2205 }
2206 SCS.setToType(0, FromType);
2207
2208 // The second conversion can be an integral promotion, floating
2209 // point promotion, integral conversion, floating point conversion,
2210 // floating-integral conversion, pointer conversion,
2211 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2212 // For overloading in C, this can also be a "compatible-type"
2213 // conversion.
2214 bool IncompatibleObjC = false;
2217 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2218 // The unqualified versions of the types are the same: there's no
2219 // conversion to do.
2220 SCS.Second = ICK_Identity;
2221 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2222 // Integral promotion (C++ 4.5).
2224 FromType = ToType.getUnqualifiedType();
2225 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2226 // Floating point promotion (C++ 4.6).
2228 FromType = ToType.getUnqualifiedType();
2229 } else if (S.IsComplexPromotion(FromType, ToType)) {
2230 // Complex promotion (Clang extension)
2232 FromType = ToType.getUnqualifiedType();
2233 } else if (ToType->isBooleanType() &&
2234 (FromType->isArithmeticType() ||
2235 FromType->isAnyPointerType() ||
2236 FromType->isBlockPointerType() ||
2237 FromType->isMemberPointerType())) {
2238 // Boolean conversions (C++ 4.12).
2240 FromType = S.Context.BoolTy;
2241 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2242 ToType->isIntegralType(S.Context)) {
2243 // Integral conversions (C++ 4.7).
2245 FromType = ToType.getUnqualifiedType();
2246 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2247 // Complex conversions (C99 6.3.1.6)
2249 FromType = ToType.getUnqualifiedType();
2250 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2251 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2252 // Complex-real conversions (C99 6.3.1.7)
2254 FromType = ToType.getUnqualifiedType();
2255 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2256 // Floating point conversions (C++ 4.8).
2258 FromType = ToType.getUnqualifiedType();
2259 } else if ((FromType->isRealFloatingType() &&
2260 ToType->isIntegralType(S.Context)) ||
2262 ToType->isRealFloatingType())) {
2263
2264 // Floating-integral conversions (C++ 4.9).
2266 FromType = ToType.getUnqualifiedType();
2267 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2269 } else if (AllowObjCWritebackConversion &&
2270 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2272 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2273 FromType, IncompatibleObjC)) {
2274 // Pointer conversions (C++ 4.10).
2276 SCS.IncompatibleObjC = IncompatibleObjC;
2277 FromType = FromType.getUnqualifiedType();
2278 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2279 InOverloadResolution, FromType)) {
2280 // Pointer to member conversions (4.11).
2282 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, ElementICK,
2283 From, InOverloadResolution, CStyle)) {
2284 SCS.Second = SecondICK;
2285 SCS.Element = ElementICK;
2286 FromType = ToType.getUnqualifiedType();
2287 } else if (!S.getLangOpts().CPlusPlus &&
2288 S.Context.typesAreCompatible(ToType, FromType)) {
2289 // Compatible conversions (Clang extension for C function overloading)
2291 FromType = ToType.getUnqualifiedType();
2293 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2295 FromType = ToType;
2296 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2297 CStyle)) {
2298 // tryAtomicConversion has updated the standard conversion sequence
2299 // appropriately.
2300 return true;
2301 } else if (ToType->isEventT() &&
2303 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2305 FromType = ToType;
2306 } else if (ToType->isQueueT() &&
2308 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2310 FromType = ToType;
2311 } else if (ToType->isSamplerT() &&
2314 FromType = ToType;
2315 } else if ((ToType->isFixedPointType() &&
2316 FromType->isConvertibleToFixedPointType()) ||
2317 (FromType->isFixedPointType() &&
2318 ToType->isConvertibleToFixedPointType())) {
2320 FromType = ToType;
2321 } else {
2322 // No second conversion required.
2323 SCS.Second = ICK_Identity;
2324 }
2325 SCS.setToType(1, FromType);
2326
2327 // The third conversion can be a function pointer conversion or a
2328 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2329 bool ObjCLifetimeConversion;
2330 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2331 // Function pointer conversions (removing 'noexcept') including removal of
2332 // 'noreturn' (Clang extension).
2334 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2335 ObjCLifetimeConversion)) {
2337 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2338 FromType = ToType;
2339 } else {
2340 // No conversion required
2341 SCS.Third = ICK_Identity;
2342 }
2343
2344 // C++ [over.best.ics]p6:
2345 // [...] Any difference in top-level cv-qualification is
2346 // subsumed by the initialization itself and does not constitute
2347 // a conversion. [...]
2348 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2349 QualType CanonTo = S.Context.getCanonicalType(ToType);
2350 if (CanonFrom.getLocalUnqualifiedType()
2351 == CanonTo.getLocalUnqualifiedType() &&
2352 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2353 FromType = ToType;
2354 CanonFrom = CanonTo;
2355 }
2356
2357 SCS.setToType(2, FromType);
2358
2359 if (CanonFrom == CanonTo)
2360 return true;
2361
2362 // If we have not converted the argument type to the parameter type,
2363 // this is a bad conversion sequence, unless we're resolving an overload in C.
2364 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2365 return false;
2366
2367 ExprResult ER = ExprResult{From};
2370 /*Diagnose=*/false,
2371 /*DiagnoseCFAudited=*/false,
2372 /*ConvertRHS=*/false);
2373 ImplicitConversionKind SecondConv;
2374 switch (Conv) {
2375 case Sema::Compatible:
2376 SecondConv = ICK_C_Only_Conversion;
2377 break;
2378 // For our purposes, discarding qualifiers is just as bad as using an
2379 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2380 // qualifiers, as well.
2385 break;
2386 default:
2387 return false;
2388 }
2389
2390 // First can only be an lvalue conversion, so we pretend that this was the
2391 // second conversion. First should already be valid from earlier in the
2392 // function.
2393 SCS.Second = SecondConv;
2394 SCS.setToType(1, ToType);
2395
2396 // Third is Identity, because Second should rank us worse than any other
2397 // conversion. This could also be ICK_Qualification, but it's simpler to just
2398 // lump everything in with the second conversion, and we don't gain anything
2399 // from making this ICK_Qualification.
2400 SCS.Third = ICK_Identity;
2401 SCS.setToType(2, ToType);
2402 return true;
2403}
2404
2405static bool
2407 QualType &ToType,
2408 bool InOverloadResolution,
2410 bool CStyle) {
2411
2412 const RecordType *UT = ToType->getAsUnionType();
2413 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2414 return false;
2415 // The field to initialize within the transparent union.
2416 RecordDecl *UD = UT->getDecl();
2417 // It's compatible if the expression matches any of the fields.
2418 for (const auto *it : UD->fields()) {
2419 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2420 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2421 ToType = it->getType();
2422 return true;
2423 }
2424 }
2425 return false;
2426}
2427
2428/// IsIntegralPromotion - Determines whether the conversion from the
2429/// expression From (whose potentially-adjusted type is FromType) to
2430/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2431/// sets PromotedType to the promoted type.
2432bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2433 const BuiltinType *To = ToType->getAs<BuiltinType>();
2434 // All integers are built-in.
2435 if (!To) {
2436 return false;
2437 }
2438
2439 // An rvalue of type char, signed char, unsigned char, short int, or
2440 // unsigned short int can be converted to an rvalue of type int if
2441 // int can represent all the values of the source type; otherwise,
2442 // the source rvalue can be converted to an rvalue of type unsigned
2443 // int (C++ 4.5p1).
2444 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2445 !FromType->isEnumeralType()) {
2446 if ( // We can promote any signed, promotable integer type to an int
2447 (FromType->isSignedIntegerType() ||
2448 // We can promote any unsigned integer type whose size is
2449 // less than int to an int.
2450 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2451 return To->getKind() == BuiltinType::Int;
2452 }
2453
2454 return To->getKind() == BuiltinType::UInt;
2455 }
2456
2457 // C++11 [conv.prom]p3:
2458 // A prvalue of an unscoped enumeration type whose underlying type is not
2459 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2460 // following types that can represent all the values of the enumeration
2461 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2462 // unsigned int, long int, unsigned long int, long long int, or unsigned
2463 // long long int. If none of the types in that list can represent all the
2464 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2465 // type can be converted to an rvalue a prvalue of the extended integer type
2466 // with lowest integer conversion rank (4.13) greater than the rank of long
2467 // long in which all the values of the enumeration can be represented. If
2468 // there are two such extended types, the signed one is chosen.
2469 // C++11 [conv.prom]p4:
2470 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2471 // can be converted to a prvalue of its underlying type. Moreover, if
2472 // integral promotion can be applied to its underlying type, a prvalue of an
2473 // unscoped enumeration type whose underlying type is fixed can also be
2474 // converted to a prvalue of the promoted underlying type.
2475 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2476 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2477 // provided for a scoped enumeration.
2478 if (FromEnumType->getDecl()->isScoped())
2479 return false;
2480
2481 // We can perform an integral promotion to the underlying type of the enum,
2482 // even if that's not the promoted type. Note that the check for promoting
2483 // the underlying type is based on the type alone, and does not consider
2484 // the bitfield-ness of the actual source expression.
2485 if (FromEnumType->getDecl()->isFixed()) {
2486 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2487 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2488 IsIntegralPromotion(nullptr, Underlying, ToType);
2489 }
2490
2491 // We have already pre-calculated the promotion type, so this is trivial.
2492 if (ToType->isIntegerType() &&
2493 isCompleteType(From->getBeginLoc(), FromType))
2494 return Context.hasSameUnqualifiedType(
2495 ToType, FromEnumType->getDecl()->getPromotionType());
2496
2497 // C++ [conv.prom]p5:
2498 // If the bit-field has an enumerated type, it is treated as any other
2499 // value of that type for promotion purposes.
2500 //
2501 // ... so do not fall through into the bit-field checks below in C++.
2502 if (getLangOpts().CPlusPlus)
2503 return false;
2504 }
2505
2506 // C++0x [conv.prom]p2:
2507 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2508 // to an rvalue a prvalue of the first of the following types that can
2509 // represent all the values of its underlying type: int, unsigned int,
2510 // long int, unsigned long int, long long int, or unsigned long long int.
2511 // If none of the types in that list can represent all the values of its
2512 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2513 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2514 // type.
2515 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2516 ToType->isIntegerType()) {
2517 // Determine whether the type we're converting from is signed or
2518 // unsigned.
2519 bool FromIsSigned = FromType->isSignedIntegerType();
2520 uint64_t FromSize = Context.getTypeSize(FromType);
2521
2522 // The types we'll try to promote to, in the appropriate
2523 // order. Try each of these types.
2524 QualType PromoteTypes[6] = {
2525 Context.IntTy, Context.UnsignedIntTy,
2526 Context.LongTy, Context.UnsignedLongTy ,
2527 Context.LongLongTy, Context.UnsignedLongLongTy
2528 };
2529 for (int Idx = 0; Idx < 6; ++Idx) {
2530 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2531 if (FromSize < ToSize ||
2532 (FromSize == ToSize &&
2533 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2534 // We found the type that we can promote to. If this is the
2535 // type we wanted, we have a promotion. Otherwise, no
2536 // promotion.
2537 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2538 }
2539 }
2540 }
2541
2542 // An rvalue for an integral bit-field (9.6) can be converted to an
2543 // rvalue of type int if int can represent all the values of the
2544 // bit-field; otherwise, it can be converted to unsigned int if
2545 // unsigned int can represent all the values of the bit-field. If
2546 // the bit-field is larger yet, no integral promotion applies to
2547 // it. If the bit-field has an enumerated type, it is treated as any
2548 // other value of that type for promotion purposes (C++ 4.5p3).
2549 // FIXME: We should delay checking of bit-fields until we actually perform the
2550 // conversion.
2551 //
2552 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2553 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2554 // bit-fields and those whose underlying type is larger than int) for GCC
2555 // compatibility.
2556 if (From) {
2557 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2558 std::optional<llvm::APSInt> BitWidth;
2559 if (FromType->isIntegralType(Context) &&
2560 (BitWidth =
2561 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2562 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2563 ToSize = Context.getTypeSize(ToType);
2564
2565 // Are we promoting to an int from a bitfield that fits in an int?
2566 if (*BitWidth < ToSize ||
2567 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2568 return To->getKind() == BuiltinType::Int;
2569 }
2570
2571 // Are we promoting to an unsigned int from an unsigned bitfield
2572 // that fits into an unsigned int?
2573 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2574 return To->getKind() == BuiltinType::UInt;
2575 }
2576
2577 return false;
2578 }
2579 }
2580 }
2581
2582 // An rvalue of type bool can be converted to an rvalue of type int,
2583 // with false becoming zero and true becoming one (C++ 4.5p4).
2584 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2585 return true;
2586 }
2587
2588 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2589 // integral type.
2590 if (Context.getLangOpts().HLSL)
2591 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2592
2593 return false;
2594}
2595
2596/// IsFloatingPointPromotion - Determines whether the conversion from
2597/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2598/// returns true and sets PromotedType to the promoted type.
2600 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2601 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2602 /// An rvalue of type float can be converted to an rvalue of type
2603 /// double. (C++ 4.6p1).
2604 if (FromBuiltin->getKind() == BuiltinType::Float &&
2605 ToBuiltin->getKind() == BuiltinType::Double)
2606 return true;
2607
2608 // C99 6.3.1.5p1:
2609 // When a float is promoted to double or long double, or a
2610 // double is promoted to long double [...].
2611 if (!getLangOpts().CPlusPlus &&
2612 (FromBuiltin->getKind() == BuiltinType::Float ||
2613 FromBuiltin->getKind() == BuiltinType::Double) &&
2614 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2615 ToBuiltin->getKind() == BuiltinType::Float128 ||
2616 ToBuiltin->getKind() == BuiltinType::Ibm128))
2617 return true;
2618
2619 // Half can be promoted to float.
2620 if (!getLangOpts().NativeHalfType &&
2621 FromBuiltin->getKind() == BuiltinType::Half &&
2622 ToBuiltin->getKind() == BuiltinType::Float)
2623 return true;
2624 }
2625
2626 return false;
2627}
2628
2629/// Determine if a conversion is a complex promotion.
2630///
2631/// A complex promotion is defined as a complex -> complex conversion
2632/// where the conversion between the underlying real types is a
2633/// floating-point or integral promotion.
2635 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2636 if (!FromComplex)
2637 return false;
2638
2639 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2640 if (!ToComplex)
2641 return false;
2642
2643 return IsFloatingPointPromotion(FromComplex->getElementType(),
2644 ToComplex->getElementType()) ||
2645 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2646 ToComplex->getElementType());
2647}
2648
2649/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2650/// the pointer type FromPtr to a pointer to type ToPointee, with the
2651/// same type qualifiers as FromPtr has on its pointee type. ToType,
2652/// if non-empty, will be a pointer to ToType that may or may not have
2653/// the right set of qualifiers on its pointee.
2654///
2655static QualType
2657 QualType ToPointee, QualType ToType,
2658 ASTContext &Context,
2659 bool StripObjCLifetime = false) {
2660 assert((FromPtr->getTypeClass() == Type::Pointer ||
2661 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2662 "Invalid similarly-qualified pointer type");
2663
2664 /// Conversions to 'id' subsume cv-qualifier conversions.
2665 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2666 return ToType.getUnqualifiedType();
2667
2668 QualType CanonFromPointee
2669 = Context.getCanonicalType(FromPtr->getPointeeType());
2670 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2671 Qualifiers Quals = CanonFromPointee.getQualifiers();
2672
2673 if (StripObjCLifetime)
2674 Quals.removeObjCLifetime();
2675
2676 // Exact qualifier match -> return the pointer type we're converting to.
2677 if (CanonToPointee.getLocalQualifiers() == Quals) {
2678 // ToType is exactly what we need. Return it.
2679 if (!ToType.isNull())
2680 return ToType.getUnqualifiedType();
2681
2682 // Build a pointer to ToPointee. It has the right qualifiers
2683 // already.
2684 if (isa<ObjCObjectPointerType>(ToType))
2685 return Context.getObjCObjectPointerType(ToPointee);
2686 return Context.getPointerType(ToPointee);
2687 }
2688
2689 // Just build a canonical type that has the right qualifiers.
2690 QualType QualifiedCanonToPointee
2691 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2692
2693 if (isa<ObjCObjectPointerType>(ToType))
2694 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2695 return Context.getPointerType(QualifiedCanonToPointee);
2696}
2697
2699 bool InOverloadResolution,
2700 ASTContext &Context) {
2701 // Handle value-dependent integral null pointer constants correctly.
2702 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2703 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2705 return !InOverloadResolution;
2706
2707 return Expr->isNullPointerConstant(Context,
2708 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2710}
2711
2712/// IsPointerConversion - Determines whether the conversion of the
2713/// expression From, which has the (possibly adjusted) type FromType,
2714/// can be converted to the type ToType via a pointer conversion (C++
2715/// 4.10). If so, returns true and places the converted type (that
2716/// might differ from ToType in its cv-qualifiers at some level) into
2717/// ConvertedType.
2718///
2719/// This routine also supports conversions to and from block pointers
2720/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2721/// pointers to interfaces. FIXME: Once we've determined the
2722/// appropriate overloading rules for Objective-C, we may want to
2723/// split the Objective-C checks into a different routine; however,
2724/// GCC seems to consider all of these conversions to be pointer
2725/// conversions, so for now they live here. IncompatibleObjC will be
2726/// set if the conversion is an allowed Objective-C conversion that
2727/// should result in a warning.
2729 bool InOverloadResolution,
2730 QualType& ConvertedType,
2731 bool &IncompatibleObjC) {
2732 IncompatibleObjC = false;
2733 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2734 IncompatibleObjC))
2735 return true;
2736
2737 // Conversion from a null pointer constant to any Objective-C pointer type.
2738 if (ToType->isObjCObjectPointerType() &&
2739 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2740 ConvertedType = ToType;
2741 return true;
2742 }
2743
2744 // Blocks: Block pointers can be converted to void*.
2745 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2746 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2747 ConvertedType = ToType;
2748 return true;
2749 }
2750 // Blocks: A null pointer constant can be converted to a block
2751 // pointer type.
2752 if (ToType->isBlockPointerType() &&
2753 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2754 ConvertedType = ToType;
2755 return true;
2756 }
2757
2758 // If the left-hand-side is nullptr_t, the right side can be a null
2759 // pointer constant.
2760 if (ToType->isNullPtrType() &&
2761 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2762 ConvertedType = ToType;
2763 return true;
2764 }
2765
2766 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2767 if (!ToTypePtr)
2768 return false;
2769
2770 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2771 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2772 ConvertedType = ToType;
2773 return true;
2774 }
2775
2776 // Beyond this point, both types need to be pointers
2777 // , including objective-c pointers.
2778 QualType ToPointeeType = ToTypePtr->getPointeeType();
2779 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2780 !getLangOpts().ObjCAutoRefCount) {
2781 ConvertedType = BuildSimilarlyQualifiedPointerType(
2782 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2783 Context);
2784 return true;
2785 }
2786 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2787 if (!FromTypePtr)
2788 return false;
2789
2790 QualType FromPointeeType = FromTypePtr->getPointeeType();
2791
2792 // If the unqualified pointee types are the same, this can't be a
2793 // pointer conversion, so don't do all of the work below.
2794 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2795 return false;
2796
2797 // An rvalue of type "pointer to cv T," where T is an object type,
2798 // can be converted to an rvalue of type "pointer to cv void" (C++
2799 // 4.10p2).
2800 if (FromPointeeType->isIncompleteOrObjectType() &&
2801 ToPointeeType->isVoidType()) {
2802 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2803 ToPointeeType,
2804 ToType, Context,
2805 /*StripObjCLifetime=*/true);
2806 return true;
2807 }
2808
2809 // MSVC allows implicit function to void* type conversion.
2810 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2811 ToPointeeType->isVoidType()) {
2812 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2813 ToPointeeType,
2814 ToType, Context);
2815 return true;
2816 }
2817
2818 // When we're overloading in C, we allow a special kind of pointer
2819 // conversion for compatible-but-not-identical pointee types.
2820 if (!getLangOpts().CPlusPlus &&
2821 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2822 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2823 ToPointeeType,
2824 ToType, Context);
2825 return true;
2826 }
2827
2828 // C++ [conv.ptr]p3:
2829 //
2830 // An rvalue of type "pointer to cv D," where D is a class type,
2831 // can be converted to an rvalue of type "pointer to cv B," where
2832 // B is a base class (clause 10) of D. If B is an inaccessible
2833 // (clause 11) or ambiguous (10.2) base class of D, a program that
2834 // necessitates this conversion is ill-formed. The result of the
2835 // conversion is a pointer to the base class sub-object of the
2836 // derived class object. The null pointer value is converted to
2837 // the null pointer value of the destination type.
2838 //
2839 // Note that we do not check for ambiguity or inaccessibility
2840 // here. That is handled by CheckPointerConversion.
2841 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2842 ToPointeeType->isRecordType() &&
2843 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2844 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2845 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2846 ToPointeeType,
2847 ToType, Context);
2848 return true;
2849 }
2850
2851 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2852 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2853 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2854 ToPointeeType,
2855 ToType, Context);
2856 return true;
2857 }
2858
2859 return false;
2860}
2861
2862/// Adopt the given qualifiers for the given type.
2864 Qualifiers TQs = T.getQualifiers();
2865
2866 // Check whether qualifiers already match.
2867 if (TQs == Qs)
2868 return T;
2869
2870 if (Qs.compatiblyIncludes(TQs))
2871 return Context.getQualifiedType(T, Qs);
2872
2873 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2874}
2875
2876/// isObjCPointerConversion - Determines whether this is an
2877/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2878/// with the same arguments and return values.
2880 QualType& ConvertedType,
2881 bool &IncompatibleObjC) {
2882 if (!getLangOpts().ObjC)
2883 return false;
2884
2885 // The set of qualifiers on the type we're converting from.
2886 Qualifiers FromQualifiers = FromType.getQualifiers();
2887
2888 // First, we handle all conversions on ObjC object pointer types.
2889 const ObjCObjectPointerType* ToObjCPtr =
2890 ToType->getAs<ObjCObjectPointerType>();
2891 const ObjCObjectPointerType *FromObjCPtr =
2892 FromType->getAs<ObjCObjectPointerType>();
2893
2894 if (ToObjCPtr && FromObjCPtr) {
2895 // If the pointee types are the same (ignoring qualifications),
2896 // then this is not a pointer conversion.
2897 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2898 FromObjCPtr->getPointeeType()))
2899 return false;
2900
2901 // Conversion between Objective-C pointers.
2902 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2903 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2904 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2905 if (getLangOpts().CPlusPlus && LHS && RHS &&
2907 FromObjCPtr->getPointeeType()))
2908 return false;
2909 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2910 ToObjCPtr->getPointeeType(),
2911 ToType, Context);
2912 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2913 return true;
2914 }
2915
2916 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2917 // Okay: this is some kind of implicit downcast of Objective-C
2918 // interfaces, which is permitted. However, we're going to
2919 // complain about it.
2920 IncompatibleObjC = true;
2921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2922 ToObjCPtr->getPointeeType(),
2923 ToType, Context);
2924 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2925 return true;
2926 }
2927 }
2928 // Beyond this point, both types need to be C pointers or block pointers.
2929 QualType ToPointeeType;
2930 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2931 ToPointeeType = ToCPtr->getPointeeType();
2932 else if (const BlockPointerType *ToBlockPtr =
2933 ToType->getAs<BlockPointerType>()) {
2934 // Objective C++: We're able to convert from a pointer to any object
2935 // to a block pointer type.
2936 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2937 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2938 return true;
2939 }
2940 ToPointeeType = ToBlockPtr->getPointeeType();
2941 }
2942 else if (FromType->getAs<BlockPointerType>() &&
2943 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2944 // Objective C++: We're able to convert from a block pointer type to a
2945 // pointer to any object.
2946 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2947 return true;
2948 }
2949 else
2950 return false;
2951
2952 QualType FromPointeeType;
2953 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2954 FromPointeeType = FromCPtr->getPointeeType();
2955 else if (const BlockPointerType *FromBlockPtr =
2956 FromType->getAs<BlockPointerType>())
2957 FromPointeeType = FromBlockPtr->getPointeeType();
2958 else
2959 return false;
2960
2961 // If we have pointers to pointers, recursively check whether this
2962 // is an Objective-C conversion.
2963 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2964 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2965 IncompatibleObjC)) {
2966 // We always complain about this conversion.
2967 IncompatibleObjC = true;
2968 ConvertedType = Context.getPointerType(ConvertedType);
2969 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2970 return true;
2971 }
2972 // Allow conversion of pointee being objective-c pointer to another one;
2973 // as in I* to id.
2974 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2975 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2976 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2977 IncompatibleObjC)) {
2978
2979 ConvertedType = Context.getPointerType(ConvertedType);
2980 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2981 return true;
2982 }
2983
2984 // If we have pointers to functions or blocks, check whether the only
2985 // differences in the argument and result types are in Objective-C
2986 // pointer conversions. If so, we permit the conversion (but
2987 // complain about it).
2988 const FunctionProtoType *FromFunctionType
2989 = FromPointeeType->getAs<FunctionProtoType>();
2990 const FunctionProtoType *ToFunctionType
2991 = ToPointeeType->getAs<FunctionProtoType>();
2992 if (FromFunctionType && ToFunctionType) {
2993 // If the function types are exactly the same, this isn't an
2994 // Objective-C pointer conversion.
2995 if (Context.getCanonicalType(FromPointeeType)
2996 == Context.getCanonicalType(ToPointeeType))
2997 return false;
2998
2999 // Perform the quick checks that will tell us whether these
3000 // function types are obviously different.
3001 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3002 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3003 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3004 return false;
3005
3006 bool HasObjCConversion = false;
3007 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3008 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3009 // Okay, the types match exactly. Nothing to do.
3010 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3011 ToFunctionType->getReturnType(),
3012 ConvertedType, IncompatibleObjC)) {
3013 // Okay, we have an Objective-C pointer conversion.
3014 HasObjCConversion = true;
3015 } else {
3016 // Function types are too different. Abort.
3017 return false;
3018 }
3019
3020 // Check argument types.
3021 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3022 ArgIdx != NumArgs; ++ArgIdx) {
3023 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3024 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3025 if (Context.getCanonicalType(FromArgType)
3026 == Context.getCanonicalType(ToArgType)) {
3027 // Okay, the types match exactly. Nothing to do.
3028 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3029 ConvertedType, IncompatibleObjC)) {
3030 // Okay, we have an Objective-C pointer conversion.
3031 HasObjCConversion = true;
3032 } else {
3033 // Argument types are too different. Abort.
3034 return false;
3035 }
3036 }
3037
3038 if (HasObjCConversion) {
3039 // We had an Objective-C conversion. Allow this pointer
3040 // conversion, but complain about it.
3041 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3042 IncompatibleObjC = true;
3043 return true;
3044 }
3045 }
3046
3047 return false;
3048}
3049
3050/// Determine whether this is an Objective-C writeback conversion,
3051/// used for parameter passing when performing automatic reference counting.
3052///
3053/// \param FromType The type we're converting form.
3054///
3055/// \param ToType The type we're converting to.
3056///
3057/// \param ConvertedType The type that will be produced after applying
3058/// this conversion.
3060 QualType &ConvertedType) {
3061 if (!getLangOpts().ObjCAutoRefCount ||
3062 Context.hasSameUnqualifiedType(FromType, ToType))
3063 return false;
3064
3065 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
3066 QualType ToPointee;
3067 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
3068 ToPointee = ToPointer->getPointeeType();
3069 else
3070 return false;
3071
3072 Qualifiers ToQuals = ToPointee.getQualifiers();
3073 if (!ToPointee->isObjCLifetimeType() ||
3075 !ToQuals.withoutObjCLifetime().empty())
3076 return false;
3077
3078 // Argument must be a pointer to __strong to __weak.
3079 QualType FromPointee;
3080 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
3081 FromPointee = FromPointer->getPointeeType();
3082 else
3083 return false;
3084
3085 Qualifiers FromQuals = FromPointee.getQualifiers();
3086 if (!FromPointee->isObjCLifetimeType() ||
3087 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
3088 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
3089 return false;
3090
3091 // Make sure that we have compatible qualifiers.
3093 if (!ToQuals.compatiblyIncludes(FromQuals))
3094 return false;
3095
3096 // Remove qualifiers from the pointee type we're converting from; they
3097 // aren't used in the compatibility check belong, and we'll be adding back
3098 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
3099 FromPointee = FromPointee.getUnqualifiedType();
3100
3101 // The unqualified form of the pointee types must be compatible.
3102 ToPointee = ToPointee.getUnqualifiedType();
3103 bool IncompatibleObjC;
3104 if (Context.typesAreCompatible(FromPointee, ToPointee))
3105 FromPointee = ToPointee;
3106 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
3107 IncompatibleObjC))
3108 return false;
3109
3110 /// Construct the type we're converting to, which is a pointer to
3111 /// __autoreleasing pointee.
3112 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
3113 ConvertedType = Context.getPointerType(FromPointee);
3114 return true;
3115}
3116
3118 QualType& ConvertedType) {
3119 QualType ToPointeeType;
3120 if (const BlockPointerType *ToBlockPtr =
3121 ToType->getAs<BlockPointerType>())
3122 ToPointeeType = ToBlockPtr->getPointeeType();
3123 else
3124 return false;
3125
3126 QualType FromPointeeType;
3127 if (const BlockPointerType *FromBlockPtr =
3128 FromType->getAs<BlockPointerType>())
3129 FromPointeeType = FromBlockPtr->getPointeeType();
3130 else
3131 return false;
3132 // We have pointer to blocks, check whether the only
3133 // differences in the argument and result types are in Objective-C
3134 // pointer conversions. If so, we permit the conversion.
3135
3136 const FunctionProtoType *FromFunctionType
3137 = FromPointeeType->getAs<FunctionProtoType>();
3138 const FunctionProtoType *ToFunctionType
3139 = ToPointeeType->getAs<FunctionProtoType>();
3140
3141 if (!FromFunctionType || !ToFunctionType)
3142 return false;
3143
3144 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3145 return true;
3146
3147 // Perform the quick checks that will tell us whether these
3148 // function types are obviously different.
3149 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3150 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3151 return false;
3152
3153 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3154 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3155 if (FromEInfo != ToEInfo)
3156 return false;
3157
3158 bool IncompatibleObjC = false;
3159 if (Context.hasSameType(FromFunctionType->getReturnType(),
3160 ToFunctionType->getReturnType())) {
3161 // Okay, the types match exactly. Nothing to do.
3162 } else {
3163 QualType RHS = FromFunctionType->getReturnType();
3164 QualType LHS = ToFunctionType->getReturnType();
3165 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3166 !RHS.hasQualifiers() && LHS.hasQualifiers())
3167 LHS = LHS.getUnqualifiedType();
3168
3169 if (Context.hasSameType(RHS,LHS)) {
3170 // OK exact match.
3171 } else if (isObjCPointerConversion(RHS, LHS,
3172 ConvertedType, IncompatibleObjC)) {
3173 if (IncompatibleObjC)
3174 return false;
3175 // Okay, we have an Objective-C pointer conversion.
3176 }
3177 else
3178 return false;
3179 }
3180
3181 // Check argument types.
3182 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3183 ArgIdx != NumArgs; ++ArgIdx) {
3184 IncompatibleObjC = false;
3185 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3186 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3187 if (Context.hasSameType(FromArgType, ToArgType)) {
3188 // Okay, the types match exactly. Nothing to do.
3189 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3190 ConvertedType, IncompatibleObjC)) {
3191 if (IncompatibleObjC)
3192 return false;
3193 // Okay, we have an Objective-C pointer conversion.
3194 } else
3195 // Argument types are too different. Abort.
3196 return false;
3197 }
3198
3200 bool CanUseToFPT, CanUseFromFPT;
3201 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3202 CanUseToFPT, CanUseFromFPT,
3203 NewParamInfos))
3204 return false;
3205
3206 ConvertedType = ToType;
3207 return true;
3208}
3209
3210enum {
3219
3220/// Attempts to get the FunctionProtoType from a Type. Handles
3221/// MemberFunctionPointers properly.
3223 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3224 return FPT;
3225
3226 if (auto *MPT = FromType->getAs<MemberPointerType>())
3227 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3228
3229 return nullptr;
3230}
3231
3232/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3233/// function types. Catches different number of parameter, mismatch in
3234/// parameter types, and different return types.
3236 QualType FromType, QualType ToType) {
3237 // If either type is not valid, include no extra info.
3238 if (FromType.isNull() || ToType.isNull()) {
3239 PDiag << ft_default;
3240 return;
3241 }
3242
3243 // Get the function type from the pointers.
3244 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3245 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3246 *ToMember = ToType->castAs<MemberPointerType>();
3247 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3248 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3249 << QualType(FromMember->getClass(), 0);
3250 return;
3251 }
3252 FromType = FromMember->getPointeeType();
3253 ToType = ToMember->getPointeeType();
3254 }
3255
3256 if (FromType->isPointerType())
3257 FromType = FromType->getPointeeType();
3258 if (ToType->isPointerType())
3259 ToType = ToType->getPointeeType();
3260
3261 // Remove references.
3262 FromType = FromType.getNonReferenceType();
3263 ToType = ToType.getNonReferenceType();
3264
3265 // Don't print extra info for non-specialized template functions.
3266 if (FromType->isInstantiationDependentType() &&
3267 !FromType->getAs<TemplateSpecializationType>()) {
3268 PDiag << ft_default;
3269 return;
3270 }
3271
3272 // No extra info for same types.
3273 if (Context.hasSameType(FromType, ToType)) {
3274 PDiag << ft_default;
3275 return;
3276 }
3277
3278 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3279 *ToFunction = tryGetFunctionProtoType(ToType);
3280
3281 // Both types need to be function types.
3282 if (!FromFunction || !ToFunction) {
3283 PDiag << ft_default;
3284 return;
3285 }
3286
3287 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3288 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3289 << FromFunction->getNumParams();
3290 return;
3291 }
3292
3293 // Handle different parameter types.
3294 unsigned ArgPos;
3295 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3296 PDiag << ft_parameter_mismatch << ArgPos + 1
3297 << ToFunction->getParamType(ArgPos)
3298 << FromFunction->getParamType(ArgPos);
3299 return;
3300 }
3301
3302 // Handle different return type.
3303 if (!Context.hasSameType(FromFunction->getReturnType(),
3304 ToFunction->getReturnType())) {
3305 PDiag << ft_return_type << ToFunction->getReturnType()
3306 << FromFunction->getReturnType();
3307 return;
3308 }
3309
3310 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3311 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3312 << FromFunction->getMethodQuals();
3313 return;
3314 }
3315
3316 // Handle exception specification differences on canonical type (in C++17
3317 // onwards).
3318 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3319 ->isNothrow() !=
3320 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3321 ->isNothrow()) {
3322 PDiag << ft_noexcept;
3323 return;
3324 }
3325
3326 // Unable to find a difference, so add no extra info.
3327 PDiag << ft_default;
3328}
3329
3330/// FunctionParamTypesAreEqual - This routine checks two function proto types
3331/// for equality of their parameter types. Caller has already checked that
3332/// they have same number of parameters. If the parameters are different,
3333/// ArgPos will have the parameter index of the first different parameter.
3334/// If `Reversed` is true, the parameters of `NewType` will be compared in
3335/// reverse order. That's useful if one of the functions is being used as a C++20
3336/// synthesized operator overload with a reversed parameter order.
3338 ArrayRef<QualType> New, unsigned *ArgPos,
3339 bool Reversed) {
3340 assert(llvm::size(Old) == llvm::size(New) &&
3341 "Can't compare parameters of functions with different number of "
3342 "parameters!");
3343
3344 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3345 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3346 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3347
3348 // Ignore address spaces in pointee type. This is to disallow overloading
3349 // on __ptr32/__ptr64 address spaces.
3350 QualType OldType =
3351 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3352 QualType NewType =
3353 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3354
3355 if (!Context.hasSameType(OldType, NewType)) {
3356 if (ArgPos)
3357 *ArgPos = Idx;
3358 return false;
3359 }
3360 }
3361 return true;
3362}
3363
3365 const FunctionProtoType *NewType,
3366 unsigned *ArgPos, bool Reversed) {
3367 return FunctionParamTypesAreEqual(OldType->param_types(),
3368 NewType->param_types(), ArgPos, Reversed);
3369}
3370
3372 const FunctionDecl *NewFunction,
3373 unsigned *ArgPos,
3374 bool Reversed) {
3375
3376 if (OldFunction->getNumNonObjectParams() !=
3377 NewFunction->getNumNonObjectParams())
3378 return false;
3379
3380 unsigned OldIgnore =
3382 unsigned NewIgnore =
3384
3385 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3386 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3387
3388 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3389 NewPT->param_types().slice(NewIgnore),
3390 ArgPos, Reversed);
3391}
3392
3393/// CheckPointerConversion - Check the pointer conversion from the
3394/// expression From to the type ToType. This routine checks for
3395/// ambiguous or inaccessible derived-to-base pointer
3396/// conversions for which IsPointerConversion has already returned
3397/// true. It returns true and produces a diagnostic if there was an
3398/// error, or returns false otherwise.
3400 CastKind &Kind,
3401 CXXCastPath& BasePath,
3402 bool IgnoreBaseAccess,
3403 bool Diagnose) {
3404 QualType FromType = From->getType();
3405 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3406
3407 Kind = CK_BitCast;
3408
3409 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3412 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3413 DiagRuntimeBehavior(From->getExprLoc(), From,
3414 PDiag(diag::warn_impcast_bool_to_null_pointer)
3415 << ToType << From->getSourceRange());
3416 else if (!isUnevaluatedContext())
3417 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3418 << ToType << From->getSourceRange();
3419 }
3420 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3421 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3422 QualType FromPointeeType = FromPtrType->getPointeeType(),
3423 ToPointeeType = ToPtrType->getPointeeType();
3424
3425 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3426 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3427 // We must have a derived-to-base conversion. Check an
3428 // ambiguous or inaccessible conversion.
3429 unsigned InaccessibleID = 0;
3430 unsigned AmbiguousID = 0;
3431 if (Diagnose) {
3432 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3433 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3434 }
3435 if (CheckDerivedToBaseConversion(
3436 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3437 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3438 &BasePath, IgnoreBaseAccess))
3439 return true;
3440
3441 // The conversion was successful.
3442 Kind = CK_DerivedToBase;
3443 }
3444
3445 if (Diagnose && !IsCStyleOrFunctionalCast &&
3446 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3447 assert(getLangOpts().MSVCCompat &&
3448 "this should only be possible with MSVCCompat!");
3449 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3450 << From->getSourceRange();
3451 }
3452 }
3453 } else if (const ObjCObjectPointerType *ToPtrType =
3454 ToType->getAs<ObjCObjectPointerType>()) {
3455 if (const ObjCObjectPointerType *FromPtrType =
3456 FromType->getAs<ObjCObjectPointerType>()) {
3457 // Objective-C++ conversions are always okay.
3458 // FIXME: We should have a different class of conversions for the
3459 // Objective-C++ implicit conversions.
3460 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3461 return false;
3462 } else if (FromType->isBlockPointerType()) {
3463 Kind = CK_BlockPointerToObjCPointerCast;
3464 } else {
3465 Kind = CK_CPointerToObjCPointerCast;
3466 }
3467 } else if (ToType->isBlockPointerType()) {
3468 if (!FromType->isBlockPointerType())
3469 Kind = CK_AnyPointerToBlockPointerCast;
3470 }
3471
3472 // We shouldn't fall into this case unless it's valid for other
3473 // reasons.
3475 Kind = CK_NullToPointer;
3476
3477 return false;
3478}
3479
3480/// IsMemberPointerConversion - Determines whether the conversion of the
3481/// expression From, which has the (possibly adjusted) type FromType, can be
3482/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3483/// If so, returns true and places the converted type (that might differ from
3484/// ToType in its cv-qualifiers at some level) into ConvertedType.
3486 QualType ToType,
3487 bool InOverloadResolution,
3488 QualType &ConvertedType) {
3489 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3490 if (!ToTypePtr)
3491 return false;
3492
3493 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3494 if (From->isNullPointerConstant(Context,
3495 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3497 ConvertedType = ToType;
3498 return true;
3499 }
3500
3501 // Otherwise, both types have to be member pointers.
3502 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3503 if (!FromTypePtr)
3504 return false;
3505
3506 // A pointer to member of B can be converted to a pointer to member of D,
3507 // where D is derived from B (C++ 4.11p2).
3508 QualType FromClass(FromTypePtr->getClass(), 0);
3509 QualType ToClass(ToTypePtr->getClass(), 0);
3510
3511 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3512 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3513 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3514 ToClass.getTypePtr());
3515 return true;
3516 }
3517
3518 return false;
3519}
3520
3521/// CheckMemberPointerConversion - Check the member pointer conversion from the
3522/// expression From to the type ToType. This routine checks for ambiguous or
3523/// virtual or inaccessible base-to-derived member pointer conversions
3524/// for which IsMemberPointerConversion has already returned true. It returns
3525/// true and produces a diagnostic if there was an error, or returns false
3526/// otherwise.
3528 CastKind &Kind,
3529 CXXCastPath &BasePath,
3530 bool IgnoreBaseAccess) {
3531 QualType FromType = From->getType();
3532 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3533 if (!FromPtrType) {
3534 // This must be a null pointer to member pointer conversion
3535 assert(From->isNullPointerConstant(Context,
3537 "Expr must be null pointer constant!");
3538 Kind = CK_NullToMemberPointer;
3539 return false;
3540 }
3541
3542 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3543 assert(ToPtrType && "No member pointer cast has a target type "
3544 "that is not a member pointer.");
3545
3546 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3547 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3548
3549 // FIXME: What about dependent types?
3550 assert(FromClass->isRecordType() && "Pointer into non-class.");
3551 assert(ToClass->isRecordType() && "Pointer into non-class.");
3552
3553 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3554 /*DetectVirtual=*/true);
3555 bool DerivationOkay =
3556 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3557 assert(DerivationOkay &&
3558 "Should not have been called if derivation isn't OK.");
3559 (void)DerivationOkay;
3560
3561 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3562 getUnqualifiedType())) {
3563 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3564 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3565 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3566 return true;
3567 }
3568
3569 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3570 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3571 << FromClass << ToClass << QualType(VBase, 0)
3572 << From->getSourceRange();
3573 return true;
3574 }
3575
3576 if (!IgnoreBaseAccess)
3577 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3578 Paths.front(),
3579 diag::err_downcast_from_inaccessible_base);
3580
3581 // Must be a base to derived member conversion.
3582 BuildBasePathArray(Paths, BasePath);
3583 Kind = CK_BaseToDerivedMemberPointer;
3584 return false;
3585}
3586
3587/// Determine whether the lifetime conversion between the two given
3588/// qualifiers sets is nontrivial.
3590 Qualifiers ToQuals) {
3591 // Converting anything to const __unsafe_unretained is trivial.
3592 if (ToQuals.hasConst() &&
3594 return false;
3595
3596 return true;
3597}
3598
3599/// Perform a single iteration of the loop for checking if a qualification
3600/// conversion is valid.
3601///
3602/// Specifically, check whether any change between the qualifiers of \p
3603/// FromType and \p ToType is permissible, given knowledge about whether every
3604/// outer layer is const-qualified.
3606 bool CStyle, bool IsTopLevel,
3607 bool &PreviousToQualsIncludeConst,
3608 bool &ObjCLifetimeConversion) {
3609 Qualifiers FromQuals = FromType.getQualifiers();
3610 Qualifiers ToQuals = ToType.getQualifiers();
3611
3612 // Ignore __unaligned qualifier.
3613 FromQuals.removeUnaligned();
3614
3615 // Objective-C ARC:
3616 // Check Objective-C lifetime conversions.
3617 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3618 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3619 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3620 ObjCLifetimeConversion = true;
3621 FromQuals.removeObjCLifetime();
3622 ToQuals.removeObjCLifetime();
3623 } else {
3624 // Qualification conversions cannot cast between different
3625 // Objective-C lifetime qualifiers.
3626 return false;
3627 }
3628 }
3629
3630 // Allow addition/removal of GC attributes but not changing GC attributes.
3631 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3632 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3633 FromQuals.removeObjCGCAttr();
3634 ToQuals.removeObjCGCAttr();
3635 }
3636
3637 // -- for every j > 0, if const is in cv 1,j then const is in cv
3638 // 2,j, and similarly for volatile.
3639 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3640 return false;
3641
3642 // If address spaces mismatch:
3643 // - in top level it is only valid to convert to addr space that is a
3644 // superset in all cases apart from C-style casts where we allow
3645 // conversions between overlapping address spaces.
3646 // - in non-top levels it is not a valid conversion.
3647 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3648 (!IsTopLevel ||
3649 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3650 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3651 return false;
3652
3653 // -- if the cv 1,j and cv 2,j are different, then const is in
3654 // every cv for 0 < k < j.
3655 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3656 !PreviousToQualsIncludeConst)
3657 return false;
3658
3659 // The following wording is from C++20, where the result of the conversion
3660 // is T3, not T2.
3661 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3662 // "array of unknown bound of"
3663 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3664 return false;
3665
3666 // -- if the resulting P3,i is different from P1,i [...], then const is
3667 // added to every cv 3_k for 0 < k < i.
3668 if (!CStyle && FromType->isConstantArrayType() &&
3669 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3670 return false;
3671
3672 // Keep track of whether all prior cv-qualifiers in the "to" type
3673 // include const.
3674 PreviousToQualsIncludeConst =
3675 PreviousToQualsIncludeConst && ToQuals.hasConst();
3676 return true;
3677}
3678
3679/// IsQualificationConversion - Determines whether the conversion from
3680/// an rvalue of type FromType to ToType is a qualification conversion
3681/// (C++ 4.4).
3682///
3683/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3684/// when the qualification conversion involves a change in the Objective-C
3685/// object lifetime.
3686bool
3688 bool CStyle, bool &ObjCLifetimeConversion) {
3689 FromType = Context.getCanonicalType(FromType);
3690 ToType = Context.getCanonicalType(ToType);
3691 ObjCLifetimeConversion = false;
3692
3693 // If FromType and ToType are the same type, this is not a
3694 // qualification conversion.
3695 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3696 return false;
3697
3698 // (C++ 4.4p4):
3699 // A conversion can add cv-qualifiers at levels other than the first
3700 // in multi-level pointers, subject to the following rules: [...]
3701 bool PreviousToQualsIncludeConst = true;
3702 bool UnwrappedAnyPointer = false;
3703 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3705 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3706 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3707 return false;
3708 UnwrappedAnyPointer = true;
3709 }
3710
3711 // We are left with FromType and ToType being the pointee types
3712 // after unwrapping the original FromType and ToType the same number
3713 // of times. If we unwrapped any pointers, and if FromType and
3714 // ToType have the same unqualified type (since we checked
3715 // qualifiers above), then this is a qualification conversion.
3716 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3717}
3718
3719/// - Determine whether this is a conversion from a scalar type to an
3720/// atomic type.
3721///
3722/// If successful, updates \c SCS's second and third steps in the conversion
3723/// sequence to finish the conversion.
3724static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3725 bool InOverloadResolution,
3727 bool CStyle) {
3728 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3729 if (!ToAtomic)
3730 return false;
3731
3733 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3734 InOverloadResolution, InnerSCS,
3735 CStyle, /*AllowObjCWritebackConversion=*/false))
3736 return false;
3737
3738 SCS.Second = InnerSCS.Second;
3739 SCS.setToType(1, InnerSCS.getToType(1));
3740 SCS.Third = InnerSCS.Third;
3743 SCS.setToType(2, InnerSCS.getToType(2));
3744 return true;
3745}
3746
3748 CXXConstructorDecl *Constructor,
3749 QualType Type) {
3750 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3751 if (CtorType->getNumParams() > 0) {
3752 QualType FirstArg = CtorType->getParamType(0);
3753 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3754 return true;
3755 }
3756 return false;
3757}
3758
3759static OverloadingResult
3761 CXXRecordDecl *To,
3763 OverloadCandidateSet &CandidateSet,
3764 bool AllowExplicit) {
3766 for (auto *D : S.LookupConstructors(To)) {
3767 auto Info = getConstructorInfo(D);
3768 if (!Info)
3769 continue;
3770
3771 bool Usable = !Info.Constructor->isInvalidDecl() &&
3772 S.isInitListConstructor(Info.Constructor);
3773 if (Usable) {
3774 bool SuppressUserConversions = false;
3775 if (Info.ConstructorTmpl)
3776 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3777 /*ExplicitArgs*/ nullptr, From,
3778 CandidateSet, SuppressUserConversions,
3779 /*PartialOverloading*/ false,
3780 AllowExplicit);
3781 else
3782 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3783 CandidateSet, SuppressUserConversions,
3784 /*PartialOverloading*/ false, AllowExplicit);
3785 }
3786 }
3787
3788 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3789
3791 switch (auto Result =
3792 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3793 case OR_Deleted:
3794 case OR_Success: {
3795 // Record the standard conversion we used and the conversion function.
3796 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3797 QualType ThisType = Constructor->getFunctionObjectParameterType();
3798 // Initializer lists don't have conversions as such.
3800 User.HadMultipleCandidates = HadMultipleCandidates;
3801 User.ConversionFunction = Constructor;
3802 User.FoundConversionFunction = Best->FoundDecl;
3804 User.After.setFromType(ThisType);
3805 User.After.setAllToTypes(ToType);
3806 return Result;
3807 }
3808
3810 return OR_No_Viable_Function;
3811 case OR_Ambiguous:
3812 return OR_Ambiguous;
3813 }
3814
3815 llvm_unreachable("Invalid OverloadResult!");
3816}
3817
3818/// Determines whether there is a user-defined conversion sequence
3819/// (C++ [over.ics.user]) that converts expression From to the type
3820/// ToType. If such a conversion exists, User will contain the
3821/// user-defined conversion sequence that performs such a conversion
3822/// and this routine will return true. Otherwise, this routine returns
3823/// false and User is unspecified.
3824///
3825/// \param AllowExplicit true if the conversion should consider C++0x
3826/// "explicit" conversion functions as well as non-explicit conversion
3827/// functions (C++0x [class.conv.fct]p2).
3828///
3829/// \param AllowObjCConversionOnExplicit true if the conversion should
3830/// allow an extra Objective-C pointer conversion on uses of explicit
3831/// constructors. Requires \c AllowExplicit to also be set.
3832static OverloadingResult
3835 OverloadCandidateSet &CandidateSet,
3836 AllowedExplicit AllowExplicit,
3837 bool AllowObjCConversionOnExplicit) {
3838 assert(AllowExplicit != AllowedExplicit::None ||
3839 !AllowObjCConversionOnExplicit);
3841
3842 // Whether we will only visit constructors.
3843 bool ConstructorsOnly = false;
3844
3845 // If the type we are conversion to is a class type, enumerate its
3846 // constructors.
3847 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3848 // C++ [over.match.ctor]p1:
3849 // When objects of class type are direct-initialized (8.5), or
3850 // copy-initialized from an expression of the same or a
3851 // derived class type (8.5), overload resolution selects the
3852 // constructor. [...] For copy-initialization, the candidate
3853 // functions are all the converting constructors (12.3.1) of
3854 // that class. The argument list is the expression-list within
3855 // the parentheses of the initializer.
3856 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3857 (From->getType()->getAs<RecordType>() &&
3858 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3859 ConstructorsOnly = true;
3860
3861 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3862 // We're not going to find any constructors.
3863 } else if (CXXRecordDecl *ToRecordDecl
3864 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3865
3866 Expr **Args = &From;
3867 unsigned NumArgs = 1;
3868 bool ListInitializing = false;
3869 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3870 // But first, see if there is an init-list-constructor that will work.
3872 S, From, ToType, ToRecordDecl, User, CandidateSet,
3873 AllowExplicit == AllowedExplicit::All);
3875 return Result;
3876 // Never mind.
3877 CandidateSet.clear(
3879
3880 // If we're list-initializing, we pass the individual elements as
3881 // arguments, not the entire list.
3882 Args = InitList->getInits();
3883 NumArgs = InitList->getNumInits();
3884 ListInitializing = true;
3885 }
3886
3887 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3888 auto Info = getConstructorInfo(D);
3889 if (!Info)
3890 continue;
3891
3892 bool Usable = !Info.Constructor->isInvalidDecl();
3893 if (!ListInitializing)
3894 Usable = Usable && Info.Constructor->isConvertingConstructor(
3895 /*AllowExplicit*/ true);
3896 if (Usable) {
3897 bool SuppressUserConversions = !ConstructorsOnly;
3898 // C++20 [over.best.ics.general]/4.5:
3899 // if the target is the first parameter of a constructor [of class
3900 // X] and the constructor [...] is a candidate by [...] the second
3901 // phase of [over.match.list] when the initializer list has exactly
3902 // one element that is itself an initializer list, [...] and the
3903 // conversion is to X or reference to cv X, user-defined conversion
3904 // sequences are not cnosidered.
3905 if (SuppressUserConversions && ListInitializing) {
3906 SuppressUserConversions =
3907 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3908 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3909 ToType);
3910 }
3911 if (Info.ConstructorTmpl)
3913 Info.ConstructorTmpl, Info.FoundDecl,
3914 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3915 CandidateSet, SuppressUserConversions,
3916 /*PartialOverloading*/ false,
3917 AllowExplicit == AllowedExplicit::All);
3918 else
3919 // Allow one user-defined conversion when user specifies a
3920 // From->ToType conversion via an static cast (c-style, etc).
3921 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3922 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3923 SuppressUserConversions,
3924 /*PartialOverloading*/ false,
3925 AllowExplicit == AllowedExplicit::All);
3926 }
3927 }
3928 }
3929 }
3930
3931 // Enumerate conversion functions, if we're allowed to.
3932 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3933 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3934 // No conversion functions from incomplete types.
3935 } else if (const RecordType *FromRecordType =
3936 From->getType()->getAs<RecordType>()) {
3937 if (CXXRecordDecl *FromRecordDecl
3938 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3939 // Add all of the conversion functions as candidates.
3940 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3941 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3942 DeclAccessPair FoundDecl = I.getPair();
3943 NamedDecl *D = FoundDecl.getDecl();
3944 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3945 if (isa<UsingShadowDecl>(D))
3946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3947
3948 CXXConversionDecl *Conv;
3949 FunctionTemplateDecl *ConvTemplate;
3950 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3951 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3952 else
3953 Conv = cast<CXXConversionDecl>(D);
3954
3955 if (ConvTemplate)
3957 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3958 CandidateSet, AllowObjCConversionOnExplicit,
3959 AllowExplicit != AllowedExplicit::None);
3960 else
3961 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3962 CandidateSet, AllowObjCConversionOnExplicit,
3963 AllowExplicit != AllowedExplicit::None);
3964 }
3965 }
3966 }
3967
3968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3969
3971 switch (auto Result =
3972 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3973 case OR_Success:
3974 case OR_Deleted:
3975 // Record the standard conversion we used and the conversion function.
3976 if (CXXConstructorDecl *Constructor
3977 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3978 // C++ [over.ics.user]p1:
3979 // If the user-defined conversion is specified by a
3980 // constructor (12.3.1), the initial standard conversion
3981 // sequence converts the source type to the type required by
3982 // the argument of the constructor.
3983 //
3984 if (isa<InitListExpr>(From)) {
3985 // Initializer lists don't have conversions as such.
3987 } else {
3988 if (Best->Conversions[0].isEllipsis())
3989 User.EllipsisConversion = true;
3990 else {
3991 User.Before = Best->Conversions[0].Standard;
3992 User.EllipsisConversion = false;
3993 }
3994 }
3995 User.HadMultipleCandidates = HadMultipleCandidates;
3996 User.ConversionFunction = Constructor;
3997 User.FoundConversionFunction = Best->FoundDecl;
3999 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4000 User.After.setAllToTypes(ToType);
4001 return Result;
4002 }
4003 if (CXXConversionDecl *Conversion
4004 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4005 // C++ [over.ics.user]p1:
4006 //
4007 // [...] If the user-defined conversion is specified by a
4008 // conversion function (12.3.2), the initial standard
4009 // conversion sequence converts the source type to the
4010 // implicit object parameter of the conversion function.
4011 User.Before = Best->Conversions[0].Standard;
4012 User.HadMultipleCandidates = HadMultipleCandidates;
4013 User.ConversionFunction = Conversion;
4014 User.FoundConversionFunction = Best->FoundDecl;
4015 User.EllipsisConversion = false;
4016
4017 // C++ [over.ics.user]p2:
4018 // The second standard conversion sequence converts the
4019 // result of the user-defined conversion to the target type
4020 // for the sequence. Since an implicit conversion sequence
4021 // is an initialization, the special rules for
4022 // initialization by user-defined conversion apply when
4023 // selecting the best user-defined conversion for a
4024 // user-defined conversion sequence (see 13.3.3 and
4025 // 13.3.3.1).
4026 User.After = Best->FinalConversion;
4027 return Result;
4028 }
4029 llvm_unreachable("Not a constructor or conversion function?");
4030
4032 return OR_No_Viable_Function;
4033
4034 case OR_Ambiguous:
4035 return OR_Ambiguous;
4036 }
4037
4038 llvm_unreachable("Invalid OverloadResult!");
4039}
4040
4041bool
4044 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4046 OverloadingResult OvResult =
4047 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4048 CandidateSet, AllowedExplicit::None, false);
4049
4050 if (!(OvResult == OR_Ambiguous ||
4051 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4052 return false;
4053
4054 auto Cands = CandidateSet.CompleteCandidates(
4055 *this,
4057 From);
4058 if (OvResult == OR_Ambiguous)
4059 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4060 << From->getType() << ToType << From->getSourceRange();
4061 else { // OR_No_Viable_Function && !CandidateSet.empty()
4062 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4063 diag::err_typecheck_nonviable_condition_incomplete,
4064 From->getType(), From->getSourceRange()))
4065 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4066 << false << From->getType() << From->getSourceRange() << ToType;
4067 }
4068
4069 CandidateSet.NoteCandidates(
4070 *this, From, Cands);
4071 return true;
4072}
4073
4074// Helper for compareConversionFunctions that gets the FunctionType that the
4075// conversion-operator return value 'points' to, or nullptr.
4076static const FunctionType *
4078 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4079 const PointerType *RetPtrTy =
4080 ConvFuncTy->getReturnType()->getAs<PointerType>();
4081
4082 if (!RetPtrTy)
4083 return nullptr;
4084
4085 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4086}
4087
4088/// Compare the user-defined conversion functions or constructors
4089/// of two user-defined conversion sequences to determine whether any ordering
4090/// is possible.
4093 FunctionDecl *Function2) {
4094 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4095 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4096 if (!Conv1 || !Conv2)
4098
4099 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4101
4102 // Objective-C++:
4103 // If both conversion functions are implicitly-declared conversions from
4104 // a lambda closure type to a function pointer and a block pointer,
4105 // respectively, always prefer the conversion to a function pointer,
4106 // because the function pointer is more lightweight and is more likely
4107 // to keep code working.
4108 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4109 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4110 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4111 if (Block1 != Block2)
4112 return Block1 ? ImplicitConversionSequence::Worse
4114 }
4115
4116 // In order to support multiple calling conventions for the lambda conversion
4117 // operator (such as when the free and member function calling convention is
4118 // different), prefer the 'free' mechanism, followed by the calling-convention
4119 // of operator(). The latter is in place to support the MSVC-like solution of
4120 // defining ALL of the possible conversions in regards to calling-convention.
4121 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4122 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4123
4124 if (Conv1FuncRet && Conv2FuncRet &&
4125 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4126 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4127 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4128
4129 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4130 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4131
4132 CallingConv CallOpCC =
4133 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4135 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4137 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4138
4139 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4140 for (CallingConv CC : PrefOrder) {
4141 if (Conv1CC == CC)
4143 if (Conv2CC == CC)
4145 }
4146 }
4147
4149}
4150
4152 const ImplicitConversionSequence &ICS) {
4154 (ICS.isUserDefined() &&
4156}
4157
4158/// CompareImplicitConversionSequences - Compare two implicit
4159/// conversion sequences to determine whether one is better than the
4160/// other or if they are indistinguishable (C++ 13.3.3.2).
4163 const ImplicitConversionSequence& ICS1,
4164 const ImplicitConversionSequence& ICS2)
4165{
4166 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4167 // conversion sequences (as defined in 13.3.3.1)
4168 // -- a standard conversion sequence (13.3.3.1.1) is a better
4169 // conversion sequence than a user-defined conversion sequence or
4170 // an ellipsis conversion sequence, and
4171 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4172 // conversion sequence than an ellipsis conversion sequence
4173 // (13.3.3.1.3).
4174 //
4175 // C++0x [over.best.ics]p10:
4176 // For the purpose of ranking implicit conversion sequences as
4177 // described in 13.3.3.2, the ambiguous conversion sequence is
4178 // treated as a user-defined sequence that is indistinguishable
4179 // from any other user-defined conversion sequence.
4180
4181 // String literal to 'char *' conversion has been deprecated in C++03. It has
4182 // been removed from C++11. We still accept this conversion, if it happens at
4183 // the best viable function. Otherwise, this conversion is considered worse
4184 // than ellipsis conversion. Consider this as an extension; this is not in the
4185 // standard. For example:
4186 //
4187 // int &f(...); // #1
4188 // void f(char*); // #2
4189 // void g() { int &r = f("foo"); }
4190 //
4191 // In C++03, we pick #2 as the best viable function.
4192 // In C++11, we pick #1 as the best viable function, because ellipsis
4193 // conversion is better than string-literal to char* conversion (since there
4194 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4195 // convert arguments, #2 would be the best viable function in C++11.
4196 // If the best viable function has this conversion, a warning will be issued
4197 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4198
4199 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4202 // Ill-formedness must not differ
4203 ICS1.isBad() == ICS2.isBad())
4207
4208 if (ICS1.getKindRank() < ICS2.getKindRank())
4210 if (ICS2.getKindRank() < ICS1.getKindRank())
4212
4213 // The following checks require both conversion sequences to be of
4214 // the same kind.
4215 if (ICS1.getKind() != ICS2.getKind())
4217
4220
4221 // Two implicit conversion sequences of the same form are
4222 // indistinguishable conversion sequences unless one of the
4223 // following rules apply: (C++ 13.3.3.2p3):
4224
4225 // List-initialization sequence L1 is a better conversion sequence than
4226 // list-initialization sequence L2 if:
4227 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4228 // if not that,
4229 // — L1 and L2 convert to arrays of the same element type, and either the
4230 // number of elements n_1 initialized by L1 is less than the number of
4231 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4232 // an array of unknown bound and L1 does not,
4233 // even if one of the other rules in this paragraph would otherwise apply.
4234 if (!ICS1.isBad()) {
4235 bool StdInit1 = false, StdInit2 = false;
4238 nullptr);
4241 nullptr);
4242 if (StdInit1 != StdInit2)
4243 return StdInit1 ? ImplicitConversionSequence::Better
4245
4248 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4250 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4252 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4253 CAT2->getElementType())) {
4254 // Both to arrays of the same element type
4255 if (CAT1->getSize() != CAT2->getSize())
4256 // Different sized, the smaller wins
4257 return CAT1->getSize().ult(CAT2->getSize())
4262 // One is incomplete, it loses
4266 }
4267 }
4268 }
4269
4270 if (ICS1.isStandard())
4271 // Standard conversion sequence S1 is a better conversion sequence than
4272 // standard conversion sequence S2 if [...]
4274 ICS1.Standard, ICS2.Standard);
4275 else if (ICS1.isUserDefined()) {
4276 // User-defined conversion sequence U1 is a better conversion
4277 // sequence than another user-defined conversion sequence U2 if
4278 // they contain the same user-defined conversion function or
4279 // constructor and if the second standard conversion sequence of
4280 // U1 is better than the second standard conversion sequence of
4281 // U2 (C++ 13.3.3.2p3).
4285 ICS1.UserDefined.After,
4286 ICS2.UserDefined.After);
4287 else
4291 }
4292
4293 return Result;
4294}
4295
4296// Per 13.3.3.2p3, compare the given standard conversion sequences to
4297// determine if one is a proper subset of the other.
4300 const StandardConversionSequence& SCS1,
4301 const StandardConversionSequence& SCS2) {
4304
4305 // the identity conversion sequence is considered to be a subsequence of
4306 // any non-identity conversion sequence
4307 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4309 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4311
4312 if (SCS1.Second != SCS2.Second) {
4313 if (SCS1.Second == ICK_Identity)
4315 else if (SCS2.Second == ICK_Identity)
4317 else
4319 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4321
4322 if (SCS1.Third == SCS2.Third) {
4323 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4325 }
4326
4327 if (SCS1.Third == ICK_Identity)
4331
4332 if (SCS2.Third == ICK_Identity)
4336
4338}
4339
4340/// Determine whether one of the given reference bindings is better
4341/// than the other based on what kind of bindings they are.
4342static bool
4344 const StandardConversionSequence &SCS2) {
4345 // C++0x [over.ics.rank]p3b4:
4346 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4347 // implicit object parameter of a non-static member function declared
4348 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4349 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4350 // lvalue reference to a function lvalue and S2 binds an rvalue
4351 // reference*.
4352 //
4353 // FIXME: Rvalue references. We're going rogue with the above edits,
4354 // because the semantics in the current C++0x working paper (N3225 at the
4355 // time of this writing) break the standard definition of std::forward
4356 // and std::reference_wrapper when dealing with references to functions.
4357 // Proposed wording changes submitted to CWG for consideration.
4360 return false;
4361
4362 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4363 SCS2.IsLvalueReference) ||
4366}
4367
4369 None,
4372};
4373
4374/// Returns kind of fixed enum promotion the \a SCS uses.
4375static FixedEnumPromotion
4377
4378 if (SCS.Second != ICK_Integral_Promotion)
4379 return FixedEnumPromotion::None;
4380
4381 QualType FromType = SCS.getFromType();
4382 if (!FromType->isEnumeralType())
4383 return FixedEnumPromotion::None;
4384
4385 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4386 if (!Enum->isFixed())
4387 return FixedEnumPromotion::None;
4388
4389 QualType UnderlyingType = Enum->getIntegerType();
4390 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4391 return FixedEnumPromotion::ToUnderlyingType;
4392
4393 return FixedEnumPromotion::ToPromotedUnderlyingType;
4394}
4395
4396/// CompareStandardConversionSequences - Compare two standard
4397/// conversion sequences to determine whether one is better than the
4398/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4401 const StandardConversionSequence& SCS1,
4402 const StandardConversionSequence& SCS2)
4403{
4404 // Standard conversion sequence S1 is a better conversion sequence
4405 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4406
4407 // -- S1 is a proper subsequence of S2 (comparing the conversion
4408 // sequences in the canonical form defined by 13.3.3.1.1,
4409 // excluding any Lvalue Transformation; the identity conversion
4410 // sequence is considered to be a subsequence of any
4411 // non-identity conversion sequence) or, if not that,
4414 return CK;
4415
4416 // -- the rank of S1 is better than the rank of S2 (by the rules
4417 // defined below), or, if not that,
4418 ImplicitConversionRank Rank1 = SCS1.getRank();
4419 ImplicitConversionRank Rank2 = SCS2.getRank();
4420 if (Rank1 < Rank2)
4422 else if (Rank2 < Rank1)
4424
4425 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4426 // are indistinguishable unless one of the following rules
4427 // applies:
4428
4429 // A conversion that is not a conversion of a pointer, or
4430 // pointer to member, to bool is better than another conversion
4431 // that is such a conversion.
4433 return SCS2.isPointerConversionToBool()
4436
4437 // C++14 [over.ics.rank]p4b2:
4438 // This is retroactively applied to C++11 by CWG 1601.
4439 //
4440 // A conversion that promotes an enumeration whose underlying type is fixed
4441 // to its underlying type is better than one that promotes to the promoted
4442 // underlying type, if the two are different.
4445 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4446 FEP1 != FEP2)
4447 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4450
4451 // C++ [over.ics.rank]p4b2:
4452 //
4453 // If class B is derived directly or indirectly from class A,
4454 // conversion of B* to A* is better than conversion of B* to
4455 // void*, and conversion of A* to void* is better than conversion
4456 // of B* to void*.
4457 bool SCS1ConvertsToVoid
4459 bool SCS2ConvertsToVoid
4461 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4462 // Exactly one of the conversion sequences is a conversion to
4463 // a void pointer; it's the worse conversion.
4464 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4466 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4467 // Neither conversion sequence converts to a void pointer; compare
4468 // their derived-to-base conversions.
4470 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4471 return DerivedCK;
4472 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4473 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4474 // Both conversion sequences are conversions to void
4475 // pointers. Compare the source types to determine if there's an
4476 // inheritance relationship in their sources.
4477 QualType FromType1 = SCS1.getFromType();
4478 QualType FromType2 = SCS2.getFromType();
4479
4480 // Adjust the types we're converting from via the array-to-pointer
4481 // conversion, if we need to.
4482 if (SCS1.First == ICK_Array_To_Pointer)
4483 FromType1 = S.Context.getArrayDecayedType(FromType1);
4484 if (SCS2.First == ICK_Array_To_Pointer)
4485 FromType2 = S.Context.getArrayDecayedType(FromType2);
4486
4487 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4488 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4489
4490 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4492 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4494
4495 // Objective-C++: If one interface is more specific than the
4496 // other, it is the better one.
4497 const ObjCObjectPointerType* FromObjCPtr1
4498 = FromType1->getAs<ObjCObjectPointerType>();
4499 const ObjCObjectPointerType* FromObjCPtr2
4500 = FromType2->getAs<ObjCObjectPointerType>();
4501 if (FromObjCPtr1 && FromObjCPtr2) {
4502 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4503 FromObjCPtr2);
4504 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4505 FromObjCPtr1);
4506 if (AssignLeft != AssignRight) {
4507 return AssignLeft? ImplicitConversionSequence::Better
4509 }
4510 }
4511 }
4512
4513 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4514 // Check for a better reference binding based on the kind of bindings.
4515 if (isBetterReferenceBindingKind(SCS1, SCS2))
4517 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4519 }
4520
4521 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4522 // bullet 3).
4524 = CompareQualificationConversions(S, SCS1, SCS2))
4525 return QualCK;
4526
4527 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4528 // C++ [over.ics.rank]p3b4:
4529 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4530 // which the references refer are the same type except for
4531 // top-level cv-qualifiers, and the type to which the reference
4532 // initialized by S2 refers is more cv-qualified than the type
4533 // to which the reference initialized by S1 refers.
4534 QualType T1 = SCS1.getToType(2);
4535 QualType T2 = SCS2.getToType(2);
4536 T1 = S.Context.getCanonicalType(T1);
4537 T2 = S.Context.getCanonicalType(T2);
4538 Qualifiers T1Quals, T2Quals;
4539 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4540 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4541 if (UnqualT1 == UnqualT2) {
4542 // Objective-C++ ARC: If the references refer to objects with different
4543 // lifetimes, prefer bindings that don't change lifetime.
4549 }
4550
4551 // If the type is an array type, promote the element qualifiers to the
4552 // type for comparison.
4553 if (isa<ArrayType>(T1) && T1Quals)
4554 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4555 if (isa<ArrayType>(T2) && T2Quals)
4556 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4557 if (T2.isMoreQualifiedThan(T1))
4559 if (T1.isMoreQualifiedThan(T2))
4561 }
4562 }
4563
4564 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4565 // floating-to-integral conversion if the integral conversion
4566 // is between types of the same size.
4567 // For example:
4568 // void f(float);
4569 // void f(int);
4570 // int main {
4571 // long a;
4572 // f(a);
4573 // }
4574 // Here, MSVC will call f(int) instead of generating a compile error
4575 // as clang will do in standard mode.
4576 if (S.getLangOpts().MSVCCompat &&
4579 SCS2.Second == ICK_Floating_Integral &&
4580 S.Context.getTypeSize(SCS1.getFromType()) ==
4581 S.Context.getTypeSize(SCS1.getToType(2)))
4583
4584 // Prefer a compatible vector conversion over a lax vector conversion
4585 // For example:
4586 //
4587 // typedef float __v4sf __attribute__((__vector_size__(16)));
4588 // void f(vector float);
4589 // void f(vector signed int);
4590 // int main() {
4591 // __v4sf a;
4592 // f(a);
4593 // }
4594 // Here, we'd like to choose f(vector float) and not
4595 // report an ambiguous call error
4596 if (SCS1.Second == ICK_Vector_Conversion &&
4597 SCS2.Second == ICK_Vector_Conversion) {
4598 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4599 SCS1.getFromType(), SCS1.getToType(2));
4600 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4601 SCS2.getFromType(), SCS2.getToType(2));
4602
4603 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4604 return SCS1IsCompatibleVectorConversion
4607 }
4608
4609 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4611 bool SCS1IsCompatibleSVEVectorConversion =
4613 bool SCS2IsCompatibleSVEVectorConversion =
4615
4616 if (SCS1IsCompatibleSVEVectorConversion !=
4617 SCS2IsCompatibleSVEVectorConversion)
4618 return SCS1IsCompatibleSVEVectorConversion
4621 }
4622
4623 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4625 bool SCS1IsCompatibleRVVVectorConversion =
4627 bool SCS2IsCompatibleRVVVectorConversion =
4629
4630 if (SCS1IsCompatibleRVVVectorConversion !=
4631 SCS2IsCompatibleRVVVectorConversion)
4632 return SCS1IsCompatibleRVVVectorConversion
4635 }
4636
4638}
4639
4640/// CompareQualificationConversions - Compares two standard conversion
4641/// sequences to determine whether they can be ranked based on their
4642/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4645 const StandardConversionSequence& SCS1,
4646 const StandardConversionSequence& SCS2) {
4647 // C++ [over.ics.rank]p3:
4648 // -- S1 and S2 differ only in their qualification conversion and
4649 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4650 // [C++98]
4651 // [...] and the cv-qualification signature of type T1 is a proper subset
4652 // of the cv-qualification signature of type T2, and S1 is not the
4653 // deprecated string literal array-to-pointer conversion (4.2).
4654 // [C++2a]
4655 // [...] where T1 can be converted to T2 by a qualification conversion.
4656 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4657 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4659
4660 // FIXME: the example in the standard doesn't use a qualification
4661 // conversion (!)
4662 QualType T1 = SCS1.getToType(2);
4663 QualType T2 = SCS2.getToType(2);
4664 T1 = S.Context.getCanonicalType(T1);
4665 T2 = S.Context.getCanonicalType(T2);
4666 assert(!T1->isReferenceType() && !T2->isReferenceType());
4667 Qualifiers T1Quals, T2Quals;
4668 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4669 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4670
4671 // If the types are the same, we won't learn anything by unwrapping
4672 // them.
4673 if (UnqualT1 == UnqualT2)
4675
4676 // Don't ever prefer a standard conversion sequence that uses the deprecated
4677 // string literal array to pointer conversion.
4678 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4679 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4680
4681 // Objective-C++ ARC:
4682 // Prefer qualification conversions not involving a change in lifetime
4683 // to qualification conversions that do change lifetime.
4686 CanPick1 = false;
4689 CanPick2 = false;
4690
4691 bool ObjCLifetimeConversion;
4692 if (CanPick1 &&
4693 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4694 CanPick1 = false;
4695 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4696 // directions, so we can't short-cut this second check in general.
4697 if (CanPick2 &&
4698 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4699 CanPick2 = false;
4700
4701 if (CanPick1 != CanPick2)
4702 return CanPick1 ? ImplicitConversionSequence::Better
4705}
4706
4707/// CompareDerivedToBaseConversions - Compares two standard conversion
4708/// sequences to determine whether they can be ranked based on their
4709/// various kinds of derived-to-base conversions (C++
4710/// [over.ics.rank]p4b3). As part of these checks, we also look at
4711/// conversions between Objective-C interface types.
4714 const StandardConversionSequence& SCS1,
4715 const StandardConversionSequence& SCS2) {
4716 QualType FromType1 = SCS1.getFromType();
4717 QualType ToType1 = SCS1.getToType(1);
4718 QualType FromType2 = SCS2.getFromType();
4719 QualType ToType2 = SCS2.getToType(1);
4720
4721 // Adjust the types we're converting from via the array-to-pointer
4722 // conversion, if we need to.
4723 if (SCS1.First == ICK_Array_To_Pointer)
4724 FromType1 = S.Context.getArrayDecayedType(FromType1);
4725 if (SCS2.First == ICK_Array_To_Pointer)
4726 FromType2 = S.Context.getArrayDecayedType(FromType2);
4727
4728 // Canonicalize all of the types.
4729 FromType1 = S.Context.getCanonicalType(FromType1);
4730 ToType1 = S.Context.getCanonicalType(ToType1);
4731 FromType2 = S.Context.getCanonicalType(FromType2);
4732 ToType2 = S.Context.getCanonicalType(ToType2);
4733
4734 // C++ [over.ics.rank]p4b3:
4735 //
4736 // If class B is derived directly or indirectly from class A and
4737 // class C is derived directly or indirectly from B,
4738 //
4739 // Compare based on pointer conversions.
4740 if (SCS1.Second == ICK_Pointer_Conversion &&
4742 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4743 FromType1->isPointerType() && FromType2->isPointerType() &&
4744 ToType1->isPointerType() && ToType2->isPointerType()) {
4745 QualType FromPointee1 =
4746 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4747 QualType ToPointee1 =
4748 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4749 QualType FromPointee2 =
4750 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4751 QualType ToPointee2 =
4752 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4753
4754 // -- conversion of C* to B* is better than conversion of C* to A*,
4755 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4756 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4758 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4760 }
4761
4762 // -- conversion of B* to A* is better than conversion of C* to A*,
4763 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4764 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4766 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4768 }
4769 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4771 const ObjCObjectPointerType *FromPtr1
4772 = FromType1->getAs<ObjCObjectPointerType>();
4773 const ObjCObjectPointerType *FromPtr2
4774 = FromType2->getAs<ObjCObjectPointerType>();
4775 const ObjCObjectPointerType *ToPtr1
4776 = ToType1->getAs<ObjCObjectPointerType>();
4777 const ObjCObjectPointerType *ToPtr2
4778 = ToType2->getAs<ObjCObjectPointerType>();
4779
4780 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4781 // Apply the same conversion ranking rules for Objective-C pointer types
4782 // that we do for C++ pointers to class types. However, we employ the
4783 // Objective-C pseudo-subtyping relationship used for assignment of
4784 // Objective-C pointer types.
4785 bool FromAssignLeft
4786 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4787 bool FromAssignRight
4788 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4789 bool ToAssignLeft
4790 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4791 bool ToAssignRight
4792 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4793
4794 // A conversion to an a non-id object pointer type or qualified 'id'
4795 // type is better than a conversion to 'id'.
4796 if (ToPtr1->isObjCIdType() &&
4797 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4799 if (ToPtr2->isObjCIdType() &&
4800 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4802
4803 // A conversion to a non-id object pointer type is better than a
4804 // conversion to a qualified 'id' type
4805 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4807 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4809
4810 // A conversion to an a non-Class object pointer type or qualified 'Class'
4811 // type is better than a conversion to 'Class'.
4812 if (ToPtr1->isObjCClassType() &&
4813 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4815 if (ToPtr2->isObjCClassType() &&
4816 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4818
4819 // A conversion to a non-Class object pointer type is better than a
4820 // conversion to a qualified 'Class' type.
4821 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4823 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4825
4826 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4827 if (S.Context.hasSameType(FromType1, FromType2) &&
4828 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4829 (ToAssignLeft != ToAssignRight)) {
4830 if (FromPtr1->isSpecialized()) {
4831 // "conversion of B<A> * to B * is better than conversion of B * to
4832 // C *.
4833 bool IsFirstSame =
4834 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4835 bool IsSecondSame =
4836 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4837 if (IsFirstSame) {
4838 if (!IsSecondSame)
4840 } else if (IsSecondSame)
4842 }
4843 return ToAssignLeft? ImplicitConversionSequence::Worse
4845 }
4846
4847 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4848 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4849 (FromAssignLeft != FromAssignRight))
4850 return FromAssignLeft? ImplicitConversionSequence::Better
4852 }
4853 }
4854
4855 // Ranking of member-pointer types.
4856 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4857 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4858 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4859 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4860 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4861 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4862 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4863 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4864 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4865 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4866 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4867 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4868 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4869 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4870 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4871 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4872 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4873 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4875 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4877 }
4878 // conversion of B::* to C::* is better than conversion of A::* to C::*
4879 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4880 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4882 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4884 }
4885 }
4886
4887 if (SCS1.Second == ICK_Derived_To_Base) {
4888 // -- conversion of C to B is better than conversion of C to A,
4889 // -- binding of an expression of type C to a reference of type
4890 // B& is better than binding an expression of type C to a
4891 // reference of type A&,
4892 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4893 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4894 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4896 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4898 }
4899
4900 // -- conversion of B to A is better than conversion of C to A.
4901 // -- binding of an expression of type B to a reference of type
4902 // A& is better than binding an expression of type C to a
4903 // reference of type A&,
4904 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4905 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4906 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4908 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4910 }
4911 }
4912
4914}
4915
4917 if (!T.getQualifiers().hasUnaligned())
4918 return T;
4919
4920 Qualifiers Q;
4921 T = Ctx.getUnqualifiedArrayType(T, Q);
4922 Q.removeUnaligned();
4923 return Ctx.getQualifiedType(T, Q);
4924}
4925
4926/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4927/// determine whether they are reference-compatible,
4928/// reference-related, or incompatible, for use in C++ initialization by
4929/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4930/// type, and the first type (T1) is the pointee type of the reference
4931/// type being initialized.
4934 QualType OrigT1, QualType OrigT2,
4935 ReferenceConversions *ConvOut) {
4936 assert(!OrigT1->isReferenceType() &&
4937 "T1 must be the pointee type of the reference type");
4938 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4939
4940 QualType T1 = Context.getCanonicalType(OrigT1);
4941 QualType T2 = Context.getCanonicalType(OrigT2);
4942 Qualifiers T1Quals, T2Quals;
4943 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4944 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4945
4946 ReferenceConversions ConvTmp;
4947 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4948 Conv = ReferenceConversions();
4949
4950 // C++2a [dcl.init.ref]p4:
4951 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4952 // reference-related to "cv2 T2" if T1 is similar to T2, or
4953 // T1 is a base class of T2.
4954 // "cv1 T1" is reference-compatible with "cv2 T2" if
4955 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4956 // "pointer to cv1 T1" via a standard conversion sequence.
4957
4958 // Check for standard conversions we can apply to pointers: derived-to-base
4959 // conversions, ObjC pointer conversions, and function pointer conversions.
4960 // (Qualification conversions are checked last.)
4961 QualType ConvertedT2;
4962 if (UnqualT1 == UnqualT2) {
4963 // Nothing to do.
4964 } else if (isCompleteType(Loc, OrigT2) &&
4965 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4966 Conv |= ReferenceConversions::DerivedToBase;
4967 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4968 UnqualT2->isObjCObjectOrInterfaceType() &&
4969 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4970 Conv |= ReferenceConversions::ObjC;
4971 else if (UnqualT2->isFunctionType() &&
4972 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4973 Conv |= ReferenceConversions::Function;
4974 // No need to check qualifiers; function types don't have them.
4975 return Ref_Compatible;
4976 }
4977 bool ConvertedReferent = Conv != 0;
4978
4979 // We can have a qualification conversion. Compute whether the types are
4980 // similar at the same time.
4981 bool PreviousToQualsIncludeConst = true;
4982 bool TopLevel = true;
4983 do {
4984 if (T1 == T2)
4985 break;
4986
4987 // We will need a qualification conversion.
4988 Conv |= ReferenceConversions::Qualification;
4989
4990 // Track whether we performed a qualification conversion anywhere other
4991 // than the top level. This matters for ranking reference bindings in
4992 // overload resolution.
4993 if (!TopLevel)
4994 Conv |= ReferenceConversions::NestedQualification;
4995
4996 // MS compiler ignores __unaligned qualifier for references; do the same.
4997 T1 = withoutUnaligned(Context, T1);
4998 T2 = withoutUnaligned(Context, T2);
4999
5000 // If we find a qualifier mismatch, the types are not reference-compatible,
5001 // but are still be reference-related if they're similar.
5002 bool ObjCLifetimeConversion = false;
5003 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5004 PreviousToQualsIncludeConst,
5005 ObjCLifetimeConversion))
5006 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5007 ? Ref_Related
5008 : Ref_Incompatible;
5009
5010 // FIXME: Should we track this for any level other than the first?
5011 if (ObjCLifetimeConversion)
5012 Conv |= ReferenceConversions::ObjCLifetime;
5013
5014 TopLevel = false;
5015 } while (Context.UnwrapSimilarTypes(T1, T2));
5016
5017 // At this point, if the types are reference-related, we must either have the
5018 // same inner type (ignoring qualifiers), or must have already worked out how
5019 // to convert the referent.
5020 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5021 ? Ref_Compatible
5022 : Ref_Incompatible;
5023}
5024
5025/// Look for a user-defined conversion to a value reference-compatible
5026/// with DeclType. Return true if something definite is found.
5027static bool
5029 QualType DeclType, SourceLocation DeclLoc,
5030 Expr *Init, QualType T2, bool AllowRvalues,
5031 bool AllowExplicit) {
5032 assert(T2->isRecordType() && "Can only find conversions of record types.");
5033 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5034
5035 OverloadCandidateSet CandidateSet(
5037 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5038 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5039 NamedDecl *D = *I;
5040 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5041 if (isa<UsingShadowDecl>(D))
5042 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5043
5044 FunctionTemplateDecl *ConvTemplate
5045 = dyn_cast<FunctionTemplateDecl>(D);
5046 CXXConversionDecl *Conv;
5047 if (ConvTemplate)
5048 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5049 else
5050 Conv = cast<CXXConversionDecl>(D);
5051
5052 if (AllowRvalues) {
5053 // If we are initializing an rvalue reference, don't permit conversion
5054 // functions that return lvalues.
5055 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5056 const ReferenceType *RefType
5058 if (RefType && !RefType->getPointeeType()->isFunctionType())
5059 continue;
5060 }
5061
5062 if (!ConvTemplate &&
5064 DeclLoc,
5065 Conv->getConversionType()
5070 continue;
5071 } else {
5072 // If the conversion function doesn't return a reference type,
5073 // it can't be considered for this conversion. An rvalue reference
5074 // is only acceptable if its referencee is a function type.
5075
5076 const ReferenceType *RefType =
5078 if (!RefType ||
5079 (!RefType->isLValueReferenceType() &&
5080 !RefType->getPointeeType()->isFunctionType()))
5081 continue;
5082 }
5083
5084 if (ConvTemplate)
5086 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5087 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5088 else
5090 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5091 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5092 }
5093
5094 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5095
5097 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5098 case OR_Success:
5099 // C++ [over.ics.ref]p1:
5100 //
5101 // [...] If the parameter binds directly to the result of
5102 // applying a conversion function to the argument
5103 // expression, the implicit conversion sequence is a
5104 // user-defined conversion sequence (13.3.3.1.2), with the
5105 // second standard conversion sequence either an identity
5106 // conversion or, if the conversion function returns an
5107 // entity of a type that is a derived class of the parameter
5108 // type, a derived-to-base Conversion.
5109 if (!Best->FinalConversion.DirectBinding)
5110 return false;
5111
5112 ICS.setUserDefined();
5113 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5114 ICS.UserDefined.After = Best->FinalConversion;
5115 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5116 ICS.UserDefined.ConversionFunction = Best->Function;
5117 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5118 ICS.UserDefined.EllipsisConversion = false;
5119 assert(ICS.UserDefined.After.ReferenceBinding &&
5121 "Expected a direct reference binding!");
5122 return true;
5123
5124 case OR_Ambiguous:
5125 ICS.setAmbiguous();
5126 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5127 Cand != CandidateSet.end(); ++Cand)
5128 if (Cand->Best)
5129 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5130 return true;
5131
5133 case OR_Deleted:
5134 // There was no suitable conversion, or we found a deleted
5135 // conversion; continue with other checks.
5136 return false;
5137 }
5138
5139 llvm_unreachable("Invalid OverloadResult!");
5140}
5141
5142/// Compute an implicit conversion sequence for reference
5143/// initialization.
5146 SourceLocation DeclLoc,
5147 bool SuppressUserConversions,
5148 bool AllowExplicit) {
5149 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5150
5151 // Most paths end in a failed conversion.
5154
5155 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5156 QualType T2 = Init->getType();
5157
5158 // If the initializer is the address of an overloaded function, try
5159 // to resolve the overloaded function. If all goes well, T2 is the
5160 // type of the resulting function.
5161 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5162 DeclAccessPair Found;
5164 false, Found))
5165 T2 = Fn->getType();
5166 }
5167
5168 // Compute some basic properties of the types and the initializer.
5169 bool isRValRef = DeclType->isRValueReferenceType();
5170 Expr::Classification InitCategory = Init->Classify(S.Context);
5171
5173 Sema::ReferenceCompareResult RefRelationship =
5174 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5175
5176 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5177 ICS.setStandard();
5179 // FIXME: A reference binding can be a function conversion too. We should
5180 // consider that when ordering reference-to-function bindings.
5181 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5183 : (RefConv & Sema::ReferenceConversions::ObjC)
5185 : ICK_Identity;
5187 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5188 // a reference binding that performs a non-top-level qualification
5189 // conversion as a qualification conversion, not as an identity conversion.
5190 ICS.Standard.Third = (RefConv &
5191 Sema::ReferenceConversions::NestedQualification)
5193 : ICK_Identity;
5194 ICS.Standard.setFromType(T2);
5195 ICS.Standard.setToType(0, T2);
5196 ICS.Standard.setToType(1, T1);
5197 ICS.Standard.setToType(2, T1);
5198 ICS.Standard.ReferenceBinding = true;
5199 ICS.Standard.DirectBinding = BindsDirectly;
5200 ICS.Standard.IsLvalueReference = !isRValRef;
5202 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5205 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5206 ICS.Standard.CopyConstructor = nullptr;
5208 };
5209
5210 // C++0x [dcl.init.ref]p5:
5211 // A reference to type "cv1 T1" is initialized by an expression
5212 // of type "cv2 T2" as follows:
5213
5214 // -- If reference is an lvalue reference and the initializer expression
5215 if (!isRValRef) {
5216 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5217 // reference-compatible with "cv2 T2," or
5218 //
5219 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5220 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5221 // C++ [over.ics.ref]p1:
5222 // When a parameter of reference type binds directly (8.5.3)
5223 // to an argument expression, the implicit conversion sequence
5224 // is the identity conversion, unless the argument expression
5225 // has a type that is a derived class of the parameter type,
5226 // in which case the implicit conversion sequence is a
5227 // derived-to-base Conversion (13.3.3.1).
5228 SetAsReferenceBinding(/*BindsDirectly=*/true);
5229
5230 // Nothing more to do: the inaccessibility/ambiguity check for
5231 // derived-to-base conversions is suppressed when we're
5232 // computing the implicit conversion sequence (C++
5233 // [over.best.ics]p2).
5234 return ICS;
5235 }
5236
5237 // -- has a class type (i.e., T2 is a class type), where T1 is
5238 // not reference-related to T2, and can be implicitly
5239 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5240 // is reference-compatible with "cv3 T3" 92) (this
5241 // conversion is selected by enumerating the applicable
5242 // conversion functions (13.3.1.6) and choosing the best
5243 // one through overload resolution (13.3)),
5244 if (!SuppressUserConversions && T2->isRecordType() &&
5245 S.isCompleteType(DeclLoc, T2) &&
5246 RefRelationship == Sema::Ref_Incompatible) {
5247 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5248 Init, T2, /*AllowRvalues=*/false,
5249 AllowExplicit))
5250 return ICS;
5251 }
5252 }
5253
5254 // -- Otherwise, the reference shall be an lvalue reference to a
5255 // non-volatile const type (i.e., cv1 shall be const), or the reference
5256 // shall be an rvalue reference.
5257 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5258 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5260 return ICS;
5261 }
5262
5263 // -- If the initializer expression
5264 //
5265 // -- is an xvalue, class prvalue, array prvalue or function
5266 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5267 if (RefRelationship == Sema::Ref_Compatible &&
5268 (InitCategory.isXValue() ||
5269 (InitCategory.isPRValue() &&
5270 (T2->isRecordType() || T2->isArrayType())) ||
5271 (InitCategory.isLValue() && T2->isFunctionType()))) {
5272 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5273 // binding unless we're binding to a class prvalue.
5274 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5275 // allow the use of rvalue references in C++98/03 for the benefit of
5276 // standard library implementors; therefore, we need the xvalue check here.
5277 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5278 !(InitCategory.isPRValue() || T2->isRecordType()));
5279 return ICS;
5280 }
5281
5282 // -- has a class type (i.e., T2 is a class type), where T1 is not
5283 // reference-related to T2, and can be implicitly converted to
5284 // an xvalue, class prvalue, or function lvalue of type
5285 // "cv3 T3", where "cv1 T1" is reference-compatible with
5286 // "cv3 T3",
5287 //
5288 // then the reference is bound to the value of the initializer
5289 // expression in the first case and to the result of the conversion
5290 // in the second case (or, in either case, to an appropriate base
5291 // class subobject).
5292 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5293 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5294 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5295 Init, T2, /*AllowRvalues=*/true,
5296 AllowExplicit)) {
5297 // In the second case, if the reference is an rvalue reference
5298 // and the second standard conversion sequence of the
5299 // user-defined conversion sequence includes an lvalue-to-rvalue
5300 // conversion, the program is ill-formed.
5301 if (ICS.isUserDefined() && isRValRef &&
5304
5305 return ICS;
5306 }
5307
5308 // A temporary of function type cannot be created; don't even try.
5309 if (T1->isFunctionType())
5310 return ICS;
5311
5312 // -- Otherwise, a temporary of type "cv1 T1" is created and
5313 // initialized from the initializer expression using the
5314 // rules for a non-reference copy initialization (8.5). The
5315 // reference is then bound to the temporary. If T1 is
5316 // reference-related to T2, cv1 must be the same
5317 // cv-qualification as, or greater cv-qualification than,
5318 // cv2; otherwise, the program is ill-formed.
5319 if (RefRelationship == Sema::Ref_Related) {
5320 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5321 // we would be reference-compatible or reference-compatible with
5322 // added qualification. But that wasn't the case, so the reference
5323 // initialization fails.
5324 //
5325 // Note that we only want to check address spaces and cvr-qualifiers here.
5326 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5327 Qualifiers T1Quals = T1.getQualifiers();
5328 Qualifiers T2Quals = T2.getQualifiers();
5329 T1Quals.removeObjCGCAttr();
5330 T1Quals.removeObjCLifetime();
5331 T2Quals.removeObjCGCAttr();
5332 T2Quals.removeObjCLifetime();
5333 // MS compiler ignores __unaligned qualifier for references; do the same.
5334 T1Quals.removeUnaligned();
5335 T2Quals.removeUnaligned();
5336 if (!T1Quals.compatiblyIncludes(T2Quals))
5337 return ICS;
5338 }
5339
5340 // If at least one of the types is a class type, the types are not
5341 // related, and we aren't allowed any user conversions, the
5342 // reference binding fails. This case is important for breaking
5343 // recursion, since TryImplicitConversion below will attempt to
5344 // create a temporary through the use of a copy constructor.
5345 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5346 (T1->isRecordType() || T2->isRecordType()))
5347 return ICS;
5348
5349 // If T1 is reference-related to T2 and the reference is an rvalue
5350 // reference, the initializer expression shall not be an lvalue.
5351 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5352 Init->Classify(S.Context).isLValue()) {
5354 return ICS;
5355 }
5356
5357 // C++ [over.ics.ref]p2:
5358 // When a parameter of reference type is not bound directly to
5359 // an argument expression, the conversion sequence is the one
5360 // required to convert the argument expression to the
5361 // underlying type of the reference according to
5362 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5363 // to copy-initializing a temporary of the underlying type with
5364 // the argument expression. Any difference in top-level
5365 // cv-qualification is subsumed by the initialization itself
5366 // and does not constitute a conversion.
5367 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5368 AllowedExplicit::None,
5369 /*InOverloadResolution=*/false,
5370 /*CStyle=*/false,
5371 /*AllowObjCWritebackConversion=*/false,
5372 /*AllowObjCConversionOnExplicit=*/false);
5373
5374 // Of course, that's still a reference binding.
5375 if (ICS.isStandard()) {
5376 ICS.Standard.ReferenceBinding = true;
5377 ICS.Standard.IsLvalueReference = !isRValRef;
5378 ICS.Standard.BindsToFunctionLvalue = false;
5379 ICS.Standard.BindsToRvalue = true;
5382 } else if (ICS.isUserDefined()) {
5383 const ReferenceType *LValRefType =
5386
5387 // C++ [over.ics.ref]p3:
5388 // Except for an implicit object parameter, for which see 13.3.1, a
5389 // standard conversion sequence cannot be formed if it requires [...]
5390 // binding an rvalue reference to an lvalue other than a function
5391 // lvalue.
5392 // Note that the function case is not possible here.
5393 if (isRValRef && LValRefType) {
5395 return ICS;
5396 }
5397
5399 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5401 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5404 }
5405
5406 return ICS;
5407}
5408
5410TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5411 bool SuppressUserConversions,
5412 bool InOverloadResolution,
5413 bool AllowObjCWritebackConversion,
5414 bool AllowExplicit = false);
5415
5416/// TryListConversion - Try to copy-initialize a value of type ToType from the
5417/// initializer list From.
5420 bool SuppressUserConversions,
5421 bool InOverloadResolution,
5422 bool AllowObjCWritebackConversion) {
5423 // C++11 [over.ics.list]p1:
5424 // When an argument is an initializer list, it is not an expression and
5425 // special rules apply for converting it to a parameter type.
5426
5428 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5429
5430 // We need a complete type for what follows. With one C++20 exception,
5431 // incomplete types can never be initialized from init lists.
5432 QualType InitTy = ToType;
5433 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5434 if (AT && S.getLangOpts().CPlusPlus20)
5435 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5436 // C++20 allows list initialization of an incomplete array type.
5437 InitTy = IAT->getElementType();
5438 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5439 return Result;
5440
5441 // C++20 [over.ics.list]/2:
5442 // If the initializer list is a designated-initializer-list, a conversion
5443 // is only possible if the parameter has an aggregate type
5444 //
5445 // FIXME: The exception for reference initialization here is not part of the
5446 // language rules, but follow other compilers in adding it as a tentative DR
5447 // resolution.
5448 bool IsDesignatedInit = From->hasDesignatedInit();
5449 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5450 IsDesignatedInit)
5451 return Result;
5452
5453 // Per DR1467:
5454 // If the parameter type is a class X and the initializer list has a single
5455 // element of type cv U, where U is X or a class derived from X, the
5456 // implicit conversion sequence is the one required to convert the element
5457 // to the parameter type.
5458 //
5459 // Otherwise, if the parameter type is a character array [... ]
5460 // and the initializer list has a single element that is an
5461 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5462 // implicit conversion sequence is the identity conversion.
5463 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5464 if (ToType->isRecordType()) {
5465 QualType InitType = From->getInit(0)->getType();
5466 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5467 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5468 return TryCopyInitialization(S, From->getInit(0), ToType,
5469 SuppressUserConversions,
5470 InOverloadResolution,
5471 AllowObjCWritebackConversion);
5472 }
5473
5474 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5475 InitializedEntity Entity =
5477 /*Consumed=*/false);
5478 if (S.CanPerformCopyInitialization(Entity, From)) {
5479 Result.setStandard();
5480 Result.Standard.setAsIdentityConversion();
5481 Result.Standard.setFromType(ToType);
5482 Result.Standard.setAllToTypes(ToType);
5483 return Result;
5484 }
5485 }
5486 }
5487
5488 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5489 // C++11 [over.ics.list]p2:
5490 // If the parameter type is std::initializer_list<X> or "array of X" and
5491 // all the elements can be implicitly converted to X, the implicit
5492 // conversion sequence is the worst conversion necessary to convert an
5493 // element of the list to X.
5494 //
5495 // C++14 [over.ics.list]p3:
5496 // Otherwise, if the parameter type is "array of N X", if the initializer
5497 // list has exactly N elements or if it has fewer than N elements and X is
5498 // default-constructible, and if all the elements of the initializer list
5499 // can be implicitly converted to X, the implicit conversion sequence is
5500 // the worst conversion necessary to convert an element of the list to X.
5501 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5502 unsigned e = From->getNumInits();
5505 QualType());
5506 QualType ContTy = ToType;
5507 bool IsUnbounded = false;
5508 if (AT) {
5509 InitTy = AT->getElementType();
5510 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5511 if (CT->getSize().ult(e)) {
5512 // Too many inits, fatally bad
5514 ToType);
5515 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5516 return Result;
5517 }
5518 if (CT->getSize().ugt(e)) {
5519 // Need an init from empty {}, is there one?
5520 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5521 From->getEndLoc());
5522 EmptyList.setType(S.Context.VoidTy);
5523 DfltElt = TryListConversion(
5524 S, &EmptyList, InitTy, SuppressUserConversions,
5525 InOverloadResolution, AllowObjCWritebackConversion);
5526 if (DfltElt.isBad()) {
5527 // No {} init, fatally bad
5529 ToType);
5530 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5531 return Result;
5532 }
5533 }
5534 } else {
5535 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5536 IsUnbounded = true;
5537 if (!e) {
5538 // Cannot convert to zero-sized.
5540 ToType);
5541 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5542 return Result;
5543 }
5544 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5545 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5547 }
5548 }
5549
5550 Result.setStandard();
5551 Result.Standard.setAsIdentityConversion();
5552 Result.Standard.setFromType(InitTy);
5553 Result.Standard.setAllToTypes(InitTy);
5554 for (unsigned i = 0; i < e; ++i) {
5555 Expr *Init = From->getInit(i);
5557 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5558 AllowObjCWritebackConversion);
5559
5560 // Keep the worse conversion seen so far.
5561 // FIXME: Sequences are not totally ordered, so 'worse' can be
5562 // ambiguous. CWG has been informed.
5564 Result) ==
5566 Result = ICS;
5567 // Bail as soon as we find something unconvertible.
5568 if (Result.isBad()) {
5569 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5570 return Result;
5571 }
5572 }
5573 }
5574
5575 // If we needed any implicit {} initialization, compare that now.
5576 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5577 // has been informed that this might not be the best thing.
5578 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5579 S, From->getEndLoc(), DfltElt, Result) ==
5581 Result = DfltElt;
5582 // Record the type being initialized so that we may compare sequences
5583 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5584 return Result;
5585 }
5586
5587 // C++14 [over.ics.list]p4:
5588 // C++11 [over.ics.list]p3:
5589 // Otherwise, if the parameter is a non-aggregate class X and overload
5590 // resolution chooses a single best constructor [...] the implicit
5591 // conversion sequence is a user-defined conversion sequence. If multiple
5592 // constructors are viable but none is better than the others, the
5593 // implicit conversion sequence is a user-defined conversion sequence.
5594 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5595 // This function can deal with initializer lists.
5596 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5597 AllowedExplicit::None,
5598 InOverloadResolution, /*CStyle=*/false,
5599 AllowObjCWritebackConversion,
5600 /*AllowObjCConversionOnExplicit=*/false);
5601 }
5602
5603 // C++14 [over.ics.list]p5:
5604 // C++11 [over.ics.list]p4:
5605 // Otherwise, if the parameter has an aggregate type which can be
5606 // initialized from the initializer list [...] the implicit conversion
5607 // sequence is a user-defined conversion sequence.
5608 if (ToType->isAggregateType()) {
5609 // Type is an aggregate, argument is an init list. At this point it comes
5610 // down to checking whether the initialization works.
5611 // FIXME: Find out whether this parameter is consumed or not.
5612 InitializedEntity Entity =
5614 /*Consumed=*/false);
5616 From)) {
5617 Result.setUserDefined();
5618 Result.UserDefined.Before.setAsIdentityConversion();
5619 // Initializer lists don't have a type.
5620 Result.UserDefined.Before.setFromType(QualType());
5621 Result.UserDefined.Before.setAllToTypes(QualType());
5622
5623 Result.UserDefined.After.setAsIdentityConversion();
5624 Result.UserDefined.After.setFromType(ToType);
5625 Result.UserDefined.After.setAllToTypes(ToType);
5626 Result.UserDefined.ConversionFunction = nullptr;
5627 }
5628 return Result;
5629 }
5630
5631 // C++14 [over.ics.list]p6:
5632 // C++11 [over.ics.list]p5:
5633 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5634 if (ToType->isReferenceType()) {
5635 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5636 // mention initializer lists in any way. So we go by what list-
5637 // initialization would do and try to extrapolate from that.
5638
5639 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5640
5641 // If the initializer list has a single element that is reference-related
5642 // to the parameter type, we initialize the reference from that.
5643 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5644 Expr *Init = From->getInit(0);
5645
5646 QualType T2 = Init->getType();
5647
5648 // If the initializer is the address of an overloaded function, try
5649 // to resolve the overloaded function. If all goes well, T2 is the
5650 // type of the resulting function.
5651 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5652 DeclAccessPair Found;
5654 Init, ToType, false, Found))
5655 T2 = Fn->getType();
5656 }
5657
5658 // Compute some basic properties of the types and the initializer.
5659 Sema::ReferenceCompareResult RefRelationship =
5660 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5661
5662 if (RefRelationship >= Sema::Ref_Related) {
5663 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5664 SuppressUserConversions,
5665 /*AllowExplicit=*/false);
5666 }
5667 }
5668
5669 // Otherwise, we bind the reference to a temporary created from the
5670 // initializer list.
5671 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5672 InOverloadResolution,
5673 AllowObjCWritebackConversion);
5674 if (Result.isFailure())
5675 return Result;
5676 assert(!Result.isEllipsis() &&
5677 "Sub-initialization cannot result in ellipsis conversion.");
5678
5679 // Can we even bind to a temporary?
5680 if (ToType->isRValueReferenceType() ||
5681 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5682 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5683 Result.UserDefined.After;
5684 SCS.ReferenceBinding = true;
5686 SCS.BindsToRvalue = true;
5687 SCS.BindsToFunctionLvalue = false;
5690 } else
5692 From, ToType);
5693 return Result;
5694 }
5695
5696 // C++14 [over.ics.list]p7:
5697 // C++11 [over.ics.list]p6:
5698 // Otherwise, if the parameter type is not a class:
5699 if (!ToType->isRecordType()) {
5700 // - if the initializer list has one element that is not itself an
5701 // initializer list, the implicit conversion sequence is the one
5702 // required to convert the element to the parameter type.
5703 unsigned NumInits = From->getNumInits();
5704 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5705 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5706 SuppressUserConversions,
5707 InOverloadResolution,
5708 AllowObjCWritebackConversion);
5709 // - if the initializer list has no elements, the implicit conversion
5710 // sequence is the identity conversion.
5711 else if (NumInits == 0) {
5712 Result.setStandard();
5713 Result.Standard.setAsIdentityConversion();
5714 Result.Standard.setFromType(ToType);
5715 Result.Standard.setAllToTypes(ToType);
5716 }
5717 return Result;
5718 }
5719
5720 // C++14 [over.ics.list]p8:
5721 // C++11 [over.ics.list]p7:
5722 // In all cases other than those enumerated above, no conversion is possible
5723 return Result;
5724}
5725
5726/// TryCopyInitialization - Try to copy-initialize a value of type
5727/// ToType from the expression From. Return the implicit conversion
5728/// sequence required to pass this argument, which may be a bad
5729/// conversion sequence (meaning that the argument cannot be passed to
5730/// a parameter of this type). If @p SuppressUserConversions, then we
5731/// do not permit any user-defined conversion sequences.
5734 bool SuppressUserConversions,
5735 bool InOverloadResolution,
5736 bool AllowObjCWritebackConversion,
5737 bool AllowExplicit) {
5738 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5739 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5740 InOverloadResolution,AllowObjCWritebackConversion);
5741
5742 if (ToType->isReferenceType())
5743 return TryReferenceInit(S, From, ToType,
5744 /*FIXME:*/ From->getBeginLoc(),
5745 SuppressUserConversions, AllowExplicit);
5746
5747 return TryImplicitConversion(S, From, ToType,
5748 SuppressUserConversions,
5749 AllowedExplicit::None,
5750 InOverloadResolution,
5751 /*CStyle=*/false,
5752 AllowObjCWritebackConversion,
5753 /*AllowObjCConversionOnExplicit=*/false);
5754}
5755
5756static bool TryCopyInitialization(const CanQualType FromQTy,
5757 const CanQualType ToQTy,
5758 Sema &S,
5759 SourceLocation Loc,
5760 ExprValueKind FromVK) {
5761 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5763 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5764
5765 return !ICS.isBad();
5766}
5767
5768/// TryObjectArgumentInitialization - Try to initialize the object
5769/// parameter of the given member function (@c Method) from the
5770/// expression @p From.
5772 Sema &S, SourceLocation Loc, QualType FromType,
5773 Expr::Classification FromClassification, CXXMethodDecl *Method,
5774 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5775 QualType ExplicitParameterType = QualType(),
5776 bool SuppressUserConversion = false) {
5777
5778 // We need to have an object of class type.
5779 if (const auto *PT = FromType->getAs<PointerType>()) {
5780 FromType = PT->getPointeeType();
5781
5782 // When we had a pointer, it's implicitly dereferenced, so we
5783 // better have an lvalue.
5784 assert(FromClassification.isLValue());
5785 }
5786
5787 auto ValueKindFromClassification = [](Expr::Classification C) {
5788 if (C.isPRValue())
5789 return clang::VK_PRValue;
5790 if (C.isXValue())
5791 return VK_XValue;
5792 return clang::VK_LValue;
5793 };
5794
5795 if (Method->isExplicitObjectMemberFunction()) {
5796 if (ExplicitParameterType.isNull())
5797 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5798 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5799 ValueKindFromClassification(FromClassification));
5801 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5802 /*InOverloadResolution=*/true, false);
5803 if (ICS.isBad())
5804 ICS.Bad.FromExpr = nullptr;
5805 return ICS;
5806 }
5807
5808 assert(FromType->isRecordType());
5809
5810 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5811 // C++98 [class.dtor]p2:
5812 // A destructor can be invoked for a const, volatile or const volatile
5813 // object.
5814 // C++98 [over.match.funcs]p4:
5815 // For static member functions, the implicit object parameter is considered
5816 // to match any object (since if the function is selected, the object is
5817 // discarded).
5818 Qualifiers Quals = Method->getMethodQualifiers();
5819 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5820 Quals.addConst();
5821 Quals.addVolatile();
5822 }
5823
5824 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5825
5826 // Set up the conversion sequence as a "bad" conversion, to allow us
5827 // to exit early.
5829
5830 // C++0x [over.match.funcs]p4:
5831 // For non-static member functions, the type of the implicit object
5832 // parameter is
5833 //
5834 // - "lvalue reference to cv X" for functions declared without a
5835 // ref-qualifier or with the & ref-qualifier
5836 // - "rvalue reference to cv X" for functions declared with the &&
5837 // ref-qualifier
5838 //
5839 // where X is the class of which the function is a member and cv is the
5840 // cv-qualification on the member function declaration.
5841 //
5842 // However, when finding an implicit conversion sequence for the argument, we
5843 // are not allowed to perform user-defined conversions
5844 // (C++ [over.match.funcs]p5). We perform a simplified version of
5845 // reference binding here, that allows class rvalues to bind to
5846 // non-constant references.
5847
5848 // First check the qualifiers.
5849 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5850 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5851 if (ImplicitParamType.getCVRQualifiers() !=
5852 FromTypeCanon.getLocalCVRQualifiers() &&
5853 !ImplicitParamType.isAtLeastAsQualifiedAs(
5854 withoutUnaligned(S.Context, FromTypeCanon))) {
5856 FromType, ImplicitParamType);
5857 return ICS;
5858 }
5859
5860 if (FromTypeCanon.hasAddressSpace()) {
5861 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5862 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5863 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5865 FromType, ImplicitParamType);
5866 return ICS;
5867 }
5868 }
5869
5870 // Check that we have either the same type or a derived type. It
5871 // affects the conversion rank.
5872 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5873 ImplicitConversionKind SecondKind;
5874 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5875 SecondKind = ICK_Identity;
5876 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5877 SecondKind = ICK_Derived_To_Base;
5878 } else if (!Method->isExplicitObjectMemberFunction()) {
5880 FromType, ImplicitParamType);
5881 return ICS;
5882 }
5883
5884 // Check the ref-qualifier.
5885 switch (Method->getRefQualifier()) {
5886 case RQ_None:
5887 // Do nothing; we don't care about lvalueness or rvalueness.
5888 break;
5889
5890 case RQ_LValue:
5891 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5892 // non-const lvalue reference cannot bind to an rvalue
5894 ImplicitParamType);
5895 return ICS;
5896 }
5897 break;
5898
5899 case RQ_RValue:
5900 if (!FromClassification.isRValue()) {
5901 // rvalue reference cannot bind to an lvalue
5903 ImplicitParamType);
5904 return ICS;
5905 }
5906 break;
5907 }
5908
5909 // Success. Mark this as a reference binding.
5910 ICS.setStandard();
5912 ICS.Standard.Second = SecondKind;
5913 ICS.Standard.setFromType(FromType);
5914 ICS.Standard.setAllToTypes(ImplicitParamType);
5915 ICS.Standard.ReferenceBinding = true;
5916 ICS.Standard.DirectBinding = true;
5918 ICS.Standard.BindsToFunctionLvalue = false;
5919 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5921 = (Method->getRefQualifier() == RQ_None);
5922 return ICS;
5923}
5924
5925/// PerformObjectArgumentInitialization - Perform initialization of
5926/// the implicit object parameter for the given Method with the given
5927/// expression.
5929 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5930 CXXMethodDecl *Method) {
5931 QualType FromRecordType, DestType;
5932 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5933
5934 Expr::Classification FromClassification;
5935 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5936 FromRecordType = PT->getPointeeType();
5937 DestType = Method->getThisType();
5938 FromClassification = Expr::Classification::makeSimpleLValue();
5939 } else {
5940 FromRecordType = From->getType();
5941 DestType = ImplicitParamRecordType;
5942 FromClassification = From->Classify(Context);
5943
5944 // When performing member access on a prvalue, materialize a temporary.
5945 if (From->isPRValue()) {
5946 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5947 Method->getRefQualifier() !=
5949 }
5950 }
5951
5952 // Note that we always use the true parent context when performing
5953 // the actual argument initialization.
5955 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5956 Method->getParent());
5957 if (ICS.isBad()) {
5958 switch (ICS.Bad.Kind) {
5960 Qualifiers FromQs = FromRecordType.getQualifiers();
5961 Qualifiers ToQs = DestType.getQualifiers();
5962 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5963 if (CVR) {
5964 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5965 << Method->getDeclName() << FromRecordType << (CVR - 1)
5966 << From->getSourceRange();
5967 Diag(Method->getLocation(), diag::note_previous_decl)
5968 << Method->getDeclName();
5969 return ExprError();
5970 }
5971 break;
5972 }
5973
5976 bool IsRValueQualified =
5978 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5979 << Method->getDeclName() << FromClassification.isRValue()
5980 << IsRValueQualified;
5981 Diag(Method->getLocation(), diag::note_previous_decl)
5982 << Method->getDeclName();
5983 return ExprError();
5984 }
5985
5988 break;
5989
5992 llvm_unreachable("Lists are not objects");
5993 }
5994
5995 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5996 << ImplicitParamRecordType << FromRecordType
5997 << From->getSourceRange();
5998 }
5999
6000 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6001 ExprResult FromRes =
6002 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6003 if (FromRes.isInvalid())
6004 return ExprError();
6005 From = FromRes.get();
6006 }
6007
6008 if (!Context.hasSameType(From->getType(), DestType)) {
6009 CastKind CK;
6010 QualType PteeTy = DestType->getPointeeType();
6011 LangAS DestAS =
6012 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6013 if (FromRecordType.getAddressSpace() != DestAS)
6014 CK = CK_AddressSpaceConversion;
6015 else
6016 CK = CK_NoOp;
6017 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6018 }
6019 return From;
6020}
6021
6022/// TryContextuallyConvertToBool - Attempt to contextually convert the
6023/// expression From to bool (C++0x [conv]p3).
6026 // C++ [dcl.init]/17.8:
6027 // - Otherwise, if the initialization is direct-initialization, the source
6028 // type is std::nullptr_t, and the destination type is bool, the initial
6029 // value of the object being initialized is false.
6030 if (From->getType()->isNullPtrType())
6032 S.Context.BoolTy,
6033 From->isGLValue());
6034
6035 // All other direct-initialization of bool is equivalent to an implicit
6036 // conversion to bool in which explicit conversions are permitted.
6037 return TryImplicitConversion(S, From, S.Context.BoolTy,
6038 /*SuppressUserConversions=*/false,
6039 AllowedExplicit::Conversions,
6040 /*InOverloadResolution=*/false,
6041 /*CStyle=*/false,
6042 /*AllowObjCWritebackConversion=*/false,
6043 /*AllowObjCConversionOnExplicit=*/false);
6044}
6045
6046/// PerformContextuallyConvertToBool - Perform a contextual conversion
6047/// of the expression From to bool (C++0x [conv]p3).
6049 if (checkPlaceholderForOverload(*this, From))
6050 return ExprError();
6051
6053 if (!ICS.isBad())
6054 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
6055
6056 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6057 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6058 << From->getType() << From->getSourceRange();
6059 return ExprError();
6060}
6061
6062/// Check that the specified conversion is permitted in a converted constant
6063/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6064/// is acceptable.
6067 // Since we know that the target type is an integral or unscoped enumeration
6068 // type, most conversion kinds are impossible. All possible First and Third
6069 // conversions are fine.
6070 switch (SCS.Second) {
6071 case ICK_Identity:
6073 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6075 return true;
6076
6078 // Conversion from an integral or unscoped enumeration type to bool is
6079 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6080 // conversion, so we allow it in a converted constant expression.
6081 //
6082 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6083 // a lot of popular code. We should at least add a warning for this
6084 // (non-conforming) extension.
6086 SCS.getToType(2)->isBooleanType();
6087
6089 case ICK_Pointer_Member:
6090 // C++1z: null pointer conversions and null member pointer conversions are
6091 // only permitted if the source type is std::nullptr_t.
6092 return SCS.getFromType()->isNullPtrType();
6093
6104 case ICK_Vector_Splat:
6105 case ICK_Complex_Real:
6114 return false;
6115
6120 llvm_unreachable("found a first conversion kind in Second");
6121
6123 case ICK_Qualification:
6124 llvm_unreachable("found a third conversion kind in Second");
6125
6127 break;
6128 }
6129
6130 llvm_unreachable("unknown conversion kind");
6131}
6132
6133/// BuildConvertedConstantExpression - Check that the expression From is a
6134/// converted constant expression of type T, perform the conversion but
6135/// does not evaluate the expression
6137 QualType T,
6138 Sema::CCEKind CCE,
6139 NamedDecl *Dest,
6140 APValue &PreNarrowingValue) {
6141 assert(S.getLangOpts().CPlusPlus11 &&
6142 "converted constant expression outside C++11");
6143
6144 if (checkPlaceholderForOverload(S, From))
6145 return ExprError();
6146
6147 // C++1z [expr.const]p3:
6148 // A converted constant expression of type T is an expression,
6149 // implicitly converted to type T, where the converted
6150 // expression is a constant expression and the implicit conversion
6151 // sequence contains only [... list of conversions ...].
6155 : TryCopyInitialization(S, From, T,
6156 /*SuppressUserConversions=*/false,
6157 /*InOverloadResolution=*/false,
6158 /*AllowObjCWritebackConversion=*/false,
6159 /*AllowExplicit=*/false);
6160 StandardConversionSequence *SCS = nullptr;
6161 switch (ICS.getKind()) {
6163 SCS = &ICS.Standard;
6164 break;
6166 if (T->isRecordType())
6167 SCS = &ICS.UserDefined.Before;
6168 else
6169 SCS = &ICS.UserDefined.After;
6170 break;
6174 return S.Diag(From->getBeginLoc(),
6175 diag::err_typecheck_converted_constant_expression)
6176 << From->getType() << From->getSourceRange() << T;
6177 return ExprError();
6178
6181 llvm_unreachable("bad conversion in converted constant expression");
6182 }
6183
6184 // Check that we would only use permitted conversions.
6185 if (!CheckConvertedConstantConversions(S, *SCS)) {
6186 return S.Diag(From->getBeginLoc(),
6187 diag::err_typecheck_converted_constant_expression_disallowed)
6188 << From->getType() << From->getSourceRange() << T;
6189 }
6190 // [...] and where the reference binding (if any) binds directly.
6191 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6192 return S.Diag(From->getBeginLoc(),
6193 diag::err_typecheck_converted_constant_expression_indirect)
6194 << From->getType() << From->getSourceRange() << T;
6195 }
6196 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6197 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6198 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6199 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6200 // case explicitly.
6201 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6202 return S.Diag(From->getBeginLoc(),
6203 diag::err_reference_bind_to_bitfield_in_cce)
6204 << From->getSourceRange();
6205 }
6206
6207 // Usually we can simply apply the ImplicitConversionSequence we formed
6208 // earlier, but that's not guaranteed to work when initializing an object of
6209 // class type.
6211 if (T->isRecordType()) {
6212 assert(CCE == Sema::CCEK_TemplateArg &&
6213 "unexpected class type converted constant expr");
6216 T, cast<NonTypeTemplateParmDecl>(Dest)),
6217 SourceLocation(), From);
6218 } else {
6220 }
6221 if (Result.isInvalid())
6222 return Result;
6223
6224 // C++2a [intro.execution]p5:
6225 // A full-expression is [...] a constant-expression [...]
6226 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6227 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6229 if (Result.isInvalid())
6230 return Result;
6231
6232 // Check for a narrowing implicit conversion.
6233 bool ReturnPreNarrowingValue = false;
6234 QualType PreNarrowingType;
6235 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6236 PreNarrowingType)) {
6238 // Implicit conversion to a narrower type, but the expression is
6239 // value-dependent so we can't tell whether it's actually narrowing.
6241 // Implicit conversion to a narrower type, and the value is not a constant
6242 // expression. We'll diagnose this in a moment.
6243 case NK_Not_Narrowing:
6244 break;
6245
6247 if (CCE == Sema::CCEK_ArrayBound &&
6248 PreNarrowingType->isIntegralOrEnumerationType() &&
6249 PreNarrowingValue.isInt()) {
6250 // Don't diagnose array bound narrowing here; we produce more precise
6251 // errors by allowing the un-narrowed value through.
6252 ReturnPreNarrowingValue = true;
6253 break;
6254 }
6255 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6256 << CCE << /*Constant*/ 1
6257 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6258 break;
6259
6260 case NK_Type_Narrowing:
6261 // FIXME: It would be better to diagnose that the expression is not a
6262 // constant expression.
6263 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6264 << CCE << /*Constant*/ 0 << From->getType() << T;
6265 break;
6266 }
6267 if (!ReturnPreNarrowingValue)
6268 PreNarrowingValue = {};
6269
6270 return Result;
6271}
6272
6273/// CheckConvertedConstantExpression - Check that the expression From is a
6274/// converted constant expression of type T, perform the conversion and produce
6275/// the converted expression, per C++11 [expr.const]p3.
6278 Sema::CCEKind CCE,
6279 bool RequireInt,
6280 NamedDecl *Dest) {
6281
6282 APValue PreNarrowingValue;
6284 PreNarrowingValue);
6285 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6286 Value = APValue();
6287 return Result;
6288 }
6289 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6290 RequireInt, PreNarrowingValue);
6291}
6292
6294 CCEKind CCE,
6295 NamedDecl *Dest) {
6296 APValue PreNarrowingValue;
6297 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6298 PreNarrowingValue);
6299}
6300
6302 APValue &Value, CCEKind CCE,
6303 NamedDecl *Dest) {
6304 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6305 Dest);
6306}
6307
6309 llvm::APSInt &Value,
6310 CCEKind CCE) {
6311 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6312
6313 APValue V;
6314 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6315 /*Dest=*/nullptr);
6316 if (!R.isInvalid() && !R.get()->isValueDependent())
6317 Value = V.getInt();
6318 return R;
6319}
6320
6321/// EvaluateConvertedConstantExpression - Evaluate an Expression
6322/// That is a converted constant expression
6323/// (which was built with BuildConvertedConstantExpression)
6326 Sema::CCEKind CCE, bool RequireInt,
6327 const APValue &PreNarrowingValue) {
6328
6329 ExprResult Result = E;
6330 // Check the expression is a constant expression.
6332 Expr::EvalResult Eval;
6333 Eval.Diag = &Notes;
6334
6335 ConstantExprKind Kind;
6336 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6337 Kind = ConstantExprKind::ClassTemplateArgument;
6338 else if (CCE == Sema::CCEK_TemplateArg)
6339 Kind = ConstantExprKind::NonClassTemplateArgument;
6340 else
6341 Kind = ConstantExprKind::Normal;
6342
6343 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6344 (RequireInt && !Eval.Val.isInt())) {
6345 // The expression can't be folded, so we can't keep it at this position in
6346 // the AST.
6347 Result = ExprError();
6348 } else {
6349 Value = Eval.Val;
6350
6351 if (Notes.empty()) {
6352 // It's a constant expression.
6353 Expr *E = Result.get();
6354 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6355 // We expect a ConstantExpr to have a value associated with it
6356 // by this point.
6357 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6358 "ConstantExpr has no value associated with it");
6359 (void)CE;
6360 } else {
6361 E = ConstantExpr::Create(Context, Result.get(), Value);
6362 }
6363 if (!PreNarrowingValue.isAbsent())
6364 Value = std::move(PreNarrowingValue);
6365 return E;
6366 }
6367 }
6368
6369 // It's not a constant expression. Produce an appropriate diagnostic.
6370 if (Notes.size() == 1 &&
6371 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6372 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6373 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6374 diag::note_constexpr_invalid_template_arg) {
6375 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6376 for (unsigned I = 0; I < Notes.size(); ++I)
6377 Diag(Notes[I].first, Notes[I].second);
6378 } else {
6379 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6380 << CCE << E->getSourceRange();
6381 for (unsigned I = 0; I < Notes.size(); ++I)
6382 Diag(Notes[I].first, Notes[I].second);
6383 }
6384 return ExprError();
6385}
6386
6387/// dropPointerConversions - If the given standard conversion sequence
6388/// involves any pointer conversions, remove them. This may change
6389/// the result type of the conversion sequence.
6391 if (SCS.Second == ICK_Pointer_Conversion) {
6392 SCS.Second = ICK_Identity;
6393 SCS.Element = ICK_Identity;
6394 SCS.Third = ICK_Identity;
6395 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6396 }
6397}
6398
6399/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6400/// convert the expression From to an Objective-C pointer type.
6403 // Do an implicit conversion to 'id'.
6406 = TryImplicitConversion(S, From, Ty,
6407 // FIXME: Are these flags correct?
6408 /*SuppressUserConversions=*/false,
6409 AllowedExplicit::Conversions,
6410 /*InOverloadResolution=*/false,
6411 /*CStyle=*/false,
6412 /*AllowObjCWritebackConversion=*/false,
6413 /*AllowObjCConversionOnExplicit=*/true);
6414
6415 // Strip off any final conversions to 'id'.
6416 switch (ICS.getKind()) {
6421 break;
6422
6425 break;
6426
6429 break;
6430 }
6431
6432 return ICS;
6433}
6434
6435/// PerformContextuallyConvertToObjCPointer - Perform a contextual
6436/// conversion of the expression From to an Objective-C pointer type.
6437/// Returns a valid but null ExprResult if no conversion sequence exists.
6439 if (checkPlaceholderForOverload(*this, From))
6440 return ExprError();
6441
6442 QualType Ty = Context.getObjCIdType();
6445 if (!ICS.isBad())
6446 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6447 return ExprResult();
6448}
6449
6450static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6451 const Expr *Base = nullptr;
6452 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6453 "expected a member expression");
6454
6455 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6456 M && !M->isImplicitAccess())
6457 Base = M->getBase();
6458 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6459 M && !M->isImplicitAccess())
6460 Base = M->getBase();
6461
6462 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6463
6464 if (T->isPointerType())
6465 T = T->getPointeeType();
6466
6467 return T;
6468}
6469
6471 const FunctionDecl *Fun) {
6472 QualType ObjType = Obj->getType();
6473 if (ObjType->isPointerType()) {
6474 ObjType = ObjType->getPointeeType();
6475 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6477 /*CanOverflow=*/false, FPOptionsOverride());
6478 }
6479 if (Obj->Classify(S.getASTContext()).isPRValue()) {
6481 ObjType, Obj,
6483 }
6484 return Obj;
6485}
6486
6488 FunctionDecl *Fun) {
6489 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6492 Obj->getExprLoc(), Obj);
6493}
6494
6496 Expr *Object, MultiExprArg &Args,
6497 SmallVectorImpl<Expr *> &NewArgs) {
6498 assert(Method->isExplicitObjectMemberFunction() &&
6499 "Method is not an explicit member function");
6500 assert(NewArgs.empty() && "NewArgs should be empty");
6501 NewArgs.reserve(Args.size() + 1);
6502 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6503 NewArgs.push_back(This);
6504 NewArgs.append(Args.begin(), Args.end());
6505 Args = NewArgs;
6506}
6507
6508/// Determine whether the provided type is an integral type, or an enumeration
6509/// type of a permitted flavor.
6511 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6513}
6514
6515static ExprResult
6518 QualType T, UnresolvedSetImpl &ViableConversions) {
6519
6520 if (Converter.Suppress)
6521 return ExprError();
6522
6523 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6524 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6525 CXXConversionDecl *Conv =
6526 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6528 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6529 }
6530 return From;
6531}
6532
6533static bool
6536 QualType T, bool HadMultipleCandidates,
6537 UnresolvedSetImpl &ExplicitConversions) {
6538 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6539 DeclAccessPair Found = ExplicitConversions[0];
6540 CXXConversionDecl *Conversion =
6541 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6542
6543 // The user probably meant to invoke the given explicit
6544 // conversion; use it.
6545 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6546 std::string TypeStr;
6547 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6548
6549 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6551 "static_cast<" + TypeStr + ">(")
6553 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6554 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6555
6556 // If we aren't in a SFINAE context, build a call to the
6557 // explicit conversion function.
6558 if (SemaRef.isSFINAEContext())
6559 return true;
6560
6561 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6562 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6563 HadMultipleCandidates);
6564 if (Result.isInvalid())
6565 return true;
6566 // Record usage of conversion in an implicit cast.
6567 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6568 CK_UserDefinedConversion, Result.get(),
6569 nullptr, Result.get()->getValueKind(),
6570 SemaRef.CurFPFeatureOverrides());
6571 }
6572 return false;
6573}
6574
6575static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6577 QualType T, bool HadMultipleCandidates,
6578 DeclAccessPair &Found) {
6579 CXXConversionDecl *Conversion =
6580 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6581 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6582
6583 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6584 if (!Converter.SuppressConversion) {
6585 if (SemaRef.isSFINAEContext())
6586 return true;
6587
6588 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6589 << From->getSourceRange();
6590 }
6591
6592 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6593 HadMultipleCandidates);
6594 if (Result.isInvalid())
6595 return true;
6596 // Record usage of conversion in an implicit cast.
6597 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6598 CK_UserDefinedConversion, Result.get(),
6599 nullptr, Result.get()->getValueKind(),
6600 SemaRef.CurFPFeatureOverrides());
6601 return false;
6602}
6603
6605 Sema &SemaRef, SourceLocation Loc, Expr *From,
6607 if (!Converter.match(From->getType()) && !Converter.Suppress)
6608 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6609 << From->getSourceRange();
6610
6611 return SemaRef.DefaultLvalueConversion(From);
6612}
6613
6614static void
6616 UnresolvedSetImpl &ViableConversions,
6617 OverloadCandidateSet &CandidateSet) {
6618 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6619 DeclAccessPair FoundDecl = ViableConversions[I];
6620 NamedDecl *D = FoundDecl.getDecl();
6621 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6622 if (isa<UsingShadowDecl>(D))
6623 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6624
6625 CXXConversionDecl *Conv;
6626 FunctionTemplateDecl *ConvTemplate;
6627 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6628 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6629 else
6630 Conv = cast<CXXConversionDecl>(D);
6631
6632 if (ConvTemplate)
6634 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6635 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6636 else
6637 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6638 ToType, CandidateSet,
6639 /*AllowObjCConversionOnExplicit=*/false,
6640 /*AllowExplicit*/ true);
6641 }
6642}
6643
6644/// Attempt to convert the given expression to a type which is accepted
6645/// by the given converter.
6646///
6647/// This routine will attempt to convert an expression of class type to a
6648/// type accepted by the specified converter. In C++11 and before, the class
6649/// must have a single non-explicit conversion function converting to a matching
6650/// type. In C++1y, there can be multiple such conversion functions, but only
6651/// one target type.
6652///
6653/// \param Loc The source location of the construct that requires the
6654/// conversion.
6655///
6656/// \param From The expression we're converting from.
6657///
6658/// \param Converter Used to control and diagnose the conversion process.
6659///
6660/// \returns The expression, converted to an integral or enumeration type if
6661/// successful.
6663 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6664 // We can't perform any more checking for type-dependent expressions.
6665 if (From->isTypeDependent())
6666 return From;
6667
6668 // Process placeholders immediately.
6669 if (From->hasPlaceholderType()) {
6670 ExprResult result = CheckPlaceholderExpr(From);
6671 if (result.isInvalid())
6672 return result;
6673 From = result.get();
6674 }
6675
6676 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6677 ExprResult Converted = DefaultLvalueConversion(From);
6678 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6679 // If the expression already has a matching type, we're golden.
6680 if (Converter.match(T))
6681 return Converted;
6682
6683 // FIXME: Check for missing '()' if T is a function type?
6684
6685 // We can only perform contextual implicit conversions on objects of class
6686 // type.
6687 const RecordType *RecordTy = T->getAs<RecordType>();
6688 if (!RecordTy || !getLangOpts().CPlusPlus) {
6689 if (!Converter.Suppress)
6690 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6691 return From;
6692 }
6693
6694 // We must have a complete class type.
6695 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6696 ContextualImplicitConverter &Converter;
6697 Expr *From;
6698
6699 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6700 : Converter(Converter), From(From) {}
6701
6702 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6703 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6704 }
6705 } IncompleteDiagnoser(Converter, From);
6706
6707 if (Converter.Suppress ? !isCompleteType(Loc, T)
6708 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6709 return From;
6710
6711 // Look for a conversion to an integral or enumeration type.
6713 ViableConversions; // These are *potentially* viable in C++1y.
6714 UnresolvedSet<4> ExplicitConversions;
6715 const auto &Conversions =
6716 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6717
6718 bool HadMultipleCandidates =
6719 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6720
6721 // To check that there is only one target type, in C++1y:
6722 QualType ToType;
6723 bool HasUniqueTargetType = true;
6724
6725 // Collect explicit or viable (potentially in C++1y) conversions.
6726 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6727 NamedDecl *D = (*I)->getUnderlyingDecl();
6728 CXXConversionDecl *Conversion;
6729 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6730 if (ConvTemplate) {
6731 if (getLangOpts().CPlusPlus14)
6732 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6733 else
6734 continue; // C++11 does not consider conversion operator templates(?).
6735 } else
6736 Conversion = cast<CXXConversionDecl>(D);
6737
6738 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6739 "Conversion operator templates are considered potentially "
6740 "viable in C++1y");
6741
6742 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6743 if (Converter.match(CurToType) || ConvTemplate) {
6744
6745 if (Conversion->isExplicit()) {
6746 // FIXME: For C++1y, do we need this restriction?
6747 // cf. diagnoseNoViableConversion()
6748 if (!ConvTemplate)
6749 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6750 } else {
6751 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6752 if (ToType.isNull())
6753 ToType = CurToType.getUnqualifiedType();
6754 else if (HasUniqueTargetType &&
6755 (CurToType.getUnqualifiedType() != ToType))
6756 HasUniqueTargetType = false;
6757 }
6758 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6759 }
6760 }
6761 }
6762
6763 if (getLangOpts().CPlusPlus14) {
6764 // C++1y [conv]p6:
6765 // ... An expression e of class type E appearing in such a context
6766 // is said to be contextually implicitly converted to a specified
6767 // type T and is well-formed if and only if e can be implicitly
6768 // converted to a type T that is determined as follows: E is searched
6769 // for conversion functions whose return type is cv T or reference to
6770 // cv T such that T is allowed by the context. There shall be
6771 // exactly one such T.
6772
6773 // If no unique T is found:
6774 if (ToType.isNull()) {
6775 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6776 HadMultipleCandidates,
6777 ExplicitConversions))
6778 return ExprError();
6779 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6780 }
6781
6782 // If more than one unique Ts are found:
6783 if (!HasUniqueTargetType)
6784 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6785 ViableConversions);
6786
6787 // If one unique T is found:
6788 // First, build a candidate set from the previously recorded
6789 // potentially viable conversions.
6791 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6792 CandidateSet);
6793
6794 // Then, perform overload resolution over the candidate set.
6796 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6797 case OR_Success: {
6798 // Apply this conversion.
6799 DeclAccessPair Found =
6800 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6801 if (recordConversion(*this, Loc, From, Converter, T,
6802 HadMultipleCandidates, Found))
6803 return ExprError();
6804 break;
6805 }
6806 case OR_Ambiguous:
6807 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6808 ViableConversions);
6810 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6811 HadMultipleCandidates,
6812 ExplicitConversions))
6813 return ExprError();
6814 [[fallthrough]];
6815 case OR_Deleted:
6816 // We'll complain below about a non-integral condition type.
6817 break;
6818 }
6819 } else {
6820 switch (ViableConversions.size()) {
6821 case 0: {
6822 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6823 HadMultipleCandidates,
6824 ExplicitConversions))
6825 return ExprError();
6826
6827 // We'll complain below about a non-integral condition type.
6828 break;
6829 }
6830 case 1: {
6831 // Apply this conversion.
6832 DeclAccessPair Found = ViableConversions[0];
6833 if (recordConversion(*this, Loc, From, Converter, T,
6834 HadMultipleCandidates, Found))
6835 return ExprError();
6836 break;
6837 }
6838 default:
6839 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6840 ViableConversions);
6841 }
6842 }
6843
6844 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6845}
6846
6847/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6848/// an acceptable non-member overloaded operator for a call whose
6849/// arguments have types T1 (and, if non-empty, T2). This routine
6850/// implements the check in C++ [over.match.oper]p3b2 concerning
6851/// enumeration types.
6853 FunctionDecl *Fn,
6854 ArrayRef<Expr *> Args) {
6855 QualType T1 = Args[0]->getType();
6856 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6857
6858 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6859 return true;
6860
6861 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6862 return true;
6863
6864 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6865 if (Proto->getNumParams() < 1)
6866 return false;
6867
6868 if (T1->isEnumeralType()) {
6869 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6870 if (Context.hasSameUnqualifiedType(T1, ArgType))
6871 return true;
6872 }
6873
6874 if (Proto->getNumParams() < 2)
6875 return false;
6876
6877 if (!T2.isNull() && T2->isEnumeralType()) {
6878 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6879 if (Context.hasSameUnqualifiedType(T2, ArgType))
6880 return true;
6881 }
6882
6883 return false;
6884}
6885
6888 return false;
6889
6890 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6891 return FD->isTargetMultiVersion();
6892
6893 if (!FD->isMultiVersion())
6894 return false;
6895
6896 // Among multiple target versions consider either the default,
6897 // or the first non-default in the absence of default version.
6898 unsigned SeenAt = 0;
6899 unsigned I = 0;
6900 bool HasDefault = false;
6902 FD, [&](const FunctionDecl *CurFD) {
6903 if (FD == CurFD)
6904 SeenAt = I;
6905 else if (CurFD->isTargetMultiVersionDefault())
6906 HasDefault = true;
6907 ++I;
6908 });
6909 return HasDefault || SeenAt != 0;
6910}
6911
6912/// AddOverloadCandidate - Adds the given function to the set of
6913/// candidate functions, using the given function call arguments. If
6914/// @p SuppressUserConversions, then don't allow user-defined
6915/// conversions via constructors or conversion operators.
6916///
6917/// \param PartialOverloading true if we are performing "partial" overloading
6918/// based on an incomplete set of function arguments. This feature is used by
6919/// code completion.
6922 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6923 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6924 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6925 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6926 const FunctionProtoType *Proto
6927 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6928 assert(Proto && "Functions without a prototype cannot be overloaded");
6929 assert(!Function->getDescribedFunctionTemplate() &&
6930 "Use AddTemplateOverloadCandidate for function templates");
6931
6932 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6933 if (!isa<CXXConstructorDecl>(Method)) {
6934 // If we get here, it's because we're calling a member function
6935 // that is named without a member access expression (e.g.,
6936 // "this->f") that was either written explicitly or created
6937 // implicitly. This can happen with a qualified call to a member
6938 // function, e.g., X::f(). We use an empty type for the implied
6939 // object argument (C++ [over.call.func]p3), and the acting context
6940 // is irrelevant.
6941 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6943 CandidateSet, SuppressUserConversions,
6944 PartialOverloading, EarlyConversions, PO);
6945 return;
6946 }
6947 // We treat a constructor like a non-member function, since its object
6948 // argument doesn't participate in overload resolution.
6949 }
6950
6951 if (!CandidateSet.isNewCandidate(Function, PO))
6952 return;
6953
6954 // C++11 [class.copy]p11: [DR1402]
6955 // A defaulted move constructor that is defined as deleted is ignored by
6956 // overload resolution.
6957 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6958 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6959 Constructor->isMoveConstructor())
6960 return;
6961
6962 // Overload resolution is always an unevaluated context.
6965
6966 // C++ [over.match.oper]p3:
6967 // if no operand has a class type, only those non-member functions in the
6968 // lookup set that have a first parameter of type T1 or "reference to
6969 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6970 // is a right operand) a second parameter of type T2 or "reference to
6971 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6972 // candidate functions.
6973 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6975 return;
6976
6977 // Add this candidate
6978 OverloadCandidate &Candidate =
6979 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6980 Candidate.FoundDecl = FoundDecl;
6981 Candidate.Function = Function;
6982 Candidate.Viable = true;
6983 Candidate.RewriteKind =
6984 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6985 Candidate.IsSurrogate = false;
6986 Candidate.IsADLCandidate = IsADLCandidate;
6987 Candidate.IgnoreObjectArgument = false;
6988 Candidate.ExplicitCallArguments = Args.size();
6989
6990 // Explicit functions are not actually candidates at all if we're not
6991 // allowing them in this context, but keep them around so we can point
6992 // to them in diagnostics.
6993 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6994 Candidate.Viable = false;
6995 Candidate.FailureKind = ovl_fail_explicit;
6996 return;
6997 }
6998
6999 // Functions with internal linkage are only viable in the same module unit.
7000 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7001 /// FIXME: Currently, the semantics of linkage in clang is slightly
7002 /// different from the semantics in C++ spec. In C++ spec, only names
7003 /// have linkage. So that all entities of the same should share one
7004 /// linkage. But in clang, different entities of the same could have
7005 /// different linkage.
7006 NamedDecl *ND = Function;
7007 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
7008 ND = SpecInfo->getTemplate();
7009
7010 if (ND->getFormalLinkage() == Linkage::Internal) {
7011 Candidate.Viable = false;
7013 return;
7014 }
7015 }
7016
7018 Candidate.Viable = false;
7020 return;
7021 }
7022
7023 if (Constructor) {
7024 // C++ [class.copy]p3:
7025 // A member function template is never instantiated to perform the copy
7026 // of a class object to an object of its class type.
7027 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7028 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7029 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7030 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7031 ClassType))) {
7032 Candidate.Viable = false;
7034 return;
7035 }
7036
7037 // C++ [over.match.funcs]p8: (proposed DR resolution)
7038 // A constructor inherited from class type C that has a first parameter
7039 // of type "reference to P" (including such a constructor instantiated
7040 // from a template) is excluded from the set of candidate functions when
7041 // constructing an object of type cv D if the argument list has exactly
7042 // one argument and D is reference-related to P and P is reference-related
7043 // to C.
7044 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7045 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7046 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7047 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7048 QualType C = Context.getRecordType(Constructor->getParent());
7049 QualType D = Context.getRecordType(Shadow->getParent());
7050 SourceLocation Loc = Args.front()->getExprLoc();
7051 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7052 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7053 Candidate.Viable = false;
7055 return;
7056 }
7057 }
7058
7059 // Check that the constructor is capable of constructing an object in the
7060 // destination address space.
7062 Constructor->getMethodQualifiers().getAddressSpace(),
7063 CandidateSet.getDestAS())) {
7064 Candidate.Viable = false;
7066 }
7067 }
7068
7069 unsigned NumParams = Proto->getNumParams();
7070
7071 // (C++ 13.3.2p2): A candidate function having fewer than m
7072 // parameters is viable only if it has an ellipsis in its parameter
7073 // list (8.3.5).
7074 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7075 !Proto->isVariadic() &&
7076 shouldEnforceArgLimit(PartialOverloading, Function)) {
7077 Candidate.Viable = false;
7079 return;
7080 }
7081
7082 // (C++ 13.3.2p2): A candidate function having more than m parameters
7083 // is viable only if the (m+1)st parameter has a default argument
7084 // (8.3.6). For the purposes of overload resolution, the
7085 // parameter list is truncated on the right, so that there are
7086 // exactly m parameters.
7087 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7088 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7089 !PartialOverloading) {
7090 // Not enough arguments.
7091 Candidate.Viable = false;
7093 return;
7094 }
7095
7096 // (CUDA B.1): Check for invalid calls between targets.
7097 if (getLangOpts().CUDA) {
7098 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7099 // Skip the check for callers that are implicit members, because in this
7100 // case we may not yet know what the member's target is; the target is
7101 // inferred for the member automatically, based on the bases and fields of
7102 // the class.
7103 if (!(Caller && Caller->isImplicit()) &&
7104 !CUDA().IsAllowedCall(Caller, Function)) {
7105 Candidate.Viable = false;
7106 Candidate.FailureKind = ovl_fail_bad_target;
7107 return;
7108 }
7109 }
7110
7111 if (Function->getTrailingRequiresClause()) {
7112 ConstraintSatisfaction Satisfaction;
7113 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7114 /*ForOverloadResolution*/ true) ||
7115 !Satisfaction.IsSatisfied) {
7116 Candidate.Viable = false;
7118 return;
7119 }
7120 }
7121
7122 // Determine the implicit conversion sequences for each of the
7123 // arguments.
7124 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7125 unsigned ConvIdx =
7126 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7127 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7128 // We already formed a conversion sequence for this parameter during
7129 // template argument deduction.
7130 } else if (ArgIdx < NumParams) {
7131 // (C++ 13.3.2p3): for F to be a viable function, there shall
7132 // exist for each argument an implicit conversion sequence
7133 // (13.3.3.1) that converts that argument to the corresponding
7134 // parameter of F.
7135 QualType ParamType = Proto->getParamType(ArgIdx);
7136 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7137 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7138 /*InOverloadResolution=*/true,
7139 /*AllowObjCWritebackConversion=*/
7140 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7141 if (Candidate.Conversions[ConvIdx].isBad()) {
7142 Candidate.Viable = false;
7144 return;
7145 }
7146 } else {
7147 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7148 // argument for which there is no corresponding parameter is
7149 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7150 Candidate.Conversions[ConvIdx].setEllipsis();
7151 }
7152 }
7153
7154 if (EnableIfAttr *FailedAttr =
7155 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7156 Candidate.Viable = false;
7157 Candidate.FailureKind = ovl_fail_enable_if;
7158 Candidate.DeductionFailure.Data = FailedAttr;
7159 return;
7160 }
7161}
7162
7164Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7166 if (Methods.size() <= 1)
7167 return nullptr;
7168
7169 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7170 bool Match = true;
7171 ObjCMethodDecl *Method = Methods[b];
7172 unsigned NumNamedArgs = Sel.getNumArgs();
7173 // Method might have more arguments than selector indicates. This is due
7174 // to addition of c-style arguments in method.
7175 if (Method->param_size() > NumNamedArgs)
7176 NumNamedArgs = Method->param_size();
7177 if (Args.size() < NumNamedArgs)
7178 continue;
7179
7180 for (unsigned i = 0; i < NumNamedArgs; i++) {
7181 // We can't do any type-checking on a type-dependent argument.
7182 if (Args[i]->isTypeDependent()) {
7183 Match = false;
7184 break;
7185 }
7186
7187 ParmVarDecl *param = Method->parameters()[i];
7188 Expr *argExpr = Args[i];
7189 assert(argExpr && "SelectBestMethod(): missing expression");
7190
7191 // Strip the unbridged-cast placeholder expression off unless it's
7192 // a consumed argument.
7193 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7194 !param->hasAttr<CFConsumedAttr>())
7195 argExpr = stripARCUnbridgedCast(argExpr);
7196
7197 // If the parameter is __unknown_anytype, move on to the next method.
7198 if (param->getType() == Context.UnknownAnyTy) {
7199 Match = false;
7200 break;
7201 }
7202
7203 ImplicitConversionSequence ConversionState
7204 = TryCopyInitialization(*this, argExpr, param->getType(),
7205 /*SuppressUserConversions*/false,
7206 /*InOverloadResolution=*/true,
7207 /*AllowObjCWritebackConversion=*/
7208 getLangOpts().ObjCAutoRefCount,
7209 /*AllowExplicit*/false);
7210 // This function looks for a reasonably-exact match, so we consider
7211 // incompatible pointer conversions to be a failure here.
7212 if (ConversionState.isBad() ||
7213 (ConversionState.isStandard() &&
7214 ConversionState.Standard.Second ==
7216 Match = false;
7217 break;
7218 }
7219 }
7220 // Promote additional arguments to variadic methods.
7221 if (Match && Method->isVariadic()) {
7222 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7223 if (Args[i]->isTypeDependent()) {
7224 Match = false;
7225 break;
7226 }
7227 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7228 nullptr);
7229 if (Arg.isInvalid()) {
7230 Match = false;
7231 break;
7232 }
7233 }
7234 } else {
7235 // Check for extra arguments to non-variadic methods.
7236 if (Args.size() != NumNamedArgs)
7237 Match = false;
7238 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7239 // Special case when selectors have no argument. In this case, select
7240 // one with the most general result type of 'id'.
7241 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7242 QualType ReturnT = Methods[b]->getReturnType();
7243 if (ReturnT->isObjCIdType())
7244 return Methods[b];
7245 }
7246 }
7247 }
7248
7249 if (Match)
7250 return Method;
7251 }
7252 return nullptr;
7253}
7254
7256 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7257 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7258 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7259 if (ThisArg) {
7260 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7261 assert(!isa<CXXConstructorDecl>(Method) &&
7262 "Shouldn't have `this` for ctors!");
7263 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7265 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7266 if (R.isInvalid())
7267 return false;
7268 ConvertedThis = R.get();
7269 } else {
7270 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7271 (void)MD;
7272 assert((MissingImplicitThis || MD->isStatic() ||
7273 isa<CXXConstructorDecl>(MD)) &&
7274 "Expected `this` for non-ctor instance methods");
7275 }
7276 ConvertedThis = nullptr;
7277 }
7278
7279 // Ignore any variadic arguments. Converting them is pointless, since the
7280 // user can't refer to them in the function condition.
7281 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7282
7283 // Convert the arguments.
7284 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7285 ExprResult R;
7287 S.Context, Function->getParamDecl(I)),
7288 SourceLocation(), Args[I]);
7289
7290 if (R.isInvalid())
7291 return false;
7292
7293 ConvertedArgs.push_back(R.get());
7294 }
7295
7296 if (Trap.hasErrorOccurred())
7297 return false;
7298
7299 // Push default arguments if needed.
7300 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7301 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7302 ParmVarDecl *P = Function->getParamDecl(i);
7303 if (!P->hasDefaultArg())
7304 return false;
7306 if (R.isInvalid())
7307 return false;
7308 ConvertedArgs.push_back(R.get());
7309 }
7310
7311 if (Trap.hasErrorOccurred())
7312 return false;
7313 }
7314 return true;
7315}
7316
7318 SourceLocation CallLoc,
7319 ArrayRef<Expr *> Args,
7320 bool MissingImplicitThis) {
7321 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7322 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7323 return nullptr;
7324
7325 SFINAETrap Trap(*this);
7326 SmallVector<Expr *, 16> ConvertedArgs;
7327 // FIXME: We should look into making enable_if late-parsed.
7328 Expr *DiscardedThis;
7330 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7331 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7332 return *EnableIfAttrs.begin();
7333
7334 for (auto *EIA : EnableIfAttrs) {
7336 // FIXME: This doesn't consider value-dependent cases, because doing so is
7337 // very difficult. Ideally, we should handle them more gracefully.
7338 if (EIA->getCond()->isValueDependent() ||
7339 !EIA->getCond()->EvaluateWithSubstitution(
7340 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7341 return EIA;
7342
7343 if (!Result.isInt() || !Result.getInt().getBoolValue())
7344 return EIA;
7345 }
7346 return nullptr;
7347}
7348
7349template <typename CheckFn>
7351 bool ArgDependent, SourceLocation Loc,
7352 CheckFn &&IsSuccessful) {
7354 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7355 if (ArgDependent == DIA->getArgDependent())
7356 Attrs.push_back(DIA);
7357 }
7358
7359 // Common case: No diagnose_if attributes, so we can quit early.
7360 if (Attrs.empty())
7361 return false;
7362
7363 auto WarningBegin = std::stable_partition(
7364 Attrs.begin(), Attrs.end(),
7365 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7366
7367 // Note that diagnose_if attributes are late-parsed, so they appear in the
7368 // correct order (unlike enable_if attributes).
7369 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7370 IsSuccessful);
7371 if (ErrAttr != WarningBegin) {
7372 const DiagnoseIfAttr *DIA = *ErrAttr;
7373 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7374 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7375 << DIA->getParent() << DIA->getCond()->getSourceRange();
7376 return true;
7377 }
7378
7379 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7380 if (IsSuccessful(DIA)) {
7381 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7382 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7383 << DIA->getParent() << DIA->getCond()->getSourceRange();
7384 }
7385
7386 return false;
7387}
7388
7390 const Expr *ThisArg,
7392 SourceLocation Loc) {
7394 *this, Function, /*ArgDependent=*/true, Loc,
7395 [&](const DiagnoseIfAttr *DIA) {
7397 // It's sane to use the same Args for any redecl of this function, since
7398 // EvaluateWithSubstitution only cares about the position of each
7399 // argument in the arg list, not the ParmVarDecl* it maps to.
7400 if (!DIA->getCond()->EvaluateWithSubstitution(
7401 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7402 return false;
7403 return Result.isInt() && Result.getInt().getBoolValue();
7404 });
7405}
7406
7408 SourceLocation Loc) {
7410 *this, ND, /*ArgDependent=*/false, Loc,
7411 [&](const DiagnoseIfAttr *DIA) {
7412 bool Result;
7413 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7414 Result;
7415 });
7416}
7417
7418/// Add all of the function declarations in the given function set to
7419/// the overload candidate set.
7421 ArrayRef<Expr *> Args,
7422 OverloadCandidateSet &CandidateSet,
7423 TemplateArgumentListInfo *ExplicitTemplateArgs,
7424 bool SuppressUserConversions,
7425 bool PartialOverloading,
7426 bool FirstArgumentIsBase) {
7427 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7428 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7429 ArrayRef<Expr *> FunctionArgs = Args;
7430
7431 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7432 FunctionDecl *FD =
7433 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7434
7435 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7436 QualType ObjectType;
7437 Expr::Classification ObjectClassification;
7438 if (Args.size() > 0) {
7439 if (Expr *E = Args[0]) {
7440 // Use the explicit base to restrict the lookup:
7441 ObjectType = E->getType();
7442 // Pointers in the object arguments are implicitly dereferenced, so we
7443 // always classify them as l-values.
7444 if (!ObjectType.isNull() && ObjectType->isPointerType())
7445 ObjectClassification = Expr::Classification::makeSimpleLValue();
7446 else
7447 ObjectClassification = E->Classify(Context);
7448 } // .. else there is an implicit base.
7449 FunctionArgs = Args.slice(1);
7450 }
7451 if (FunTmpl) {
7452 AddMethodTemplateCandidate(
7453 FunTmpl, F.getPair(),
7454 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7455 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7456 FunctionArgs, CandidateSet, SuppressUserConversions,
7457 PartialOverloading);
7458 } else {
7459 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7460 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7461 ObjectClassification, FunctionArgs, CandidateSet,
7462 SuppressUserConversions, PartialOverloading);
7463 }
7464 } else {
7465 // This branch handles both standalone functions and static methods.
7466
7467 // Slice the first argument (which is the base) when we access
7468 // static method as non-static.
7469 if (Args.size() > 0 &&
7470 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7471 !isa<CXXConstructorDecl>(FD)))) {
7472 assert(cast<CXXMethodDecl>(FD)->isStatic());
7473 FunctionArgs = Args.slice(1);
7474 }
7475 if (FunTmpl) {
7476 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7477 ExplicitTemplateArgs, FunctionArgs,
7478 CandidateSet, SuppressUserConversions,
7479 PartialOverloading);
7480 } else {
7481 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7482 SuppressUserConversions, PartialOverloading);
7483 }
7484 }
7485 }
7486}
7487
7488/// AddMethodCandidate - Adds a named decl (which is some kind of
7489/// method) as a method candidate to the given overload set.
7491 Expr::Classification ObjectClassification,
7492 ArrayRef<Expr *> Args,
7493 OverloadCandidateSet &CandidateSet,
7494 bool SuppressUserConversions,
7496 NamedDecl *Decl = FoundDecl.getDecl();
7497 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7498
7499 if (isa<UsingShadowDecl>(Decl))
7500 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7501
7502 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7503 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7504 "Expected a member function template");
7505 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7506 /*ExplicitArgs*/ nullptr, ObjectType,
7507 ObjectClassification, Args, CandidateSet,
7508 SuppressUserConversions, false, PO);
7509 } else {
7510 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7511 ObjectType, ObjectClassification, Args, CandidateSet,
7512 SuppressUserConversions, false, std::nullopt, PO);
7513 }
7514}
7515
7516/// AddMethodCandidate - Adds the given C++ member function to the set
7517/// of candidate functions, using the given function call arguments
7518/// and the object argument (@c Object). For example, in a call
7519/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7520/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7521/// allow user-defined conversions via constructors or conversion
7522/// operators.
7523void
7525 CXXRecordDecl *ActingContext, QualType ObjectType,
7526 Expr::Classification ObjectClassification,
7527 ArrayRef<Expr *> Args,
7528 OverloadCandidateSet &CandidateSet,
7529 bool SuppressUserConversions,
7530 bool PartialOverloading,
7531 ConversionSequenceList EarlyConversions,
7533 const FunctionProtoType *Proto
7534 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7535 assert(Proto && "Methods without a prototype cannot be overloaded");
7536 assert(!isa<CXXConstructorDecl>(Method) &&
7537 "Use AddOverloadCandidate for constructors");
7538
7539 if (!CandidateSet.isNewCandidate(Method, PO))
7540 return;
7541
7542 // C++11 [class.copy]p23: [DR1402]
7543 // A defaulted move assignment operator that is defined as deleted is
7544 // ignored by overload resolution.
7545 if (Method->isDefaulted() && Method->isDeleted() &&
7546 Method->isMoveAssignmentOperator())
7547 return;
7548
7549 // Overload resolution is always an unevaluated context.
7552
7553 // Add this candidate
7554 OverloadCandidate &Candidate =
7555 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7556 Candidate.FoundDecl = FoundDecl;
7557 Candidate.Function = Method;
7558 Candidate.RewriteKind =
7559 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7560 Candidate.IsSurrogate = false;
7561 Candidate.IgnoreObjectArgument = false;
7562 Candidate.ExplicitCallArguments = Args.size();
7563
7564 unsigned NumParams = Method->getNumExplicitParams();
7565 unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7566
7567 // (C++ 13.3.2p2): A candidate function having fewer than m
7568 // parameters is viable only if it has an ellipsis in its parameter
7569 // list (8.3.5).
7570 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7571 !Proto->isVariadic() &&
7572 shouldEnforceArgLimit(PartialOverloading, Method)) {
7573 Candidate.Viable = false;
7575 return;
7576 }
7577
7578 // (C++ 13.3.2p2): A candidate function having more than m parameters
7579 // is viable only if the (m+1)st parameter has a default argument
7580 // (8.3.6). For the purposes of overload resolution, the
7581 // parameter list is truncated on the right, so that there are
7582 // exactly m parameters.
7583 unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7584 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7585 // Not enough arguments.
7586 Candidate.Viable = false;
7588 return;
7589 }
7590
7591 Candidate.Viable = true;
7592
7593 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7594 if (ObjectType.isNull())
7595 Candidate.IgnoreObjectArgument = true;
7596 else if (Method->isStatic()) {
7597 // [over.best.ics.general]p8
7598 // When the parameter is the implicit object parameter of a static member
7599 // function, the implicit conversion sequence is a standard conversion
7600 // sequence that is neither better nor worse than any other standard
7601 // conversion sequence.
7602 //
7603 // This is a rule that was introduced in C++23 to support static lambdas. We
7604 // apply it retroactively because we want to support static lambdas as an
7605 // extension and it doesn't hurt previous code.
7606 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7607 } else {
7608 // Determine the implicit conversion sequence for the object
7609 // parameter.
7610 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7611 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7612 Method, ActingContext, /*InOverloadResolution=*/true);
7613 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7614 Candidate.Viable = false;
7616 return;
7617 }
7618 }
7619
7620 // (CUDA B.1): Check for invalid calls between targets.
7621 if (getLangOpts().CUDA)
7622 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7623 Method)) {
7624 Candidate.Viable = false;
7625 Candidate.FailureKind = ovl_fail_bad_target;
7626 return;
7627 }
7628
7629 if (Method->getTrailingRequiresClause()) {
7630 ConstraintSatisfaction Satisfaction;
7631 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7632 /*ForOverloadResolution*/ true) ||
7633 !Satisfaction.IsSatisfied) {
7634 Candidate.Viable = false;
7636 return;
7637 }
7638 }
7639
7640 // Determine the implicit conversion sequences for each of the
7641 // arguments.
7642 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7643 unsigned ConvIdx =
7644 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7645 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7646 // We already formed a conversion sequence for this parameter during
7647 // template argument deduction.
7648 } else if (ArgIdx < NumParams) {
7649 // (C++ 13.3.2p3): for F to be a viable function, there shall
7650 // exist for each argument an implicit conversion sequence
7651 // (13.3.3.1) that converts that argument to the corresponding
7652 // parameter of F.
7653 QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7654 Candidate.Conversions[ConvIdx]
7655 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7656 SuppressUserConversions,
7657 /*InOverloadResolution=*/true,
7658 /*AllowObjCWritebackConversion=*/
7659 getLangOpts().ObjCAutoRefCount);
7660 if (Candidate.Conversions[ConvIdx].isBad()) {
7661 Candidate.Viable = false;
7663 return;
7664 }
7665 } else {
7666 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7667 // argument for which there is no corresponding parameter is
7668 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7669 Candidate.Conversions[ConvIdx].setEllipsis();
7670 }
7671 }
7672
7673 if (EnableIfAttr *FailedAttr =
7674 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7675 Candidate.Viable = false;
7676 Candidate.FailureKind = ovl_fail_enable_if;
7677 Candidate.DeductionFailure.Data = FailedAttr;
7678 return;
7679 }
7680
7681 if (isNonViableMultiVersionOverload(Method)) {
7682 Candidate.Viable = false;
7684 }
7685}
7686
7687/// Add a C++ member function template as a candidate to the candidate
7688/// set, using template argument deduction to produce an appropriate member
7689/// function template specialization.
7691 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7692 CXXRecordDecl *ActingContext,
7693 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7694 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7695 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7696 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7697 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7698 return;
7699
7700 // C++ [over.match.funcs]p7:
7701 // In each case where a candidate is a function template, candidate
7702 // function template specializations are generated using template argument
7703 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7704 // candidate functions in the usual way.113) A given name can refer to one
7705 // or more function templates and also to a set of overloaded non-template
7706 // functions. In such a case, the candidate functions generated from each
7707 // function template are combined with the set of non-template candidate
7708 // functions.
7709 TemplateDeductionInfo Info(CandidateSet.getLocation());
7710 FunctionDecl *Specialization = nullptr;
7711 ConversionSequenceList Conversions;
7713 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7714 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7715 ObjectClassification,
7716 [&](ArrayRef<QualType> ParamTypes) {
7717 return CheckNonDependentConversions(
7718 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7719 SuppressUserConversions, ActingContext, ObjectType,
7720 ObjectClassification, PO);
7721 });
7723 OverloadCandidate &Candidate =
7724 CandidateSet.addCandidate(Conversions.size(), Conversions);
7725 Candidate.FoundDecl = FoundDecl;
7726 Candidate.Function = MethodTmpl->getTemplatedDecl();
7727 Candidate.Viable = false;
7728 Candidate.RewriteKind =
7729 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7730 Candidate.IsSurrogate = false;
7731 Candidate.IgnoreObjectArgument =
7732 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7733 ObjectType.isNull();
7734 Candidate.ExplicitCallArguments = Args.size();
7737 else {
7740 Info);
7741 }
7742 return;
7743 }
7744
7745 // Add the function template specialization produced by template argument
7746 // deduction as a candidate.
7747 assert(Specialization && "Missing member function template specialization?");
7748 assert(isa<CXXMethodDecl>(Specialization) &&
7749 "Specialization is not a member function?");
7750 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7751 ActingContext, ObjectType, ObjectClassification, Args,
7752 CandidateSet, SuppressUserConversions, PartialOverloading,
7753 Conversions, PO);
7754}
7755
7756/// Determine whether a given function template has a simple explicit specifier
7757/// or a non-value-dependent explicit-specification that evaluates to true.
7760}
7761
7762/// Add a C++ function template specialization as a candidate
7763/// in the candidate set, using template argument deduction to produce
7764/// an appropriate function template specialization.
7766 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7767 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7768 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7769 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7770 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7771 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7772 return;
7773
7774 // If the function template has a non-dependent explicit specification,
7775 // exclude it now if appropriate; we are not permitted to perform deduction
7776 // and substitution in this case.
7777 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7778 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7779 Candidate.FoundDecl = FoundDecl;
7780 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7781 Candidate.Viable = false;
7782 Candidate.FailureKind = ovl_fail_explicit;
7783 return;
7784 }
7785
7786 // C++ [over.match.funcs]p7:
7787 // In each case where a candidate is a function template, candidate
7788 // function template specializations are generated using template argument
7789 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7790 // candidate functions in the usual way.113) A given name can refer to one
7791 // or more function templates and also to a set of overloaded non-template
7792 // functions. In such a case, the candidate functions generated from each
7793 // function template are combined with the set of non-template candidate
7794 // functions.
7795 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7796 FunctionTemplate->getTemplateDepth());
7797 FunctionDecl *Specialization = nullptr;
7798 ConversionSequenceList Conversions;
7800 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7801 PartialOverloading, AggregateCandidateDeduction,
7802 /*ObjectType=*/QualType(),
7803 /*ObjectClassification=*/Expr::Classification(),
7804 [&](ArrayRef<QualType> ParamTypes) {
7805 return CheckNonDependentConversions(
7806 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7807 SuppressUserConversions, nullptr, QualType(), {}, PO);
7808 });
7810 OverloadCandidate &Candidate =
7811 CandidateSet.addCandidate(Conversions.size(), Conversions);
7812 Candidate.FoundDecl = FoundDecl;
7813 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7814 Candidate.Viable = false;
7815 Candidate.RewriteKind =
7816 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7817 Candidate.IsSurrogate = false;
7818 Candidate.IsADLCandidate = IsADLCandidate;
7819 // Ignore the object argument if there is one, since we don't have an object
7820 // type.
7821 Candidate.IgnoreObjectArgument =
7822 isa<CXXMethodDecl>(Candidate.Function) &&
7823 !isa<CXXConstructorDecl>(Candidate.Function);
7824 Candidate.ExplicitCallArguments = Args.size();
7827 else {
7830 Info);
7831 }
7832 return;
7833 }
7834
7835 // Add the function template specialization produced by template argument
7836 // deduction as a candidate.
7837 assert(Specialization && "Missing function template specialization?");
7838 AddOverloadCandidate(
7839 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7840 PartialOverloading, AllowExplicit,
7841 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7843}
7844
7845/// Check that implicit conversion sequences can be formed for each argument
7846/// whose corresponding parameter has a non-dependent type, per DR1391's
7847/// [temp.deduct.call]p10.
7849 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7850 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7851 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7852 CXXRecordDecl *ActingContext, QualType ObjectType,
7853 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7854 // FIXME: The cases in which we allow explicit conversions for constructor
7855 // arguments never consider calling a constructor template. It's not clear
7856 // that is correct.
7857 const bool AllowExplicit = false;
7858
7859 auto *FD = FunctionTemplate->getTemplatedDecl();
7860 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7861 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7862 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7863
7864 Conversions =
7865 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7866
7867 // Overload resolution is always an unevaluated context.
7870
7871 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7872 // require that, but this check should never result in a hard error, and
7873 // overload resolution is permitted to sidestep instantiations.
7874 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7875 !ObjectType.isNull()) {
7876 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7877 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7878 !ParamTypes[0]->isDependentType()) {
7879 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7880 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7881 Method, ActingContext, /*InOverloadResolution=*/true,
7882 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7883 : QualType());
7884 if (Conversions[ConvIdx].isBad())
7885 return true;
7886 }
7887 }
7888
7889 unsigned Offset =
7890 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7891
7892 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7893 I != N; ++I) {
7894 QualType ParamType = ParamTypes[I + Offset];
7895 if (!ParamType->isDependentType()) {
7896 unsigned ConvIdx;
7898 ConvIdx = Args.size() - 1 - I;
7899 assert(Args.size() + ThisConversions == 2 &&
7900 "number of args (including 'this') must be exactly 2 for "
7901 "reversed order");
7902 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7903 // would also be 0. 'this' got ConvIdx = 1 previously.
7904 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7905 } else {
7906 // For members, 'this' got ConvIdx = 0 previously.
7907 ConvIdx = ThisConversions + I;
7908 }
7909 Conversions[ConvIdx]
7910 = TryCopyInitialization(*this, Args[I], ParamType,
7911 SuppressUserConversions,
7912 /*InOverloadResolution=*/true,
7913 /*AllowObjCWritebackConversion=*/
7914 getLangOpts().ObjCAutoRefCount,
7915 AllowExplicit);
7916 if (Conversions[ConvIdx].isBad())
7917 return true;
7918 }
7919 }
7920
7921 return false;
7922}
7923
7924/// Determine whether this is an allowable conversion from the result
7925/// of an explicit conversion operator to the expected type, per C++
7926/// [over.match.conv]p1 and [over.match.ref]p1.
7927///
7928/// \param ConvType The return type of the conversion function.
7929///
7930/// \param ToType The type we are converting to.
7931///
7932/// \param AllowObjCPointerConversion Allow a conversion from one
7933/// Objective-C pointer to another.
7934///
7935/// \returns true if the conversion is allowable, false otherwise.
7937 QualType ConvType, QualType ToType,
7938 bool AllowObjCPointerConversion) {
7939 QualType ToNonRefType = ToType.getNonReferenceType();
7940
7941 // Easy case: the types are the same.
7942 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7943 return true;
7944
7945 // Allow qualification conversions.
7946 bool ObjCLifetimeConversion;
7947 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7948 ObjCLifetimeConversion))
7949 return true;
7950
7951 // If we're not allowed to consider Objective-C pointer conversions,
7952 // we're done.
7953 if (!AllowObjCPointerConversion)
7954 return false;
7955
7956 // Is this an Objective-C pointer conversion?
7957 bool IncompatibleObjC = false;
7958 QualType ConvertedType;
7959 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7960 IncompatibleObjC);
7961}
7962
7963/// AddConversionCandidate - Add a C++ conversion function as a
7964/// candidate in the candidate set (C++ [over.match.conv],
7965/// C++ [over.match.copy]). From is the expression we're converting from,
7966/// and ToType is the type that we're eventually trying to convert to
7967/// (which may or may not be the same type as the type that the
7968/// conversion function produces).
7970 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7971 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7972 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7973 bool AllowExplicit, bool AllowResultConversion) {
7974 assert(!Conversion->getDescribedFunctionTemplate() &&
7975 "Conversion function templates use AddTemplateConversionCandidate");
7976 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7977 if (!CandidateSet.isNewCandidate(Conversion))
7978 return;
7979
7980 // If the conversion function has an undeduced return type, trigger its
7981 // deduction now.
7982 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7983 if (DeduceReturnType(Conversion, From->getExprLoc()))
7984 return;
7985 ConvType = Conversion->getConversionType().getNonReferenceType();
7986 }
7987
7988 // If we don't allow any conversion of the result type, ignore conversion
7989 // functions that don't convert to exactly (possibly cv-qualified) T.
7990 if (!AllowResultConversion &&
7991 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7992 return;
7993
7994 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7995 // operator is only a candidate if its return type is the target type or
7996 // can be converted to the target type with a qualification conversion.
7997 //
7998 // FIXME: Include such functions in the candidate list and explain why we
7999 // can't select them.
8000 if (Conversion->isExplicit() &&
8001 !isAllowableExplicitConversion(*this, ConvType, ToType,
8002 AllowObjCConversionOnExplicit))
8003 return;
8004
8005 // Overload resolution is always an unevaluated context.
8008
8009 // Add this candidate
8010 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8011 Candidate.FoundDecl = FoundDecl;
8012 Candidate.Function = Conversion;
8013 Candidate.IsSurrogate = false;
8014 Candidate.IgnoreObjectArgument = false;
8016 Candidate.FinalConversion.setFromType(ConvType);
8017 Candidate.FinalConversion.setAllToTypes(ToType);
8018 Candidate.Viable = true;
8019 Candidate.ExplicitCallArguments = 1;
8020
8021 // Explicit functions are not actually candidates at all if we're not
8022 // allowing them in this context, but keep them around so we can point
8023 // to them in diagnostics.
8024 if (!AllowExplicit && Conversion->isExplicit()) {
8025 Candidate.Viable = false;
8026 Candidate.FailureKind = ovl_fail_explicit;
8027 return;
8028 }
8029
8030 // C++ [over.match.funcs]p4:
8031 // For conversion functions, the function is considered to be a member of
8032 // the class of the implicit implied object argument for the purpose of
8033 // defining the type of the implicit object parameter.
8034 //
8035 // Determine the implicit conversion sequence for the implicit
8036 // object parameter.
8037 QualType ObjectType = From->getType();
8038 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8039 ObjectType = FromPtrType->getPointeeType();
8040 const auto *ConversionContext =
8041 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8042
8043 // C++23 [over.best.ics.general]
8044 // However, if the target is [...]
8045 // - the object parameter of a user-defined conversion function
8046 // [...] user-defined conversion sequences are not considered.
8048 *this, CandidateSet.getLocation(), From->getType(),
8049 From->Classify(Context), Conversion, ConversionContext,
8050 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8051 /*SuppressUserConversion*/ true);
8052
8053 if (Candidate.Conversions[0].isBad()) {
8054 Candidate.Viable = false;
8056 return;
8057 }
8058
8059 if (Conversion->getTrailingRequiresClause()) {
8060 ConstraintSatisfaction Satisfaction;
8061 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8062 !Satisfaction.IsSatisfied) {
8063 Candidate.Viable = false;
8065 return;
8066 }
8067 }
8068
8069 // We won't go through a user-defined type conversion function to convert a
8070 // derived to base as such conversions are given Conversion Rank. They only
8071 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8072 QualType FromCanon
8073 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8074 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8075 if (FromCanon == ToCanon ||
8076 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8077 Candidate.Viable = false;
8079 return;
8080 }
8081
8082 // To determine what the conversion from the result of calling the
8083 // conversion function to the type we're eventually trying to
8084 // convert to (ToType), we need to synthesize a call to the
8085 // conversion function and attempt copy initialization from it. This
8086 // makes sure that we get the right semantics with respect to
8087 // lvalues/rvalues and the type. Fortunately, we can allocate this
8088 // call on the stack and we don't need its arguments to be
8089 // well-formed.
8090 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8091 VK_LValue, From->getBeginLoc());
8093 Context.getPointerType(Conversion->getType()),
8094 CK_FunctionToPointerDecay, &ConversionRef,
8096
8097 QualType ConversionType = Conversion->getConversionType();
8098 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8099 Candidate.Viable = false;
8101 return;
8102 }
8103
8104 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8105
8106 // Note that it is safe to allocate CallExpr on the stack here because
8107 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8108 // allocator).
8109 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8110
8111 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8112 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8113 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8114
8116 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8117 /*SuppressUserConversions=*/true,
8118 /*InOverloadResolution=*/false,
8119 /*AllowObjCWritebackConversion=*/false);
8120
8121 switch (ICS.getKind()) {
8123 Candidate.FinalConversion = ICS.Standard;
8124
8125 // C++ [over.ics.user]p3:
8126 // If the user-defined conversion is specified by a specialization of a
8127 // conversion function template, the second standard conversion sequence
8128 // shall have exact match rank.
8129 if (Conversion->getPrimaryTemplate() &&
8131 Candidate.Viable = false;
8133 return;
8134 }
8135
8136 // C++0x [dcl.init.ref]p5:
8137 // In the second case, if the reference is an rvalue reference and
8138 // the second standard conversion sequence of the user-defined
8139 // conversion sequence includes an lvalue-to-rvalue conversion, the
8140 // program is ill-formed.
8141 if (ToType->isRValueReferenceType() &&
8143 Candidate.Viable = false;
8145 return;
8146 }
8147 break;
8148
8150 Candidate.Viable = false;
8152 return;
8153
8154 default:
8155 llvm_unreachable(
8156 "Can only end up with a standard conversion sequence or failure");
8157 }
8158
8159 if (EnableIfAttr *FailedAttr =
8160 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8161 Candidate.Viable = false;
8162 Candidate.FailureKind = ovl_fail_enable_if;
8163 Candidate.DeductionFailure.Data = FailedAttr;
8164 return;
8165 }
8166
8167 if (isNonViableMultiVersionOverload(Conversion)) {
8168 Candidate.Viable = false;
8170 }
8171}
8172
8173/// Adds a conversion function template specialization
8174/// candidate to the overload set, using template argument deduction
8175/// to deduce the template arguments of the conversion function
8176/// template from the type that we are converting to (C++
8177/// [temp.deduct.conv]).
8179 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8180 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8181 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8182 bool AllowExplicit, bool AllowResultConversion) {
8183 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8184 "Only conversion function templates permitted here");
8185
8186 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8187 return;
8188
8189 // If the function template has a non-dependent explicit specification,
8190 // exclude it now if appropriate; we are not permitted to perform deduction
8191 // and substitution in this case.
8192 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8193 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8194 Candidate.FoundDecl = FoundDecl;
8195 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8196 Candidate.Viable = false;
8197 Candidate.FailureKind = ovl_fail_explicit;
8198 return;
8199 }
8200
8201 QualType ObjectType = From->getType();
8202 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8203
8204 TemplateDeductionInfo Info(CandidateSet.getLocation());
8207 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8208 Specialization, Info);
8210 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8211 Candidate.FoundDecl = FoundDecl;
8212 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8213 Candidate.Viable = false;
8215 Candidate.IsSurrogate = false;
8216 Candidate.IgnoreObjectArgument = false;
8217 Candidate.ExplicitCallArguments = 1;
8219 Info);
8220 return;
8221 }
8222
8223 // Add the conversion function template specialization produced by
8224 // template argument deduction as a candidate.
8225 assert(Specialization && "Missing function template specialization?");
8226 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8227 CandidateSet, AllowObjCConversionOnExplicit,
8228 AllowExplicit, AllowResultConversion);
8229}
8230
8231/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8232/// converts the given @c Object to a function pointer via the
8233/// conversion function @c Conversion, and then attempts to call it
8234/// with the given arguments (C++ [over.call.object]p2-4). Proto is
8235/// the type of function that we'll eventually be calling.
8237 DeclAccessPair FoundDecl,
8238 CXXRecordDecl *ActingContext,
8239 const FunctionProtoType *Proto,
8240 Expr *Object,
8241 ArrayRef<Expr *> Args,
8242 OverloadCandidateSet& CandidateSet) {
8243 if (!CandidateSet.isNewCandidate(Conversion))
8244 return;
8245
8246 // Overload resolution is always an unevaluated context.
8249
8250 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8251 Candidate.FoundDecl = FoundDecl;
8252 Candidate.Function = nullptr;
8253 Candidate.Surrogate = Conversion;
8254 Candidate.Viable = true;
8255 Candidate.IsSurrogate = true;
8256 Candidate.IgnoreObjectArgument = false;
8257 Candidate.ExplicitCallArguments = Args.size();
8258
8259 // Determine the implicit conversion sequence for the implicit
8260 // object parameter.
8261 ImplicitConversionSequence ObjectInit;
8262 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8263 ObjectInit = TryCopyInitialization(*this, Object,
8264 Conversion->getParamDecl(0)->getType(),
8265 /*SuppressUserConversions=*/false,
8266 /*InOverloadResolution=*/true, false);
8267 } else {
8269 *this, CandidateSet.getLocation(), Object->getType(),
8270 Object->Classify(Context), Conversion, ActingContext);
8271 }
8272
8273 if (ObjectInit.isBad()) {
8274 Candidate.Viable = false;
8276 Candidate.Conversions[0] = ObjectInit;
8277 return;
8278 }
8279
8280 // The first conversion is actually a user-defined conversion whose
8281 // first conversion is ObjectInit's standard conversion (which is
8282 // effectively a reference binding). Record it as such.
8283 Candidate.Conversions[0].setUserDefined();
8284 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8285 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8286 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8287 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8288 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8289 Candidate.Conversions[0].UserDefined.After
8290 = Candidate.Conversions[0].UserDefined.Before;
8291 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8292
8293 // Find the
8294 unsigned NumParams = Proto->getNumParams();
8295
8296 // (C++ 13.3.2p2): A candidate function having fewer than m
8297 // parameters is viable only if it has an ellipsis in its parameter
8298 // list (8.3.5).
8299 if (Args.size() > NumParams && !Proto->isVariadic()) {
8300 Candidate.Viable = false;
8302 return;
8303 }
8304
8305 // Function types don't have any default arguments, so just check if
8306 // we have enough arguments.
8307 if (Args.size() < NumParams) {
8308 // Not enough arguments.
8309 Candidate.Viable = false;
8311 return;
8312 }
8313
8314 // Determine the implicit conversion sequences for each of the
8315 // arguments.
8316 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8317 if (ArgIdx < NumParams) {
8318 // (C++ 13.3.2p3): for F to be a viable function, there shall
8319 // exist for each argument an implicit conversion sequence
8320 // (13.3.3.1) that converts that argument to the corresponding
8321 // parameter of F.
8322 QualType ParamType = Proto->getParamType(ArgIdx);
8323 Candidate.Conversions[ArgIdx + 1]
8324 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8325 /*SuppressUserConversions=*/false,
8326 /*InOverloadResolution=*/false,
8327 /*AllowObjCWritebackConversion=*/
8328 getLangOpts().ObjCAutoRefCount);
8329 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8330 Candidate.Viable = false;
8332 return;
8333 }
8334 } else {
8335 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8336 // argument for which there is no corresponding parameter is
8337 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8338 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8339 }
8340 }
8341
8342 if (Conversion->getTrailingRequiresClause()) {
8343 ConstraintSatisfaction Satisfaction;
8344 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8345 /*ForOverloadResolution*/ true) ||
8346 !Satisfaction.IsSatisfied) {
8347 Candidate.Viable = false;
8349 return;
8350 }
8351 }
8352
8353 if (EnableIfAttr *FailedAttr =
8354 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8355 Candidate.Viable = false;
8356 Candidate.FailureKind = ovl_fail_enable_if;
8357 Candidate.DeductionFailure.Data = FailedAttr;
8358 return;
8359 }
8360}
8361
8362/// Add all of the non-member operator function declarations in the given
8363/// function set to the overload candidate set.
8365 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8366 OverloadCandidateSet &CandidateSet,
8367 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8368 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8369 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8370 ArrayRef<Expr *> FunctionArgs = Args;
8371
8372 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8373 FunctionDecl *FD =
8374 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8375
8376 // Don't consider rewritten functions if we're not rewriting.
8377 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8378 continue;
8379
8380 assert(!isa<CXXMethodDecl>(FD) &&
8381 "unqualified operator lookup found a member function");
8382
8383 if (FunTmpl) {
8384 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8385 FunctionArgs, CandidateSet);
8386 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8387 AddTemplateOverloadCandidate(
8388 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8389 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8390 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8391 } else {
8392 if (ExplicitTemplateArgs)
8393 continue;
8394 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8395 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8396 AddOverloadCandidate(
8397 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8398 false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8400 }
8401 }
8402}
8403
8404/// Add overload candidates for overloaded operators that are
8405/// member functions.
8406///
8407/// Add the overloaded operator candidates that are member functions
8408/// for the operator Op that was used in an operator expression such
8409/// as "x Op y". , Args/NumArgs provides the operator arguments, and
8410/// CandidateSet will store the added overload candidates. (C++
8411/// [over.match.oper]).
8413 SourceLocation OpLoc,
8414 ArrayRef<Expr *> Args,
8415 OverloadCandidateSet &CandidateSet,
8418
8419 // C++ [over.match.oper]p3:
8420 // For a unary operator @ with an operand of a type whose
8421 // cv-unqualified version is T1, and for a binary operator @ with
8422 // a left operand of a type whose cv-unqualified version is T1 and
8423 // a right operand of a type whose cv-unqualified version is T2,
8424 // three sets of candidate functions, designated member
8425 // candidates, non-member candidates and built-in candidates, are
8426 // constructed as follows:
8427 QualType T1 = Args[0]->getType();
8428
8429 // -- If T1 is a complete class type or a class currently being
8430 // defined, the set of member candidates is the result of the
8431 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8432 // the set of member candidates is empty.
8433 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8434 // Complete the type if it can be completed.
8435 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8436 return;
8437 // If the type is neither complete nor being defined, bail out now.
8438 if (!T1Rec->getDecl()->getDefinition())
8439 return;
8440
8441 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8442 LookupQualifiedName(Operators, T1Rec->getDecl());
8443 Operators.suppressAccessDiagnostics();
8444
8445 for (LookupResult::iterator Oper = Operators.begin(),
8446 OperEnd = Operators.end();
8447 Oper != OperEnd; ++Oper) {
8448 if (Oper->getAsFunction() &&
8450 !CandidateSet.getRewriteInfo().shouldAddReversed(
8451 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8452 continue;
8453 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8454 Args[0]->Classify(Context), Args.slice(1),
8455 CandidateSet, /*SuppressUserConversion=*/false, PO);
8456 }
8457 }
8458}
8459
8460/// AddBuiltinCandidate - Add a candidate for a built-in
8461/// operator. ResultTy and ParamTys are the result and parameter types
8462/// of the built-in candidate, respectively. Args and NumArgs are the
8463/// arguments being passed to the candidate. IsAssignmentOperator
8464/// should be true when this built-in candidate is an assignment
8465/// operator. NumContextualBoolArguments is the number of arguments
8466/// (at the beginning of the argument list) that will be contextually
8467/// converted to bool.
8469 OverloadCandidateSet& CandidateSet,
8470 bool IsAssignmentOperator,
8471 unsigned NumContextualBoolArguments) {
8472 // Overload resolution is always an unevaluated context.
8475
8476 // Add this candidate
8477 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8478 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8479 Candidate.Function = nullptr;
8480 Candidate.IsSurrogate = false;
8481 Candidate.IgnoreObjectArgument = false;
8482 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8483
8484 // Determine the implicit conversion sequences for each of the
8485 // arguments.
8486 Candidate.Viable = true;
8487 Candidate.ExplicitCallArguments = Args.size();
8488 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8489 // C++ [over.match.oper]p4:
8490 // For the built-in assignment operators, conversions of the
8491 // left operand are restricted as follows:
8492 // -- no temporaries are introduced to hold the left operand, and
8493 // -- no user-defined conversions are applied to the left
8494 // operand to achieve a type match with the left-most
8495 // parameter of a built-in candidate.
8496 //
8497 // We block these conversions by turning off user-defined
8498 // conversions, since that is the only way that initialization of
8499 // a reference to a non-class type can occur from something that
8500 // is not of the same type.
8501 if (ArgIdx < NumContextualBoolArguments) {
8502 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8503 "Contextual conversion to bool requires bool type");
8504 Candidate.Conversions[ArgIdx]
8505 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8506 } else {
8507 Candidate.Conversions[ArgIdx]
8508 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8509 ArgIdx == 0 && IsAssignmentOperator,
8510 /*InOverloadResolution=*/false,
8511 /*AllowObjCWritebackConversion=*/
8512 getLangOpts().ObjCAutoRefCount);
8513 }
8514 if (Candidate.Conversions[ArgIdx].isBad()) {
8515 Candidate.Viable = false;
8517 break;
8518 }
8519 }
8520}
8521
8522namespace {
8523
8524/// BuiltinCandidateTypeSet - A set of types that will be used for the
8525/// candidate operator functions for built-in operators (C++
8526/// [over.built]). The types are separated into pointer types and
8527/// enumeration types.
8528class BuiltinCandidateTypeSet {
8529 /// TypeSet - A set of types.
8530 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8531
8532 /// PointerTypes - The set of pointer types that will be used in the
8533 /// built-in candidates.
8534 TypeSet PointerTypes;
8535
8536 /// MemberPointerTypes - The set of member pointer types that will be
8537 /// used in the built-in candidates.
8538 TypeSet MemberPointerTypes;
8539
8540 /// EnumerationTypes - The set of enumeration types that will be
8541 /// used in the built-in candidates.
8542 TypeSet EnumerationTypes;
8543
8544 /// The set of vector types that will be used in the built-in
8545 /// candidates.
8546 TypeSet VectorTypes;
8547
8548 /// The set of matrix types that will be used in the built-in
8549 /// candidates.
8550 TypeSet MatrixTypes;
8551
8552 /// The set of _BitInt types that will be used in the built-in candidates.
8553 TypeSet BitIntTypes;
8554
8555 /// A flag indicating non-record types are viable candidates
8556 bool HasNonRecordTypes;
8557
8558 /// A flag indicating whether either arithmetic or enumeration types
8559 /// were present in the candidate set.
8560 bool HasArithmeticOrEnumeralTypes;
8561
8562 /// A flag indicating whether the nullptr type was present in the
8563 /// candidate set.
8564 bool HasNullPtrType;
8565
8566 /// Sema - The semantic analysis instance where we are building the
8567 /// candidate type set.
8568 Sema &SemaRef;
8569
8570 /// Context - The AST context in which we will build the type sets.
8571 ASTContext &Context;
8572
8573 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8574 const Qualifiers &VisibleQuals);
8575 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8576
8577public:
8578 /// iterator - Iterates through the types that are part of the set.
8579 typedef TypeSet::iterator iterator;
8580
8581 BuiltinCandidateTypeSet(Sema &SemaRef)
8582 : HasNonRecordTypes(false),
8583 HasArithmeticOrEnumeralTypes(false),
8584 HasNullPtrType(false),
8585 SemaRef(SemaRef),
8586 Context(SemaRef.Context) { }
8587
8588 void AddTypesConvertedFrom(QualType Ty,
8589 SourceLocation Loc,
8590 bool AllowUserConversions,
8591 bool AllowExplicitConversions,
8592 const Qualifiers &VisibleTypeConversionsQuals);
8593
8594 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8595 llvm::iterator_range<iterator> member_pointer_types() {
8596 return MemberPointerTypes;
8597 }
8598 llvm::iterator_range<iterator> enumeration_types() {
8599 return EnumerationTypes;
8600 }
8601 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8602 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8603 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8604
8605 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8606 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8607 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8608 bool hasNullPtrType() const { return HasNullPtrType; }
8609};
8610
8611} // end anonymous namespace
8612
8613/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8614/// the set of pointer types along with any more-qualified variants of
8615/// that type. For example, if @p Ty is "int const *", this routine
8616/// will add "int const *", "int const volatile *", "int const
8617/// restrict *", and "int const volatile restrict *" to the set of
8618/// pointer types. Returns true if the add of @p Ty itself succeeded,
8619/// false otherwise.
8620///
8621/// FIXME: what to do about extended qualifiers?
8622bool
8623BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8624 const Qualifiers &VisibleQuals) {
8625
8626 // Insert this type.
8627 if (!PointerTypes.insert(Ty))
8628 return false;
8629
8630 QualType PointeeTy;
8631 const PointerType *PointerTy = Ty->getAs<PointerType>();
8632 bool buildObjCPtr = false;
8633 if (!PointerTy) {
8635 PointeeTy = PTy->getPointeeType();
8636 buildObjCPtr = true;
8637 } else {
8638 PointeeTy = PointerTy->getPointeeType();
8639 }
8640
8641 // Don't add qualified variants of arrays. For one, they're not allowed
8642 // (the qualifier would sink to the element type), and for another, the
8643 // only overload situation where it matters is subscript or pointer +- int,
8644 // and those shouldn't have qualifier variants anyway.
8645 if (PointeeTy->isArrayType())
8646 return true;
8647
8648 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8649 bool hasVolatile = VisibleQuals.hasVolatile();
8650 bool hasRestrict = VisibleQuals.hasRestrict();
8651
8652 // Iterate through all strict supersets of BaseCVR.
8653 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8654 if ((CVR | BaseCVR) != CVR) continue;
8655 // Skip over volatile if no volatile found anywhere in the types.
8656 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8657
8658 // Skip over restrict if no restrict found anywhere in the types, or if
8659 // the type cannot be restrict-qualified.
8660 if ((CVR & Qualifiers::Restrict) &&
8661 (!hasRestrict ||
8662 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8663 continue;
8664
8665 // Build qualified pointee type.
8666 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8667
8668 // Build qualified pointer type.
8669 QualType QPointerTy;
8670 if (!buildObjCPtr)
8671 QPointerTy = Context.getPointerType(QPointeeTy);
8672 else
8673 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8674
8675 // Insert qualified pointer type.
8676 PointerTypes.insert(QPointerTy);
8677 }
8678
8679 return true;
8680}
8681
8682/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8683/// to the set of pointer types along with any more-qualified variants of
8684/// that type. For example, if @p Ty is "int const *", this routine
8685/// will add "int const *", "int const volatile *", "int const
8686/// restrict *", and "int const volatile restrict *" to the set of
8687/// pointer types. Returns true if the add of @p Ty itself succeeded,
8688/// false otherwise.
8689///
8690/// FIXME: what to do about extended qualifiers?
8691bool
8692BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8693 QualType Ty) {
8694 // Insert this type.
8695 if (!MemberPointerTypes.insert(Ty))
8696 return false;
8697
8698 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8699 assert(PointerTy && "type was not a member pointer type!");
8700
8701 QualType PointeeTy = PointerTy->getPointeeType();
8702 // Don't add qualified variants of arrays. For one, they're not allowed
8703 // (the qualifier would sink to the element type), and for another, the
8704 // only overload situation where it matters is subscript or pointer +- int,
8705 // and those shouldn't have qualifier variants anyway.
8706 if (PointeeTy->isArrayType())
8707 return true;
8708 const Type *ClassTy = PointerTy->getClass();
8709
8710 // Iterate through all strict supersets of the pointee type's CVR
8711 // qualifiers.
8712 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8713 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8714 if ((CVR | BaseCVR) != CVR) continue;
8715
8716 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8717 MemberPointerTypes.insert(
8718 Context.getMemberPointerType(QPointeeTy, ClassTy));
8719 }
8720
8721 return true;
8722}
8723
8724/// AddTypesConvertedFrom - Add each of the types to which the type @p
8725/// Ty can be implicit converted to the given set of @p Types. We're
8726/// primarily interested in pointer types and enumeration types. We also
8727/// take member pointer types, for the conditional operator.
8728/// AllowUserConversions is true if we should look at the conversion
8729/// functions of a class type, and AllowExplicitConversions if we
8730/// should also include the explicit conversion functions of a class
8731/// type.
8732void
8733BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8734 SourceLocation Loc,
8735 bool AllowUserConversions,
8736 bool AllowExplicitConversions,
8737 const Qualifiers &VisibleQuals) {
8738 // Only deal with canonical types.
8739 Ty = Context.getCanonicalType(Ty);
8740
8741 // Look through reference types; they aren't part of the type of an
8742 // expression for the purposes of conversions.
8743 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8744 Ty = RefTy->getPointeeType();
8745
8746 // If we're dealing with an array type, decay to the pointer.
8747 if (Ty->isArrayType())
8748 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8749
8750 // Otherwise, we don't care about qualifiers on the type.
8751 Ty = Ty.getLocalUnqualifiedType();
8752
8753 // Flag if we ever add a non-record type.
8754 const RecordType *TyRec = Ty->getAs<RecordType>();
8755 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8756
8757 // Flag if we encounter an arithmetic type.
8758 HasArithmeticOrEnumeralTypes =
8759 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8760
8761 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8762 PointerTypes.insert(Ty);
8763 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8764 // Insert our type, and its more-qualified variants, into the set
8765 // of types.
8766 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8767 return;
8768 } else if (Ty->isMemberPointerType()) {
8769 // Member pointers are far easier, since the pointee can't be converted.
8770 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8771 return;
8772 } else if (Ty->isEnumeralType()) {
8773 HasArithmeticOrEnumeralTypes = true;
8774 EnumerationTypes.insert(Ty);
8775 } else if (Ty->isBitIntType()) {
8776 HasArithmeticOrEnumeralTypes = true;
8777 BitIntTypes.insert(Ty);
8778 } else if (Ty->isVectorType()) {
8779 // We treat vector types as arithmetic types in many contexts as an
8780 // extension.
8781 HasArithmeticOrEnumeralTypes = true;
8782 VectorTypes.insert(Ty);
8783 } else if (Ty->isMatrixType()) {
8784 // Similar to vector types, we treat vector types as arithmetic types in
8785 // many contexts as an extension.
8786 HasArithmeticOrEnumeralTypes = true;
8787 MatrixTypes.insert(Ty);
8788 } else if (Ty->isNullPtrType()) {
8789 HasNullPtrType = true;
8790 } else if (AllowUserConversions && TyRec) {
8791 // No conversion functions in incomplete types.
8792 if (!SemaRef.isCompleteType(Loc, Ty))
8793 return;
8794
8795 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8796 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8797 if (isa<UsingShadowDecl>(D))
8798 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8799
8800 // Skip conversion function templates; they don't tell us anything
8801 // about which builtin types we can convert to.
8802 if (isa<FunctionTemplateDecl>(D))
8803 continue;
8804
8805 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8806 if (AllowExplicitConversions || !Conv->isExplicit()) {
8807 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8808 VisibleQuals);
8809 }
8810 }
8811 }
8812}
8813/// Helper function for adjusting address spaces for the pointer or reference
8814/// operands of builtin operators depending on the argument.
8816 Expr *Arg) {
8818}
8819
8820/// Helper function for AddBuiltinOperatorCandidates() that adds
8821/// the volatile- and non-volatile-qualified assignment operators for the
8822/// given type to the candidate set.
8824 QualType T,
8825 ArrayRef<Expr *> Args,
8826 OverloadCandidateSet &CandidateSet) {
8827 QualType ParamTypes[2];
8828
8829 // T& operator=(T&, T)
8830 ParamTypes[0] = S.Context.getLValueReferenceType(
8832 ParamTypes[1] = T;
8833 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8834 /*IsAssignmentOperator=*/true);
8835
8837 // volatile T& operator=(volatile T&, T)
8838 ParamTypes[0] = S.Context.getLValueReferenceType(
8840 Args[0]));
8841 ParamTypes[1] = T;
8842 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8843 /*IsAssignmentOperator=*/true);
8844 }
8845}
8846
8847/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8848/// if any, found in visible type conversion functions found in ArgExpr's type.
8849static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8850 Qualifiers VRQuals;
8851 const RecordType *TyRec;
8852 if (const MemberPointerType *RHSMPType =
8853 ArgExpr->getType()->getAs<MemberPointerType>())
8854 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8855 else
8856 TyRec = ArgExpr->getType()->getAs<RecordType>();
8857 if (!TyRec) {
8858 // Just to be safe, assume the worst case.
8859 VRQuals.addVolatile();
8860 VRQuals.addRestrict();
8861 return VRQuals;
8862 }
8863
8864 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8865 if (!ClassDecl->hasDefinition())
8866 return VRQuals;
8867
8868 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8869 if (isa<UsingShadowDecl>(D))
8870 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8871 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8872 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8873 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8874 CanTy = ResTypeRef->getPointeeType();
8875 // Need to go down the pointer/mempointer chain and add qualifiers
8876 // as see them.
8877 bool done = false;
8878 while (!done) {
8879 if (CanTy.isRestrictQualified())
8880 VRQuals.addRestrict();
8881 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8882 CanTy = ResTypePtr->getPointeeType();
8883 else if (const MemberPointerType *ResTypeMPtr =
8884 CanTy->getAs<MemberPointerType>())
8885 CanTy = ResTypeMPtr->getPointeeType();
8886 else
8887 done = true;
8888 if (CanTy.isVolatileQualified())
8889 VRQuals.addVolatile();
8890 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8891 return VRQuals;
8892 }
8893 }
8894 }
8895 return VRQuals;
8896}
8897
8898// Note: We're currently only handling qualifiers that are meaningful for the
8899// LHS of compound assignment overloading.
8901 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8902 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8903 // _Atomic
8904 if (Available.hasAtomic()) {
8905 Available.removeAtomic();
8906 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8907 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8908 return;
8909 }
8910
8911 // volatile
8912 if (Available.hasVolatile()) {
8913 Available.removeVolatile();
8914 assert(!Applied.hasVolatile());
8915 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8916 Callback);
8917 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8918 return;
8919 }
8920
8921 Callback(Applied);
8922}
8923
8925 QualifiersAndAtomic Quals,
8926 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8928 Callback);
8929}
8930
8932 QualifiersAndAtomic Quals,
8933 Sema &S) {
8934 if (Quals.hasAtomic())
8936 if (Quals.hasVolatile())
8939}
8940
8941namespace {
8942
8943/// Helper class to manage the addition of builtin operator overload
8944/// candidates. It provides shared state and utility methods used throughout
8945/// the process, as well as a helper method to add each group of builtin
8946/// operator overloads from the standard to a candidate set.
8947class BuiltinOperatorOverloadBuilder {
8948 // Common instance state available to all overload candidate addition methods.
8949 Sema &S;
8950 ArrayRef<Expr *> Args;
8951 QualifiersAndAtomic VisibleTypeConversionsQuals;
8952 bool HasArithmeticOrEnumeralCandidateType;
8954 OverloadCandidateSet &CandidateSet;
8955
8956 static constexpr int ArithmeticTypesCap = 26;
8958
8959 // Define some indices used to iterate over the arithmetic types in
8960 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8961 // types are that preserved by promotion (C++ [over.built]p2).
8962 unsigned FirstIntegralType,
8963 LastIntegralType;
8964 unsigned FirstPromotedIntegralType,
8965 LastPromotedIntegralType;
8966 unsigned FirstPromotedArithmeticType,
8967 LastPromotedArithmeticType;
8968 unsigned NumArithmeticTypes;
8969
8970 void InitArithmeticTypes() {
8971 // Start of promoted types.
8972 FirstPromotedArithmeticType = 0;
8973 ArithmeticTypes.push_back(S.Context.FloatTy);
8974 ArithmeticTypes.push_back(S.Context.DoubleTy);
8975 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8977 ArithmeticTypes.push_back(S.Context.Float128Ty);
8979 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8980
8981 // Start of integral types.
8982 FirstIntegralType = ArithmeticTypes.size();
8983 FirstPromotedIntegralType = ArithmeticTypes.size();
8984 ArithmeticTypes.push_back(S.Context.IntTy);
8985 ArithmeticTypes.push_back(S.Context.LongTy);
8986 ArithmeticTypes.push_back(S.Context.LongLongTy);
8990 ArithmeticTypes.push_back(S.Context.Int128Ty);
8991 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8992 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8993 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8997 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8998
8999 /// We add candidates for the unique, unqualified _BitInt types present in
9000 /// the candidate type set. The candidate set already handled ensuring the
9001 /// type is unqualified and canonical, but because we're adding from N
9002 /// different sets, we need to do some extra work to unique things. Insert
9003 /// the candidates into a unique set, then move from that set into the list
9004 /// of arithmetic types.
9005 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9006 llvm::for_each(CandidateTypes, [&BitIntCandidates](
9007 BuiltinCandidateTypeSet &Candidate) {
9008 for (QualType BitTy : Candidate.bitint_types())
9009 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9010 });
9011 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9012 LastPromotedIntegralType = ArithmeticTypes.size();
9013 LastPromotedArithmeticType = ArithmeticTypes.size();
9014 // End of promoted types.
9015
9016 ArithmeticTypes.push_back(S.Context.BoolTy);
9017 ArithmeticTypes.push_back(S.Context.CharTy);
9018 ArithmeticTypes.push_back(S.Context.WCharTy);
9019 if (S.Context.getLangOpts().Char8)
9020 ArithmeticTypes.push_back(S.Context.Char8Ty);
9021 ArithmeticTypes.push_back(S.Context.Char16Ty);
9022 ArithmeticTypes.push_back(S.Context.Char32Ty);
9023 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9024 ArithmeticTypes.push_back(S.Context.ShortTy);
9025 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9026 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9027 LastIntegralType = ArithmeticTypes.size();
9028 NumArithmeticTypes = ArithmeticTypes.size();
9029 // End of integral types.
9030 // FIXME: What about complex? What about half?
9031
9032 // We don't know for sure how many bit-precise candidates were involved, so
9033 // we subtract those from the total when testing whether we're under the
9034 // cap or not.
9035 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9036 ArithmeticTypesCap &&
9037 "Enough inline storage for all arithmetic types.");
9038 }
9039
9040 /// Helper method to factor out the common pattern of adding overloads
9041 /// for '++' and '--' builtin operators.
9042 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9043 bool HasVolatile,
9044 bool HasRestrict) {
9045 QualType ParamTypes[2] = {
9046 S.Context.getLValueReferenceType(CandidateTy),
9047 S.Context.IntTy
9048 };
9049
9050 // Non-volatile version.
9051 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9052
9053 // Use a heuristic to reduce number of builtin candidates in the set:
9054 // add volatile version only if there are conversions to a volatile type.
9055 if (HasVolatile) {
9056 ParamTypes[0] =
9058 S.Context.getVolatileType(CandidateTy));
9059 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9060 }
9061
9062 // Add restrict version only if there are conversions to a restrict type
9063 // and our candidate type is a non-restrict-qualified pointer.
9064 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9065 !CandidateTy.isRestrictQualified()) {
9066 ParamTypes[0]
9069 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9070
9071 if (HasVolatile) {
9072 ParamTypes[0]
9074 S.Context.getCVRQualifiedType(CandidateTy,
9077 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9078 }
9079 }
9080
9081 }
9082
9083 /// Helper to add an overload candidate for a binary builtin with types \p L
9084 /// and \p R.
9085 void AddCandidate(QualType L, QualType R) {
9086 QualType LandR[2] = {L, R};
9087 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9088 }
9089
9090public:
9091 BuiltinOperatorOverloadBuilder(
9092 Sema &S, ArrayRef<Expr *> Args,
9093 QualifiersAndAtomic VisibleTypeConversionsQuals,
9094 bool HasArithmeticOrEnumeralCandidateType,
9096 OverloadCandidateSet &CandidateSet)
9097 : S(S), Args(Args),
9098 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9099 HasArithmeticOrEnumeralCandidateType(
9100 HasArithmeticOrEnumeralCandidateType),
9101 CandidateTypes(CandidateTypes),
9102 CandidateSet(CandidateSet) {
9103
9104 InitArithmeticTypes();
9105 }
9106
9107 // Increment is deprecated for bool since C++17.
9108 //
9109 // C++ [over.built]p3:
9110 //
9111 // For every pair (T, VQ), where T is an arithmetic type other
9112 // than bool, and VQ is either volatile or empty, there exist
9113 // candidate operator functions of the form
9114 //
9115 // VQ T& operator++(VQ T&);
9116 // T operator++(VQ T&, int);
9117 //
9118 // C++ [over.built]p4:
9119 //
9120 // For every pair (T, VQ), where T is an arithmetic type other
9121 // than bool, and VQ is either volatile or empty, there exist
9122 // candidate operator functions of the form
9123 //
9124 // VQ T& operator--(VQ T&);
9125 // T operator--(VQ T&, int);
9126 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9127 if (!HasArithmeticOrEnumeralCandidateType)
9128 return;
9129
9130 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9131 const auto TypeOfT = ArithmeticTypes[Arith];
9132 if (TypeOfT == S.Context.BoolTy) {
9133 if (Op == OO_MinusMinus)
9134 continue;
9135 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9136 continue;
9137 }
9138 addPlusPlusMinusMinusStyleOverloads(
9139 TypeOfT,
9140 VisibleTypeConversionsQuals.hasVolatile(),
9141 VisibleTypeConversionsQuals.hasRestrict());
9142 }
9143 }
9144
9145 // C++ [over.built]p5:
9146 //
9147 // For every pair (T, VQ), where T is a cv-qualified or
9148 // cv-unqualified object type, and VQ is either volatile or
9149 // empty, there exist candidate operator functions of the form
9150 //
9151 // T*VQ& operator++(T*VQ&);
9152 // T*VQ& operator--(T*VQ&);
9153 // T* operator++(T*VQ&, int);
9154 // T* operator--(T*VQ&, int);
9155 void addPlusPlusMinusMinusPointerOverloads() {
9156 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9157 // Skip pointer types that aren't pointers to object types.
9158 if (!PtrTy->getPointeeType()->isObjectType())
9159 continue;
9160
9161 addPlusPlusMinusMinusStyleOverloads(
9162 PtrTy,
9163 (!PtrTy.isVolatileQualified() &&
9164 VisibleTypeConversionsQuals.hasVolatile()),
9165 (!PtrTy.isRestrictQualified() &&
9166 VisibleTypeConversionsQuals.hasRestrict()));
9167 }
9168 }
9169
9170 // C++ [over.built]p6:
9171 // For every cv-qualified or cv-unqualified object type T, there
9172 // exist candidate operator functions of the form
9173 //
9174 // T& operator*(T*);
9175 //
9176 // C++ [over.built]p7:
9177 // For every function type T that does not have cv-qualifiers or a
9178 // ref-qualifier, there exist candidate operator functions of the form
9179 // T& operator*(T*);
9180 void addUnaryStarPointerOverloads() {
9181 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9182 QualType PointeeTy = ParamTy->getPointeeType();
9183 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9184 continue;
9185
9186 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9187 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9188 continue;
9189
9190 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9191 }
9192 }
9193
9194 // C++ [over.built]p9:
9195 // For every promoted arithmetic type T, there exist candidate
9196 // operator functions of the form
9197 //
9198 // T operator+(T);
9199 // T operator-(T);
9200 void addUnaryPlusOrMinusArithmeticOverloads() {
9201 if (!HasArithmeticOrEnumeralCandidateType)
9202 return;
9203
9204 for (unsigned Arith = FirstPromotedArithmeticType;
9205 Arith < LastPromotedArithmeticType; ++Arith) {
9206 QualType ArithTy = ArithmeticTypes[Arith];
9207 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9208 }
9209
9210 // Extension: We also add these operators for vector types.
9211 for (QualType VecTy : CandidateTypes[0].vector_types())
9212 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9213 }
9214
9215 // C++ [over.built]p8:
9216 // For every type T, there exist candidate operator functions of
9217 // the form
9218 //
9219 // T* operator+(T*);
9220 void addUnaryPlusPointerOverloads() {
9221 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9222 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9223 }
9224
9225 // C++ [over.built]p10:
9226 // For every promoted integral type T, there exist candidate
9227 // operator functions of the form
9228 //
9229 // T operator~(T);
9230 void addUnaryTildePromotedIntegralOverloads() {
9231 if (!HasArithmeticOrEnumeralCandidateType)
9232 return;
9233
9234 for (unsigned Int = FirstPromotedIntegralType;
9235 Int < LastPromotedIntegralType; ++Int) {
9236 QualType IntTy = ArithmeticTypes[Int];
9237 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9238 }
9239
9240 // Extension: We also add this operator for vector types.
9241 for (QualType VecTy : CandidateTypes[0].vector_types())
9242 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9243 }
9244
9245 // C++ [over.match.oper]p16:
9246 // For every pointer to member type T or type std::nullptr_t, there
9247 // exist candidate operator functions of the form
9248 //
9249 // bool operator==(T,T);
9250 // bool operator!=(T,T);
9251 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9252 /// Set of (canonical) types that we've already handled.
9254
9255 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9256 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9257 // Don't add the same builtin candidate twice.
9258 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9259 continue;
9260
9261 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9262 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9263 }
9264
9265 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9267 if (AddedTypes.insert(NullPtrTy).second) {
9268 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9269 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9270 }
9271 }
9272 }
9273 }
9274
9275 // C++ [over.built]p15:
9276 //
9277 // For every T, where T is an enumeration type or a pointer type,
9278 // there exist candidate operator functions of the form
9279 //
9280 // bool operator<(T, T);
9281 // bool operator>(T, T);
9282 // bool operator<=(T, T);
9283 // bool operator>=(T, T);
9284 // bool operator==(T, T);
9285 // bool operator!=(T, T);
9286 // R operator<=>(T, T)
9287 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9288 // C++ [over.match.oper]p3:
9289 // [...]the built-in candidates include all of the candidate operator
9290 // functions defined in 13.6 that, compared to the given operator, [...]
9291 // do not have the same parameter-type-list as any non-template non-member
9292 // candidate.
9293 //
9294 // Note that in practice, this only affects enumeration types because there
9295 // aren't any built-in candidates of record type, and a user-defined operator
9296 // must have an operand of record or enumeration type. Also, the only other
9297 // overloaded operator with enumeration arguments, operator=,
9298 // cannot be overloaded for enumeration types, so this is the only place
9299 // where we must suppress candidates like this.
9301 UserDefinedBinaryOperators;
9302
9303 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9304 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9305 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9306 CEnd = CandidateSet.end();
9307 C != CEnd; ++C) {
9308 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9309 continue;
9310
9311 if (C->Function->isFunctionTemplateSpecialization())
9312 continue;
9313
9314 // We interpret "same parameter-type-list" as applying to the
9315 // "synthesized candidate, with the order of the two parameters
9316 // reversed", not to the original function.
9317 bool Reversed = C->isReversed();
9318 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9319 ->getType()
9320 .getUnqualifiedType();
9321 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9322 ->getType()
9323 .getUnqualifiedType();
9324
9325 // Skip if either parameter isn't of enumeral type.
9326 if (!FirstParamType->isEnumeralType() ||
9327 !SecondParamType->isEnumeralType())
9328 continue;
9329
9330 // Add this operator to the set of known user-defined operators.
9331 UserDefinedBinaryOperators.insert(
9332 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9333 S.Context.getCanonicalType(SecondParamType)));
9334 }
9335 }
9336 }
9337
9338 /// Set of (canonical) types that we've already handled.
9340
9341 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9342 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9343 // Don't add the same builtin candidate twice.
9344 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9345 continue;
9346 if (IsSpaceship && PtrTy->isFunctionPointerType())
9347 continue;
9348
9349 QualType ParamTypes[2] = {PtrTy, PtrTy};
9350 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9351 }
9352 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9353 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9354
9355 // Don't add the same builtin candidate twice, or if a user defined
9356 // candidate exists.
9357 if (!AddedTypes.insert(CanonType).second ||
9358 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9359 CanonType)))
9360 continue;
9361 QualType ParamTypes[2] = {EnumTy, EnumTy};
9362 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9363 }
9364 }
9365 }
9366
9367 // C++ [over.built]p13:
9368 //
9369 // For every cv-qualified or cv-unqualified object type T
9370 // there exist candidate operator functions of the form
9371 //
9372 // T* operator+(T*, ptrdiff_t);
9373 // T& operator[](T*, ptrdiff_t); [BELOW]
9374 // T* operator-(T*, ptrdiff_t);
9375 // T* operator+(ptrdiff_t, T*);
9376 // T& operator[](ptrdiff_t, T*); [BELOW]
9377 //
9378 // C++ [over.built]p14:
9379 //
9380 // For every T, where T is a pointer to object type, there
9381 // exist candidate operator functions of the form
9382 //
9383 // ptrdiff_t operator-(T, T);
9384 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9385 /// Set of (canonical) types that we've already handled.
9387
9388 for (int Arg = 0; Arg < 2; ++Arg) {
9389 QualType AsymmetricParamTypes[2] = {
9392 };
9393 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9394 QualType PointeeTy = PtrTy->getPointeeType();
9395 if (!PointeeTy->isObjectType())
9396 continue;
9397
9398 AsymmetricParamTypes[Arg] = PtrTy;
9399 if (Arg == 0 || Op == OO_Plus) {
9400 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9401 // T* operator+(ptrdiff_t, T*);
9402 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9403 }
9404 if (Op == OO_Minus) {
9405 // ptrdiff_t operator-(T, T);
9406 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9407 continue;
9408
9409 QualType ParamTypes[2] = {PtrTy, PtrTy};
9410 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9411 }
9412 }
9413 }
9414 }
9415
9416 // C++ [over.built]p12:
9417 //
9418 // For every pair of promoted arithmetic types L and R, there
9419 // exist candidate operator functions of the form
9420 //
9421 // LR operator*(L, R);
9422 // LR operator/(L, R);
9423 // LR operator+(L, R);
9424 // LR operator-(L, R);
9425 // bool operator<(L, R);
9426 // bool operator>(L, R);
9427 // bool operator<=(L, R);
9428 // bool operator>=(L, R);
9429 // bool operator==(L, R);
9430 // bool operator!=(L, R);
9431 //
9432 // where LR is the result of the usual arithmetic conversions
9433 // between types L and R.
9434 //
9435 // C++ [over.built]p24:
9436 //
9437 // For every pair of promoted arithmetic types L and R, there exist
9438 // candidate operator functions of the form
9439 //
9440 // LR operator?(bool, L, R);
9441 //
9442 // where LR is the result of the usual arithmetic conversions
9443 // between types L and R.
9444 // Our candidates ignore the first parameter.
9445 void addGenericBinaryArithmeticOverloads() {
9446 if (!HasArithmeticOrEnumeralCandidateType)
9447 return;
9448
9449 for (unsigned Left = FirstPromotedArithmeticType;
9450 Left < LastPromotedArithmeticType; ++Left) {
9451 for (unsigned Right = FirstPromotedArithmeticType;
9452 Right < LastPromotedArithmeticType; ++Right) {
9453 QualType LandR[2] = { ArithmeticTypes[Left],
9454 ArithmeticTypes[Right] };
9455 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9456 }
9457 }
9458
9459 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9460 // conditional operator for vector types.
9461 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9462 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9463 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9464 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9465 }
9466 }
9467
9468 /// Add binary operator overloads for each candidate matrix type M1, M2:
9469 /// * (M1, M1) -> M1
9470 /// * (M1, M1.getElementType()) -> M1
9471 /// * (M2.getElementType(), M2) -> M2
9472 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9473 void addMatrixBinaryArithmeticOverloads() {
9474 if (!HasArithmeticOrEnumeralCandidateType)
9475 return;
9476
9477 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9478 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9479 AddCandidate(M1, M1);
9480 }
9481
9482 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9483 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9484 if (!CandidateTypes[0].containsMatrixType(M2))
9485 AddCandidate(M2, M2);
9486 }
9487 }
9488
9489 // C++2a [over.built]p14:
9490 //
9491 // For every integral type T there exists a candidate operator function
9492 // of the form
9493 //
9494 // std::strong_ordering operator<=>(T, T)
9495 //
9496 // C++2a [over.built]p15:
9497 //
9498 // For every pair of floating-point types L and R, there exists a candidate
9499 // operator function of the form
9500 //
9501 // std::partial_ordering operator<=>(L, R);
9502 //
9503 // FIXME: The current specification for integral types doesn't play nice with
9504 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9505 // comparisons. Under the current spec this can lead to ambiguity during
9506 // overload resolution. For example:
9507 //
9508 // enum A : int {a};
9509 // auto x = (a <=> (long)42);
9510 //
9511 // error: call is ambiguous for arguments 'A' and 'long'.
9512 // note: candidate operator<=>(int, int)
9513 // note: candidate operator<=>(long, long)
9514 //
9515 // To avoid this error, this function deviates from the specification and adds
9516 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9517 // arithmetic types (the same as the generic relational overloads).
9518 //
9519 // For now this function acts as a placeholder.
9520 void addThreeWayArithmeticOverloads() {
9521 addGenericBinaryArithmeticOverloads();
9522 }
9523
9524 // C++ [over.built]p17:
9525 //
9526 // For every pair of promoted integral types L and R, there
9527 // exist candidate operator functions of the form
9528 //
9529 // LR operator%(L, R);
9530 // LR operator&(L, R);
9531 // LR operator^(L, R);
9532 // LR operator|(L, R);
9533 // L operator<<(L, R);
9534 // L operator>>(L, R);
9535 //
9536 // where LR is the result of the usual arithmetic conversions
9537 // between types L and R.
9538 void addBinaryBitwiseArithmeticOverloads() {
9539 if (!HasArithmeticOrEnumeralCandidateType)
9540 return;
9541
9542 for (unsigned Left = FirstPromotedIntegralType;
9543 Left < LastPromotedIntegralType; ++Left) {
9544 for (unsigned Right = FirstPromotedIntegralType;
9545 Right < LastPromotedIntegralType; ++Right) {
9546 QualType LandR[2] = { ArithmeticTypes[Left],
9547 ArithmeticTypes[Right] };
9548 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9549 }
9550 }
9551 }
9552
9553 // C++ [over.built]p20:
9554 //
9555 // For every pair (T, VQ), where T is an enumeration or
9556 // pointer to member type and VQ is either volatile or
9557 // empty, there exist candidate operator functions of the form
9558 //
9559 // VQ T& operator=(VQ T&, T);
9560 void addAssignmentMemberPointerOrEnumeralOverloads() {
9561 /// Set of (canonical) types that we've already handled.
9563
9564 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9565 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9566 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9567 continue;
9568
9569 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9570 }
9571
9572 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9573 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9574 continue;
9575
9576 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9577 }
9578 }
9579 }
9580
9581 // C++ [over.built]p19:
9582 //
9583 // For every pair (T, VQ), where T is any type and VQ is either
9584 // volatile or empty, there exist candidate operator functions
9585 // of the form
9586 //
9587 // T*VQ& operator=(T*VQ&, T*);
9588 //
9589 // C++ [over.built]p21:
9590 //
9591 // For every pair (T, VQ), where T is a cv-qualified or
9592 // cv-unqualified object type and VQ is either volatile or
9593 // empty, there exist candidate operator functions of the form
9594 //
9595 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9596 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9597 void addAssignmentPointerOverloads(bool isEqualOp) {
9598 /// Set of (canonical) types that we've already handled.
9600
9601 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9602 // If this is operator=, keep track of the builtin candidates we added.
9603 if (isEqualOp)
9604 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9605 else if (!PtrTy->getPointeeType()->isObjectType())
9606 continue;
9607
9608 // non-volatile version
9609 QualType ParamTypes[2] = {
9611 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9612 };
9613 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9614 /*IsAssignmentOperator=*/ isEqualOp);
9615
9616 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9617 VisibleTypeConversionsQuals.hasVolatile();
9618 if (NeedVolatile) {
9619 // volatile version
9620 ParamTypes[0] =
9622 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9623 /*IsAssignmentOperator=*/isEqualOp);
9624 }
9625
9626 if (!PtrTy.isRestrictQualified() &&
9627 VisibleTypeConversionsQuals.hasRestrict()) {
9628 // restrict version
9629 ParamTypes[0] =
9631 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9632 /*IsAssignmentOperator=*/isEqualOp);
9633
9634 if (NeedVolatile) {
9635 // volatile restrict version
9636 ParamTypes[0] =
9639 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9640 /*IsAssignmentOperator=*/isEqualOp);
9641 }
9642 }
9643 }
9644
9645 if (isEqualOp) {
9646 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9647 // Make sure we don't add the same candidate twice.
9648 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9649 continue;
9650
9651 QualType ParamTypes[2] = {
9653 PtrTy,
9654 };
9655
9656 // non-volatile version
9657 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9658 /*IsAssignmentOperator=*/true);
9659
9660 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9661 VisibleTypeConversionsQuals.hasVolatile();
9662 if (NeedVolatile) {
9663 // volatile version
9664 ParamTypes[0] = S.Context.getLValueReferenceType(
9665 S.Context.getVolatileType(PtrTy));
9666 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9667 /*IsAssignmentOperator=*/true);
9668 }
9669
9670 if (!PtrTy.isRestrictQualified() &&
9671 VisibleTypeConversionsQuals.hasRestrict()) {
9672 // restrict version
9673 ParamTypes[0] = S.Context.getLValueReferenceType(
9674 S.Context.getRestrictType(PtrTy));
9675 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9676 /*IsAssignmentOperator=*/true);
9677
9678 if (NeedVolatile) {
9679 // volatile restrict version
9680 ParamTypes[0] =
9683 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9684 /*IsAssignmentOperator=*/true);
9685 }
9686 }
9687 }
9688 }
9689 }
9690
9691 // C++ [over.built]p18:
9692 //
9693 // For every triple (L, VQ, R), where L is an arithmetic type,
9694 // VQ is either volatile or empty, and R is a promoted
9695 // arithmetic type, there exist candidate operator functions of
9696 // the form
9697 //
9698 // VQ L& operator=(VQ L&, R);
9699 // VQ L& operator*=(VQ L&, R);
9700 // VQ L& operator/=(VQ L&, R);
9701 // VQ L& operator+=(VQ L&, R);
9702 // VQ L& operator-=(VQ L&, R);
9703 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9704 if (!HasArithmeticOrEnumeralCandidateType)
9705 return;
9706
9707 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9708 for (unsigned Right = FirstPromotedArithmeticType;
9709 Right < LastPromotedArithmeticType; ++Right) {
9710 QualType ParamTypes[2];
9711 ParamTypes[1] = ArithmeticTypes[Right];
9713 S, ArithmeticTypes[Left], Args[0]);
9714
9716 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9717 ParamTypes[0] =
9718 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9719 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9720 /*IsAssignmentOperator=*/isEqualOp);
9721 });
9722 }
9723 }
9724
9725 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9726 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9727 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9728 QualType ParamTypes[2];
9729 ParamTypes[1] = Vec2Ty;
9730 // Add this built-in operator as a candidate (VQ is empty).
9731 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9732 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9733 /*IsAssignmentOperator=*/isEqualOp);
9734
9735 // Add this built-in operator as a candidate (VQ is 'volatile').
9736 if (VisibleTypeConversionsQuals.hasVolatile()) {
9737 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9738 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9739 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9740 /*IsAssignmentOperator=*/isEqualOp);
9741 }
9742 }
9743 }
9744
9745 // C++ [over.built]p22:
9746 //
9747 // For every triple (L, VQ, R), where L is an integral type, VQ
9748 // is either volatile or empty, and R is a promoted integral
9749 // type, there exist candidate operator functions of the form
9750 //
9751 // VQ L& operator%=(VQ L&, R);
9752 // VQ L& operator<<=(VQ L&, R);
9753 // VQ L& operator>>=(VQ L&, R);
9754 // VQ L& operator&=(VQ L&, R);
9755 // VQ L& operator^=(VQ L&, R);
9756 // VQ L& operator|=(VQ L&, R);
9757 void addAssignmentIntegralOverloads() {
9758 if (!HasArithmeticOrEnumeralCandidateType)
9759 return;
9760
9761 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9762 for (unsigned Right = FirstPromotedIntegralType;
9763 Right < LastPromotedIntegralType; ++Right) {
9764 QualType ParamTypes[2];
9765 ParamTypes[1] = ArithmeticTypes[Right];
9767 S, ArithmeticTypes[Left], Args[0]);
9768
9770 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9771 ParamTypes[0] =
9772 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9773 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9774 });
9775 }
9776 }
9777 }
9778
9779 // C++ [over.operator]p23:
9780 //
9781 // There also exist candidate operator functions of the form
9782 //
9783 // bool operator!(bool);
9784 // bool operator&&(bool, bool);
9785 // bool operator||(bool, bool);
9786 void addExclaimOverload() {
9787 QualType ParamTy = S.Context.BoolTy;
9788 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9789 /*IsAssignmentOperator=*/false,
9790 /*NumContextualBoolArguments=*/1);
9791 }
9792 void addAmpAmpOrPipePipeOverload() {
9793 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9794 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9795 /*IsAssignmentOperator=*/false,
9796 /*NumContextualBoolArguments=*/2);
9797 }
9798
9799 // C++ [over.built]p13:
9800 //
9801 // For every cv-qualified or cv-unqualified object type T there
9802 // exist candidate operator functions of the form
9803 //
9804 // T* operator+(T*, ptrdiff_t); [ABOVE]
9805 // T& operator[](T*, ptrdiff_t);
9806 // T* operator-(T*, ptrdiff_t); [ABOVE]
9807 // T* operator+(ptrdiff_t, T*); [ABOVE]
9808 // T& operator[](ptrdiff_t, T*);
9809 void addSubscriptOverloads() {
9810 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9811 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9812 QualType PointeeType = PtrTy->getPointeeType();
9813 if (!PointeeType->isObjectType())
9814 continue;
9815
9816 // T& operator[](T*, ptrdiff_t)
9817 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9818 }
9819
9820 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9821 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9822 QualType PointeeType = PtrTy->getPointeeType();
9823 if (!PointeeType->isObjectType())
9824 continue;
9825
9826 // T& operator[](ptrdiff_t, T*)
9827 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9828 }
9829 }
9830
9831 // C++ [over.built]p11:
9832 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9833 // C1 is the same type as C2 or is a derived class of C2, T is an object
9834 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9835 // there exist candidate operator functions of the form
9836 //
9837 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9838 //
9839 // where CV12 is the union of CV1 and CV2.
9840 void addArrowStarOverloads() {
9841 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9842 QualType C1Ty = PtrTy;
9843 QualType C1;
9845 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9846 if (!isa<RecordType>(C1))
9847 continue;
9848 // heuristic to reduce number of builtin candidates in the set.
9849 // Add volatile/restrict version only if there are conversions to a
9850 // volatile/restrict type.
9851 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9852 continue;
9853 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9854 continue;
9855 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9856 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9857 QualType C2 = QualType(mptr->getClass(), 0);
9858 C2 = C2.getUnqualifiedType();
9859 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9860 break;
9861 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9862 // build CV12 T&
9863 QualType T = mptr->getPointeeType();
9864 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9865 T.isVolatileQualified())
9866 continue;
9867 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9868 T.isRestrictQualified())
9869 continue;
9870 T = Q1.apply(S.Context, T);
9871 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9872 }
9873 }
9874 }
9875
9876 // Note that we don't consider the first argument, since it has been
9877 // contextually converted to bool long ago. The candidates below are
9878 // therefore added as binary.
9879 //
9880 // C++ [over.built]p25:
9881 // For every type T, where T is a pointer, pointer-to-member, or scoped
9882 // enumeration type, there exist candidate operator functions of the form
9883 //
9884 // T operator?(bool, T, T);
9885 //
9886 void addConditionalOperatorOverloads() {
9887 /// Set of (canonical) types that we've already handled.
9889
9890 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9891 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9892 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9893 continue;
9894
9895 QualType ParamTypes[2] = {PtrTy, PtrTy};
9896 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9897 }
9898
9899 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9900 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9901 continue;
9902
9903 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9904 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9905 }
9906
9907 if (S.getLangOpts().CPlusPlus11) {
9908 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9909 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9910 continue;
9911
9912 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9913 continue;
9914
9915 QualType ParamTypes[2] = {EnumTy, EnumTy};
9916 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9917 }
9918 }
9919 }
9920 }
9921};
9922
9923} // end anonymous namespace
9924
9925/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9926/// operator overloads to the candidate set (C++ [over.built]), based
9927/// on the operator @p Op and the arguments given. For example, if the
9928/// operator is a binary '+', this routine might add "int
9929/// operator+(int, int)" to cover integer addition.
9931 SourceLocation OpLoc,
9932 ArrayRef<Expr *> Args,
9933 OverloadCandidateSet &CandidateSet) {
9934 // Find all of the types that the arguments can convert to, but only
9935 // if the operator we're looking at has built-in operator candidates
9936 // that make use of these types. Also record whether we encounter non-record
9937 // candidate types or either arithmetic or enumeral candidate types.
9938 QualifiersAndAtomic VisibleTypeConversionsQuals;
9939 VisibleTypeConversionsQuals.addConst();
9940 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9941 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9942 if (Args[ArgIdx]->getType()->isAtomicType())
9943 VisibleTypeConversionsQuals.addAtomic();
9944 }
9945
9946 bool HasNonRecordCandidateType = false;
9947 bool HasArithmeticOrEnumeralCandidateType = false;
9949 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9950 CandidateTypes.emplace_back(*this);
9951 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9952 OpLoc,
9953 true,
9954 (Op == OO_Exclaim ||
9955 Op == OO_AmpAmp ||
9956 Op == OO_PipePipe),
9957 VisibleTypeConversionsQuals);
9958 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9959 CandidateTypes[ArgIdx].hasNonRecordTypes();
9960 HasArithmeticOrEnumeralCandidateType =
9961 HasArithmeticOrEnumeralCandidateType ||
9962 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9963 }
9964
9965 // Exit early when no non-record types have been added to the candidate set
9966 // for any of the arguments to the operator.
9967 //
9968 // We can't exit early for !, ||, or &&, since there we have always have
9969 // 'bool' overloads.
9970 if (!HasNonRecordCandidateType &&
9971 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9972 return;
9973
9974 // Setup an object to manage the common state for building overloads.
9975 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9976 VisibleTypeConversionsQuals,
9977 HasArithmeticOrEnumeralCandidateType,
9978 CandidateTypes, CandidateSet);
9979
9980 // Dispatch over the operation to add in only those overloads which apply.
9981 switch (Op) {
9982 case OO_None:
9984 llvm_unreachable("Expected an overloaded operator");
9985
9986 case OO_New:
9987 case OO_Delete:
9988 case OO_Array_New:
9989 case OO_Array_Delete:
9990 case OO_Call:
9991 llvm_unreachable(
9992 "Special operators don't use AddBuiltinOperatorCandidates");
9993
9994 case OO_Comma:
9995 case OO_Arrow:
9996 case OO_Coawait:
9997 // C++ [over.match.oper]p3:
9998 // -- For the operator ',', the unary operator '&', the
9999 // operator '->', or the operator 'co_await', the
10000 // built-in candidates set is empty.
10001 break;
10002
10003 case OO_Plus: // '+' is either unary or binary
10004 if (Args.size() == 1)
10005 OpBuilder.addUnaryPlusPointerOverloads();
10006 [[fallthrough]];
10007
10008 case OO_Minus: // '-' is either unary or binary
10009 if (Args.size() == 1) {
10010 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10011 } else {
10012 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10013 OpBuilder.addGenericBinaryArithmeticOverloads();
10014 OpBuilder.addMatrixBinaryArithmeticOverloads();
10015 }
10016 break;
10017
10018 case OO_Star: // '*' is either unary or binary
10019 if (Args.size() == 1)
10020 OpBuilder.addUnaryStarPointerOverloads();
10021 else {
10022 OpBuilder.addGenericBinaryArithmeticOverloads();
10023 OpBuilder.addMatrixBinaryArithmeticOverloads();
10024 }
10025 break;
10026
10027 case OO_Slash:
10028 OpBuilder.addGenericBinaryArithmeticOverloads();
10029 break;
10030
10031 case OO_PlusPlus:
10032 case OO_MinusMinus:
10033 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10034 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10035 break;
10036
10037 case OO_EqualEqual:
10038 case OO_ExclaimEqual:
10039 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10040 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10041 OpBuilder.addGenericBinaryArithmeticOverloads();
10042 break;
10043
10044 case OO_Less:
10045 case OO_Greater:
10046 case OO_LessEqual:
10047 case OO_GreaterEqual:
10048 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10049 OpBuilder.addGenericBinaryArithmeticOverloads();
10050 break;
10051
10052 case OO_Spaceship:
10053 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10054 OpBuilder.addThreeWayArithmeticOverloads();
10055 break;
10056
10057 case OO_Percent:
10058 case OO_Caret:
10059 case OO_Pipe:
10060 case OO_LessLess:
10061 case OO_GreaterGreater:
10062 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10063 break;
10064
10065 case OO_Amp: // '&' is either unary or binary
10066 if (Args.size() == 1)
10067 // C++ [over.match.oper]p3:
10068 // -- For the operator ',', the unary operator '&', or the
10069 // operator '->', the built-in candidates set is empty.
10070 break;
10071
10072 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10073 break;
10074
10075 case OO_Tilde:
10076 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10077 break;
10078
10079 case OO_Equal:
10080 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10081 [[fallthrough]];
10082
10083 case OO_PlusEqual:
10084 case OO_MinusEqual:
10085 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10086 [[fallthrough]];
10087
10088 case OO_StarEqual:
10089 case OO_SlashEqual:
10090 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10091 break;
10092
10093 case OO_PercentEqual:
10094 case OO_LessLessEqual:
10095 case OO_GreaterGreaterEqual:
10096 case OO_AmpEqual:
10097 case OO_CaretEqual:
10098 case OO_PipeEqual:
10099 OpBuilder.addAssignmentIntegralOverloads();
10100 break;
10101
10102 case OO_Exclaim:
10103 OpBuilder.addExclaimOverload();
10104 break;
10105
10106 case OO_AmpAmp:
10107 case OO_PipePipe:
10108 OpBuilder.addAmpAmpOrPipePipeOverload();
10109 break;
10110
10111 case OO_Subscript:
10112 if (Args.size() == 2)
10113 OpBuilder.addSubscriptOverloads();
10114 break;
10115
10116 case OO_ArrowStar:
10117 OpBuilder.addArrowStarOverloads();
10118 break;
10119
10120 case OO_Conditional:
10121 OpBuilder.addConditionalOperatorOverloads();
10122 OpBuilder.addGenericBinaryArithmeticOverloads();
10123 break;
10124 }
10125}
10126
10127/// Add function candidates found via argument-dependent lookup
10128/// to the set of overloading candidates.
10129///
10130/// This routine performs argument-dependent name lookup based on the
10131/// given function name (which may also be an operator name) and adds
10132/// all of the overload candidates found by ADL to the overload
10133/// candidate set (C++ [basic.lookup.argdep]).
10134void
10136 SourceLocation Loc,
10137 ArrayRef<Expr *> Args,
10138 TemplateArgumentListInfo *ExplicitTemplateArgs,
10139 OverloadCandidateSet& CandidateSet,
10140 bool PartialOverloading) {
10141 ADLResult Fns;
10142
10143 // FIXME: This approach for uniquing ADL results (and removing
10144 // redundant candidates from the set) relies on pointer-equality,
10145 // which means we need to key off the canonical decl. However,
10146 // always going back to the canonical decl might not get us the
10147 // right set of default arguments. What default arguments are
10148 // we supposed to consider on ADL candidates, anyway?
10149
10150 // FIXME: Pass in the explicit template arguments?
10151 ArgumentDependentLookup(Name, Loc, Args, Fns);
10152
10153 // Erase all of the candidates we already knew about.
10154 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10155 CandEnd = CandidateSet.end();
10156 Cand != CandEnd; ++Cand)
10157 if (Cand->Function) {
10158 Fns.erase(Cand->Function);
10159 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
10160 Fns.erase(FunTmpl);
10161 }
10162
10163 // For each of the ADL candidates we found, add it to the overload
10164 // set.
10165 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10167
10168 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10169 if (ExplicitTemplateArgs)
10170 continue;
10171
10172 AddOverloadCandidate(
10173 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10174 PartialOverloading, /*AllowExplicit=*/true,
10175 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10176 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10177 AddOverloadCandidate(
10178 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10179 /*SuppressUserConversions=*/false, PartialOverloading,
10180 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10181 ADLCallKind::UsesADL, std::nullopt,
10183 }
10184 } else {
10185 auto *FTD = cast<FunctionTemplateDecl>(*I);
10186 AddTemplateOverloadCandidate(
10187 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10188 /*SuppressUserConversions=*/false, PartialOverloading,
10189 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10190 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10191 *this, Args, FTD->getTemplatedDecl())) {
10192 AddTemplateOverloadCandidate(
10193 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10194 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10195 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10197 }
10198 }
10199 }
10200}
10201
10202namespace {
10203enum class Comparison { Equal, Better, Worse };
10204}
10205
10206/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10207/// overload resolution.
10208///
10209/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10210/// Cand1's first N enable_if attributes have precisely the same conditions as
10211/// Cand2's first N enable_if attributes (where N = the number of enable_if
10212/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10213///
10214/// Note that you can have a pair of candidates such that Cand1's enable_if
10215/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10216/// worse than Cand1's.
10217static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10218 const FunctionDecl *Cand2) {
10219 // Common case: One (or both) decls don't have enable_if attrs.
10220 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10221 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10222 if (!Cand1Attr || !Cand2Attr) {
10223 if (Cand1Attr == Cand2Attr)
10224 return Comparison::Equal;
10225 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10226 }
10227
10228 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10229 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10230
10231 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10232 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10233 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10234 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10235
10236 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10237 // has fewer enable_if attributes than Cand2, and vice versa.
10238 if (!Cand1A)
10239 return Comparison::Worse;
10240 if (!Cand2A)
10241 return Comparison::Better;
10242
10243 Cand1ID.clear();
10244 Cand2ID.clear();
10245
10246 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10247 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10248 if (Cand1ID != Cand2ID)
10249 return Comparison::Worse;
10250 }
10251
10252 return Comparison::Equal;
10253}
10254
10255static Comparison
10257 const OverloadCandidate &Cand2) {
10258 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10259 !Cand2.Function->isMultiVersion())
10260 return Comparison::Equal;
10261
10262 // If both are invalid, they are equal. If one of them is invalid, the other
10263 // is better.
10264 if (Cand1.Function->isInvalidDecl()) {
10265 if (Cand2.Function->isInvalidDecl())
10266 return Comparison::Equal;
10267 return Comparison::Worse;
10268 }
10269 if (Cand2.Function->isInvalidDecl())
10270 return Comparison::Better;
10271
10272 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10273 // cpu_dispatch, else arbitrarily based on the identifiers.
10274 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10275 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10276 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10277 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10278
10279 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10280 return Comparison::Equal;
10281
10282 if (Cand1CPUDisp && !Cand2CPUDisp)
10283 return Comparison::Better;
10284 if (Cand2CPUDisp && !Cand1CPUDisp)
10285 return Comparison::Worse;
10286
10287 if (Cand1CPUSpec && Cand2CPUSpec) {
10288 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10289 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10290 ? Comparison::Better
10291 : Comparison::Worse;
10292
10293 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10294 FirstDiff = std::mismatch(
10295 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10296 Cand2CPUSpec->cpus_begin(),
10297 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10298 return LHS->getName() == RHS->getName();
10299 });
10300
10301 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10302 "Two different cpu-specific versions should not have the same "
10303 "identifier list, otherwise they'd be the same decl!");
10304 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10305 ? Comparison::Better
10306 : Comparison::Worse;
10307 }
10308 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10309}
10310
10311/// Compute the type of the implicit object parameter for the given function,
10312/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10313/// null QualType if there is a 'matches anything' implicit object parameter.
10314static std::optional<QualType>
10316 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10317 return std::nullopt;
10318
10319 auto *M = cast<CXXMethodDecl>(F);
10320 // Static member functions' object parameters match all types.
10321 if (M->isStatic())
10322 return QualType();
10323 return M->getFunctionObjectParameterReferenceType();
10324}
10325
10326// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10327// represent the same entity.
10328static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10329 const FunctionDecl *F2) {
10330 if (declaresSameEntity(F1, F2))
10331 return true;
10332 auto PT1 = F1->getPrimaryTemplate();
10333 auto PT2 = F2->getPrimaryTemplate();
10334 if (PT1 && PT2) {
10335 if (declaresSameEntity(PT1, PT2) ||
10336 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10337 PT2->getInstantiatedFromMemberTemplate()))
10338 return true;
10339 }
10340 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10341 // different functions with same params). Consider removing this (as no test
10342 // fail w/o it).
10343 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10344 if (First) {
10345 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10346 return *T;
10347 }
10348 assert(I < F->getNumParams());
10349 return F->getParamDecl(I++)->getType();
10350 };
10351
10352 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10353 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10354
10355 if (F1NumParams != F2NumParams)
10356 return false;
10357
10358 unsigned I1 = 0, I2 = 0;
10359 for (unsigned I = 0; I != F1NumParams; ++I) {
10360 QualType T1 = NextParam(F1, I1, I == 0);
10361 QualType T2 = NextParam(F2, I2, I == 0);
10362 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10363 if (!Context.hasSameUnqualifiedType(T1, T2))
10364 return false;
10365 }
10366 return true;
10367}
10368
10369/// We're allowed to use constraints partial ordering only if the candidates
10370/// have the same parameter types:
10371/// [over.match.best.general]p2.6
10372/// F1 and F2 are non-template functions with the same
10373/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10375 const OverloadCandidate &Cand1,
10376 const OverloadCandidate &Cand2) {
10377 if (!Cand1.Function || !Cand2.Function)
10378 return false;
10379
10380 FunctionDecl *Fn1 = Cand1.Function;
10381 FunctionDecl *Fn2 = Cand2.Function;
10382
10383 if (Fn1->isVariadic() != Fn1->isVariadic())
10384 return false;
10385
10387 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10388 return false;
10389
10390 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10391 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10392 if (Mem1 && Mem2) {
10393 // if they are member functions, both are direct members of the same class,
10394 // and
10395 if (Mem1->getParent() != Mem2->getParent())
10396 return false;
10397 // if both are non-static member functions, they have the same types for
10398 // their object parameters
10399 if (Mem1->isInstance() && Mem2->isInstance() &&
10401 Mem1->getFunctionObjectParameterReferenceType(),
10402 Mem1->getFunctionObjectParameterReferenceType()))
10403 return false;
10404 }
10405 return true;
10406}
10407
10408/// isBetterOverloadCandidate - Determines whether the first overload
10409/// candidate is a better candidate than the second (C++ 13.3.3p1).
10411 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10413 // Define viable functions to be better candidates than non-viable
10414 // functions.
10415 if (!Cand2.Viable)
10416 return Cand1.Viable;
10417 else if (!Cand1.Viable)
10418 return false;
10419
10420 // [CUDA] A function with 'never' preference is marked not viable, therefore
10421 // is never shown up here. The worst preference shown up here is 'wrong side',
10422 // e.g. an H function called by a HD function in device compilation. This is
10423 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10424 // function which is called only by an H function. A deferred diagnostic will
10425 // be triggered if it is emitted. However a wrong-sided function is still
10426 // a viable candidate here.
10427 //
10428 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10429 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10430 // can be emitted, Cand1 is not better than Cand2. This rule should have
10431 // precedence over other rules.
10432 //
10433 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10434 // other rules should be used to determine which is better. This is because
10435 // host/device based overloading resolution is mostly for determining
10436 // viability of a function. If two functions are both viable, other factors
10437 // should take precedence in preference, e.g. the standard-defined preferences
10438 // like argument conversion ranks or enable_if partial-ordering. The
10439 // preference for pass-object-size parameters is probably most similar to a
10440 // type-based-overloading decision and so should take priority.
10441 //
10442 // If other rules cannot determine which is better, CUDA preference will be
10443 // used again to determine which is better.
10444 //
10445 // TODO: Currently IdentifyPreference does not return correct values
10446 // for functions called in global variable initializers due to missing
10447 // correct context about device/host. Therefore we can only enforce this
10448 // rule when there is a caller. We should enforce this rule for functions
10449 // in global variable initializers once proper context is added.
10450 //
10451 // TODO: We can only enable the hostness based overloading resolution when
10452 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10453 // overloading resolution diagnostics.
10454 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10455 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10456 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10457 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10458 bool IsCand1ImplicitHD =
10460 bool IsCand2ImplicitHD =
10462 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10463 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10464 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10465 // The implicit HD function may be a function in a system header which
10466 // is forced by pragma. In device compilation, if we prefer HD candidates
10467 // over wrong-sided candidates, overloading resolution may change, which
10468 // may result in non-deferrable diagnostics. As a workaround, we let
10469 // implicit HD candidates take equal preference as wrong-sided candidates.
10470 // This will preserve the overloading resolution.
10471 // TODO: We still need special handling of implicit HD functions since
10472 // they may incur other diagnostics to be deferred. We should make all
10473 // host/device related diagnostics deferrable and remove special handling
10474 // of implicit HD functions.
10475 auto EmitThreshold =
10476 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10477 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10480 auto Cand1Emittable = P1 > EmitThreshold;
10481 auto Cand2Emittable = P2 > EmitThreshold;
10482 if (Cand1Emittable && !Cand2Emittable)
10483 return true;
10484 if (!Cand1Emittable && Cand2Emittable)
10485 return false;
10486 }
10487 }
10488
10489 // C++ [over.match.best]p1: (Changed in C++23)
10490 //
10491 // -- if F is a static member function, ICS1(F) is defined such
10492 // that ICS1(F) is neither better nor worse than ICS1(G) for
10493 // any function G, and, symmetrically, ICS1(G) is neither
10494 // better nor worse than ICS1(F).
10495 unsigned StartArg = 0;
10496 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10497 StartArg = 1;
10498
10499 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10500 // We don't allow incompatible pointer conversions in C++.
10501 if (!S.getLangOpts().CPlusPlus)
10502 return ICS.isStandard() &&
10503 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10504
10505 // The only ill-formed conversion we allow in C++ is the string literal to
10506 // char* conversion, which is only considered ill-formed after C++11.
10507 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10509 };
10510
10511 // Define functions that don't require ill-formed conversions for a given
10512 // argument to be better candidates than functions that do.
10513 unsigned NumArgs = Cand1.Conversions.size();
10514 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10515 bool HasBetterConversion = false;
10516 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10517 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10518 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10519 if (Cand1Bad != Cand2Bad) {
10520 if (Cand1Bad)
10521 return false;
10522 HasBetterConversion = true;
10523 }
10524 }
10525
10526 if (HasBetterConversion)
10527 return true;
10528
10529 // C++ [over.match.best]p1:
10530 // A viable function F1 is defined to be a better function than another
10531 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10532 // conversion sequence than ICSi(F2), and then...
10533 bool HasWorseConversion = false;
10534 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10536 Cand1.Conversions[ArgIdx],
10537 Cand2.Conversions[ArgIdx])) {
10539 // Cand1 has a better conversion sequence.
10540 HasBetterConversion = true;
10541 break;
10542
10544 if (Cand1.Function && Cand2.Function &&
10545 Cand1.isReversed() != Cand2.isReversed() &&
10546 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10547 // Work around large-scale breakage caused by considering reversed
10548 // forms of operator== in C++20:
10549 //
10550 // When comparing a function against a reversed function, if we have a
10551 // better conversion for one argument and a worse conversion for the
10552 // other, the implicit conversion sequences are treated as being equally
10553 // good.
10554 //
10555 // This prevents a comparison function from being considered ambiguous
10556 // with a reversed form that is written in the same way.
10557 //
10558 // We diagnose this as an extension from CreateOverloadedBinOp.
10559 HasWorseConversion = true;
10560 break;
10561 }
10562
10563 // Cand1 can't be better than Cand2.
10564 return false;
10565
10567 // Do nothing.
10568 break;
10569 }
10570 }
10571
10572 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10573 // ICSj(F2), or, if not that,
10574 if (HasBetterConversion && !HasWorseConversion)
10575 return true;
10576
10577 // -- the context is an initialization by user-defined conversion
10578 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10579 // from the return type of F1 to the destination type (i.e.,
10580 // the type of the entity being initialized) is a better
10581 // conversion sequence than the standard conversion sequence
10582 // from the return type of F2 to the destination type.
10584 Cand1.Function && Cand2.Function &&
10585 isa<CXXConversionDecl>(Cand1.Function) &&
10586 isa<CXXConversionDecl>(Cand2.Function)) {
10587 // First check whether we prefer one of the conversion functions over the
10588 // other. This only distinguishes the results in non-standard, extension
10589 // cases such as the conversion from a lambda closure type to a function
10590 // pointer or block.
10595 Cand1.FinalConversion,
10596 Cand2.FinalConversion);
10597
10600
10601 // FIXME: Compare kind of reference binding if conversion functions
10602 // convert to a reference type used in direct reference binding, per
10603 // C++14 [over.match.best]p1 section 2 bullet 3.
10604 }
10605
10606 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10607 // as combined with the resolution to CWG issue 243.
10608 //
10609 // When the context is initialization by constructor ([over.match.ctor] or
10610 // either phase of [over.match.list]), a constructor is preferred over
10611 // a conversion function.
10612 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10613 Cand1.Function && Cand2.Function &&
10614 isa<CXXConstructorDecl>(Cand1.Function) !=
10615 isa<CXXConstructorDecl>(Cand2.Function))
10616 return isa<CXXConstructorDecl>(Cand1.Function);
10617
10618 // -- F1 is a non-template function and F2 is a function template
10619 // specialization, or, if not that,
10620 bool Cand1IsSpecialization = Cand1.Function &&
10622 bool Cand2IsSpecialization = Cand2.Function &&
10624 if (Cand1IsSpecialization != Cand2IsSpecialization)
10625 return Cand2IsSpecialization;
10626
10627 // -- F1 and F2 are function template specializations, and the function
10628 // template for F1 is more specialized than the template for F2
10629 // according to the partial ordering rules described in 14.5.5.2, or,
10630 // if not that,
10631 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10632 const auto *Obj1Context =
10633 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10634 const auto *Obj2Context =
10635 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10636 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10638 Cand2.Function->getPrimaryTemplate(), Loc,
10639 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10640 : TPOC_Call,
10642 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10643 : QualType{},
10644 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10645 : QualType{},
10646 Cand1.isReversed() ^ Cand2.isReversed())) {
10647 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10648 }
10649 }
10650
10651 // -— F1 and F2 are non-template functions with the same
10652 // parameter-type-lists, and F1 is more constrained than F2 [...],
10653 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10654 sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10655 FunctionDecl *Function1 = Cand1.Function;
10656 FunctionDecl *Function2 = Cand2.Function;
10657 if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10658 Function1 = MF;
10659 if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10660 Function2 = MF;
10661
10662 const Expr *RC1 = Function1->getTrailingRequiresClause();
10663 const Expr *RC2 = Function2->getTrailingRequiresClause();
10664 if (RC1 && RC2) {
10665 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10666 if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10667 AtLeastAsConstrained1) ||
10668 S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10669 AtLeastAsConstrained2))
10670 return false;
10671 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10672 return AtLeastAsConstrained1;
10673 } else if (RC1 || RC2) {
10674 return RC1 != nullptr;
10675 }
10676 }
10677
10678 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10679 // class B of D, and for all arguments the corresponding parameters of
10680 // F1 and F2 have the same type.
10681 // FIXME: Implement the "all parameters have the same type" check.
10682 bool Cand1IsInherited =
10683 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10684 bool Cand2IsInherited =
10685 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10686 if (Cand1IsInherited != Cand2IsInherited)
10687 return Cand2IsInherited;
10688 else if (Cand1IsInherited) {
10689 assert(Cand2IsInherited);
10690 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10691 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10692 if (Cand1Class->isDerivedFrom(Cand2Class))
10693 return true;
10694 if (Cand2Class->isDerivedFrom(Cand1Class))
10695 return false;
10696 // Inherited from sibling base classes: still ambiguous.
10697 }
10698
10699 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10700 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10701 // with reversed order of parameters and F1 is not
10702 //
10703 // We rank reversed + different operator as worse than just reversed, but
10704 // that comparison can never happen, because we only consider reversing for
10705 // the maximally-rewritten operator (== or <=>).
10706 if (Cand1.RewriteKind != Cand2.RewriteKind)
10707 return Cand1.RewriteKind < Cand2.RewriteKind;
10708
10709 // Check C++17 tie-breakers for deduction guides.
10710 {
10711 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10712 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10713 if (Guide1 && Guide2) {
10714 // -- F1 is generated from a deduction-guide and F2 is not
10715 if (Guide1->isImplicit() != Guide2->isImplicit())
10716 return Guide2->isImplicit();
10717
10718 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10719 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10720 return true;
10721 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10722 return false;
10723
10724 // --F1 is generated from a non-template constructor and F2 is generated
10725 // from a constructor template
10726 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10727 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10728 if (Constructor1 && Constructor2) {
10729 bool isC1Templated = Constructor1->getTemplatedKind() !=
10731 bool isC2Templated = Constructor2->getTemplatedKind() !=
10733 if (isC1Templated != isC2Templated)
10734 return isC2Templated;
10735 }
10736 }
10737 }
10738
10739 // Check for enable_if value-based overload resolution.
10740 if (Cand1.Function && Cand2.Function) {
10741 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10742 if (Cmp != Comparison::Equal)
10743 return Cmp == Comparison::Better;
10744 }
10745
10746 bool HasPS1 = Cand1.Function != nullptr &&
10748 bool HasPS2 = Cand2.Function != nullptr &&
10750 if (HasPS1 != HasPS2 && HasPS1)
10751 return true;
10752
10753 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10754 if (MV == Comparison::Better)
10755 return true;
10756 if (MV == Comparison::Worse)
10757 return false;
10758
10759 // If other rules cannot determine which is better, CUDA preference is used
10760 // to determine which is better.
10761 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10762 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10763 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10764 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10765 }
10766
10767 // General member function overloading is handled above, so this only handles
10768 // constructors with address spaces.
10769 // This only handles address spaces since C++ has no other
10770 // qualifier that can be used with constructors.
10771 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10772 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10773 if (CD1 && CD2) {
10774 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10775 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10776 if (AS1 != AS2) {
10778 return true;
10780 return false;
10781 }
10782 }
10783
10784 return false;
10785}
10786
10787/// Determine whether two declarations are "equivalent" for the purposes of
10788/// name lookup and overload resolution. This applies when the same internal/no
10789/// linkage entity is defined by two modules (probably by textually including
10790/// the same header). In such a case, we don't consider the declarations to
10791/// declare the same entity, but we also don't want lookups with both
10792/// declarations visible to be ambiguous in some cases (this happens when using
10793/// a modularized libstdc++).
10795 const NamedDecl *B) {
10796 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10797 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10798 if (!VA || !VB)
10799 return false;
10800
10801 // The declarations must be declaring the same name as an internal linkage
10802 // entity in different modules.
10803 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10804 VB->getDeclContext()->getRedeclContext()) ||
10805 getOwningModule(VA) == getOwningModule(VB) ||
10806 VA->isExternallyVisible() || VB->isExternallyVisible())
10807 return false;
10808
10809 // Check that the declarations appear to be equivalent.
10810 //
10811 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10812 // For constants and functions, we should check the initializer or body is
10813 // the same. For non-constant variables, we shouldn't allow it at all.
10814 if (Context.hasSameType(VA->getType(), VB->getType()))
10815 return true;
10816
10817 // Enum constants within unnamed enumerations will have different types, but
10818 // may still be similar enough to be interchangeable for our purposes.
10819 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10820 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10821 // Only handle anonymous enums. If the enumerations were named and
10822 // equivalent, they would have been merged to the same type.
10823 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10824 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10825 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10826 !Context.hasSameType(EnumA->getIntegerType(),
10827 EnumB->getIntegerType()))
10828 return false;
10829 // Allow this only if the value is the same for both enumerators.
10830 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10831 }
10832 }
10833
10834 // Nothing else is sufficiently similar.
10835 return false;
10836}
10837
10840 assert(D && "Unknown declaration");
10841 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10842
10843 Module *M = getOwningModule(D);
10844 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10845 << !M << (M ? M->getFullModuleName() : "");
10846
10847 for (auto *E : Equiv) {
10848 Module *M = getOwningModule(E);
10849 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10850 << !M << (M ? M->getFullModuleName() : "");
10851 }
10852}
10853
10855 return FailureKind == ovl_fail_bad_deduction &&
10856 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10858 static_cast<CNSInfo *>(DeductionFailure.Data)
10859 ->Satisfaction.ContainsErrors;
10860}
10861
10862/// Computes the best viable function (C++ 13.3.3)
10863/// within an overload candidate set.
10864///
10865/// \param Loc The location of the function name (or operator symbol) for
10866/// which overload resolution occurs.
10867///
10868/// \param Best If overload resolution was successful or found a deleted
10869/// function, \p Best points to the candidate function found.
10870///
10871/// \returns The result of overload resolution.
10874 iterator &Best) {
10876 std::transform(begin(), end(), std::back_inserter(Candidates),
10877 [](OverloadCandidate &Cand) { return &Cand; });
10878
10879 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10880 // are accepted by both clang and NVCC. However, during a particular
10881 // compilation mode only one call variant is viable. We need to
10882 // exclude non-viable overload candidates from consideration based
10883 // only on their host/device attributes. Specifically, if one
10884 // candidate call is WrongSide and the other is SameSide, we ignore
10885 // the WrongSide candidate.
10886 // We only need to remove wrong-sided candidates here if
10887 // -fgpu-exclude-wrong-side-overloads is off. When
10888 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10889 // uniformly in isBetterOverloadCandidate.
10890 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10891 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10892 bool ContainsSameSideCandidate =
10893 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10894 // Check viable function only.
10895 return Cand->Viable && Cand->Function &&
10896 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10898 });
10899 if (ContainsSameSideCandidate) {
10900 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10901 // Check viable function only to avoid unnecessary data copying/moving.
10902 return Cand->Viable && Cand->Function &&
10903 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10905 };
10906 llvm::erase_if(Candidates, IsWrongSideCandidate);
10907 }
10908 }
10909
10910 // Find the best viable function.
10911 Best = end();
10912 for (auto *Cand : Candidates) {
10913 Cand->Best = false;
10914 if (Cand->Viable) {
10915 if (Best == end() ||
10916 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10917 Best = Cand;
10918 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10919 // This candidate has constraint that we were unable to evaluate because
10920 // it referenced an expression that contained an error. Rather than fall
10921 // back onto a potentially unintended candidate (made worse by
10922 // subsuming constraints), treat this as 'no viable candidate'.
10923 Best = end();
10924 return OR_No_Viable_Function;
10925 }
10926 }
10927
10928 // If we didn't find any viable functions, abort.
10929 if (Best == end())
10930 return OR_No_Viable_Function;
10931
10933
10935 PendingBest.push_back(&*Best);
10936 Best->Best = true;
10937
10938 // Make sure that this function is better than every other viable
10939 // function. If not, we have an ambiguity.
10940 while (!PendingBest.empty()) {
10941 auto *Curr = PendingBest.pop_back_val();
10942 for (auto *Cand : Candidates) {
10943 if (Cand->Viable && !Cand->Best &&
10944 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10945 PendingBest.push_back(Cand);
10946 Cand->Best = true;
10947
10949 Curr->Function))
10950 EquivalentCands.push_back(Cand->Function);
10951 else
10952 Best = end();
10953 }
10954 }
10955 }
10956
10957 // If we found more than one best candidate, this is ambiguous.
10958 if (Best == end())
10959 return OR_Ambiguous;
10960
10961 // Best is the best viable function.
10962 if (Best->Function && Best->Function->isDeleted())
10963 return OR_Deleted;
10964
10965 if (!EquivalentCands.empty())
10967 EquivalentCands);
10968
10969 return OR_Success;
10970}
10971
10972namespace {
10973
10974enum OverloadCandidateKind {
10975 oc_function,
10976 oc_method,
10977 oc_reversed_binary_operator,
10978 oc_constructor,
10979 oc_implicit_default_constructor,
10980 oc_implicit_copy_constructor,
10981 oc_implicit_move_constructor,
10982 oc_implicit_copy_assignment,
10983 oc_implicit_move_assignment,
10984 oc_implicit_equality_comparison,
10985 oc_inherited_constructor
10986};
10987
10988enum OverloadCandidateSelect {
10989 ocs_non_template,
10990 ocs_template,
10991 ocs_described_template,
10992};
10993
10994static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10995ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10996 const FunctionDecl *Fn,
10998 std::string &Description) {
10999
11000 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11001 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11002 isTemplate = true;
11003 Description = S.getTemplateArgumentBindingsText(
11004 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11005 }
11006
11007 OverloadCandidateSelect Select = [&]() {
11008 if (!Description.empty())
11009 return ocs_described_template;
11010 return isTemplate ? ocs_template : ocs_non_template;
11011 }();
11012
11013 OverloadCandidateKind Kind = [&]() {
11014 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11015 return oc_implicit_equality_comparison;
11016
11017 if (CRK & CRK_Reversed)
11018 return oc_reversed_binary_operator;
11019
11020 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11021 if (!Ctor->isImplicit()) {
11022 if (isa<ConstructorUsingShadowDecl>(Found))
11023 return oc_inherited_constructor;
11024 else
11025 return oc_constructor;
11026 }
11027
11028 if (Ctor->isDefaultConstructor())
11029 return oc_implicit_default_constructor;
11030
11031 if (Ctor->isMoveConstructor())
11032 return oc_implicit_move_constructor;
11033
11034 assert(Ctor->isCopyConstructor() &&
11035 "unexpected sort of implicit constructor");
11036 return oc_implicit_copy_constructor;
11037 }
11038
11039 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11040 // This actually gets spelled 'candidate function' for now, but
11041 // it doesn't hurt to split it out.
11042 if (!Meth->isImplicit())
11043 return oc_method;
11044
11045 if (Meth->isMoveAssignmentOperator())
11046 return oc_implicit_move_assignment;
11047
11048 if (Meth->isCopyAssignmentOperator())
11049 return oc_implicit_copy_assignment;
11050
11051 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11052 return oc_method;
11053 }
11054
11055 return oc_function;
11056 }();
11057
11058 return std::make_pair(Kind, Select);
11059}
11060
11061void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11062 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11063 // set.
11064 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11065 S.Diag(FoundDecl->getLocation(),
11066 diag::note_ovl_candidate_inherited_constructor)
11067 << Shadow->getNominatedBaseClass();
11068}
11069
11070} // end anonymous namespace
11071
11073 const FunctionDecl *FD) {
11074 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11075 bool AlwaysTrue;
11076 if (EnableIf->getCond()->isValueDependent() ||
11077 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11078 return false;
11079 if (!AlwaysTrue)
11080 return false;
11081 }
11082 return true;
11083}
11084
11085/// Returns true if we can take the address of the function.
11086///
11087/// \param Complain - If true, we'll emit a diagnostic
11088/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11089/// we in overload resolution?
11090/// \param Loc - The location of the statement we're complaining about. Ignored
11091/// if we're not complaining, or if we're in overload resolution.
11093 bool Complain,
11094 bool InOverloadResolution,
11095 SourceLocation Loc) {
11096 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11097 if (Complain) {
11098 if (InOverloadResolution)
11099 S.Diag(FD->getBeginLoc(),
11100 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11101 else
11102 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11103 }
11104 return false;
11105 }
11106
11107 if (FD->getTrailingRequiresClause()) {
11108 ConstraintSatisfaction Satisfaction;
11109 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11110 return false;
11111 if (!Satisfaction.IsSatisfied) {
11112 if (Complain) {
11113 if (InOverloadResolution) {
11114 SmallString<128> TemplateArgString;
11115 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11116 TemplateArgString += " ";
11117 TemplateArgString += S.getTemplateArgumentBindingsText(
11118 FunTmpl->getTemplateParameters(),
11120 }
11121
11122 S.Diag(FD->getBeginLoc(),
11123 diag::note_ovl_candidate_unsatisfied_constraints)
11124 << TemplateArgString;
11125 } else
11126 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11127 << FD;
11128 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11129 }
11130 return false;
11131 }
11132 }
11133
11134 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11135 return P->hasAttr<PassObjectSizeAttr>();
11136 });
11137 if (I == FD->param_end())
11138 return true;
11139
11140 if (Complain) {
11141 // Add one to ParamNo because it's user-facing
11142 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11143 if (InOverloadResolution)
11144 S.Diag(FD->getLocation(),
11145 diag::note_ovl_candidate_has_pass_object_size_params)
11146 << ParamNo;
11147 else
11148 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11149 << FD << ParamNo;
11150 }
11151 return false;
11152}
11153
11155 const FunctionDecl *FD) {
11156 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11157 /*InOverloadResolution=*/true,
11158 /*Loc=*/SourceLocation());
11159}
11160
11162 bool Complain,
11163 SourceLocation Loc) {
11164 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11165 /*InOverloadResolution=*/false,
11166 Loc);
11167}
11168
11169// Don't print candidates other than the one that matches the calling
11170// convention of the call operator, since that is guaranteed to exist.
11172 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11173
11174 if (!ConvD)
11175 return false;
11176 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11177 if (!RD->isLambda())
11178 return false;
11179
11180 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11181 CallingConv CallOpCC =
11182 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11183 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11184 CallingConv ConvToCC =
11185 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11186
11187 return ConvToCC != CallOpCC;
11188}
11189
11190// Notes the location of an overload candidate.
11192 OverloadCandidateRewriteKind RewriteKind,
11193 QualType DestType, bool TakingAddress) {
11194 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11195 return;
11196 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11197 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11198 return;
11199 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11200 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11201 return;
11203 return;
11204
11205 std::string FnDesc;
11206 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11207 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11208 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11209 << (unsigned)KSPair.first << (unsigned)KSPair.second
11210 << Fn << FnDesc;
11211
11212 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11213 Diag(Fn->getLocation(), PD);
11214 MaybeEmitInheritedConstructorNote(*this, Found);
11215}
11216
11217static void
11219 // Perhaps the ambiguity was caused by two atomic constraints that are
11220 // 'identical' but not equivalent:
11221 //
11222 // void foo() requires (sizeof(T) > 4) { } // #1
11223 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11224 //
11225 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11226 // #2 to subsume #1, but these constraint are not considered equivalent
11227 // according to the subsumption rules because they are not the same
11228 // source-level construct. This behavior is quite confusing and we should try
11229 // to help the user figure out what happened.
11230
11231 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11232 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11233 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11234 if (!I->Function)
11235 continue;
11237 if (auto *Template = I->Function->getPrimaryTemplate())
11238 Template->getAssociatedConstraints(AC);
11239 else
11240 I->Function->getAssociatedConstraints(AC);
11241 if (AC.empty())
11242 continue;
11243 if (FirstCand == nullptr) {
11244 FirstCand = I->Function;
11245 FirstAC = AC;
11246 } else if (SecondCand == nullptr) {
11247 SecondCand = I->Function;
11248 SecondAC = AC;
11249 } else {
11250 // We have more than one pair of constrained functions - this check is
11251 // expensive and we'd rather not try to diagnose it.
11252 return;
11253 }
11254 }
11255 if (!SecondCand)
11256 return;
11257 // The diagnostic can only happen if there are associated constraints on
11258 // both sides (there needs to be some identical atomic constraint).
11259 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11260 SecondCand, SecondAC))
11261 // Just show the user one diagnostic, they'll probably figure it out
11262 // from here.
11263 return;
11264}
11265
11266// Notes the location of all overload candidates designated through
11267// OverloadedExpr
11268void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11269 bool TakingAddress) {
11270 assert(OverloadedExpr->getType() == Context.OverloadTy);
11271
11272 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11273 OverloadExpr *OvlExpr = Ovl.Expression;
11274
11275 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11276 IEnd = OvlExpr->decls_end();
11277 I != IEnd; ++I) {
11278 if (FunctionTemplateDecl *FunTmpl =
11279 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11280 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11281 TakingAddress);
11282 } else if (FunctionDecl *Fun
11283 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11284 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11285 }
11286 }
11287}
11288
11289/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11290/// "lead" diagnostic; it will be given two arguments, the source and
11291/// target types of the conversion.
11293 Sema &S,
11294 SourceLocation CaretLoc,
11295 const PartialDiagnostic &PDiag) const {
11296 S.Diag(CaretLoc, PDiag)
11297 << Ambiguous.getFromType() << Ambiguous.getToType();
11298 unsigned CandsShown = 0;
11300 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11301 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11302 break;
11303 ++CandsShown;
11304 S.NoteOverloadCandidate(I->first, I->second);
11305 }
11306 S.Diags.overloadCandidatesShown(CandsShown);
11307 if (I != E)
11308 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11309}
11310
11312 unsigned I, bool TakingCandidateAddress) {
11313 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11314 assert(Conv.isBad());
11315 assert(Cand->Function && "for now, candidate must be a function");
11316 FunctionDecl *Fn = Cand->Function;
11317
11318 // There's a conversion slot for the object argument if this is a
11319 // non-constructor method. Note that 'I' corresponds the
11320 // conversion-slot index.
11321 bool isObjectArgument = false;
11322 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11323 if (I == 0)
11324 isObjectArgument = true;
11325 else
11326 I--;
11327 }
11328
11329 std::string FnDesc;
11330 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11331 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11332 FnDesc);
11333
11334 Expr *FromExpr = Conv.Bad.FromExpr;
11335 QualType FromTy = Conv.Bad.getFromType();
11336 QualType ToTy = Conv.Bad.getToType();
11337 SourceRange ToParamRange =
11338 !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
11339
11340 if (FromTy == S.Context.OverloadTy) {
11341 assert(FromExpr && "overload set argument came from implicit argument?");
11342 Expr *E = FromExpr->IgnoreParens();
11343 if (isa<UnaryOperator>(E))
11344 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11345 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11346
11347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11348 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11349 << ToParamRange << ToTy << Name << I + 1;
11350 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11351 return;
11352 }
11353
11354 // Do some hand-waving analysis to see if the non-viability is due
11355 // to a qualifier mismatch.
11356 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11357 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11358 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11359 CToTy = RT->getPointeeType();
11360 else {
11361 // TODO: detect and diagnose the full richness of const mismatches.
11362 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11363 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11364 CFromTy = FromPT->getPointeeType();
11365 CToTy = ToPT->getPointeeType();
11366 }
11367 }
11368
11369 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11370 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11371 Qualifiers FromQs = CFromTy.getQualifiers();
11372 Qualifiers ToQs = CToTy.getQualifiers();
11373
11374 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11375 if (isObjectArgument)
11376 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11377 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11378 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11379 else
11380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11381 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11382 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11383 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11384 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11385 return;
11386 }
11387
11388 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11389 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11390 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11391 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11392 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11393 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11394 return;
11395 }
11396
11397 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11398 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11399 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11400 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11401 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11402 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11403 return;
11404 }
11405
11406 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11407 assert(CVR && "expected qualifiers mismatch");
11408
11409 if (isObjectArgument) {
11410 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11411 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11412 << FromTy << (CVR - 1);
11413 } else {
11414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11415 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11416 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11417 }
11418 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11419 return;
11420 }
11421
11424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11425 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11426 << (unsigned)isObjectArgument << I + 1
11428 << ToParamRange;
11429 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11430 return;
11431 }
11432
11433 // Special diagnostic for failure to convert an initializer list, since
11434 // telling the user that it has type void is not useful.
11435 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11436 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11437 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11438 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11441 ? 2
11442 : 0);
11443 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11444 return;
11445 }
11446
11447 // Diagnose references or pointers to incomplete types differently,
11448 // since it's far from impossible that the incompleteness triggered
11449 // the failure.
11450 QualType TempFromTy = FromTy.getNonReferenceType();
11451 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11452 TempFromTy = PTy->getPointeeType();
11453 if (TempFromTy->isIncompleteType()) {
11454 // Emit the generic diagnostic and, optionally, add the hints to it.
11455 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11456 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11457 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11458 << (unsigned)(Cand->Fix.Kind);
11459
11460 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11461 return;
11462 }
11463
11464 // Diagnose base -> derived pointer conversions.
11465 unsigned BaseToDerivedConversion = 0;
11466 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11467 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11468 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11469 FromPtrTy->getPointeeType()) &&
11470 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11471 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11472 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11473 FromPtrTy->getPointeeType()))
11474 BaseToDerivedConversion = 1;
11475 }
11476 } else if (const ObjCObjectPointerType *FromPtrTy
11477 = FromTy->getAs<ObjCObjectPointerType>()) {
11478 if (const ObjCObjectPointerType *ToPtrTy
11479 = ToTy->getAs<ObjCObjectPointerType>())
11480 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11481 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11482 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11483 FromPtrTy->getPointeeType()) &&
11484 FromIface->isSuperClassOf(ToIface))
11485 BaseToDerivedConversion = 2;
11486 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11487 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11488 !FromTy->isIncompleteType() &&
11489 !ToRefTy->getPointeeType()->isIncompleteType() &&
11490 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11491 BaseToDerivedConversion = 3;
11492 }
11493 }
11494
11495 if (BaseToDerivedConversion) {
11496 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11497 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11498 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11499 << I + 1;
11500 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11501 return;
11502 }
11503
11504 if (isa<ObjCObjectPointerType>(CFromTy) &&
11505 isa<PointerType>(CToTy)) {
11506 Qualifiers FromQs = CFromTy.getQualifiers();
11507 Qualifiers ToQs = CToTy.getQualifiers();
11508 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11509 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11510 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11511 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11512 << I + 1;
11513 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11514 return;
11515 }
11516 }
11517
11518 if (TakingCandidateAddress &&
11520 return;
11521
11522 // Emit the generic diagnostic and, optionally, add the hints to it.
11523 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11524 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11525 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11526 << (unsigned)(Cand->Fix.Kind);
11527
11528 // Check that location of Fn is not in system header.
11529 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11530 // If we can fix the conversion, suggest the FixIts.
11531 for (const FixItHint &HI : Cand->Fix.Hints)
11532 FDiag << HI;
11533 }
11534
11535 S.Diag(Fn->getLocation(), FDiag);
11536
11537 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11538}
11539
11540/// Additional arity mismatch diagnosis specific to a function overload
11541/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11542/// over a candidate in any candidate set.
11544 unsigned NumArgs) {
11545 FunctionDecl *Fn = Cand->Function;
11546 unsigned MinParams = Fn->getMinRequiredArguments();
11547
11548 // With invalid overloaded operators, it's possible that we think we
11549 // have an arity mismatch when in fact it looks like we have the
11550 // right number of arguments, because only overloaded operators have
11551 // the weird behavior of overloading member and non-member functions.
11552 // Just don't report anything.
11553 if (Fn->isInvalidDecl() &&
11555 return true;
11556
11557 if (NumArgs < MinParams) {
11558 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11560 Cand->DeductionFailure.getResult() ==
11562 } else {
11563 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11565 Cand->DeductionFailure.getResult() ==
11567 }
11568
11569 return false;
11570}
11571
11572/// General arity mismatch diagnosis over a candidate in a candidate set.
11573static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11574 unsigned NumFormalArgs) {
11575 assert(isa<FunctionDecl>(D) &&
11576 "The templated declaration should at least be a function"
11577 " when diagnosing bad template argument deduction due to too many"
11578 " or too few arguments");
11579
11580 FunctionDecl *Fn = cast<FunctionDecl>(D);
11581
11582 // TODO: treat calls to a missing default constructor as a special case
11583 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11584 unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11585
11586 // at least / at most / exactly
11587 bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11588 unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11589 unsigned mode, modeCount;
11590 if (NumFormalArgs < MinParams) {
11591 if (MinParams != ParamCount || FnTy->isVariadic() ||
11592 FnTy->isTemplateVariadic())
11593 mode = 0; // "at least"
11594 else
11595 mode = 2; // "exactly"
11596 modeCount = MinParams;
11597 } else {
11598 if (MinParams != ParamCount)
11599 mode = 1; // "at most"
11600 else
11601 mode = 2; // "exactly"
11602 modeCount = ParamCount;
11603 }
11604
11605 std::string Description;
11606 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11607 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11608
11609 if (modeCount == 1 &&
11610 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11611 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11612 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11613 << Description << mode
11614 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11615 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11616 else
11617 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11618 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11619 << Description << mode << modeCount << NumFormalArgs
11620 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11621
11622 MaybeEmitInheritedConstructorNote(S, Found);
11623}
11624
11625/// Arity mismatch diagnosis specific to a function overload candidate.
11627 unsigned NumFormalArgs) {
11628 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11629 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11630}
11631
11633 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11634 return TD;
11635 llvm_unreachable("Unsupported: Getting the described template declaration"
11636 " for bad deduction diagnosis");
11637}
11638
11639/// Diagnose a failed template-argument deduction.
11640static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11641 DeductionFailureInfo &DeductionFailure,
11642 unsigned NumArgs,
11643 bool TakingCandidateAddress) {
11644 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11645 NamedDecl *ParamD;
11646 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11647 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11648 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11649 switch (DeductionFailure.getResult()) {
11651 llvm_unreachable(
11652 "TemplateDeductionResult::Success while diagnosing bad deduction");
11654 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11655 "while diagnosing bad deduction");
11658 return;
11659
11661 assert(ParamD && "no parameter found for incomplete deduction result");
11662 S.Diag(Templated->getLocation(),
11663 diag::note_ovl_candidate_incomplete_deduction)
11664 << ParamD->getDeclName();
11665 MaybeEmitInheritedConstructorNote(S, Found);
11666 return;
11667 }
11668
11670 assert(ParamD && "no parameter found for incomplete deduction result");
11671 S.Diag(Templated->getLocation(),
11672 diag::note_ovl_candidate_incomplete_deduction_pack)
11673 << ParamD->getDeclName()
11674 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11675 << *DeductionFailure.getFirstArg();
11676 MaybeEmitInheritedConstructorNote(S, Found);
11677 return;
11678 }
11679
11681 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11682 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11683
11684 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11685
11686 // Param will have been canonicalized, but it should just be a
11687 // qualified version of ParamD, so move the qualifiers to that.
11689 Qs.strip(Param);
11690 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11691 assert(S.Context.hasSameType(Param, NonCanonParam));
11692
11693 // Arg has also been canonicalized, but there's nothing we can do
11694 // about that. It also doesn't matter as much, because it won't
11695 // have any template parameters in it (because deduction isn't
11696 // done on dependent types).
11697 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11698
11699 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11700 << ParamD->getDeclName() << Arg << NonCanonParam;
11701 MaybeEmitInheritedConstructorNote(S, Found);
11702 return;
11703 }
11704
11706 assert(ParamD && "no parameter found for inconsistent deduction result");
11707 int which = 0;
11708 if (isa<TemplateTypeParmDecl>(ParamD))
11709 which = 0;
11710 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11711 // Deduction might have failed because we deduced arguments of two
11712 // different types for a non-type template parameter.
11713 // FIXME: Use a different TDK value for this.
11714 QualType T1 =
11715 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11716 QualType T2 =
11717 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11718 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11719 S.Diag(Templated->getLocation(),
11720 diag::note_ovl_candidate_inconsistent_deduction_types)
11721 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11722 << *DeductionFailure.getSecondArg() << T2;
11723 MaybeEmitInheritedConstructorNote(S, Found);
11724 return;
11725 }
11726
11727 which = 1;
11728 } else {
11729 which = 2;
11730 }
11731
11732 // Tweak the diagnostic if the problem is that we deduced packs of
11733 // different arities. We'll print the actual packs anyway in case that
11734 // includes additional useful information.
11735 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11736 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11737 DeductionFailure.getFirstArg()->pack_size() !=
11738 DeductionFailure.getSecondArg()->pack_size()) {
11739 which = 3;
11740 }
11741
11742 S.Diag(Templated->getLocation(),
11743 diag::note_ovl_candidate_inconsistent_deduction)
11744 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11745 << *DeductionFailure.getSecondArg();
11746 MaybeEmitInheritedConstructorNote(S, Found);
11747 return;
11748 }
11749
11751 assert(ParamD && "no parameter found for invalid explicit arguments");
11752 if (ParamD->getDeclName())
11753 S.Diag(Templated->getLocation(),
11754 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11755 << ParamD->getDeclName();
11756 else {
11757 int index = 0;
11758 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11759 index = TTP->getIndex();
11760 else if (NonTypeTemplateParmDecl *NTTP
11761 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11762 index = NTTP->getIndex();
11763 else
11764 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11765 S.Diag(Templated->getLocation(),
11766 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11767 << (index + 1);
11768 }
11769 MaybeEmitInheritedConstructorNote(S, Found);
11770 return;
11771
11773 // Format the template argument list into the argument string.
11774 SmallString<128> TemplateArgString;
11775 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11776 TemplateArgString = " ";
11777 TemplateArgString += S.getTemplateArgumentBindingsText(
11778 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11779 if (TemplateArgString.size() == 1)
11780 TemplateArgString.clear();
11781 S.Diag(Templated->getLocation(),
11782 diag::note_ovl_candidate_unsatisfied_constraints)
11783 << TemplateArgString;
11784
11786 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11787 return;
11788 }
11791 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11792 return;
11793
11795 S.Diag(Templated->getLocation(),
11796 diag::note_ovl_candidate_instantiation_depth);
11797 MaybeEmitInheritedConstructorNote(S, Found);
11798 return;
11799
11801 // Format the template argument list into the argument string.
11802 SmallString<128> TemplateArgString;
11803 if (TemplateArgumentList *Args =
11804 DeductionFailure.getTemplateArgumentList()) {
11805 TemplateArgString = " ";
11806 TemplateArgString += S.getTemplateArgumentBindingsText(
11807 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11808 if (TemplateArgString.size() == 1)
11809 TemplateArgString.clear();
11810 }
11811
11812 // If this candidate was disabled by enable_if, say so.
11813 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11814 if (PDiag && PDiag->second.getDiagID() ==
11815 diag::err_typename_nested_not_found_enable_if) {
11816 // FIXME: Use the source range of the condition, and the fully-qualified
11817 // name of the enable_if template. These are both present in PDiag.
11818 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11819 << "'enable_if'" << TemplateArgString;
11820 return;
11821 }
11822
11823 // We found a specific requirement that disabled the enable_if.
11824 if (PDiag && PDiag->second.getDiagID() ==
11825 diag::err_typename_nested_not_found_requirement) {
11826 S.Diag(Templated->getLocation(),
11827 diag::note_ovl_candidate_disabled_by_requirement)
11828 << PDiag->second.getStringArg(0) << TemplateArgString;
11829 return;
11830 }
11831
11832 // Format the SFINAE diagnostic into the argument string.
11833 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11834 // formatted message in another diagnostic.
11835 SmallString<128> SFINAEArgString;
11836 SourceRange R;
11837 if (PDiag) {
11838 SFINAEArgString = ": ";
11839 R = SourceRange(PDiag->first, PDiag->first);
11840 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11841 }
11842
11843 S.Diag(Templated->getLocation(),
11844 diag::note_ovl_candidate_substitution_failure)
11845 << TemplateArgString << SFINAEArgString << R;
11846 MaybeEmitInheritedConstructorNote(S, Found);
11847 return;
11848 }
11849
11852 // Format the template argument list into the argument string.
11853 SmallString<128> TemplateArgString;
11854 if (TemplateArgumentList *Args =
11855 DeductionFailure.getTemplateArgumentList()) {
11856 TemplateArgString = " ";
11857 TemplateArgString += S.getTemplateArgumentBindingsText(
11858 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11859 if (TemplateArgString.size() == 1)
11860 TemplateArgString.clear();
11861 }
11862
11863 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11864 << (*DeductionFailure.getCallArgIndex() + 1)
11865 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11866 << TemplateArgString
11867 << (DeductionFailure.getResult() ==
11869 break;
11870 }
11871
11873 // FIXME: Provide a source location to indicate what we couldn't match.
11874 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11875 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11876 if (FirstTA.getKind() == TemplateArgument::Template &&
11877 SecondTA.getKind() == TemplateArgument::Template) {
11878 TemplateName FirstTN = FirstTA.getAsTemplate();
11879 TemplateName SecondTN = SecondTA.getAsTemplate();
11880 if (FirstTN.getKind() == TemplateName::Template &&
11881 SecondTN.getKind() == TemplateName::Template) {
11882 if (FirstTN.getAsTemplateDecl()->getName() ==
11883 SecondTN.getAsTemplateDecl()->getName()) {
11884 // FIXME: This fixes a bad diagnostic where both templates are named
11885 // the same. This particular case is a bit difficult since:
11886 // 1) It is passed as a string to the diagnostic printer.
11887 // 2) The diagnostic printer only attempts to find a better
11888 // name for types, not decls.
11889 // Ideally, this should folded into the diagnostic printer.
11890 S.Diag(Templated->getLocation(),
11891 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11892 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11893 return;
11894 }
11895 }
11896 }
11897
11898 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11899 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11900 return;
11901
11902 // FIXME: For generic lambda parameters, check if the function is a lambda
11903 // call operator, and if so, emit a prettier and more informative
11904 // diagnostic that mentions 'auto' and lambda in addition to
11905 // (or instead of?) the canonical template type parameters.
11906 S.Diag(Templated->getLocation(),
11907 diag::note_ovl_candidate_non_deduced_mismatch)
11908 << FirstTA << SecondTA;
11909 return;
11910 }
11911 // TODO: diagnose these individually, then kill off
11912 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11914 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11915 MaybeEmitInheritedConstructorNote(S, Found);
11916 return;
11918 S.Diag(Templated->getLocation(),
11919 diag::note_cuda_ovl_candidate_target_mismatch);
11920 return;
11921 }
11922}
11923
11924/// Diagnose a failed template-argument deduction, for function calls.
11926 unsigned NumArgs,
11927 bool TakingCandidateAddress) {
11931 if (CheckArityMismatch(S, Cand, NumArgs))
11932 return;
11933 }
11934 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11935 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11936}
11937
11938/// CUDA: diagnose an invalid call across targets.
11940 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11941 FunctionDecl *Callee = Cand->Function;
11942
11943 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11944 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11945
11946 std::string FnDesc;
11947 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11948 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11949 Cand->getRewriteKind(), FnDesc);
11950
11951 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11952 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11953 << FnDesc /* Ignored */
11954 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11955
11956 // This could be an implicit constructor for which we could not infer the
11957 // target due to a collsion. Diagnose that case.
11958 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11959 if (Meth != nullptr && Meth->isImplicit()) {
11960 CXXRecordDecl *ParentClass = Meth->getParent();
11962
11963 switch (FnKindPair.first) {
11964 default:
11965 return;
11966 case oc_implicit_default_constructor:
11968 break;
11969 case oc_implicit_copy_constructor:
11971 break;
11972 case oc_implicit_move_constructor:
11974 break;
11975 case oc_implicit_copy_assignment:
11977 break;
11978 case oc_implicit_move_assignment:
11980 break;
11981 };
11982
11983 bool ConstRHS = false;
11984 if (Meth->getNumParams()) {
11985 if (const ReferenceType *RT =
11986 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11987 ConstRHS = RT->getPointeeType().isConstQualified();
11988 }
11989 }
11990
11991 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11992 /* ConstRHS */ ConstRHS,
11993 /* Diagnose */ true);
11994 }
11995}
11996
11998 FunctionDecl *Callee = Cand->Function;
11999 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12000
12001 S.Diag(Callee->getLocation(),
12002 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12003 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12004}
12005
12008 assert(ES.isExplicit() && "not an explicit candidate");
12009
12010 unsigned Kind;
12011 switch (Cand->Function->getDeclKind()) {
12012 case Decl::Kind::CXXConstructor:
12013 Kind = 0;
12014 break;
12015 case Decl::Kind::CXXConversion:
12016 Kind = 1;
12017 break;
12018 case Decl::Kind::CXXDeductionGuide:
12019 Kind = Cand->Function->isImplicit() ? 0 : 2;
12020 break;
12021 default:
12022 llvm_unreachable("invalid Decl");
12023 }
12024
12025 // Note the location of the first (in-class) declaration; a redeclaration
12026 // (particularly an out-of-class definition) will typically lack the
12027 // 'explicit' specifier.
12028 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12030 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12031 First = Pattern->getFirstDecl();
12032
12033 S.Diag(First->getLocation(),
12034 diag::note_ovl_candidate_explicit)
12035 << Kind << (ES.getExpr() ? 1 : 0)
12036 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12037}
12038
12039/// Generates a 'note' diagnostic for an overload candidate. We've
12040/// already generated a primary error at the call site.
12041///
12042/// It really does need to be a single diagnostic with its caret
12043/// pointed at the candidate declaration. Yes, this creates some
12044/// major challenges of technical writing. Yes, this makes pointing
12045/// out problems with specific arguments quite awkward. It's still
12046/// better than generating twenty screens of text for every failed
12047/// overload.
12048///
12049/// It would be great to be able to express per-candidate problems
12050/// more richly for those diagnostic clients that cared, but we'd
12051/// still have to be just as careful with the default diagnostics.
12052/// \param CtorDestAS Addr space of object being constructed (for ctor
12053/// candidates only).
12055 unsigned NumArgs,
12056 bool TakingCandidateAddress,
12057 LangAS CtorDestAS = LangAS::Default) {
12058 FunctionDecl *Fn = Cand->Function;
12060 return;
12061
12062 // There is no physical candidate declaration to point to for OpenCL builtins.
12063 // Except for failed conversions, the notes are identical for each candidate,
12064 // so do not generate such notes.
12065 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12067 return;
12068
12069 // Note deleted candidates, but only if they're viable.
12070 if (Cand->Viable) {
12071 if (Fn->isDeleted()) {
12072 std::string FnDesc;
12073 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12074 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12075 Cand->getRewriteKind(), FnDesc);
12076
12077 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12078 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12079 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12080 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12081 return;
12082 }
12083
12084 // We don't really have anything else to say about viable candidates.
12085 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12086 return;
12087 }
12088
12089 switch (Cand->FailureKind) {
12092 return DiagnoseArityMismatch(S, Cand, NumArgs);
12093
12095 return DiagnoseBadDeduction(S, Cand, NumArgs,
12096 TakingCandidateAddress);
12097
12099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12100 << (Fn->getPrimaryTemplate() ? 1 : 0);
12101 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12102 return;
12103 }
12104
12106 Qualifiers QualsForPrinting;
12107 QualsForPrinting.setAddressSpace(CtorDestAS);
12108 S.Diag(Fn->getLocation(),
12109 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12110 << QualsForPrinting;
12111 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12112 return;
12113 }
12114
12118 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12119
12121 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12122 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12123 if (Cand->Conversions[I].isBad())
12124 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12125
12126 // FIXME: this currently happens when we're called from SemaInit
12127 // when user-conversion overload fails. Figure out how to handle
12128 // those conditions and diagnose them well.
12129 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12130 }
12131
12133 return DiagnoseBadTarget(S, Cand);
12134
12135 case ovl_fail_enable_if:
12136 return DiagnoseFailedEnableIfAttr(S, Cand);
12137
12138 case ovl_fail_explicit:
12139 return DiagnoseFailedExplicitSpec(S, Cand);
12140
12142 // It's generally not interesting to note copy/move constructors here.
12143 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12144 return;
12145 S.Diag(Fn->getLocation(),
12146 diag::note_ovl_candidate_inherited_constructor_slice)
12147 << (Fn->getPrimaryTemplate() ? 1 : 0)
12149 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12150 return;
12151
12153 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
12154 (void)Available;
12155 assert(!Available);
12156 break;
12157 }
12159 // Do nothing, these should simply be ignored.
12160 break;
12161
12163 std::string FnDesc;
12164 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12165 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12166 Cand->getRewriteKind(), FnDesc);
12167
12168 S.Diag(Fn->getLocation(),
12169 diag::note_ovl_candidate_constraints_not_satisfied)
12170 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12171 << FnDesc /* Ignored */;
12172 ConstraintSatisfaction Satisfaction;
12173 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12174 break;
12175 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12176 }
12177 }
12178}
12179
12182 return;
12183
12184 // Desugar the type of the surrogate down to a function type,
12185 // retaining as many typedefs as possible while still showing
12186 // the function type (and, therefore, its parameter types).
12187 QualType FnType = Cand->Surrogate->getConversionType();
12188 bool isLValueReference = false;
12189 bool isRValueReference = false;
12190 bool isPointer = false;
12191 if (const LValueReferenceType *FnTypeRef =
12192 FnType->getAs<LValueReferenceType>()) {
12193 FnType = FnTypeRef->getPointeeType();
12194 isLValueReference = true;
12195 } else if (const RValueReferenceType *FnTypeRef =
12196 FnType->getAs<RValueReferenceType>()) {
12197 FnType = FnTypeRef->getPointeeType();
12198 isRValueReference = true;
12199 }
12200 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12201 FnType = FnTypePtr->getPointeeType();
12202 isPointer = true;
12203 }
12204 // Desugar down to a function type.
12205 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12206 // Reconstruct the pointer/reference as appropriate.
12207 if (isPointer) FnType = S.Context.getPointerType(FnType);
12208 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12209 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12210
12211 if (!Cand->Viable &&
12213 S.Diag(Cand->Surrogate->getLocation(),
12214 diag::note_ovl_surrogate_constraints_not_satisfied)
12215 << Cand->Surrogate;
12216 ConstraintSatisfaction Satisfaction;
12217 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12218 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12219 } else {
12220 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12221 << FnType;
12222 }
12223}
12224
12225static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12226 SourceLocation OpLoc,
12227 OverloadCandidate *Cand) {
12228 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12229 std::string TypeStr("operator");
12230 TypeStr += Opc;
12231 TypeStr += "(";
12232 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12233 if (Cand->Conversions.size() == 1) {
12234 TypeStr += ")";
12235 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12236 } else {
12237 TypeStr += ", ";
12238 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12239 TypeStr += ")";
12240 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12241 }
12242}
12243
12245 OverloadCandidate *Cand) {
12246 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12247 if (ICS.isBad()) break; // all meaningless after first invalid
12248 if (!ICS.isAmbiguous()) continue;
12249
12251 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12252 }
12253}
12254
12256 if (Cand->Function)
12257 return Cand->Function->getLocation();
12258 if (Cand->IsSurrogate)
12259 return Cand->Surrogate->getLocation();
12260 return SourceLocation();
12261}
12262
12263static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12264 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12268 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12269
12273 return 1;
12274
12277 return 2;
12278
12286 return 3;
12287
12289 return 4;
12290
12292 return 5;
12293
12296 return 6;
12297 }
12298 llvm_unreachable("Unhandled deduction result");
12299}
12300
12301namespace {
12302
12303struct CompareOverloadCandidatesForDisplay {
12304 Sema &S;
12305 SourceLocation Loc;
12306 size_t NumArgs;
12308
12309 CompareOverloadCandidatesForDisplay(
12310 Sema &S, SourceLocation Loc, size_t NArgs,
12312 : S(S), NumArgs(NArgs), CSK(CSK) {}
12313
12314 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12315 // If there are too many or too few arguments, that's the high-order bit we
12316 // want to sort by, even if the immediate failure kind was something else.
12317 if (C->FailureKind == ovl_fail_too_many_arguments ||
12318 C->FailureKind == ovl_fail_too_few_arguments)
12319 return static_cast<OverloadFailureKind>(C->FailureKind);
12320
12321 if (C->Function) {
12322 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12324 if (NumArgs < C->Function->getMinRequiredArguments())
12326 }
12327
12328 return static_cast<OverloadFailureKind>(C->FailureKind);
12329 }
12330
12331 bool operator()(const OverloadCandidate *L,
12332 const OverloadCandidate *R) {
12333 // Fast-path this check.
12334 if (L == R) return false;
12335
12336 // Order first by viability.
12337 if (L->Viable) {
12338 if (!R->Viable) return true;
12339
12340 if (int Ord = CompareConversions(*L, *R))
12341 return Ord < 0;
12342 // Use other tie breakers.
12343 } else if (R->Viable)
12344 return false;
12345
12346 assert(L->Viable == R->Viable);
12347
12348 // Criteria by which we can sort non-viable candidates:
12349 if (!L->Viable) {
12350 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12351 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12352
12353 // 1. Arity mismatches come after other candidates.
12354 if (LFailureKind == ovl_fail_too_many_arguments ||
12355 LFailureKind == ovl_fail_too_few_arguments) {
12356 if (RFailureKind == ovl_fail_too_many_arguments ||
12357 RFailureKind == ovl_fail_too_few_arguments) {
12358 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12359 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12360 if (LDist == RDist) {
12361 if (LFailureKind == RFailureKind)
12362 // Sort non-surrogates before surrogates.
12363 return !L->IsSurrogate && R->IsSurrogate;
12364 // Sort candidates requiring fewer parameters than there were
12365 // arguments given after candidates requiring more parameters
12366 // than there were arguments given.
12367 return LFailureKind == ovl_fail_too_many_arguments;
12368 }
12369 return LDist < RDist;
12370 }
12371 return false;
12372 }
12373 if (RFailureKind == ovl_fail_too_many_arguments ||
12374 RFailureKind == ovl_fail_too_few_arguments)
12375 return true;
12376
12377 // 2. Bad conversions come first and are ordered by the number
12378 // of bad conversions and quality of good conversions.
12379 if (LFailureKind == ovl_fail_bad_conversion) {
12380 if (RFailureKind != ovl_fail_bad_conversion)
12381 return true;
12382
12383 // The conversion that can be fixed with a smaller number of changes,
12384 // comes first.
12385 unsigned numLFixes = L->Fix.NumConversionsFixed;
12386 unsigned numRFixes = R->Fix.NumConversionsFixed;
12387 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12388 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12389 if (numLFixes != numRFixes) {
12390 return numLFixes < numRFixes;
12391 }
12392
12393 // If there's any ordering between the defined conversions...
12394 if (int Ord = CompareConversions(*L, *R))
12395 return Ord < 0;
12396 } else if (RFailureKind == ovl_fail_bad_conversion)
12397 return false;
12398
12399 if (LFailureKind == ovl_fail_bad_deduction) {
12400 if (RFailureKind != ovl_fail_bad_deduction)
12401 return true;
12402
12404 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12405 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12406 if (LRank != RRank)
12407 return LRank < RRank;
12408 }
12409 } else if (RFailureKind == ovl_fail_bad_deduction)
12410 return false;
12411
12412 // TODO: others?
12413 }
12414
12415 // Sort everything else by location.
12418
12419 // Put candidates without locations (e.g. builtins) at the end.
12420 if (LLoc.isValid() && RLoc.isValid())
12421 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12422 if (LLoc.isValid() && !RLoc.isValid())
12423 return true;
12424 if (RLoc.isValid() && !LLoc.isValid())
12425 return false;
12426 assert(!LLoc.isValid() && !RLoc.isValid());
12427 // For builtins and other functions without locations, fallback to the order
12428 // in which they were added into the candidate set.
12429 return L < R;
12430 }
12431
12432private:
12433 struct ConversionSignals {
12434 unsigned KindRank = 0;
12436
12437 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12438 ConversionSignals Sig;
12439 Sig.KindRank = Seq.getKindRank();
12440 if (Seq.isStandard())
12441 Sig.Rank = Seq.Standard.getRank();
12442 else if (Seq.isUserDefined())
12443 Sig.Rank = Seq.UserDefined.After.getRank();
12444 // We intend StaticObjectArgumentConversion to compare the same as
12445 // StandardConversion with ICR_ExactMatch rank.
12446 return Sig;
12447 }
12448
12449 static ConversionSignals ForObjectArgument() {
12450 // We intend StaticObjectArgumentConversion to compare the same as
12451 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12452 return {};
12453 }
12454 };
12455
12456 // Returns -1 if conversions in L are considered better.
12457 // 0 if they are considered indistinguishable.
12458 // 1 if conversions in R are better.
12459 int CompareConversions(const OverloadCandidate &L,
12460 const OverloadCandidate &R) {
12461 // We cannot use `isBetterOverloadCandidate` because it is defined
12462 // according to the C++ standard and provides a partial order, but we need
12463 // a total order as this function is used in sort.
12464 assert(L.Conversions.size() == R.Conversions.size());
12465 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12466 auto LS = L.IgnoreObjectArgument && I == 0
12467 ? ConversionSignals::ForObjectArgument()
12468 : ConversionSignals::ForSequence(L.Conversions[I]);
12469 auto RS = R.IgnoreObjectArgument
12470 ? ConversionSignals::ForObjectArgument()
12471 : ConversionSignals::ForSequence(R.Conversions[I]);
12472 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12473 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12474 ? -1
12475 : 1;
12476 }
12477 // FIXME: find a way to compare templates for being more or less
12478 // specialized that provides a strict weak ordering.
12479 return 0;
12480 }
12481};
12482}
12483
12484/// CompleteNonViableCandidate - Normally, overload resolution only
12485/// computes up to the first bad conversion. Produces the FixIt set if
12486/// possible.
12487static void
12489 ArrayRef<Expr *> Args,
12491 assert(!Cand->Viable);
12492
12493 // Don't do anything on failures other than bad conversion.
12495 return;
12496
12497 // We only want the FixIts if all the arguments can be corrected.
12498 bool Unfixable = false;
12499 // Use a implicit copy initialization to check conversion fixes.
12501
12502 // Attempt to fix the bad conversion.
12503 unsigned ConvCount = Cand->Conversions.size();
12504 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12505 ++ConvIdx) {
12506 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12507 if (Cand->Conversions[ConvIdx].isInitialized() &&
12508 Cand->Conversions[ConvIdx].isBad()) {
12509 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12510 break;
12511 }
12512 }
12513
12514 // FIXME: this should probably be preserved from the overload
12515 // operation somehow.
12516 bool SuppressUserConversions = false;
12517
12518 unsigned ConvIdx = 0;
12519 unsigned ArgIdx = 0;
12520 ArrayRef<QualType> ParamTypes;
12521 bool Reversed = Cand->isReversed();
12522
12523 if (Cand->IsSurrogate) {
12524 QualType ConvType
12526 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12527 ConvType = ConvPtrType->getPointeeType();
12528 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12529 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12530 ConvIdx = 1;
12531 } else if (Cand->Function) {
12532 ParamTypes =
12533 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12534 if (isa<CXXMethodDecl>(Cand->Function) &&
12535 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12536 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12537 ConvIdx = 1;
12539 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12541 OO_Subscript)
12542 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12543 ArgIdx = 1;
12544 }
12545 } else {
12546 // Builtin operator.
12547 assert(ConvCount <= 3);
12548 ParamTypes = Cand->BuiltinParamTypes;
12549 }
12550
12551 // Fill in the rest of the conversions.
12552 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12553 ConvIdx != ConvCount;
12554 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12555 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12556 if (Cand->Conversions[ConvIdx].isInitialized()) {
12557 // We've already checked this conversion.
12558 } else if (ParamIdx < ParamTypes.size()) {
12559 if (ParamTypes[ParamIdx]->isDependentType())
12560 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12561 Args[ArgIdx]->getType());
12562 else {
12563 Cand->Conversions[ConvIdx] =
12564 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12565 SuppressUserConversions,
12566 /*InOverloadResolution=*/true,
12567 /*AllowObjCWritebackConversion=*/
12568 S.getLangOpts().ObjCAutoRefCount);
12569 // Store the FixIt in the candidate if it exists.
12570 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12571 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12572 }
12573 } else
12574 Cand->Conversions[ConvIdx].setEllipsis();
12575 }
12576}
12577
12580 SourceLocation OpLoc,
12581 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12582 // Sort the candidates by viability and position. Sorting directly would
12583 // be prohibitive, so we make a set of pointers and sort those.
12585 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12586 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12587 if (!Filter(*Cand))
12588 continue;
12589 switch (OCD) {
12590 case OCD_AllCandidates:
12591 if (!Cand->Viable) {
12592 if (!Cand->Function && !Cand->IsSurrogate) {
12593 // This a non-viable builtin candidate. We do not, in general,
12594 // want to list every possible builtin candidate.
12595 continue;
12596 }
12597 CompleteNonViableCandidate(S, Cand, Args, Kind);
12598 }
12599 break;
12600
12602 if (!Cand->Viable)
12603 continue;
12604 break;
12605
12607 if (!Cand->Best)
12608 continue;
12609 break;
12610 }
12611
12612 Cands.push_back(Cand);
12613 }
12614
12615 llvm::stable_sort(
12616 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12617
12618 return Cands;
12619}
12620
12622 SourceLocation OpLoc) {
12623 bool DeferHint = false;
12624 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12625 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12626 // host device candidates.
12627 auto WrongSidedCands =
12628 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12629 return (Cand.Viable == false &&
12630 Cand.FailureKind == ovl_fail_bad_target) ||
12631 (Cand.Function &&
12632 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12633 Cand.Function->template hasAttr<CUDADeviceAttr>());
12634 });
12635 DeferHint = !WrongSidedCands.empty();
12636 }
12637 return DeferHint;
12638}
12639
12640/// When overload resolution fails, prints diagnostic messages containing the
12641/// candidates in the candidate set.
12644 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12645 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12646
12647 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12648
12649 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12650
12651 // In WebAssembly we don't want to emit further diagnostics if a table is
12652 // passed as an argument to a function.
12653 bool NoteCands = true;
12654 for (const Expr *Arg : Args) {
12655 if (Arg->getType()->isWebAssemblyTableType())
12656 NoteCands = false;
12657 }
12658
12659 if (NoteCands)
12660 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12661
12662 if (OCD == OCD_AmbiguousCandidates)
12664}
12665
12668 StringRef Opc, SourceLocation OpLoc) {
12669 bool ReportedAmbiguousConversions = false;
12670
12671 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12672 unsigned CandsShown = 0;
12673 auto I = Cands.begin(), E = Cands.end();
12674 for (; I != E; ++I) {
12675 OverloadCandidate *Cand = *I;
12676
12677 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12678 ShowOverloads == Ovl_Best) {
12679 break;
12680 }
12681 ++CandsShown;
12682
12683 if (Cand->Function)
12684 NoteFunctionCandidate(S, Cand, Args.size(),
12685 /*TakingCandidateAddress=*/false, DestAS);
12686 else if (Cand->IsSurrogate)
12687 NoteSurrogateCandidate(S, Cand);
12688 else {
12689 assert(Cand->Viable &&
12690 "Non-viable built-in candidates are not added to Cands.");
12691 // Generally we only see ambiguities including viable builtin
12692 // operators if overload resolution got screwed up by an
12693 // ambiguous user-defined conversion.
12694 //
12695 // FIXME: It's quite possible for different conversions to see
12696 // different ambiguities, though.
12697 if (!ReportedAmbiguousConversions) {
12698 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12699 ReportedAmbiguousConversions = true;
12700 }
12701
12702 // If this is a viable builtin, print it.
12703 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12704 }
12705 }
12706
12707 // Inform S.Diags that we've shown an overload set with N elements. This may
12708 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12709 S.Diags.overloadCandidatesShown(CandsShown);
12710
12711 if (I != E)
12712 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12713 shouldDeferDiags(S, Args, OpLoc))
12714 << int(E - I);
12715}
12716
12717static SourceLocation
12719 return Cand->Specialization ? Cand->Specialization->getLocation()
12720 : SourceLocation();
12721}
12722
12723namespace {
12724struct CompareTemplateSpecCandidatesForDisplay {
12725 Sema &S;
12726 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12727
12728 bool operator()(const TemplateSpecCandidate *L,
12729 const TemplateSpecCandidate *R) {
12730 // Fast-path this check.
12731 if (L == R)
12732 return false;
12733
12734 // Assuming that both candidates are not matches...
12735
12736 // Sort by the ranking of deduction failures.
12740
12741 // Sort everything else by location.
12744
12745 // Put candidates without locations (e.g. builtins) at the end.
12746 if (LLoc.isInvalid())
12747 return false;
12748 if (RLoc.isInvalid())
12749 return true;
12750
12751 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12752 }
12753};
12754}
12755
12756/// Diagnose a template argument deduction failure.
12757/// We are treating these failures as overload failures due to bad
12758/// deductions.
12760 bool ForTakingAddress) {
12761 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12762 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12763}
12764
12765void TemplateSpecCandidateSet::destroyCandidates() {
12766 for (iterator i = begin(), e = end(); i != e; ++i) {
12767 i->DeductionFailure.Destroy();
12768 }
12769}
12770
12772 destroyCandidates();
12773 Candidates.clear();
12774}
12775
12776/// NoteCandidates - When no template specialization match is found, prints
12777/// diagnostic messages containing the non-matching specializations that form
12778/// the candidate set.
12779/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12780/// OCD == OCD_AllCandidates and Cand->Viable == false.
12782 // Sort the candidates by position (assuming no candidate is a match).
12783 // Sorting directly would be prohibitive, so we make a set of pointers
12784 // and sort those.
12786 Cands.reserve(size());
12787 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12788 if (Cand->Specialization)
12789 Cands.push_back(Cand);
12790 // Otherwise, this is a non-matching builtin candidate. We do not,
12791 // in general, want to list every possible builtin candidate.
12792 }
12793
12794 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12795
12796 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12797 // for generalization purposes (?).
12798 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12799
12801 unsigned CandsShown = 0;
12802 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12803 TemplateSpecCandidate *Cand = *I;
12804
12805 // Set an arbitrary limit on the number of candidates we'll spam
12806 // the user with. FIXME: This limit should depend on details of the
12807 // candidate list.
12808 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12809 break;
12810 ++CandsShown;
12811
12812 assert(Cand->Specialization &&
12813 "Non-matching built-in candidates are not added to Cands.");
12814 Cand->NoteDeductionFailure(S, ForTakingAddress);
12815 }
12816
12817 if (I != E)
12818 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12819}
12820
12821// [PossiblyAFunctionType] --> [Return]
12822// NonFunctionType --> NonFunctionType
12823// R (A) --> R(A)
12824// R (*)(A) --> R (A)
12825// R (&)(A) --> R (A)
12826// R (S::*)(A) --> R (A)
12828 QualType Ret = PossiblyAFunctionType;
12829 if (const PointerType *ToTypePtr =
12830 PossiblyAFunctionType->getAs<PointerType>())
12831 Ret = ToTypePtr->getPointeeType();
12832 else if (const ReferenceType *ToTypeRef =
12833 PossiblyAFunctionType->getAs<ReferenceType>())
12834 Ret = ToTypeRef->getPointeeType();
12835 else if (const MemberPointerType *MemTypePtr =
12836 PossiblyAFunctionType->getAs<MemberPointerType>())
12837 Ret = MemTypePtr->getPointeeType();
12838 Ret =
12839 Context.getCanonicalType(Ret).getUnqualifiedType();
12840 return Ret;
12841}
12842
12844 bool Complain = true) {
12845 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12846 S.DeduceReturnType(FD, Loc, Complain))
12847 return true;
12848
12849 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12850 if (S.getLangOpts().CPlusPlus17 &&
12851 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12852 !S.ResolveExceptionSpec(Loc, FPT))
12853 return true;
12854
12855 return false;
12856}
12857
12858namespace {
12859// A helper class to help with address of function resolution
12860// - allows us to avoid passing around all those ugly parameters
12861class AddressOfFunctionResolver {
12862 Sema& S;
12863 Expr* SourceExpr;
12864 const QualType& TargetType;
12865 QualType TargetFunctionType; // Extracted function type from target type
12866
12867 bool Complain;
12868 //DeclAccessPair& ResultFunctionAccessPair;
12869 ASTContext& Context;
12870
12871 bool TargetTypeIsNonStaticMemberFunction;
12872 bool FoundNonTemplateFunction;
12873 bool StaticMemberFunctionFromBoundPointer;
12874 bool HasComplained;
12875
12876 OverloadExpr::FindResult OvlExprInfo;
12877 OverloadExpr *OvlExpr;
12878 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12880 TemplateSpecCandidateSet FailedCandidates;
12881
12882public:
12883 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12884 const QualType &TargetType, bool Complain)
12885 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12886 Complain(Complain), Context(S.getASTContext()),
12887 TargetTypeIsNonStaticMemberFunction(
12888 !!TargetType->getAs<MemberPointerType>()),
12889 FoundNonTemplateFunction(false),
12890 StaticMemberFunctionFromBoundPointer(false),
12891 HasComplained(false),
12892 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12893 OvlExpr(OvlExprInfo.Expression),
12894 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12895 ExtractUnqualifiedFunctionTypeFromTargetType();
12896
12897 if (TargetFunctionType->isFunctionType()) {
12898 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12899 if (!UME->isImplicitAccess() &&
12901 StaticMemberFunctionFromBoundPointer = true;
12902 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12903 DeclAccessPair dap;
12905 OvlExpr, false, &dap)) {
12906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12907 if (!Method->isStatic()) {
12908 // If the target type is a non-function type and the function found
12909 // is a non-static member function, pretend as if that was the
12910 // target, it's the only possible type to end up with.
12911 TargetTypeIsNonStaticMemberFunction = true;
12912
12913 // And skip adding the function if its not in the proper form.
12914 // We'll diagnose this due to an empty set of functions.
12915 if (!OvlExprInfo.HasFormOfMemberPointer)
12916 return;
12917 }
12918
12919 Matches.push_back(std::make_pair(dap, Fn));
12920 }
12921 return;
12922 }
12923
12924 if (OvlExpr->hasExplicitTemplateArgs())
12925 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12926
12927 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12928 // C++ [over.over]p4:
12929 // If more than one function is selected, [...]
12930 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12931 if (FoundNonTemplateFunction)
12932 EliminateAllTemplateMatches();
12933 else
12934 EliminateAllExceptMostSpecializedTemplate();
12935 }
12936 }
12937
12938 if (S.getLangOpts().CUDA && Matches.size() > 1)
12939 EliminateSuboptimalCudaMatches();
12940 }
12941
12942 bool hasComplained() const { return HasComplained; }
12943
12944private:
12945 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12946 QualType Discard;
12947 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12948 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12949 }
12950
12951 /// \return true if A is considered a better overload candidate for the
12952 /// desired type than B.
12953 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12954 // If A doesn't have exactly the correct type, we don't want to classify it
12955 // as "better" than anything else. This way, the user is required to
12956 // disambiguate for us if there are multiple candidates and no exact match.
12957 return candidateHasExactlyCorrectType(A) &&
12958 (!candidateHasExactlyCorrectType(B) ||
12959 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12960 }
12961
12962 /// \return true if we were able to eliminate all but one overload candidate,
12963 /// false otherwise.
12964 bool eliminiateSuboptimalOverloadCandidates() {
12965 // Same algorithm as overload resolution -- one pass to pick the "best",
12966 // another pass to be sure that nothing is better than the best.
12967 auto Best = Matches.begin();
12968 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12969 if (isBetterCandidate(I->second, Best->second))
12970 Best = I;
12971
12972 const FunctionDecl *BestFn = Best->second;
12973 auto IsBestOrInferiorToBest = [this, BestFn](
12974 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12975 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12976 };
12977
12978 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12979 // option, so we can potentially give the user a better error
12980 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12981 return false;
12982 Matches[0] = *Best;
12983 Matches.resize(1);
12984 return true;
12985 }
12986
12987 bool isTargetTypeAFunction() const {
12988 return TargetFunctionType->isFunctionType();
12989 }
12990
12991 // [ToType] [Return]
12992
12993 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12994 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12995 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12996 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12997 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12998 }
12999
13000 // return true if any matching specializations were found
13001 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13002 const DeclAccessPair& CurAccessFunPair) {
13003 if (CXXMethodDecl *Method
13004 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13005 // Skip non-static function templates when converting to pointer, and
13006 // static when converting to member pointer.
13007 bool CanConvertToFunctionPointer =
13008 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13009 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13010 return false;
13011 }
13012 else if (TargetTypeIsNonStaticMemberFunction)
13013 return false;
13014
13015 // C++ [over.over]p2:
13016 // If the name is a function template, template argument deduction is
13017 // done (14.8.2.2), and if the argument deduction succeeds, the
13018 // resulting template argument list is used to generate a single
13019 // function template specialization, which is added to the set of
13020 // overloaded functions considered.
13021 FunctionDecl *Specialization = nullptr;
13022 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13024 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13025 Specialization, Info, /*IsAddressOfFunction*/ true);
13026 Result != TemplateDeductionResult::Success) {
13027 // Make a note of the failed deduction for diagnostics.
13028 FailedCandidates.addCandidate()
13029 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13030 MakeDeductionFailureInfo(Context, Result, Info));
13031 return false;
13032 }
13033
13034 // Template argument deduction ensures that we have an exact match or
13035 // compatible pointer-to-function arguments that would be adjusted by ICS.
13036 // This function template specicalization works.
13038 Context.getCanonicalType(Specialization->getType()),
13039 Context.getCanonicalType(TargetFunctionType)));
13040
13042 return false;
13043
13044 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13045 return true;
13046 }
13047
13048 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13049 const DeclAccessPair& CurAccessFunPair) {
13050 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13051 // Skip non-static functions when converting to pointer, and static
13052 // when converting to member pointer.
13053 bool CanConvertToFunctionPointer =
13054 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13055 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13056 return false;
13057 }
13058 else if (TargetTypeIsNonStaticMemberFunction)
13059 return false;
13060
13061 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13062 if (S.getLangOpts().CUDA) {
13063 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13064 if (!(Caller && Caller->isImplicit()) &&
13065 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13066 return false;
13067 }
13068 if (FunDecl->isMultiVersion()) {
13069 const auto *TA = FunDecl->getAttr<TargetAttr>();
13070 if (TA && !TA->isDefaultVersion())
13071 return false;
13072 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13073 if (TVA && !TVA->isDefaultVersion())
13074 return false;
13075 }
13076
13077 // If any candidate has a placeholder return type, trigger its deduction
13078 // now.
13079 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13080 Complain)) {
13081 HasComplained |= Complain;
13082 return false;
13083 }
13084
13085 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13086 return false;
13087
13088 // If we're in C, we need to support types that aren't exactly identical.
13089 if (!S.getLangOpts().CPlusPlus ||
13090 candidateHasExactlyCorrectType(FunDecl)) {
13091 Matches.push_back(std::make_pair(
13092 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13093 FoundNonTemplateFunction = true;
13094 return true;
13095 }
13096 }
13097
13098 return false;
13099 }
13100
13101 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13102 bool Ret = false;
13103
13104 // If the overload expression doesn't have the form of a pointer to
13105 // member, don't try to convert it to a pointer-to-member type.
13106 if (IsInvalidFormOfPointerToMemberFunction())
13107 return false;
13108
13109 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13110 E = OvlExpr->decls_end();
13111 I != E; ++I) {
13112 // Look through any using declarations to find the underlying function.
13113 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13114
13115 // C++ [over.over]p3:
13116 // Non-member functions and static member functions match
13117 // targets of type "pointer-to-function" or "reference-to-function."
13118 // Nonstatic member functions match targets of
13119 // type "pointer-to-member-function."
13120 // Note that according to DR 247, the containing class does not matter.
13121 if (FunctionTemplateDecl *FunctionTemplate
13122 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13123 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13124 Ret = true;
13125 }
13126 // If we have explicit template arguments supplied, skip non-templates.
13127 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13128 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13129 Ret = true;
13130 }
13131 assert(Ret || Matches.empty());
13132 return Ret;
13133 }
13134
13135 void EliminateAllExceptMostSpecializedTemplate() {
13136 // [...] and any given function template specialization F1 is
13137 // eliminated if the set contains a second function template
13138 // specialization whose function template is more specialized
13139 // than the function template of F1 according to the partial
13140 // ordering rules of 14.5.5.2.
13141
13142 // The algorithm specified above is quadratic. We instead use a
13143 // two-pass algorithm (similar to the one used to identify the
13144 // best viable function in an overload set) that identifies the
13145 // best function template (if it exists).
13146
13147 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13148 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13149 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13150
13151 // TODO: It looks like FailedCandidates does not serve much purpose
13152 // here, since the no_viable diagnostic has index 0.
13154 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13155 SourceExpr->getBeginLoc(), S.PDiag(),
13156 S.PDiag(diag::err_addr_ovl_ambiguous)
13157 << Matches[0].second->getDeclName(),
13158 S.PDiag(diag::note_ovl_candidate)
13159 << (unsigned)oc_function << (unsigned)ocs_described_template,
13160 Complain, TargetFunctionType);
13161
13162 if (Result != MatchesCopy.end()) {
13163 // Make it the first and only element
13164 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13165 Matches[0].second = cast<FunctionDecl>(*Result);
13166 Matches.resize(1);
13167 } else
13168 HasComplained |= Complain;
13169 }
13170
13171 void EliminateAllTemplateMatches() {
13172 // [...] any function template specializations in the set are
13173 // eliminated if the set also contains a non-template function, [...]
13174 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13175 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13176 ++I;
13177 else {
13178 Matches[I] = Matches[--N];
13179 Matches.resize(N);
13180 }
13181 }
13182 }
13183
13184 void EliminateSuboptimalCudaMatches() {
13185 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13186 Matches);
13187 }
13188
13189public:
13190 void ComplainNoMatchesFound() const {
13191 assert(Matches.empty());
13192 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13193 << OvlExpr->getName() << TargetFunctionType
13194 << OvlExpr->getSourceRange();
13195 if (FailedCandidates.empty())
13196 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13197 /*TakingAddress=*/true);
13198 else {
13199 // We have some deduction failure messages. Use them to diagnose
13200 // the function templates, and diagnose the non-template candidates
13201 // normally.
13202 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13203 IEnd = OvlExpr->decls_end();
13204 I != IEnd; ++I)
13205 if (FunctionDecl *Fun =
13206 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13208 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13209 /*TakingAddress=*/true);
13210 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13211 }
13212 }
13213
13214 bool IsInvalidFormOfPointerToMemberFunction() const {
13215 return TargetTypeIsNonStaticMemberFunction &&
13216 !OvlExprInfo.HasFormOfMemberPointer;
13217 }
13218
13219 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13220 // TODO: Should we condition this on whether any functions might
13221 // have matched, or is it more appropriate to do that in callers?
13222 // TODO: a fixit wouldn't hurt.
13223 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13224 << TargetType << OvlExpr->getSourceRange();
13225 }
13226
13227 bool IsStaticMemberFunctionFromBoundPointer() const {
13228 return StaticMemberFunctionFromBoundPointer;
13229 }
13230
13231 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13232 S.Diag(OvlExpr->getBeginLoc(),
13233 diag::err_invalid_form_pointer_member_function)
13234 << OvlExpr->getSourceRange();
13235 }
13236
13237 void ComplainOfInvalidConversion() const {
13238 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13239 << OvlExpr->getName() << TargetType;
13240 }
13241
13242 void ComplainMultipleMatchesFound() const {
13243 assert(Matches.size() > 1);
13244 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13245 << OvlExpr->getName() << OvlExpr->getSourceRange();
13246 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13247 /*TakingAddress=*/true);
13248 }
13249
13250 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13251
13252 int getNumMatches() const { return Matches.size(); }
13253
13254 FunctionDecl* getMatchingFunctionDecl() const {
13255 if (Matches.size() != 1) return nullptr;
13256 return Matches[0].second;
13257 }
13258
13259 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13260 if (Matches.size() != 1) return nullptr;
13261 return &Matches[0].first;
13262 }
13263};
13264}
13265
13266/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13267/// an overloaded function (C++ [over.over]), where @p From is an
13268/// expression with overloaded function type and @p ToType is the type
13269/// we're trying to resolve to. For example:
13270///
13271/// @code
13272/// int f(double);
13273/// int f(int);
13274///
13275/// int (*pfd)(double) = f; // selects f(double)
13276/// @endcode
13277///
13278/// This routine returns the resulting FunctionDecl if it could be
13279/// resolved, and NULL otherwise. When @p Complain is true, this
13280/// routine will emit diagnostics if there is an error.
13283 QualType TargetType,
13284 bool Complain,
13285 DeclAccessPair &FoundResult,
13286 bool *pHadMultipleCandidates) {
13287 assert(AddressOfExpr->getType() == Context.OverloadTy);
13288
13289 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13290 Complain);
13291 int NumMatches = Resolver.getNumMatches();
13292 FunctionDecl *Fn = nullptr;
13293 bool ShouldComplain = Complain && !Resolver.hasComplained();
13294 if (NumMatches == 0 && ShouldComplain) {
13295 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13296 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13297 else
13298 Resolver.ComplainNoMatchesFound();
13299 }
13300 else if (NumMatches > 1 && ShouldComplain)
13301 Resolver.ComplainMultipleMatchesFound();
13302 else if (NumMatches == 1) {
13303 Fn = Resolver.getMatchingFunctionDecl();
13304 assert(Fn);
13305 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13306 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13307 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13308 if (Complain) {
13309 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13310 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13311 else
13312 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13313 }
13314 }
13315
13316 if (pHadMultipleCandidates)
13317 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13318 return Fn;
13319}
13320
13321/// Given an expression that refers to an overloaded function, try to
13322/// resolve that function to a single function that can have its address taken.
13323/// This will modify `Pair` iff it returns non-null.
13324///
13325/// This routine can only succeed if from all of the candidates in the overload
13326/// set for SrcExpr that can have their addresses taken, there is one candidate
13327/// that is more constrained than the rest.
13331 OverloadExpr *Ovl = R.Expression;
13332 bool IsResultAmbiguous = false;
13333 FunctionDecl *Result = nullptr;
13334 DeclAccessPair DAP;
13335 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13336
13337 // Return positive for better, negative for worse, 0 for equal preference.
13338 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13339 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13340 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13341 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13342 };
13343
13344 auto CheckMoreConstrained = [&](FunctionDecl *FD1,
13345 FunctionDecl *FD2) -> std::optional<bool> {
13347 FD1 = MF;
13349 FD2 = MF;
13351 FD1->getAssociatedConstraints(AC1);
13352 FD2->getAssociatedConstraints(AC2);
13353 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
13354 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
13355 return std::nullopt;
13356 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
13357 return std::nullopt;
13358 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
13359 return std::nullopt;
13360 return AtLeastAsConstrained1;
13361 };
13362
13363 // Don't use the AddressOfResolver because we're specifically looking for
13364 // cases where we have one overload candidate that lacks
13365 // enable_if/pass_object_size/...
13366 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13367 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13368 if (!FD)
13369 return nullptr;
13370
13372 continue;
13373
13374 // If we found a better result, update Result.
13375 auto FoundBetter = [&]() {
13376 IsResultAmbiguous = false;
13377 DAP = I.getPair();
13378 Result = FD;
13379 };
13380
13381 // We have more than one result - see if it is more constrained than the
13382 // previous one.
13383 if (Result) {
13384 // Check CUDA preference first. If the candidates have differennt CUDA
13385 // preference, choose the one with higher CUDA preference. Otherwise,
13386 // choose the one with more constraints.
13387 if (getLangOpts().CUDA) {
13388 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13389 // FD has different preference than Result.
13390 if (PreferenceByCUDA != 0) {
13391 // FD is more preferable than Result.
13392 if (PreferenceByCUDA > 0)
13393 FoundBetter();
13394 continue;
13395 }
13396 }
13397 // FD has the same CUDA prefernece than Result. Continue check
13398 // constraints.
13399 std::optional<bool> MoreConstrainedThanPrevious =
13400 CheckMoreConstrained(FD, Result);
13401 if (!MoreConstrainedThanPrevious) {
13402 IsResultAmbiguous = true;
13403 AmbiguousDecls.push_back(FD);
13404 continue;
13405 }
13406 if (!*MoreConstrainedThanPrevious)
13407 continue;
13408 // FD is more constrained - replace Result with it.
13409 }
13410 FoundBetter();
13411 }
13412
13413 if (IsResultAmbiguous)
13414 return nullptr;
13415
13416 if (Result) {
13418 // We skipped over some ambiguous declarations which might be ambiguous with
13419 // the selected result.
13420 for (FunctionDecl *Skipped : AmbiguousDecls) {
13421 // If skipped candidate has different CUDA preference than the result,
13422 // there is no ambiguity. Otherwise check whether they have different
13423 // constraints.
13424 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13425 continue;
13426 if (!CheckMoreConstrained(Skipped, Result))
13427 return nullptr;
13428 }
13429 Pair = DAP;
13430 }
13431 return Result;
13432}
13433
13434/// Given an overloaded function, tries to turn it into a non-overloaded
13435/// function reference using resolveAddressOfSingleOverloadCandidate. This
13436/// will perform access checks, diagnose the use of the resultant decl, and, if
13437/// requested, potentially perform a function-to-pointer decay.
13438///
13439/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13440/// Otherwise, returns true. This may emit diagnostics and return true.
13442 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13443 Expr *E = SrcExpr.get();
13444 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13445
13446 DeclAccessPair DAP;
13447 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13448 if (!Found || Found->isCPUDispatchMultiVersion() ||
13450 return false;
13451
13452 // Emitting multiple diagnostics for a function that is both inaccessible and
13453 // unavailable is consistent with our behavior elsewhere. So, always check
13454 // for both.
13455 DiagnoseUseOfDecl(Found, E->getExprLoc());
13456 CheckAddressOfMemberAccess(E, DAP);
13457 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13458 if (Res.isInvalid())
13459 return false;
13460 Expr *Fixed = Res.get();
13461 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13462 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13463 else
13464 SrcExpr = Fixed;
13465 return true;
13466}
13467
13468/// Given an expression that refers to an overloaded function, try to
13469/// resolve that overloaded function expression down to a single function.
13470///
13471/// This routine can only resolve template-ids that refer to a single function
13472/// template, where that template-id refers to a single template whose template
13473/// arguments are either provided by the template-id or have defaults,
13474/// as described in C++0x [temp.arg.explicit]p3.
13475///
13476/// If no template-ids are found, no diagnostics are emitted and NULL is
13477/// returned.
13479 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13480 TemplateSpecCandidateSet *FailedTSC) {
13481 // C++ [over.over]p1:
13482 // [...] [Note: any redundant set of parentheses surrounding the
13483 // overloaded function name is ignored (5.1). ]
13484 // C++ [over.over]p1:
13485 // [...] The overloaded function name can be preceded by the &
13486 // operator.
13487
13488 // If we didn't actually find any template-ids, we're done.
13489 if (!ovl->hasExplicitTemplateArgs())
13490 return nullptr;
13491
13492 TemplateArgumentListInfo ExplicitTemplateArgs;
13493 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13494
13495 // Look through all of the overloaded functions, searching for one
13496 // whose type matches exactly.
13497 FunctionDecl *Matched = nullptr;
13498 for (UnresolvedSetIterator I = ovl->decls_begin(),
13499 E = ovl->decls_end(); I != E; ++I) {
13500 // C++0x [temp.arg.explicit]p3:
13501 // [...] In contexts where deduction is done and fails, or in contexts
13502 // where deduction is not done, if a template argument list is
13503 // specified and it, along with any default template arguments,
13504 // identifies a single function template specialization, then the
13505 // template-id is an lvalue for the function template specialization.
13506 FunctionTemplateDecl *FunctionTemplate
13507 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13508
13509 // C++ [over.over]p2:
13510 // If the name is a function template, template argument deduction is
13511 // done (14.8.2.2), and if the argument deduction succeeds, the
13512 // resulting template argument list is used to generate a single
13513 // function template specialization, which is added to the set of
13514 // overloaded functions considered.
13515 FunctionDecl *Specialization = nullptr;
13516 TemplateDeductionInfo Info(ovl->getNameLoc());
13518 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13519 /*IsAddressOfFunction*/ true);
13521 // Make a note of the failed deduction for diagnostics.
13522 if (FailedTSC)
13523 FailedTSC->addCandidate().set(
13524 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13525 MakeDeductionFailureInfo(Context, Result, Info));
13526 continue;
13527 }
13528
13529 assert(Specialization && "no specialization and no error?");
13530
13531 // Multiple matches; we can't resolve to a single declaration.
13532 if (Matched) {
13533 if (Complain) {
13534 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13535 << ovl->getName();
13536 NoteAllOverloadCandidates(ovl);
13537 }
13538 return nullptr;
13539 }
13540
13541 Matched = Specialization;
13542 if (FoundResult) *FoundResult = I.getPair();
13543 }
13544
13545 if (Matched &&
13546 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13547 return nullptr;
13548
13549 return Matched;
13550}
13551
13552// Resolve and fix an overloaded expression that can be resolved
13553// because it identifies a single function template specialization.
13554//
13555// Last three arguments should only be supplied if Complain = true
13556//
13557// Return true if it was logically possible to so resolve the
13558// expression, regardless of whether or not it succeeded. Always
13559// returns true if 'complain' is set.
13561 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13562 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13563 unsigned DiagIDForComplaining) {
13564 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13565
13567
13568 DeclAccessPair found;
13569 ExprResult SingleFunctionExpression;
13570 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13571 ovl.Expression, /*complain*/ false, &found)) {
13572 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13573 SrcExpr = ExprError();
13574 return true;
13575 }
13576
13577 // It is only correct to resolve to an instance method if we're
13578 // resolving a form that's permitted to be a pointer to member.
13579 // Otherwise we'll end up making a bound member expression, which
13580 // is illegal in all the contexts we resolve like this.
13581 if (!ovl.HasFormOfMemberPointer &&
13582 isa<CXXMethodDecl>(fn) &&
13583 cast<CXXMethodDecl>(fn)->isInstance()) {
13584 if (!complain) return false;
13585
13586 Diag(ovl.Expression->getExprLoc(),
13587 diag::err_bound_member_function)
13588 << 0 << ovl.Expression->getSourceRange();
13589
13590 // TODO: I believe we only end up here if there's a mix of
13591 // static and non-static candidates (otherwise the expression
13592 // would have 'bound member' type, not 'overload' type).
13593 // Ideally we would note which candidate was chosen and why
13594 // the static candidates were rejected.
13595 SrcExpr = ExprError();
13596 return true;
13597 }
13598
13599 // Fix the expression to refer to 'fn'.
13600 SingleFunctionExpression =
13601 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13602
13603 // If desired, do function-to-pointer decay.
13604 if (doFunctionPointerConversion) {
13605 SingleFunctionExpression =
13606 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13607 if (SingleFunctionExpression.isInvalid()) {
13608 SrcExpr = ExprError();
13609 return true;
13610 }
13611 }
13612 }
13613
13614 if (!SingleFunctionExpression.isUsable()) {
13615 if (complain) {
13616 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13617 << ovl.Expression->getName()
13618 << DestTypeForComplaining
13619 << OpRangeForComplaining
13621 NoteAllOverloadCandidates(SrcExpr.get());
13622
13623 SrcExpr = ExprError();
13624 return true;
13625 }
13626
13627 return false;
13628 }
13629
13630 SrcExpr = SingleFunctionExpression;
13631 return true;
13632}
13633
13634/// Add a single candidate to the overload set.
13636 DeclAccessPair FoundDecl,
13637 TemplateArgumentListInfo *ExplicitTemplateArgs,
13638 ArrayRef<Expr *> Args,
13639 OverloadCandidateSet &CandidateSet,
13640 bool PartialOverloading,
13641 bool KnownValid) {
13642 NamedDecl *Callee = FoundDecl.getDecl();
13643 if (isa<UsingShadowDecl>(Callee))
13644 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13645
13646 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13647 if (ExplicitTemplateArgs) {
13648 assert(!KnownValid && "Explicit template arguments?");
13649 return;
13650 }
13651 // Prevent ill-formed function decls to be added as overload candidates.
13652 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13653 return;
13654
13655 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13656 /*SuppressUserConversions=*/false,
13657 PartialOverloading);
13658 return;
13659 }
13660
13661 if (FunctionTemplateDecl *FuncTemplate
13662 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13663 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13664 ExplicitTemplateArgs, Args, CandidateSet,
13665 /*SuppressUserConversions=*/false,
13666 PartialOverloading);
13667 return;
13668 }
13669
13670 assert(!KnownValid && "unhandled case in overloaded call candidate");
13671}
13672
13673/// Add the overload candidates named by callee and/or found by argument
13674/// dependent lookup to the given overload set.
13676 ArrayRef<Expr *> Args,
13677 OverloadCandidateSet &CandidateSet,
13678 bool PartialOverloading) {
13679
13680#ifndef NDEBUG
13681 // Verify that ArgumentDependentLookup is consistent with the rules
13682 // in C++0x [basic.lookup.argdep]p3:
13683 //
13684 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13685 // and let Y be the lookup set produced by argument dependent
13686 // lookup (defined as follows). If X contains
13687 //
13688 // -- a declaration of a class member, or
13689 //
13690 // -- a block-scope function declaration that is not a
13691 // using-declaration, or
13692 //
13693 // -- a declaration that is neither a function or a function
13694 // template
13695 //
13696 // then Y is empty.
13697
13698 if (ULE->requiresADL()) {
13700 E = ULE->decls_end(); I != E; ++I) {
13701 assert(!(*I)->getDeclContext()->isRecord());
13702 assert(isa<UsingShadowDecl>(*I) ||
13703 !(*I)->getDeclContext()->isFunctionOrMethod());
13704 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13705 }
13706 }
13707#endif
13708
13709 // It would be nice to avoid this copy.
13710 TemplateArgumentListInfo TABuffer;
13711 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13712 if (ULE->hasExplicitTemplateArgs()) {
13713 ULE->copyTemplateArgumentsInto(TABuffer);
13714 ExplicitTemplateArgs = &TABuffer;
13715 }
13716
13718 E = ULE->decls_end(); I != E; ++I)
13719 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13720 CandidateSet, PartialOverloading,
13721 /*KnownValid*/ true);
13722
13723 if (ULE->requiresADL())
13724 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13725 Args, ExplicitTemplateArgs,
13726 CandidateSet, PartialOverloading);
13727}
13728
13729/// Add the call candidates from the given set of lookup results to the given
13730/// overload set. Non-function lookup results are ignored.
13732 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13733 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13734 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13735 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13736 CandidateSet, false, /*KnownValid*/ false);
13737}
13738
13739/// Determine whether a declaration with the specified name could be moved into
13740/// a different namespace.
13742 switch (Name.getCXXOverloadedOperator()) {
13743 case OO_New: case OO_Array_New:
13744 case OO_Delete: case OO_Array_Delete:
13745 return false;
13746
13747 default:
13748 return true;
13749 }
13750}
13751
13752/// Attempt to recover from an ill-formed use of a non-dependent name in a
13753/// template, where the non-dependent name was declared after the template
13754/// was defined. This is common in code written for a compilers which do not
13755/// correctly implement two-stage name lookup.
13756///
13757/// Returns true if a viable candidate was found and a diagnostic was issued.
13759 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13761 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13762 CXXRecordDecl **FoundInClass = nullptr) {
13763 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13764 return false;
13765
13766 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13767 if (DC->isTransparentContext())
13768 continue;
13769
13770 SemaRef.LookupQualifiedName(R, DC);
13771
13772 if (!R.empty()) {
13774
13775 OverloadCandidateSet Candidates(FnLoc, CSK);
13776 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13777 Candidates);
13778
13781 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13782
13783 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13784 // We either found non-function declarations or a best viable function
13785 // at class scope. A class-scope lookup result disables ADL. Don't
13786 // look past this, but let the caller know that we found something that
13787 // either is, or might be, usable in this class.
13788 if (FoundInClass) {
13789 *FoundInClass = RD;
13790 if (OR == OR_Success) {
13791 R.clear();
13792 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13793 R.resolveKind();
13794 }
13795 }
13796 return false;
13797 }
13798
13799 if (OR != OR_Success) {
13800 // There wasn't a unique best function or function template.
13801 return false;
13802 }
13803
13804 // Find the namespaces where ADL would have looked, and suggest
13805 // declaring the function there instead.
13806 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13807 Sema::AssociatedClassSet AssociatedClasses;
13808 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13809 AssociatedNamespaces,
13810 AssociatedClasses);
13811 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13813 DeclContext *Std = SemaRef.getStdNamespace();
13814 for (Sema::AssociatedNamespaceSet::iterator
13815 it = AssociatedNamespaces.begin(),
13816 end = AssociatedNamespaces.end(); it != end; ++it) {
13817 // Never suggest declaring a function within namespace 'std'.
13818 if (Std && Std->Encloses(*it))
13819 continue;
13820
13821 // Never suggest declaring a function within a namespace with a
13822 // reserved name, like __gnu_cxx.
13823 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13824 if (NS &&
13825 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13826 continue;
13827
13828 SuggestedNamespaces.insert(*it);
13829 }
13830 }
13831
13832 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13833 << R.getLookupName();
13834 if (SuggestedNamespaces.empty()) {
13835 SemaRef.Diag(Best->Function->getLocation(),
13836 diag::note_not_found_by_two_phase_lookup)
13837 << R.getLookupName() << 0;
13838 } else if (SuggestedNamespaces.size() == 1) {
13839 SemaRef.Diag(Best->Function->getLocation(),
13840 diag::note_not_found_by_two_phase_lookup)
13841 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13842 } else {
13843 // FIXME: It would be useful to list the associated namespaces here,
13844 // but the diagnostics infrastructure doesn't provide a way to produce
13845 // a localized representation of a list of items.
13846 SemaRef.Diag(Best->Function->getLocation(),
13847 diag::note_not_found_by_two_phase_lookup)
13848 << R.getLookupName() << 2;
13849 }
13850
13851 // Try to recover by calling this function.
13852 return true;
13853 }
13854
13855 R.clear();
13856 }
13857
13858 return false;
13859}
13860
13861/// Attempt to recover from ill-formed use of a non-dependent operator in a
13862/// template, where the non-dependent operator was declared after the template
13863/// was defined.
13864///
13865/// Returns true if a viable candidate was found and a diagnostic was issued.
13866static bool
13868 SourceLocation OpLoc,
13869 ArrayRef<Expr *> Args) {
13870 DeclarationName OpName =
13872 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13873 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13875 /*ExplicitTemplateArgs=*/nullptr, Args);
13876}
13877
13878namespace {
13879class BuildRecoveryCallExprRAII {
13880 Sema &SemaRef;
13882
13883public:
13884 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13885 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13886 SemaRef.IsBuildingRecoveryCallExpr = true;
13887 }
13888
13889 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13890};
13891}
13892
13893/// Attempts to recover from a call where no functions were found.
13894///
13895/// This function will do one of three things:
13896/// * Diagnose, recover, and return a recovery expression.
13897/// * Diagnose, fail to recover, and return ExprError().
13898/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13899/// expected to diagnose as appropriate.
13900static ExprResult
13903 SourceLocation LParenLoc,
13905 SourceLocation RParenLoc,
13906 bool EmptyLookup, bool AllowTypoCorrection) {
13907 // Do not try to recover if it is already building a recovery call.
13908 // This stops infinite loops for template instantiations like
13909 //
13910 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13911 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13912 if (SemaRef.IsBuildingRecoveryCallExpr)
13913 return ExprResult();
13914 BuildRecoveryCallExprRAII RCE(SemaRef);
13915
13916 CXXScopeSpec SS;
13917 SS.Adopt(ULE->getQualifierLoc());
13918 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13919
13920 TemplateArgumentListInfo TABuffer;
13921 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13922 if (ULE->hasExplicitTemplateArgs()) {
13923 ULE->copyTemplateArgumentsInto(TABuffer);
13924 ExplicitTemplateArgs = &TABuffer;
13925 }
13926
13927 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13929 CXXRecordDecl *FoundInClass = nullptr;
13930 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13932 ExplicitTemplateArgs, Args, &FoundInClass)) {
13933 // OK, diagnosed a two-phase lookup issue.
13934 } else if (EmptyLookup) {
13935 // Try to recover from an empty lookup with typo correction.
13936 R.clear();
13937 NoTypoCorrectionCCC NoTypoValidator{};
13938 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13939 ExplicitTemplateArgs != nullptr,
13940 dyn_cast<MemberExpr>(Fn));
13941 CorrectionCandidateCallback &Validator =
13942 AllowTypoCorrection
13943 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13944 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13945 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13946 Args))
13947 return ExprError();
13948 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13949 // We found a usable declaration of the name in a dependent base of some
13950 // enclosing class.
13951 // FIXME: We should also explain why the candidates found by name lookup
13952 // were not viable.
13953 if (SemaRef.DiagnoseDependentMemberLookup(R))
13954 return ExprError();
13955 } else {
13956 // We had viable candidates and couldn't recover; let the caller diagnose
13957 // this.
13958 return ExprResult();
13959 }
13960
13961 // If we get here, we should have issued a diagnostic and formed a recovery
13962 // lookup result.
13963 assert(!R.empty() && "lookup results empty despite recovery");
13964
13965 // If recovery created an ambiguity, just bail out.
13966 if (R.isAmbiguous()) {
13968 return ExprError();
13969 }
13970
13971 // Build an implicit member call if appropriate. Just drop the
13972 // casts and such from the call, we don't really care.
13973 ExprResult NewFn = ExprError();
13974 if ((*R.begin())->isCXXClassMember())
13975 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13976 ExplicitTemplateArgs, S);
13977 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13978 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13979 ExplicitTemplateArgs);
13980 else
13981 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13982
13983 if (NewFn.isInvalid())
13984 return ExprError();
13985
13986 // This shouldn't cause an infinite loop because we're giving it
13987 // an expression with viable lookup results, which should never
13988 // end up here.
13989 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13990 MultiExprArg(Args.data(), Args.size()),
13991 RParenLoc);
13992}
13993
13994/// Constructs and populates an OverloadedCandidateSet from
13995/// the given function.
13996/// \returns true when an the ExprResult output parameter has been set.
13999 MultiExprArg Args,
14000 SourceLocation RParenLoc,
14001 OverloadCandidateSet *CandidateSet,
14002 ExprResult *Result) {
14003#ifndef NDEBUG
14004 if (ULE->requiresADL()) {
14005 // To do ADL, we must have found an unqualified name.
14006 assert(!ULE->getQualifier() && "qualified name with ADL");
14007
14008 // We don't perform ADL for implicit declarations of builtins.
14009 // Verify that this was correctly set up.
14010 FunctionDecl *F;
14011 if (ULE->decls_begin() != ULE->decls_end() &&
14012 ULE->decls_begin() + 1 == ULE->decls_end() &&
14013 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14014 F->getBuiltinID() && F->isImplicit())
14015 llvm_unreachable("performing ADL for builtin");
14016
14017 // We don't perform ADL in C.
14018 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14019 }
14020#endif
14021
14022 UnbridgedCastsSet UnbridgedCasts;
14023 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14024 *Result = ExprError();
14025 return true;
14026 }
14027
14028 // Add the functions denoted by the callee to the set of candidate
14029 // functions, including those from argument-dependent lookup.
14030 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14031
14032 if (getLangOpts().MSVCCompat &&
14033 CurContext->isDependentContext() && !isSFINAEContext() &&
14034 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14035
14037 if (CandidateSet->empty() ||
14038 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14040 // In Microsoft mode, if we are inside a template class member function
14041 // then create a type dependent CallExpr. The goal is to postpone name
14042 // lookup to instantiation time to be able to search into type dependent
14043 // base classes.
14044 CallExpr *CE =
14045 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14046 RParenLoc, CurFPFeatureOverrides());
14048 *Result = CE;
14049 return true;
14050 }
14051 }
14052
14053 if (CandidateSet->empty())
14054 return false;
14055
14056 UnbridgedCasts.restore();
14057 return false;
14058}
14059
14060// Guess at what the return type for an unresolvable overload should be.
14063 std::optional<QualType> Result;
14064 // Adjust Type after seeing a candidate.
14065 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14066 if (!Candidate.Function)
14067 return;
14068 if (Candidate.Function->isInvalidDecl())
14069 return;
14070 QualType T = Candidate.Function->getReturnType();
14071 if (T.isNull())
14072 return;
14073 if (!Result)
14074 Result = T;
14075 else if (Result != T)
14076 Result = QualType();
14077 };
14078
14079 // Look for an unambiguous type from a progressively larger subset.
14080 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14081 //
14082 // First, consider only the best candidate.
14083 if (Best && *Best != CS.end())
14084 ConsiderCandidate(**Best);
14085 // Next, consider only viable candidates.
14086 if (!Result)
14087 for (const auto &C : CS)
14088 if (C.Viable)
14089 ConsiderCandidate(C);
14090 // Finally, consider all candidates.
14091 if (!Result)
14092 for (const auto &C : CS)
14093 ConsiderCandidate(C);
14094
14095 if (!Result)
14096 return QualType();
14097 auto Value = *Result;
14098 if (Value.isNull() || Value->isUndeducedType())
14099 return QualType();
14100 return Value;
14101}
14102
14103/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14104/// the completed call expression. If overload resolution fails, emits
14105/// diagnostics and returns ExprError()
14108 SourceLocation LParenLoc,
14109 MultiExprArg Args,
14110 SourceLocation RParenLoc,
14111 Expr *ExecConfig,
14112 OverloadCandidateSet *CandidateSet,
14114 OverloadingResult OverloadResult,
14115 bool AllowTypoCorrection) {
14116 switch (OverloadResult) {
14117 case OR_Success: {
14118 FunctionDecl *FDecl = (*Best)->Function;
14119 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14120 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14121 return ExprError();
14122 ExprResult Res =
14123 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14124 if (Res.isInvalid())
14125 return ExprError();
14126 return SemaRef.BuildResolvedCallExpr(
14127 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14128 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14129 }
14130
14131 case OR_No_Viable_Function: {
14132 // Try to recover by looking for viable functions which the user might
14133 // have meant to call.
14134 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14135 Args, RParenLoc,
14136 CandidateSet->empty(),
14137 AllowTypoCorrection);
14138 if (Recovery.isInvalid() || Recovery.isUsable())
14139 return Recovery;
14140
14141 // If the user passes in a function that we can't take the address of, we
14142 // generally end up emitting really bad error messages. Here, we attempt to
14143 // emit better ones.
14144 for (const Expr *Arg : Args) {
14145 if (!Arg->getType()->isFunctionType())
14146 continue;
14147 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14148 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14149 if (FD &&
14150 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14151 Arg->getExprLoc()))
14152 return ExprError();
14153 }
14154 }
14155
14156 CandidateSet->NoteCandidates(
14158 Fn->getBeginLoc(),
14159 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14160 << ULE->getName() << Fn->getSourceRange()),
14161 SemaRef, OCD_AllCandidates, Args);
14162 break;
14163 }
14164
14165 case OR_Ambiguous:
14166 CandidateSet->NoteCandidates(
14168 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14169 << ULE->getName() << Fn->getSourceRange()),
14170 SemaRef, OCD_AmbiguousCandidates, Args);
14171 break;
14172
14173 case OR_Deleted: {
14174 FunctionDecl *FDecl = (*Best)->Function;
14176 Fn->getSourceRange(), ULE->getName(),
14177 *CandidateSet, FDecl, Args);
14178
14179 // We emitted an error for the unavailable/deleted function call but keep
14180 // the call in the AST.
14181 ExprResult Res =
14182 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14183 if (Res.isInvalid())
14184 return ExprError();
14185 return SemaRef.BuildResolvedCallExpr(
14186 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14187 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14188 }
14189 }
14190
14191 // Overload resolution failed, try to recover.
14192 SmallVector<Expr *, 8> SubExprs = {Fn};
14193 SubExprs.append(Args.begin(), Args.end());
14194 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14195 chooseRecoveryType(*CandidateSet, Best));
14196}
14197
14200 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14201 if (I->Viable &&
14202 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14203 I->Viable = false;
14204 I->FailureKind = ovl_fail_addr_not_available;
14205 }
14206 }
14207}
14208
14209/// BuildOverloadedCallExpr - Given the call expression that calls Fn
14210/// (which eventually refers to the declaration Func) and the call
14211/// arguments Args/NumArgs, attempt to resolve the function call down
14212/// to a specific function. If overload resolution succeeds, returns
14213/// the call expression produced by overload resolution.
14214/// Otherwise, emits diagnostics and returns ExprError.
14217 SourceLocation LParenLoc,
14218 MultiExprArg Args,
14219 SourceLocation RParenLoc,
14220 Expr *ExecConfig,
14221 bool AllowTypoCorrection,
14222 bool CalleesAddressIsTaken) {
14223 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
14225 ExprResult result;
14226
14227 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14228 &result))
14229 return result;
14230
14231 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14232 // functions that aren't addressible are considered unviable.
14233 if (CalleesAddressIsTaken)
14234 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14235
14237 OverloadingResult OverloadResult =
14238 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14239
14240 // Model the case with a call to a templated function whose definition
14241 // encloses the call and whose return type contains a placeholder type as if
14242 // the UnresolvedLookupExpr was type-dependent.
14243 if (OverloadResult == OR_Success) {
14244 const FunctionDecl *FDecl = Best->Function;
14245 if (FDecl && FDecl->isTemplateInstantiation() &&
14246 FDecl->getReturnType()->isUndeducedType()) {
14247 if (const auto *TP =
14248 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14249 TP && TP->willHaveBody()) {
14250 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14251 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14252 }
14253 }
14254 }
14255
14256 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14257 ExecConfig, &CandidateSet, &Best,
14258 OverloadResult, AllowTypoCorrection);
14259}
14260
14261static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
14262 return Functions.size() > 1 ||
14263 (Functions.size() == 1 &&
14264 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
14265}
14266
14270 const UnresolvedSetImpl &Fns,
14271 bool PerformADL) {
14272 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14273 PerformADL, IsOverloaded(Fns),
14274 Fns.begin(), Fns.end());
14275}
14276
14278 CXXConversionDecl *Method,
14279 bool HadMultipleCandidates) {
14280 // Convert the expression to match the conversion function's implicit object
14281 // parameter.
14282 ExprResult Exp;
14283 if (Method->isExplicitObjectMemberFunction())
14284 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14285 else
14286 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14287 FoundDecl, Method);
14288 if (Exp.isInvalid())
14289 return true;
14290
14291 if (Method->getParent()->isLambda() &&
14293 // This is a lambda conversion to block pointer; check if the argument
14294 // was a LambdaExpr.
14295 Expr *SubE = E;
14296 auto *CE = dyn_cast<CastExpr>(SubE);
14297 if (CE && CE->getCastKind() == CK_NoOp)
14298 SubE = CE->getSubExpr();
14299 SubE = SubE->IgnoreParens();
14300 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14301 SubE = BE->getSubExpr();
14302 if (isa<LambdaExpr>(SubE)) {
14303 // For the conversion to block pointer on a lambda expression, we
14304 // construct a special BlockLiteral instead; this doesn't really make
14305 // a difference in ARC, but outside of ARC the resulting block literal
14306 // follows the normal lifetime rules for block literals instead of being
14307 // autoreleased.
14308 PushExpressionEvaluationContext(
14309 ExpressionEvaluationContext::PotentiallyEvaluated);
14310 ExprResult BlockExp = BuildBlockForLambdaConversion(
14311 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14312 PopExpressionEvaluationContext();
14313
14314 // FIXME: This note should be produced by a CodeSynthesisContext.
14315 if (BlockExp.isInvalid())
14316 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14317 return BlockExp;
14318 }
14319 }
14320 CallExpr *CE;
14321 QualType ResultType = Method->getReturnType();
14323 ResultType = ResultType.getNonLValueExprType(Context);
14324 if (Method->isExplicitObjectMemberFunction()) {
14325 ExprResult FnExpr =
14326 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14327 HadMultipleCandidates, E->getBeginLoc());
14328 if (FnExpr.isInvalid())
14329 return ExprError();
14330 Expr *ObjectParam = Exp.get();
14331 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14332 ResultType, VK, Exp.get()->getEndLoc(),
14333 CurFPFeatureOverrides());
14334 } else {
14335 MemberExpr *ME =
14336 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14338 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14339 HadMultipleCandidates, DeclarationNameInfo(),
14341
14342 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14343 Exp.get()->getEndLoc(),
14344 CurFPFeatureOverrides());
14345 }
14346
14347 if (CheckFunctionCall(Method, CE,
14348 Method->getType()->castAs<FunctionProtoType>()))
14349 return ExprError();
14350
14351 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14352}
14353
14354/// Create a unary operation that may resolve to an overloaded
14355/// operator.
14356///
14357/// \param OpLoc The location of the operator itself (e.g., '*').
14358///
14359/// \param Opc The UnaryOperatorKind that describes this operator.
14360///
14361/// \param Fns The set of non-member functions that will be
14362/// considered by overload resolution. The caller needs to build this
14363/// set based on the context using, e.g.,
14364/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14365/// set should not contain any member functions; those will be added
14366/// by CreateOverloadedUnaryOp().
14367///
14368/// \param Input The input argument.
14371 const UnresolvedSetImpl &Fns,
14372 Expr *Input, bool PerformADL) {
14374 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14376 // TODO: provide better source location info.
14377 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14378
14379 if (checkPlaceholderForOverload(*this, Input))
14380 return ExprError();
14381
14382 Expr *Args[2] = { Input, nullptr };
14383 unsigned NumArgs = 1;
14384
14385 // For post-increment and post-decrement, add the implicit '0' as
14386 // the second argument, so that we know this is a post-increment or
14387 // post-decrement.
14388 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14389 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14390 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14391 SourceLocation());
14392 NumArgs = 2;
14393 }
14394
14395 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14396
14397 if (Input->isTypeDependent()) {
14399 // [C++26][expr.unary.op][expr.pre.incr]
14400 // The * operator yields an lvalue of type
14401 // The pre/post increment operators yied an lvalue.
14402 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14403 VK = VK_LValue;
14404
14405 if (Fns.empty())
14406 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14407 OK_Ordinary, OpLoc, false,
14408 CurFPFeatureOverrides());
14409
14410 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14411 ExprResult Fn = CreateUnresolvedLookupExpr(
14412 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14413 if (Fn.isInvalid())
14414 return ExprError();
14415 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14416 Context.DependentTy, VK, OpLoc,
14417 CurFPFeatureOverrides());
14418 }
14419
14420 // Build an empty overload set.
14422
14423 // Add the candidates from the given function set.
14424 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14425
14426 // Add operator candidates that are member functions.
14427 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14428
14429 // Add candidates from ADL.
14430 if (PerformADL) {
14431 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14432 /*ExplicitTemplateArgs*/nullptr,
14433 CandidateSet);
14434 }
14435
14436 // Add builtin operator candidates.
14437 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14438
14439 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14440
14441 // Perform overload resolution.
14443 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14444 case OR_Success: {
14445 // We found a built-in operator or an overloaded operator.
14446 FunctionDecl *FnDecl = Best->Function;
14447
14448 if (FnDecl) {
14449 Expr *Base = nullptr;
14450 // We matched an overloaded operator. Build a call to that
14451 // operator.
14452
14453 // Convert the arguments.
14454 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14455 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14456
14457 ExprResult InputInit;
14458 if (Method->isExplicitObjectMemberFunction())
14459 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14460 else
14461 InputInit = PerformImplicitObjectArgumentInitialization(
14462 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14463 if (InputInit.isInvalid())
14464 return ExprError();
14465 Base = Input = InputInit.get();
14466 } else {
14467 // Convert the arguments.
14468 ExprResult InputInit
14469 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14470 Context,
14471 FnDecl->getParamDecl(0)),
14473 Input);
14474 if (InputInit.isInvalid())
14475 return ExprError();
14476 Input = InputInit.get();
14477 }
14478
14479 // Build the actual expression node.
14480 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14481 Base, HadMultipleCandidates,
14482 OpLoc);
14483 if (FnExpr.isInvalid())
14484 return ExprError();
14485
14486 // Determine the result type.
14487 QualType ResultTy = FnDecl->getReturnType();
14489 ResultTy = ResultTy.getNonLValueExprType(Context);
14490
14491 Args[0] = Input;
14493 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14494 CurFPFeatureOverrides(), Best->IsADLCandidate);
14495
14496 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14497 return ExprError();
14498
14499 if (CheckFunctionCall(FnDecl, TheCall,
14500 FnDecl->getType()->castAs<FunctionProtoType>()))
14501 return ExprError();
14502 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14503 } else {
14504 // We matched a built-in operator. Convert the arguments, then
14505 // break out so that we will build the appropriate built-in
14506 // operator node.
14507 ExprResult InputRes = PerformImplicitConversion(
14508 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14510 if (InputRes.isInvalid())
14511 return ExprError();
14512 Input = InputRes.get();
14513 break;
14514 }
14515 }
14516
14518 // This is an erroneous use of an operator which can be overloaded by
14519 // a non-member function. Check for non-member operators which were
14520 // defined too late to be candidates.
14521 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14522 // FIXME: Recover by calling the found function.
14523 return ExprError();
14524
14525 // No viable function; fall through to handling this as a
14526 // built-in operator, which will produce an error message for us.
14527 break;
14528
14529 case OR_Ambiguous:
14530 CandidateSet.NoteCandidates(
14531 PartialDiagnosticAt(OpLoc,
14532 PDiag(diag::err_ovl_ambiguous_oper_unary)
14534 << Input->getType() << Input->getSourceRange()),
14535 *this, OCD_AmbiguousCandidates, ArgsArray,
14536 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14537 return ExprError();
14538
14539 case OR_Deleted: {
14540 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14541 // object whose method was called. Later in NoteCandidates size of ArgsArray
14542 // is passed further and it eventually ends up compared to number of
14543 // function candidate parameters which never includes the object parameter,
14544 // so slice ArgsArray to make sure apples are compared to apples.
14545 StringLiteral *Msg = Best->Function->getDeletedMessage();
14546 CandidateSet.NoteCandidates(
14547 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14549 << (Msg != nullptr)
14550 << (Msg ? Msg->getString() : StringRef())
14551 << Input->getSourceRange()),
14552 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14553 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14554 return ExprError();
14555 }
14556 }
14557
14558 // Either we found no viable overloaded operator or we matched a
14559 // built-in operator. In either case, fall through to trying to
14560 // build a built-in operation.
14561 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14562}
14563
14564/// Perform lookup for an overloaded binary operator.
14567 const UnresolvedSetImpl &Fns,
14568 ArrayRef<Expr *> Args, bool PerformADL) {
14569 SourceLocation OpLoc = CandidateSet.getLocation();
14570
14571 OverloadedOperatorKind ExtraOp =
14574 : OO_None;
14575
14576 // Add the candidates from the given function set. This also adds the
14577 // rewritten candidates using these functions if necessary.
14578 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14579
14580 // Add operator candidates that are member functions.
14581 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14582 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14583 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14585
14586 // In C++20, also add any rewritten member candidates.
14587 if (ExtraOp) {
14588 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14589 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14590 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14591 CandidateSet,
14593 }
14594
14595 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14596 // performed for an assignment operator (nor for operator[] nor operator->,
14597 // which don't get here).
14598 if (Op != OO_Equal && PerformADL) {
14600 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14601 /*ExplicitTemplateArgs*/ nullptr,
14602 CandidateSet);
14603 if (ExtraOp) {
14604 DeclarationName ExtraOpName =
14605 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14606 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14607 /*ExplicitTemplateArgs*/ nullptr,
14608 CandidateSet);
14609 }
14610 }
14611
14612 // Add builtin operator candidates.
14613 //
14614 // FIXME: We don't add any rewritten candidates here. This is strictly
14615 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14616 // resulting in our selecting a rewritten builtin candidate. For example:
14617 //
14618 // enum class E { e };
14619 // bool operator!=(E, E) requires false;
14620 // bool k = E::e != E::e;
14621 //
14622 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14623 // it seems unreasonable to consider rewritten builtin candidates. A core
14624 // issue has been filed proposing to removed this requirement.
14625 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14626}
14627
14628/// Create a binary operation that may resolve to an overloaded
14629/// operator.
14630///
14631/// \param OpLoc The location of the operator itself (e.g., '+').
14632///
14633/// \param Opc The BinaryOperatorKind that describes this operator.
14634///
14635/// \param Fns The set of non-member functions that will be
14636/// considered by overload resolution. The caller needs to build this
14637/// set based on the context using, e.g.,
14638/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14639/// set should not contain any member functions; those will be added
14640/// by CreateOverloadedBinOp().
14641///
14642/// \param LHS Left-hand argument.
14643/// \param RHS Right-hand argument.
14644/// \param PerformADL Whether to consider operator candidates found by ADL.
14645/// \param AllowRewrittenCandidates Whether to consider candidates found by
14646/// C++20 operator rewrites.
14647/// \param DefaultedFn If we are synthesizing a defaulted operator function,
14648/// the function in question. Such a function is never a candidate in
14649/// our overload resolution. This also enables synthesizing a three-way
14650/// comparison from < and == as described in C++20 [class.spaceship]p1.
14653 const UnresolvedSetImpl &Fns, Expr *LHS,
14654 Expr *RHS, bool PerformADL,
14655 bool AllowRewrittenCandidates,
14656 FunctionDecl *DefaultedFn) {
14657 Expr *Args[2] = { LHS, RHS };
14658 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14659
14660 if (!getLangOpts().CPlusPlus20)
14661 AllowRewrittenCandidates = false;
14662
14664
14665 // If either side is type-dependent, create an appropriate dependent
14666 // expression.
14667 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14668 if (Fns.empty()) {
14669 // If there are no functions to store, just build a dependent
14670 // BinaryOperator or CompoundAssignment.
14673 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14674 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14675 Context.DependentTy);
14677 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14678 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14679 }
14680
14681 // FIXME: save results of ADL from here?
14682 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14683 // TODO: provide better source location info in DNLoc component.
14685 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14686 ExprResult Fn = CreateUnresolvedLookupExpr(
14687 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14688 if (Fn.isInvalid())
14689 return ExprError();
14690 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14691 Context.DependentTy, VK_PRValue, OpLoc,
14692 CurFPFeatureOverrides());
14693 }
14694
14695 // If this is the .* operator, which is not overloadable, just
14696 // create a built-in binary operator.
14697 if (Opc == BO_PtrMemD) {
14698 auto CheckPlaceholder = [&](Expr *&Arg) {
14699 ExprResult Res = CheckPlaceholderExpr(Arg);
14700 if (Res.isUsable())
14701 Arg = Res.get();
14702 return !Res.isUsable();
14703 };
14704
14705 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14706 // expression that contains placeholders (in either the LHS or RHS).
14707 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14708 return ExprError();
14709 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14710 }
14711
14712 // Always do placeholder-like conversions on the RHS.
14713 if (checkPlaceholderForOverload(*this, Args[1]))
14714 return ExprError();
14715
14716 // Do placeholder-like conversion on the LHS; note that we should
14717 // not get here with a PseudoObject LHS.
14718 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14719 if (checkPlaceholderForOverload(*this, Args[0]))
14720 return ExprError();
14721
14722 // If this is the assignment operator, we only perform overload resolution
14723 // if the left-hand side is a class or enumeration type. This is actually
14724 // a hack. The standard requires that we do overload resolution between the
14725 // various built-in candidates, but as DR507 points out, this can lead to
14726 // problems. So we do it this way, which pretty much follows what GCC does.
14727 // Note that we go the traditional code path for compound assignment forms.
14728 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14729 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14730
14731 // Build the overload set.
14734 Op, OpLoc, AllowRewrittenCandidates));
14735 if (DefaultedFn)
14736 CandidateSet.exclude(DefaultedFn);
14737 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14738
14739 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14740
14741 // Perform overload resolution.
14743 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14744 case OR_Success: {
14745 // We found a built-in operator or an overloaded operator.
14746 FunctionDecl *FnDecl = Best->Function;
14747
14748 bool IsReversed = Best->isReversed();
14749 if (IsReversed)
14750 std::swap(Args[0], Args[1]);
14751
14752 if (FnDecl) {
14753
14754 if (FnDecl->isInvalidDecl())
14755 return ExprError();
14756
14757 Expr *Base = nullptr;
14758 // We matched an overloaded operator. Build a call to that
14759 // operator.
14760
14761 OverloadedOperatorKind ChosenOp =
14763
14764 // C++2a [over.match.oper]p9:
14765 // If a rewritten operator== candidate is selected by overload
14766 // resolution for an operator@, its return type shall be cv bool
14767 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14768 !FnDecl->getReturnType()->isBooleanType()) {
14769 bool IsExtension =
14771 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14772 : diag::err_ovl_rewrite_equalequal_not_bool)
14773 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14774 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14775 Diag(FnDecl->getLocation(), diag::note_declared_at);
14776 if (!IsExtension)
14777 return ExprError();
14778 }
14779
14780 if (AllowRewrittenCandidates && !IsReversed &&
14781 CandidateSet.getRewriteInfo().isReversible()) {
14782 // We could have reversed this operator, but didn't. Check if some
14783 // reversed form was a viable candidate, and if so, if it had a
14784 // better conversion for either parameter. If so, this call is
14785 // formally ambiguous, and allowing it is an extension.
14787 for (OverloadCandidate &Cand : CandidateSet) {
14788 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14789 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14790 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14792 *this, OpLoc, Cand.Conversions[ArgIdx],
14793 Best->Conversions[ArgIdx]) ==
14795 AmbiguousWith.push_back(Cand.Function);
14796 break;
14797 }
14798 }
14799 }
14800 }
14801
14802 if (!AmbiguousWith.empty()) {
14803 bool AmbiguousWithSelf =
14804 AmbiguousWith.size() == 1 &&
14805 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14806 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14808 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14809 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14810 if (AmbiguousWithSelf) {
14811 Diag(FnDecl->getLocation(),
14812 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14813 // Mark member== const or provide matching != to disallow reversed
14814 // args. Eg.
14815 // struct S { bool operator==(const S&); };
14816 // S()==S();
14817 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14818 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14819 !MD->isConst() &&
14820 !MD->hasCXXExplicitFunctionObjectParameter() &&
14821 Context.hasSameUnqualifiedType(
14822 MD->getFunctionObjectParameterType(),
14823 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14824 Context.hasSameUnqualifiedType(
14825 MD->getFunctionObjectParameterType(),
14826 Args[0]->getType()) &&
14827 Context.hasSameUnqualifiedType(
14828 MD->getFunctionObjectParameterType(),
14829 Args[1]->getType()))
14830 Diag(FnDecl->getLocation(),
14831 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14832 } else {
14833 Diag(FnDecl->getLocation(),
14834 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14835 for (auto *F : AmbiguousWith)
14836 Diag(F->getLocation(),
14837 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14838 }
14839 }
14840 }
14841
14842 // Check for nonnull = nullable.
14843 // This won't be caught in the arg's initialization: the parameter to
14844 // the assignment operator is not marked nonnull.
14845 if (Op == OO_Equal)
14846 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14847 Args[1]->getType(), OpLoc);
14848
14849 // Convert the arguments.
14850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14851 // Best->Access is only meaningful for class members.
14852 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14853
14854 ExprResult Arg0, Arg1;
14855 unsigned ParamIdx = 0;
14856 if (Method->isExplicitObjectMemberFunction()) {
14857 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14858 ParamIdx = 1;
14859 } else {
14860 Arg0 = PerformImplicitObjectArgumentInitialization(
14861 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14862 }
14863 Arg1 = PerformCopyInitialization(
14865 Context, FnDecl->getParamDecl(ParamIdx)),
14866 SourceLocation(), Args[1]);
14867 if (Arg0.isInvalid() || Arg1.isInvalid())
14868 return ExprError();
14869
14870 Base = Args[0] = Arg0.getAs<Expr>();
14871 Args[1] = RHS = Arg1.getAs<Expr>();
14872 } else {
14873 // Convert the arguments.
14874 ExprResult Arg0 = PerformCopyInitialization(
14876 FnDecl->getParamDecl(0)),
14877 SourceLocation(), Args[0]);
14878 if (Arg0.isInvalid())
14879 return ExprError();
14880
14881 ExprResult Arg1 =
14882 PerformCopyInitialization(
14884 FnDecl->getParamDecl(1)),
14885 SourceLocation(), Args[1]);
14886 if (Arg1.isInvalid())
14887 return ExprError();
14888 Args[0] = LHS = Arg0.getAs<Expr>();
14889 Args[1] = RHS = Arg1.getAs<Expr>();
14890 }
14891
14892 // Build the actual expression node.
14893 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14894 Best->FoundDecl, Base,
14895 HadMultipleCandidates, OpLoc);
14896 if (FnExpr.isInvalid())
14897 return ExprError();
14898
14899 // Determine the result type.
14900 QualType ResultTy = FnDecl->getReturnType();
14902 ResultTy = ResultTy.getNonLValueExprType(Context);
14903
14904 CallExpr *TheCall;
14905 ArrayRef<const Expr *> ArgsArray(Args, 2);
14906 const Expr *ImplicitThis = nullptr;
14907
14908 // We always create a CXXOperatorCallExpr, even for explicit object
14909 // members; CodeGen should take care not to emit the this pointer.
14911 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14912 CurFPFeatureOverrides(), Best->IsADLCandidate);
14913
14914 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14915 Method && Method->isImplicitObjectMemberFunction()) {
14916 // Cut off the implicit 'this'.
14917 ImplicitThis = ArgsArray[0];
14918 ArgsArray = ArgsArray.slice(1);
14919 }
14920
14921 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14922 FnDecl))
14923 return ExprError();
14924
14925 // Check for a self move.
14926 if (Op == OO_Equal)
14927 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14928
14929 if (ImplicitThis) {
14930 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14931 QualType ThisTypeFromDecl = Context.getPointerType(
14932 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14933
14934 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14935 ThisTypeFromDecl);
14936 }
14937
14938 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14939 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14940 VariadicDoesNotApply);
14941
14942 ExprResult R = MaybeBindToTemporary(TheCall);
14943 if (R.isInvalid())
14944 return ExprError();
14945
14946 R = CheckForImmediateInvocation(R, FnDecl);
14947 if (R.isInvalid())
14948 return ExprError();
14949
14950 // For a rewritten candidate, we've already reversed the arguments
14951 // if needed. Perform the rest of the rewrite now.
14952 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14953 (Op == OO_Spaceship && IsReversed)) {
14954 if (Op == OO_ExclaimEqual) {
14955 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14956 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14957 } else {
14958 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14959 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14960 Expr *ZeroLiteral =
14961 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14962
14965 Ctx.Entity = FnDecl;
14966 pushCodeSynthesisContext(Ctx);
14967
14968 R = CreateOverloadedBinOp(
14969 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14970 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14971 /*AllowRewrittenCandidates=*/false);
14972
14973 popCodeSynthesisContext();
14974 }
14975 if (R.isInvalid())
14976 return ExprError();
14977 } else {
14978 assert(ChosenOp == Op && "unexpected operator name");
14979 }
14980
14981 // Make a note in the AST if we did any rewriting.
14982 if (Best->RewriteKind != CRK_None)
14983 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14984
14985 return R;
14986 } else {
14987 // We matched a built-in operator. Convert the arguments, then
14988 // break out so that we will build the appropriate built-in
14989 // operator node.
14990 ExprResult ArgsRes0 = PerformImplicitConversion(
14991 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14993 if (ArgsRes0.isInvalid())
14994 return ExprError();
14995 Args[0] = ArgsRes0.get();
14996
14997 ExprResult ArgsRes1 = PerformImplicitConversion(
14998 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15000 if (ArgsRes1.isInvalid())
15001 return ExprError();
15002 Args[1] = ArgsRes1.get();
15003 break;
15004 }
15005 }
15006
15007 case OR_No_Viable_Function: {
15008 // C++ [over.match.oper]p9:
15009 // If the operator is the operator , [...] and there are no
15010 // viable functions, then the operator is assumed to be the
15011 // built-in operator and interpreted according to clause 5.
15012 if (Opc == BO_Comma)
15013 break;
15014
15015 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15016 // compare result using '==' and '<'.
15017 if (DefaultedFn && Opc == BO_Cmp) {
15018 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15019 Args[1], DefaultedFn);
15020 if (E.isInvalid() || E.isUsable())
15021 return E;
15022 }
15023
15024 // For class as left operand for assignment or compound assignment
15025 // operator do not fall through to handling in built-in, but report that
15026 // no overloaded assignment operator found
15028 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15029 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15030 Args, OpLoc);
15031 DeferDiagsRAII DDR(*this,
15032 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15033 if (Args[0]->getType()->isRecordType() &&
15034 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15035 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15037 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15038 if (Args[0]->getType()->isIncompleteType()) {
15039 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15040 << Args[0]->getType()
15041 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15042 }
15043 } else {
15044 // This is an erroneous use of an operator which can be overloaded by
15045 // a non-member function. Check for non-member operators which were
15046 // defined too late to be candidates.
15047 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15048 // FIXME: Recover by calling the found function.
15049 return ExprError();
15050
15051 // No viable function; try to create a built-in operation, which will
15052 // produce an error. Then, show the non-viable candidates.
15053 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15054 }
15055 assert(Result.isInvalid() &&
15056 "C++ binary operator overloading is missing candidates!");
15057 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15058 return Result;
15059 }
15060
15061 case OR_Ambiguous:
15062 CandidateSet.NoteCandidates(
15063 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15065 << Args[0]->getType()
15066 << Args[1]->getType()
15067 << Args[0]->getSourceRange()
15068 << Args[1]->getSourceRange()),
15070 OpLoc);
15071 return ExprError();
15072
15073 case OR_Deleted: {
15074 if (isImplicitlyDeleted(Best->Function)) {
15075 FunctionDecl *DeletedFD = Best->Function;
15076 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15077 if (DFK.isSpecialMember()) {
15078 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15079 << Args[0]->getType()
15080 << llvm::to_underlying(DFK.asSpecialMember());
15081 } else {
15082 assert(DFK.isComparison());
15083 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15084 << Args[0]->getType() << DeletedFD;
15085 }
15086
15087 // The user probably meant to call this special member. Just
15088 // explain why it's deleted.
15089 NoteDeletedFunction(DeletedFD);
15090 return ExprError();
15091 }
15092
15093 StringLiteral *Msg = Best->Function->getDeletedMessage();
15094 CandidateSet.NoteCandidates(
15096 OpLoc,
15097 PDiag(diag::err_ovl_deleted_oper)
15098 << getOperatorSpelling(Best->Function->getDeclName()
15099 .getCXXOverloadedOperator())
15100 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15101 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15103 OpLoc);
15104 return ExprError();
15105 }
15106 }
15107
15108 // We matched a built-in operator; build it.
15109 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15110}
15111
15113 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15114 FunctionDecl *DefaultedFn) {
15115 const ComparisonCategoryInfo *Info =
15116 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15117 // If we're not producing a known comparison category type, we can't
15118 // synthesize a three-way comparison. Let the caller diagnose this.
15119 if (!Info)
15120 return ExprResult((Expr*)nullptr);
15121
15122 // If we ever want to perform this synthesis more generally, we will need to
15123 // apply the temporary materialization conversion to the operands.
15124 assert(LHS->isGLValue() && RHS->isGLValue() &&
15125 "cannot use prvalue expressions more than once");
15126 Expr *OrigLHS = LHS;
15127 Expr *OrigRHS = RHS;
15128
15129 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15130 // each of them multiple times below.
15131 LHS = new (Context)
15132 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15133 LHS->getObjectKind(), LHS);
15134 RHS = new (Context)
15135 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15136 RHS->getObjectKind(), RHS);
15137
15138 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15139 DefaultedFn);
15140 if (Eq.isInvalid())
15141 return ExprError();
15142
15143 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15144 true, DefaultedFn);
15145 if (Less.isInvalid())
15146 return ExprError();
15147
15149 if (Info->isPartial()) {
15150 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15151 DefaultedFn);
15152 if (Greater.isInvalid())
15153 return ExprError();
15154 }
15155
15156 // Form the list of comparisons we're going to perform.
15157 struct Comparison {
15158 ExprResult Cmp;
15160 } Comparisons[4] =
15166 };
15167
15168 int I = Info->isPartial() ? 3 : 2;
15169
15170 // Combine the comparisons with suitable conditional expressions.
15172 for (; I >= 0; --I) {
15173 // Build a reference to the comparison category constant.
15174 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15175 // FIXME: Missing a constant for a comparison category. Diagnose this?
15176 if (!VI)
15177 return ExprResult((Expr*)nullptr);
15178 ExprResult ThisResult =
15179 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15180 if (ThisResult.isInvalid())
15181 return ExprError();
15182
15183 // Build a conditional unless this is the final case.
15184 if (Result.get()) {
15185 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15186 ThisResult.get(), Result.get());
15187 if (Result.isInvalid())
15188 return ExprError();
15189 } else {
15190 Result = ThisResult;
15191 }
15192 }
15193
15194 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15195 // bind the OpaqueValueExprs before they're (repeatedly) used.
15196 Expr *SyntacticForm = BinaryOperator::Create(
15197 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15198 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15199 CurFPFeatureOverrides());
15200 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15201 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15202}
15203
15205 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15206 MultiExprArg Args, SourceLocation LParenLoc) {
15207
15208 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15209 unsigned NumParams = Proto->getNumParams();
15210 unsigned NumArgsSlots =
15211 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15212 // Build the full argument list for the method call (the implicit object
15213 // parameter is placed at the beginning of the list).
15214 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15215 bool IsError = false;
15216 // Initialize the implicit object parameter.
15217 // Check the argument types.
15218 for (unsigned i = 0; i != NumParams; i++) {
15219 Expr *Arg;
15220 if (i < Args.size()) {
15221 Arg = Args[i];
15222 ExprResult InputInit =
15224 S.Context, Method->getParamDecl(i)),
15225 SourceLocation(), Arg);
15226 IsError |= InputInit.isInvalid();
15227 Arg = InputInit.getAs<Expr>();
15228 } else {
15229 ExprResult DefArg =
15230 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15231 if (DefArg.isInvalid()) {
15232 IsError = true;
15233 break;
15234 }
15235 Arg = DefArg.getAs<Expr>();
15236 }
15237
15238 MethodArgs.push_back(Arg);
15239 }
15240 return IsError;
15241}
15242
15244 SourceLocation RLoc,
15245 Expr *Base,
15246 MultiExprArg ArgExpr) {
15248 Args.push_back(Base);
15249 for (auto *e : ArgExpr) {
15250 Args.push_back(e);
15251 }
15252 DeclarationName OpName =
15253 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15254
15255 SourceRange Range = ArgExpr.empty()
15256 ? SourceRange{}
15257 : SourceRange(ArgExpr.front()->getBeginLoc(),
15258 ArgExpr.back()->getEndLoc());
15259
15260 // If either side is type-dependent, create an appropriate dependent
15261 // expression.
15263
15264 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15265 // CHECKME: no 'operator' keyword?
15266 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15267 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15268 ExprResult Fn = CreateUnresolvedLookupExpr(
15269 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15270 if (Fn.isInvalid())
15271 return ExprError();
15272 // Can't add any actual overloads yet
15273
15274 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15275 Context.DependentTy, VK_PRValue, RLoc,
15276 CurFPFeatureOverrides());
15277 }
15278
15279 // Handle placeholders
15280 UnbridgedCastsSet UnbridgedCasts;
15281 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15282 return ExprError();
15283 }
15284 // Build an empty overload set.
15286
15287 // Subscript can only be overloaded as a member function.
15288
15289 // Add operator candidates that are member functions.
15290 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15291
15292 // Add builtin operator candidates.
15293 if (Args.size() == 2)
15294 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15295
15296 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15297
15298 // Perform overload resolution.
15300 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15301 case OR_Success: {
15302 // We found a built-in operator or an overloaded operator.
15303 FunctionDecl *FnDecl = Best->Function;
15304
15305 if (FnDecl) {
15306 // We matched an overloaded operator. Build a call to that
15307 // operator.
15308
15309 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15310
15311 // Convert the arguments.
15312 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15313 SmallVector<Expr *, 2> MethodArgs;
15314
15315 // Initialize the object parameter.
15316 if (Method->isExplicitObjectMemberFunction()) {
15317 ExprResult Res =
15318 InitializeExplicitObjectArgument(*this, Args[0], Method);
15319 if (Res.isInvalid())
15320 return ExprError();
15321 Args[0] = Res.get();
15322 ArgExpr = Args;
15323 } else {
15324 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15325 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15326 if (Arg0.isInvalid())
15327 return ExprError();
15328
15329 MethodArgs.push_back(Arg0.get());
15330 }
15331
15333 *this, MethodArgs, Method, ArgExpr, LLoc);
15334 if (IsError)
15335 return ExprError();
15336
15337 // Build the actual expression node.
15338 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15339 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15341 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15342 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15343 if (FnExpr.isInvalid())
15344 return ExprError();
15345
15346 // Determine the result type
15347 QualType ResultTy = FnDecl->getReturnType();
15349 ResultTy = ResultTy.getNonLValueExprType(Context);
15350
15352 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15353 CurFPFeatureOverrides());
15354
15355 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15356 return ExprError();
15357
15358 if (CheckFunctionCall(Method, TheCall,
15359 Method->getType()->castAs<FunctionProtoType>()))
15360 return ExprError();
15361
15362 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15363 FnDecl);
15364 } else {
15365 // We matched a built-in operator. Convert the arguments, then
15366 // break out so that we will build the appropriate built-in
15367 // operator node.
15368 ExprResult ArgsRes0 = PerformImplicitConversion(
15369 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15371 if (ArgsRes0.isInvalid())
15372 return ExprError();
15373 Args[0] = ArgsRes0.get();
15374
15375 ExprResult ArgsRes1 = PerformImplicitConversion(
15376 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15378 if (ArgsRes1.isInvalid())
15379 return ExprError();
15380 Args[1] = ArgsRes1.get();
15381
15382 break;
15383 }
15384 }
15385
15386 case OR_No_Viable_Function: {
15388 CandidateSet.empty()
15389 ? (PDiag(diag::err_ovl_no_oper)
15390 << Args[0]->getType() << /*subscript*/ 0
15391 << Args[0]->getSourceRange() << Range)
15392 : (PDiag(diag::err_ovl_no_viable_subscript)
15393 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15394 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15395 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15396 return ExprError();
15397 }
15398
15399 case OR_Ambiguous:
15400 if (Args.size() == 2) {
15401 CandidateSet.NoteCandidates(
15403 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15404 << "[]" << Args[0]->getType() << Args[1]->getType()
15405 << Args[0]->getSourceRange() << Range),
15406 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15407 } else {
15408 CandidateSet.NoteCandidates(
15410 PDiag(diag::err_ovl_ambiguous_subscript_call)
15411 << Args[0]->getType()
15412 << Args[0]->getSourceRange() << Range),
15413 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15414 }
15415 return ExprError();
15416
15417 case OR_Deleted: {
15418 StringLiteral *Msg = Best->Function->getDeletedMessage();
15419 CandidateSet.NoteCandidates(
15421 PDiag(diag::err_ovl_deleted_oper)
15422 << "[]" << (Msg != nullptr)
15423 << (Msg ? Msg->getString() : StringRef())
15424 << Args[0]->getSourceRange() << Range),
15425 *this, OCD_AllCandidates, Args, "[]", LLoc);
15426 return ExprError();
15427 }
15428 }
15429
15430 // We matched a built-in operator; build it.
15431 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15432}
15433
15434/// BuildCallToMemberFunction - Build a call to a member
15435/// function. MemExpr is the expression that refers to the member
15436/// function (and includes the object parameter), Args/NumArgs are the
15437/// arguments to the function call (not including the object
15438/// parameter). The caller needs to validate that the member
15439/// expression refers to a non-static member function or an overloaded
15440/// member function.
15442 SourceLocation LParenLoc,
15443 MultiExprArg Args,
15444 SourceLocation RParenLoc,
15445 Expr *ExecConfig, bool IsExecConfig,
15446 bool AllowRecovery) {
15447 assert(MemExprE->getType() == Context.BoundMemberTy ||
15448 MemExprE->getType() == Context.OverloadTy);
15449
15450 // Dig out the member expression. This holds both the object
15451 // argument and the member function we're referring to.
15452 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15453
15454 // Determine whether this is a call to a pointer-to-member function.
15455 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15456 assert(op->getType() == Context.BoundMemberTy);
15457 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15458
15459 QualType fnType =
15460 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15461
15462 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15463 QualType resultType = proto->getCallResultType(Context);
15465
15466 // Check that the object type isn't more qualified than the
15467 // member function we're calling.
15468 Qualifiers funcQuals = proto->getMethodQuals();
15469
15470 QualType objectType = op->getLHS()->getType();
15471 if (op->getOpcode() == BO_PtrMemI)
15472 objectType = objectType->castAs<PointerType>()->getPointeeType();
15473 Qualifiers objectQuals = objectType.getQualifiers();
15474
15475 Qualifiers difference = objectQuals - funcQuals;
15476 difference.removeObjCGCAttr();
15477 difference.removeAddressSpace();
15478 if (difference) {
15479 std::string qualsString = difference.getAsString();
15480 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15481 << fnType.getUnqualifiedType()
15482 << qualsString
15483 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15484 }
15485
15487 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15488 CurFPFeatureOverrides(), proto->getNumParams());
15489
15490 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15491 call, nullptr))
15492 return ExprError();
15493
15494 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15495 return ExprError();
15496
15497 if (CheckOtherCall(call, proto))
15498 return ExprError();
15499
15500 return MaybeBindToTemporary(call);
15501 }
15502
15503 // We only try to build a recovery expr at this level if we can preserve
15504 // the return type, otherwise we return ExprError() and let the caller
15505 // recover.
15506 auto BuildRecoveryExpr = [&](QualType Type) {
15507 if (!AllowRecovery)
15508 return ExprError();
15509 std::vector<Expr *> SubExprs = {MemExprE};
15510 llvm::append_range(SubExprs, Args);
15511 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15512 Type);
15513 };
15514 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15515 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15516 RParenLoc, CurFPFeatureOverrides());
15517
15518 UnbridgedCastsSet UnbridgedCasts;
15519 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15520 return ExprError();
15521
15522 MemberExpr *MemExpr;
15523 CXXMethodDecl *Method = nullptr;
15524 bool HadMultipleCandidates = false;
15525 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15526 NestedNameSpecifier *Qualifier = nullptr;
15527 if (isa<MemberExpr>(NakedMemExpr)) {
15528 MemExpr = cast<MemberExpr>(NakedMemExpr);
15529 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15530 FoundDecl = MemExpr->getFoundDecl();
15531 Qualifier = MemExpr->getQualifier();
15532 UnbridgedCasts.restore();
15533 } else {
15534 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15535 Qualifier = UnresExpr->getQualifier();
15536
15537 QualType ObjectType = UnresExpr->getBaseType();
15538 Expr::Classification ObjectClassification
15540 : UnresExpr->getBase()->Classify(Context);
15541
15542 // Add overload candidates
15543 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15545
15546 // FIXME: avoid copy.
15547 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15548 if (UnresExpr->hasExplicitTemplateArgs()) {
15549 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15550 TemplateArgs = &TemplateArgsBuffer;
15551 }
15552
15554 E = UnresExpr->decls_end(); I != E; ++I) {
15555
15556 QualType ExplicitObjectType = ObjectType;
15557
15558 NamedDecl *Func = *I;
15559 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15560 if (isa<UsingShadowDecl>(Func))
15561 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15562
15563 bool HasExplicitParameter = false;
15564 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15565 M && M->hasCXXExplicitFunctionObjectParameter())
15566 HasExplicitParameter = true;
15567 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15568 M &&
15569 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15570 HasExplicitParameter = true;
15571
15572 if (HasExplicitParameter)
15573 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15574
15575 // Microsoft supports direct constructor calls.
15576 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15577 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15578 CandidateSet,
15579 /*SuppressUserConversions*/ false);
15580 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15581 // If explicit template arguments were provided, we can't call a
15582 // non-template member function.
15583 if (TemplateArgs)
15584 continue;
15585
15586 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15587 ObjectClassification, Args, CandidateSet,
15588 /*SuppressUserConversions=*/false);
15589 } else {
15590 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15591 I.getPair(), ActingDC, TemplateArgs,
15592 ExplicitObjectType, ObjectClassification,
15593 Args, CandidateSet,
15594 /*SuppressUserConversions=*/false);
15595 }
15596 }
15597
15598 HadMultipleCandidates = (CandidateSet.size() > 1);
15599
15600 DeclarationName DeclName = UnresExpr->getMemberName();
15601
15602 UnbridgedCasts.restore();
15603
15605 bool Succeeded = false;
15606 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15607 Best)) {
15608 case OR_Success:
15609 Method = cast<CXXMethodDecl>(Best->Function);
15610 FoundDecl = Best->FoundDecl;
15611 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15612 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15613 break;
15614 // If FoundDecl is different from Method (such as if one is a template
15615 // and the other a specialization), make sure DiagnoseUseOfDecl is
15616 // called on both.
15617 // FIXME: This would be more comprehensively addressed by modifying
15618 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15619 // being used.
15620 if (Method != FoundDecl.getDecl() &&
15621 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15622 break;
15623 Succeeded = true;
15624 break;
15625
15627 CandidateSet.NoteCandidates(
15629 UnresExpr->getMemberLoc(),
15630 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15631 << DeclName << MemExprE->getSourceRange()),
15632 *this, OCD_AllCandidates, Args);
15633 break;
15634 case OR_Ambiguous:
15635 CandidateSet.NoteCandidates(
15636 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15637 PDiag(diag::err_ovl_ambiguous_member_call)
15638 << DeclName << MemExprE->getSourceRange()),
15639 *this, OCD_AmbiguousCandidates, Args);
15640 break;
15641 case OR_Deleted:
15642 DiagnoseUseOfDeletedFunction(
15643 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15644 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15645 break;
15646 }
15647 // Overload resolution fails, try to recover.
15648 if (!Succeeded)
15649 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15650
15651 ExprResult Res =
15652 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15653 if (Res.isInvalid())
15654 return ExprError();
15655 MemExprE = Res.get();
15656
15657 // If overload resolution picked a static member
15658 // build a non-member call based on that function.
15659 if (Method->isStatic()) {
15660 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15661 ExecConfig, IsExecConfig);
15662 }
15663
15664 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15665 }
15666
15667 QualType ResultType = Method->getReturnType();
15669 ResultType = ResultType.getNonLValueExprType(Context);
15670
15671 assert(Method && "Member call to something that isn't a method?");
15672 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15673
15674 CallExpr *TheCall = nullptr;
15676 if (Method->isExplicitObjectMemberFunction()) {
15677 PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15678 NewArgs);
15679 // Build the actual expression node.
15680 ExprResult FnExpr =
15681 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15682 HadMultipleCandidates, MemExpr->getExprLoc());
15683 if (FnExpr.isInvalid())
15684 return ExprError();
15685
15686 TheCall =
15687 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15688 CurFPFeatureOverrides(), Proto->getNumParams());
15689 } else {
15690 // Convert the object argument (for a non-static member function call).
15691 // We only need to do this if there was actually an overload; otherwise
15692 // it was done at lookup.
15693 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15694 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15695 if (ObjectArg.isInvalid())
15696 return ExprError();
15697 MemExpr->setBase(ObjectArg.get());
15698 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15699 RParenLoc, CurFPFeatureOverrides(),
15700 Proto->getNumParams());
15701 }
15702
15703 // Check for a valid return type.
15704 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15705 TheCall, Method))
15706 return BuildRecoveryExpr(ResultType);
15707
15708 // Convert the rest of the arguments
15709 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15710 RParenLoc))
15711 return BuildRecoveryExpr(ResultType);
15712
15713 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15714
15715 if (CheckFunctionCall(Method, TheCall, Proto))
15716 return ExprError();
15717
15718 // In the case the method to call was not selected by the overloading
15719 // resolution process, we still need to handle the enable_if attribute. Do
15720 // that here, so it will not hide previous -- and more relevant -- errors.
15721 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15722 if (const EnableIfAttr *Attr =
15723 CheckEnableIf(Method, LParenLoc, Args, true)) {
15724 Diag(MemE->getMemberLoc(),
15725 diag::err_ovl_no_viable_member_function_in_call)
15726 << Method << Method->getSourceRange();
15727 Diag(Method->getLocation(),
15728 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15729 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15730 return ExprError();
15731 }
15732 }
15733
15734 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15735 TheCall->getDirectCallee()->isPureVirtual()) {
15736 const FunctionDecl *MD = TheCall->getDirectCallee();
15737
15738 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15739 MemExpr->performsVirtualDispatch(getLangOpts())) {
15740 Diag(MemExpr->getBeginLoc(),
15741 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15742 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15743 << MD->getParent();
15744
15745 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15746 if (getLangOpts().AppleKext)
15747 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15748 << MD->getParent() << MD->getDeclName();
15749 }
15750 }
15751
15752 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15753 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15754 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15755 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15756 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15757 MemExpr->getMemberLoc());
15758 }
15759
15760 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15761 TheCall->getDirectCallee());
15762}
15763
15764/// BuildCallToObjectOfClassType - Build a call to an object of class
15765/// type (C++ [over.call.object]), which can end up invoking an
15766/// overloaded function call operator (@c operator()) or performing a
15767/// user-defined conversion on the object argument.
15770 SourceLocation LParenLoc,
15771 MultiExprArg Args,
15772 SourceLocation RParenLoc) {
15773 if (checkPlaceholderForOverload(*this, Obj))
15774 return ExprError();
15775 ExprResult Object = Obj;
15776
15777 UnbridgedCastsSet UnbridgedCasts;
15778 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15779 return ExprError();
15780
15781 assert(Object.get()->getType()->isRecordType() &&
15782 "Requires object type argument");
15783
15784 // C++ [over.call.object]p1:
15785 // If the primary-expression E in the function call syntax
15786 // evaluates to a class object of type "cv T", then the set of
15787 // candidate functions includes at least the function call
15788 // operators of T. The function call operators of T are obtained by
15789 // ordinary lookup of the name operator() in the context of
15790 // (E).operator().
15791 OverloadCandidateSet CandidateSet(LParenLoc,
15793 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15794
15795 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15796 diag::err_incomplete_object_call, Object.get()))
15797 return true;
15798
15799 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15800 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15801 LookupQualifiedName(R, Record->getDecl());
15802 R.suppressAccessDiagnostics();
15803
15804 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15805 Oper != OperEnd; ++Oper) {
15806 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15807 Object.get()->Classify(Context), Args, CandidateSet,
15808 /*SuppressUserConversion=*/false);
15809 }
15810
15811 // When calling a lambda, both the call operator, and
15812 // the conversion operator to function pointer
15813 // are considered. But when constraint checking
15814 // on the call operator fails, it will also fail on the
15815 // conversion operator as the constraints are always the same.
15816 // As the user probably does not intend to perform a surrogate call,
15817 // we filter them out to produce better error diagnostics, ie to avoid
15818 // showing 2 failed overloads instead of one.
15819 bool IgnoreSurrogateFunctions = false;
15820 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15821 const OverloadCandidate &Candidate = *CandidateSet.begin();
15822 if (!Candidate.Viable &&
15824 IgnoreSurrogateFunctions = true;
15825 }
15826
15827 // C++ [over.call.object]p2:
15828 // In addition, for each (non-explicit in C++0x) conversion function
15829 // declared in T of the form
15830 //
15831 // operator conversion-type-id () cv-qualifier;
15832 //
15833 // where cv-qualifier is the same cv-qualification as, or a
15834 // greater cv-qualification than, cv, and where conversion-type-id
15835 // denotes the type "pointer to function of (P1,...,Pn) returning
15836 // R", or the type "reference to pointer to function of
15837 // (P1,...,Pn) returning R", or the type "reference to function
15838 // of (P1,...,Pn) returning R", a surrogate call function [...]
15839 // is also considered as a candidate function. Similarly,
15840 // surrogate call functions are added to the set of candidate
15841 // functions for each conversion function declared in an
15842 // accessible base class provided the function is not hidden
15843 // within T by another intervening declaration.
15844 const auto &Conversions =
15845 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15846 for (auto I = Conversions.begin(), E = Conversions.end();
15847 !IgnoreSurrogateFunctions && I != E; ++I) {
15848 NamedDecl *D = *I;
15849 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15850 if (isa<UsingShadowDecl>(D))
15851 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15852
15853 // Skip over templated conversion functions; they aren't
15854 // surrogates.
15855 if (isa<FunctionTemplateDecl>(D))
15856 continue;
15857
15858 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15859 if (!Conv->isExplicit()) {
15860 // Strip the reference type (if any) and then the pointer type (if
15861 // any) to get down to what might be a function type.
15862 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15863 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15864 ConvType = ConvPtrType->getPointeeType();
15865
15866 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15867 {
15868 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15869 Object.get(), Args, CandidateSet);
15870 }
15871 }
15872 }
15873
15874 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15875
15876 // Perform overload resolution.
15878 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15879 Best)) {
15880 case OR_Success:
15881 // Overload resolution succeeded; we'll build the appropriate call
15882 // below.
15883 break;
15884
15885 case OR_No_Viable_Function: {
15887 CandidateSet.empty()
15888 ? (PDiag(diag::err_ovl_no_oper)
15889 << Object.get()->getType() << /*call*/ 1
15890 << Object.get()->getSourceRange())
15891 : (PDiag(diag::err_ovl_no_viable_object_call)
15892 << Object.get()->getType() << Object.get()->getSourceRange());
15893 CandidateSet.NoteCandidates(
15894 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15895 OCD_AllCandidates, Args);
15896 break;
15897 }
15898 case OR_Ambiguous:
15899 if (!R.isAmbiguous())
15900 CandidateSet.NoteCandidates(
15901 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15902 PDiag(diag::err_ovl_ambiguous_object_call)
15903 << Object.get()->getType()
15904 << Object.get()->getSourceRange()),
15905 *this, OCD_AmbiguousCandidates, Args);
15906 break;
15907
15908 case OR_Deleted: {
15909 // FIXME: Is this diagnostic here really necessary? It seems that
15910 // 1. we don't have any tests for this diagnostic, and
15911 // 2. we already issue err_deleted_function_use for this later on anyway.
15912 StringLiteral *Msg = Best->Function->getDeletedMessage();
15913 CandidateSet.NoteCandidates(
15914 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15915 PDiag(diag::err_ovl_deleted_object_call)
15916 << Object.get()->getType() << (Msg != nullptr)
15917 << (Msg ? Msg->getString() : StringRef())
15918 << Object.get()->getSourceRange()),
15919 *this, OCD_AllCandidates, Args);
15920 break;
15921 }
15922 }
15923
15924 if (Best == CandidateSet.end())
15925 return true;
15926
15927 UnbridgedCasts.restore();
15928
15929 if (Best->Function == nullptr) {
15930 // Since there is no function declaration, this is one of the
15931 // surrogate candidates. Dig out the conversion function.
15932 CXXConversionDecl *Conv
15933 = cast<CXXConversionDecl>(
15934 Best->Conversions[0].UserDefined.ConversionFunction);
15935
15936 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15937 Best->FoundDecl);
15938 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15939 return ExprError();
15940 assert(Conv == Best->FoundDecl.getDecl() &&
15941 "Found Decl & conversion-to-functionptr should be same, right?!");
15942 // We selected one of the surrogate functions that converts the
15943 // object parameter to a function pointer. Perform the conversion
15944 // on the object argument, then let BuildCallExpr finish the job.
15945
15946 // Create an implicit member expr to refer to the conversion operator.
15947 // and then call it.
15948 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15949 Conv, HadMultipleCandidates);
15950 if (Call.isInvalid())
15951 return ExprError();
15952 // Record usage of conversion in an implicit cast.
15954 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15955 nullptr, VK_PRValue, CurFPFeatureOverrides());
15956
15957 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15958 }
15959
15960 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15961
15962 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15963 // that calls this method, using Object for the implicit object
15964 // parameter and passing along the remaining arguments.
15965 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15966
15967 // An error diagnostic has already been printed when parsing the declaration.
15968 if (Method->isInvalidDecl())
15969 return ExprError();
15970
15971 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15972 unsigned NumParams = Proto->getNumParams();
15973
15974 DeclarationNameInfo OpLocInfo(
15975 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15976 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15977 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15978 Obj, HadMultipleCandidates,
15979 OpLocInfo.getLoc(),
15980 OpLocInfo.getInfo());
15981 if (NewFn.isInvalid())
15982 return true;
15983
15984 SmallVector<Expr *, 8> MethodArgs;
15985 MethodArgs.reserve(NumParams + 1);
15986
15987 bool IsError = false;
15988
15989 // Initialize the object parameter.
15991 if (Method->isExplicitObjectMemberFunction()) {
15992 // FIXME: we should do that during the definition of the lambda when we can.
15993 DiagnoseInvalidExplicitObjectParameterInLambda(Method);
15994 PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15995 } else {
15996 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15997 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15998 if (ObjRes.isInvalid())
15999 IsError = true;
16000 else
16001 Object = ObjRes;
16002 MethodArgs.push_back(Object.get());
16003 }
16004
16006 *this, MethodArgs, Method, Args, LParenLoc);
16007
16008 // If this is a variadic call, handle args passed through "...".
16009 if (Proto->isVariadic()) {
16010 // Promote the arguments (C99 6.5.2.2p7).
16011 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16012 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
16013 nullptr);
16014 IsError |= Arg.isInvalid();
16015 MethodArgs.push_back(Arg.get());
16016 }
16017 }
16018
16019 if (IsError)
16020 return true;
16021
16022 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16023
16024 // Once we've built TheCall, all of the expressions are properly owned.
16025 QualType ResultTy = Method->getReturnType();
16027 ResultTy = ResultTy.getNonLValueExprType(Context);
16028
16030 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16031 CurFPFeatureOverrides());
16032
16033 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16034 return true;
16035
16036 if (CheckFunctionCall(Method, TheCall, Proto))
16037 return true;
16038
16039 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16040}
16041
16042/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
16043/// (if one exists), where @c Base is an expression of class type and
16044/// @c Member is the name of the member we're trying to find.
16047 bool *NoArrowOperatorFound) {
16048 assert(Base->getType()->isRecordType() &&
16049 "left-hand side must have class type");
16050
16052 return ExprError();
16053
16054 SourceLocation Loc = Base->getExprLoc();
16055
16056 // C++ [over.ref]p1:
16057 //
16058 // [...] An expression x->m is interpreted as (x.operator->())->m
16059 // for a class object x of type T if T::operator->() exists and if
16060 // the operator is selected as the best match function by the
16061 // overload resolution mechanism (13.3).
16062 DeclarationName OpName =
16063 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16065
16066 if (RequireCompleteType(Loc, Base->getType(),
16067 diag::err_typecheck_incomplete_tag, Base))
16068 return ExprError();
16069
16070 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16071 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16073
16074 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16075 Oper != OperEnd; ++Oper) {
16076 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16077 std::nullopt, CandidateSet,
16078 /*SuppressUserConversion=*/false);
16079 }
16080
16081 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16082
16083 // Perform overload resolution.
16085 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16086 case OR_Success:
16087 // Overload resolution succeeded; we'll build the call below.
16088 break;
16089
16090 case OR_No_Viable_Function: {
16091 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16092 if (CandidateSet.empty()) {
16093 QualType BaseType = Base->getType();
16094 if (NoArrowOperatorFound) {
16095 // Report this specific error to the caller instead of emitting a
16096 // diagnostic, as requested.
16097 *NoArrowOperatorFound = true;
16098 return ExprError();
16099 }
16100 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16101 << BaseType << Base->getSourceRange();
16102 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16103 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16104 << FixItHint::CreateReplacement(OpLoc, ".");
16105 }
16106 } else
16107 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16108 << "operator->" << Base->getSourceRange();
16109 CandidateSet.NoteCandidates(*this, Base, Cands);
16110 return ExprError();
16111 }
16112 case OR_Ambiguous:
16113 if (!R.isAmbiguous())
16114 CandidateSet.NoteCandidates(
16115 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16116 << "->" << Base->getType()
16117 << Base->getSourceRange()),
16119 return ExprError();
16120
16121 case OR_Deleted: {
16122 StringLiteral *Msg = Best->Function->getDeletedMessage();
16123 CandidateSet.NoteCandidates(
16124 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16125 << "->" << (Msg != nullptr)
16126 << (Msg ? Msg->getString() : StringRef())
16127 << Base->getSourceRange()),
16128 *this, OCD_AllCandidates, Base);
16129 return ExprError();
16130 }
16131 }
16132
16133 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16134
16135 // Convert the object parameter.
16136 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16137
16138 if (Method->isExplicitObjectMemberFunction()) {
16139 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16140 if (R.isInvalid())
16141 return ExprError();
16142 Base = R.get();
16143 } else {
16144 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16145 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16146 if (BaseResult.isInvalid())
16147 return ExprError();
16148 Base = BaseResult.get();
16149 }
16150
16151 // Build the operator call.
16152 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16153 Base, HadMultipleCandidates, OpLoc);
16154 if (FnExpr.isInvalid())
16155 return ExprError();
16156
16157 QualType ResultTy = Method->getReturnType();
16159 ResultTy = ResultTy.getNonLValueExprType(Context);
16160
16161 CallExpr *TheCall =
16162 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16163 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16164
16165 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16166 return ExprError();
16167
16168 if (CheckFunctionCall(Method, TheCall,
16169 Method->getType()->castAs<FunctionProtoType>()))
16170 return ExprError();
16171
16172 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16173}
16174
16175/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
16176/// a literal operator described by the provided lookup results.
16178 DeclarationNameInfo &SuffixInfo,
16179 ArrayRef<Expr*> Args,
16180 SourceLocation LitEndLoc,
16181 TemplateArgumentListInfo *TemplateArgs) {
16182 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16183
16184 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16186 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16187 TemplateArgs);
16188
16189 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16190
16191 // Perform overload resolution. This will usually be trivial, but might need
16192 // to perform substitutions for a literal operator template.
16194 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16195 case OR_Success:
16196 case OR_Deleted:
16197 break;
16198
16200 CandidateSet.NoteCandidates(
16201 PartialDiagnosticAt(UDSuffixLoc,
16202 PDiag(diag::err_ovl_no_viable_function_in_call)
16203 << R.getLookupName()),
16204 *this, OCD_AllCandidates, Args);
16205 return ExprError();
16206
16207 case OR_Ambiguous:
16208 CandidateSet.NoteCandidates(
16209 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16210 << R.getLookupName()),
16211 *this, OCD_AmbiguousCandidates, Args);
16212 return ExprError();
16213 }
16214
16215 FunctionDecl *FD = Best->Function;
16216 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16217 nullptr, HadMultipleCandidates,
16218 SuffixInfo.getLoc(),
16219 SuffixInfo.getInfo());
16220 if (Fn.isInvalid())
16221 return true;
16222
16223 // Check the argument types. This should almost always be a no-op, except
16224 // that array-to-pointer decay is applied to string literals.
16225 Expr *ConvArgs[2];
16226 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16227 ExprResult InputInit = PerformCopyInitialization(
16229 SourceLocation(), Args[ArgIdx]);
16230 if (InputInit.isInvalid())
16231 return true;
16232 ConvArgs[ArgIdx] = InputInit.get();
16233 }
16234
16235 QualType ResultTy = FD->getReturnType();
16237 ResultTy = ResultTy.getNonLValueExprType(Context);
16238
16240 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16241 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16242
16243 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16244 return ExprError();
16245
16246 if (CheckFunctionCall(FD, UDL, nullptr))
16247 return ExprError();
16248
16249 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16250}
16251
16252/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
16253/// given LookupResult is non-empty, it is assumed to describe a member which
16254/// will be invoked. Otherwise, the function will be found via argument
16255/// dependent lookup.
16256/// CallExpr is set to a valid expression and FRS_Success returned on success,
16257/// otherwise CallExpr is set to ExprError() and some non-success value
16258/// is returned.
16261 SourceLocation RangeLoc,
16262 const DeclarationNameInfo &NameInfo,
16263 LookupResult &MemberLookup,
16264 OverloadCandidateSet *CandidateSet,
16265 Expr *Range, ExprResult *CallExpr) {
16266 Scope *S = nullptr;
16267
16269 if (!MemberLookup.empty()) {
16270 ExprResult MemberRef =
16271 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16272 /*IsPtr=*/false, CXXScopeSpec(),
16273 /*TemplateKWLoc=*/SourceLocation(),
16274 /*FirstQualifierInScope=*/nullptr,
16275 MemberLookup,
16276 /*TemplateArgs=*/nullptr, S);
16277 if (MemberRef.isInvalid()) {
16278 *CallExpr = ExprError();
16279 return FRS_DiagnosticIssued;
16280 }
16281 *CallExpr =
16282 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16283 if (CallExpr->isInvalid()) {
16284 *CallExpr = ExprError();
16285 return FRS_DiagnosticIssued;
16286 }
16287 } else {
16288 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16290 NameInfo, UnresolvedSet<0>());
16291 if (FnR.isInvalid())
16292 return FRS_DiagnosticIssued;
16293 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16294
16295 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16296 CandidateSet, CallExpr);
16297 if (CandidateSet->empty() || CandidateSetError) {
16298 *CallExpr = ExprError();
16299 return FRS_NoViableFunction;
16300 }
16302 OverloadingResult OverloadResult =
16303 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16304
16305 if (OverloadResult == OR_No_Viable_Function) {
16306 *CallExpr = ExprError();
16307 return FRS_NoViableFunction;
16308 }
16309 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16310 Loc, nullptr, CandidateSet, &Best,
16311 OverloadResult,
16312 /*AllowTypoCorrection=*/false);
16313 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16314 *CallExpr = ExprError();
16315 return FRS_DiagnosticIssued;
16316 }
16317 }
16318 return FRS_Success;
16319}
16320
16321
16322/// FixOverloadedFunctionReference - E is an expression that refers to
16323/// a C++ overloaded function (possibly with some parentheses and
16324/// perhaps a '&' around it). We have resolved the overloaded function
16325/// to the function declaration Fn, so patch up the expression E to
16326/// refer (possibly indirectly) to Fn. Returns the new expr.
16328 FunctionDecl *Fn) {
16329 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16330 ExprResult SubExpr =
16331 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16332 if (SubExpr.isInvalid())
16333 return ExprError();
16334 if (SubExpr.get() == PE->getSubExpr())
16335 return PE;
16336
16337 return new (Context)
16338 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16339 }
16340
16341 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16342 ExprResult SubExpr =
16343 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16344 if (SubExpr.isInvalid())
16345 return ExprError();
16346 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16347 SubExpr.get()->getType()) &&
16348 "Implicit cast type cannot be determined from overload");
16349 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16350 if (SubExpr.get() == ICE->getSubExpr())
16351 return ICE;
16352
16353 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16354 SubExpr.get(), nullptr, ICE->getValueKind(),
16355 CurFPFeatureOverrides());
16356 }
16357
16358 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16359 if (!GSE->isResultDependent()) {
16360 ExprResult SubExpr =
16361 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16362 if (SubExpr.isInvalid())
16363 return ExprError();
16364 if (SubExpr.get() == GSE->getResultExpr())
16365 return GSE;
16366
16367 // Replace the resulting type information before rebuilding the generic
16368 // selection expression.
16369 ArrayRef<Expr *> A = GSE->getAssocExprs();
16370 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16371 unsigned ResultIdx = GSE->getResultIndex();
16372 AssocExprs[ResultIdx] = SubExpr.get();
16373
16374 if (GSE->isExprPredicate())
16376 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16377 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16378 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16379 ResultIdx);
16381 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16382 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16383 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16384 ResultIdx);
16385 }
16386 // Rather than fall through to the unreachable, return the original generic
16387 // selection expression.
16388 return GSE;
16389 }
16390
16391 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16392 assert(UnOp->getOpcode() == UO_AddrOf &&
16393 "Can only take the address of an overloaded function");
16394 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16395 if (Method->isStatic()) {
16396 // Do nothing: static member functions aren't any different
16397 // from non-member functions.
16398 } else {
16399 // Fix the subexpression, which really has to be an
16400 // UnresolvedLookupExpr holding an overloaded member function
16401 // or template.
16402 ExprResult SubExpr =
16403 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16404 if (SubExpr.isInvalid())
16405 return ExprError();
16406 if (SubExpr.get() == UnOp->getSubExpr())
16407 return UnOp;
16408
16409 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16410 SubExpr.get(), Method))
16411 return ExprError();
16412
16413 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16414 "fixed to something other than a decl ref");
16415 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16416 "fixed to a member ref with no nested name qualifier");
16417
16418 // We have taken the address of a pointer to member
16419 // function. Perform the computation here so that we get the
16420 // appropriate pointer to member type.
16421 QualType ClassType
16422 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16423 QualType MemPtrType
16424 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16425 // Under the MS ABI, lock down the inheritance model now.
16426 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16427 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16428
16429 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16430 MemPtrType, VK_PRValue, OK_Ordinary,
16431 UnOp->getOperatorLoc(), false,
16432 CurFPFeatureOverrides());
16433 }
16434 }
16435 ExprResult SubExpr =
16436 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16437 if (SubExpr.isInvalid())
16438 return ExprError();
16439 if (SubExpr.get() == UnOp->getSubExpr())
16440 return UnOp;
16441
16442 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16443 SubExpr.get());
16444 }
16445
16446 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16447 // FIXME: avoid copy.
16448 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16449 if (ULE->hasExplicitTemplateArgs()) {
16450 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16451 TemplateArgs = &TemplateArgsBuffer;
16452 }
16453
16454 QualType Type = Fn->getType();
16455 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16456
16457 // FIXME: Duplicated from BuildDeclarationNameExpr.
16458 if (unsigned BID = Fn->getBuiltinID()) {
16459 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16460 Type = Context.BuiltinFnTy;
16461 ValueKind = VK_PRValue;
16462 }
16463 }
16464
16465 DeclRefExpr *DRE = BuildDeclRefExpr(
16466 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16467 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16468 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16469 return DRE;
16470 }
16471
16472 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16473 // FIXME: avoid copy.
16474 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16475 if (MemExpr->hasExplicitTemplateArgs()) {
16476 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16477 TemplateArgs = &TemplateArgsBuffer;
16478 }
16479
16480 Expr *Base;
16481
16482 // If we're filling in a static method where we used to have an
16483 // implicit member access, rewrite to a simple decl ref.
16484 if (MemExpr->isImplicitAccess()) {
16485 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16486 DeclRefExpr *DRE = BuildDeclRefExpr(
16487 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16488 MemExpr->getQualifierLoc(), Found.getDecl(),
16489 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16490 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16491 return DRE;
16492 } else {
16493 SourceLocation Loc = MemExpr->getMemberLoc();
16494 if (MemExpr->getQualifier())
16495 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16496 Base =
16497 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16498 }
16499 } else
16500 Base = MemExpr->getBase();
16501
16502 ExprValueKind valueKind;
16503 QualType type;
16504 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16505 valueKind = VK_LValue;
16506 type = Fn->getType();
16507 } else {
16508 valueKind = VK_PRValue;
16509 type = Context.BoundMemberTy;
16510 }
16511
16512 return BuildMemberExpr(
16513 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16514 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16515 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16516 type, valueKind, OK_Ordinary, TemplateArgs);
16517 }
16518
16519 llvm_unreachable("Invalid reference to overloaded function");
16520}
16521
16523 DeclAccessPair Found,
16524 FunctionDecl *Fn) {
16525 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16526}
16527
16528bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16530 if (!PartialOverloading || !Function)
16531 return true;
16532 if (Function->isVariadic())
16533 return false;
16534 if (const auto *Proto =
16535 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16536 if (Proto->isTemplateVariadic())
16537 return false;
16538 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16539 if (const auto *Proto =
16540 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16541 if (Proto->isTemplateVariadic())
16542 return false;
16543 return true;
16544}
16545
16547 DeclarationName Name,
16548 OverloadCandidateSet &CandidateSet,
16549 FunctionDecl *Fn, MultiExprArg Args,
16550 bool IsMember) {
16551 StringLiteral *Msg = Fn->getDeletedMessage();
16552 CandidateSet.NoteCandidates(
16553 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16554 << IsMember << Name << (Msg != nullptr)
16555 << (Msg ? Msg->getString() : StringRef())
16556 << Range),
16557 *this, OCD_AllCandidates, Args);
16558}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3273
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:30
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:5703
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.
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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)
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 bool IsOverloaded(const UnresolvedSetImpl &Functions)
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 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)
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:867
iterator end()
Definition: Lookup.h:891
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:883
iterator begin()
Definition: Lookup.h:890
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:888
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:2756
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:2563
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:2579
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:1589
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:2260
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:1277
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:2155
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
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:2062
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2606
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:2329
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1102
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
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:1286
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
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:1567
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:2150
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
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:3308
QualType getElementType() const
Definition: Type.h:3320
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6979
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:4781
Pointer to a block type.
Definition: Type.h:3139
This class is used for builtin types like 'int'.
Definition: Type.h:2771
Kind getKind() const
Definition: Type.h:2813
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:2532
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2859
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2895
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2899
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:2057
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:2453
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2211
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2574
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2233
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2183
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2563
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2486
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2218
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2207
bool isStatic() const
Definition: DeclCXX.cpp:2185
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:1021
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1832
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:1593
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:73
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
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:2876
QualType getElementType() const
Definition: Type.h:2886
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:4803
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3346
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:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2065
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2190
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1938
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2058
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:85
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:1215
T * getAttr() const
Definition: DeclBase.h:578
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:598
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:1116
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:593
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:564
SourceLocation getLocation() const
Definition: DeclBase.h:444
DeclContext * getDeclContext()
Definition: DeclBase.h:453
AccessSpecifier getAccess() const
Definition: DeclBase.h:512
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:574
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:569
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:582
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:3868
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4073
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5365
EnumDecl * getDecl() const
Definition: Type.h:5372
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1896
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1920
const Expr * getExpr() const
Definition: DeclCXX.h:1905
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2143
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:4079
@ 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:3918
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:901
Represents a member of a struct/union/class.
Definition: Decl.h:3058
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:2600
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
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:2697
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2668
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:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
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:2696
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4239
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2503
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:2433
bool isDeletedAsWritten() const
Definition: Decl.h:2507
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:2348
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4397
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
bool isConsteval() const
Definition: Decl.h:2445
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:2772
void getAssociatedConstraints(SmallVectorImpl< const Expr * > &AC) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2662
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
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4014
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:2596
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4446
unsigned getNumParams() const
Definition: Type.h:4679
Qualifiers getMethodQuals() const
Definition: Type.h:4820
QualType getParamType(unsigned i) const
Definition: Type.h:4681
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4802
ArrayRef< QualType > param_types() const
Definition: Type.h:4834
Declaration of a template function.
Definition: DeclTemplate.h:958
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:4157
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4231
bool getNoReturn() const
Definition: Type.h:4205
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4046
ExtInfo getExtInfo() const
Definition: Type.h:4375
CallingConv getCallConv() const
Definition: Type.h:4374
QualType getReturnType() const
Definition: Type.h:4363
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4387
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:4470
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:3214
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:613
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:603
DeclClass * getAsSingle() const
Definition: Lookup.h:556
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:662
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:639
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
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:3250
QualType getPointeeType() const
Definition: Type.h:3266
const Type * getClass() const
Definition: Type.h:3280
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:1152
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6742
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:6798
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:6887
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:6856
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6810
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:6850
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1787
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:6862
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:2976
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3091
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3127
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3036
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3088
decls_iterator decls_begin() const
Definition: ExprCXX.h:3068
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3079
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3101
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3097
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3147
decls_iterator decls_end() const
Definition: ExprCXX.h:3071
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3085
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:2929
QualType getPointeeType() const
Definition: Type.h:2939
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4875
A (possibly-)qualified type.
Definition: Type.h:738
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7233
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7227
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7238
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3454
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1018
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:7331
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7149
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7275
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7189
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:7350
QualType getCanonicalType() const
Definition: Type.h:7201
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7243
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:890
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7321
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7222
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7270
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7195
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1125
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7181
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7089
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7096
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4272
bool hasAtomic() const
Definition: Type.h:642
bool hasRestrict() const
Definition: Type.h:641
QualifiersAndAtomic withVolatile()
Definition: Type.h:654
QualifiersAndAtomic withAtomic()
Definition: Type.h:661
bool hasVolatile() const
Definition: Type.h:639
The collection of all-type qualifiers we support.
Definition: Type.h:148
unsigned getCVRQualifiers() const
Definition: Type.h:296
GC getObjCGCAttr() const
Definition: Type.h:327
bool hasOnlyConst() const
Definition: Type.h:266
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:176
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:169
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:182
void removeObjCLifetime()
Definition: Type.h:359
bool hasConst() const
Definition: Type.h:265
void addRestrict()
Definition: Type.h:288
bool hasRestrict() const
Definition: Type.h:285
void removeObjCGCAttr()
Definition: Type.h:331
void removeUnaligned()
Definition: Type.h:323
void removeAddressSpace()
Definition: Type.h:404
void addConst()
Definition: Type.h:268
void setAddressSpace(LangAS space)
Definition: Type.h:399
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:496
bool hasVolatile() const
Definition: Type.h:275
bool hasObjCGCAttr() const
Definition: Type.h:326
ObjCLifetime getObjCLifetime() const
Definition: Type.h:353
Qualifiers withoutObjCLifetime() const
Definition: Type.h:341
bool empty() const
Definition: Type.h:441
std::string getAsString() const
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:533
LangAS getAddressSpace() const
Definition: Type.h:379
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:554
void addVolatile()
Definition: Type.h:278
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:356
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3232
Represents a struct/union/class.
Definition: Decl.h:4169
field_range fields() const
Definition: Decl.h:4375
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5339
RecordDecl * getDecl() const
Definition: Type.h:5349
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:3170
QualType getPointeeType() const
Definition: Type.h:3188
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
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:8048
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:4680
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4709
RAII class to control scope of DeferDiags.
Definition: Sema.h:7897
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:9500
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9530
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
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:2476
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:7913
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:7368
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:7380
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7376
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:167
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:998
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:8131
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8134
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8140
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8138
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...
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:1420
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:858
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:524
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.
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:527
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:8348
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:7939
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:775
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:9259
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:63
const LangOptions & getLangOpts() const
Definition: Sema.h:520
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:6655
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:856
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:6923
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
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:10023
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:651
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3449
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11724
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:996
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8535
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.
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6090
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6129
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6108
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6092
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6125
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20256
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21225
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:10476
AssignmentAction
Definition: Sema.h:5195
@ AA_Converting
Definition: Sema.h:5199
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...
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:5718
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:7798
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:7844
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
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:227
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:11699
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3334
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:8018
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:8023
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:8024
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:8022
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:8021
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:7915
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:861
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2414
DiagnosticsEngine & Diags
Definition: Sema.h:860
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
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:21451
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:10647
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.
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE=nullptr)
Builds an expression which might be an implicit member expression.
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:6729
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:1235
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:634
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:687
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:672
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
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:5879
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3415
The base class of the type hierarchy.
Definition: Type.h:1607
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2190
bool isBlockPointerType() const
Definition: Type.h:7410
bool isVoidType() const
Definition: Type.h:7695
bool isBooleanType() const
Definition: Type.h:7823
bool isObjCBuiltinType() const
Definition: Type.h:7585
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2155
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:1887
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isIncompleteArrayType() const
Definition: Type.h:7476
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2134
bool isFloat16Type() const
Definition: Type.h:7704
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:666
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool isRValueReferenceType() const
Definition: Type.h:7422
bool isConstantArrayType() const
Definition: Type.h:7472
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7850
bool isArrayType() const
Definition: Type.h:7468
bool isCharType() const
Definition: Type.cpp:2077
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:7760
bool isArithmeticType() const
Definition: Type.cpp:2269
bool isPointerType() const
Definition: Type.h:7402
bool isArrayParameterType() const
Definition: Type.h:7484
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7735
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2460
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7980
bool isReferenceType() const
Definition: Type.h:7414
bool isEnumeralType() const
Definition: Type.h:7500
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
bool isObjCQualifiedIdType() const
Definition: Type.h:7555
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7810
bool isExtVectorType() const
Definition: Type.h:7512
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2113
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7542
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2451
bool isLValueReferenceType() const
Definition: Type.h:7418
bool isBitIntType() const
Definition: Type.h:7630
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2443
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2326
bool isAnyComplexType() const
Definition: Type.h:7504
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7748
bool isHalfType() const
Definition: Type.h:7699
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7677
bool isQueueT() const
Definition: Type.h:7611
bool isMemberPointerType() const
Definition: Type.h:7450
bool isObjCIdType() const
Definition: Type.h:7567
bool isMatrixType() const
Definition: Type.h:7522
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7829
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2195
bool isEventT() const
Definition: Type.h:7603
bool isBFloat16Type() const
Definition: Type.h:7716
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7398
bool isObjCObjectPointerType() const
Definition: Type.h:7534
bool isVectorType() const
Definition: Type.h:7508
bool isObjCClassType() const
Definition: Type.h:7573
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
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:2184
bool isAnyPointerType() const
Definition: Type.h:7406
TypeClass getTypeClass() const
Definition: Type.h:2094
bool isSamplerT() const
Definition: Type.h:7599
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7913
bool isNullPtrType() const
Definition: Type.h:7728
bool isRecordType() const
Definition: Type.h:7496
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:4838
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:3173
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:3252
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3241
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:373
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3915
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4023
QualType getBaseType() const
Definition: ExprCXX.h:3997
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4007
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:3988
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4033
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4027
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:3759
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:60
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:131
@ 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:1556
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1559
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1562
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:431
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:1274
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:373
@ 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.
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:21
#define false
Definition: stdbool.h:22
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:4525
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4533
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:9796
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:9884
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9916
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8148
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6378
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.