clang 20.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
13#include "CheckExprLifetime.h"
15#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/Type.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/Support/Casting.h"
49#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdlib>
53#include <optional>
54
55using namespace clang;
56using namespace sema;
57
59
61 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
62 return P->hasAttr<PassObjectSizeAttr>();
63 });
64}
65
66/// A convenience routine for creating a decayed reference to a function.
68 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
69 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
70 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
71 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
72 return ExprError();
73 // If FoundDecl is different from Fn (such as if one is a template
74 // and the other a specialization), make sure DiagnoseUseOfDecl is
75 // called on both.
76 // FIXME: This would be more comprehensively addressed by modifying
77 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
78 // being used.
79 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
80 return ExprError();
81 DeclRefExpr *DRE = new (S.Context)
82 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
83 if (HadMultipleCandidates)
84 DRE->setHadMultipleCandidates(true);
85
87 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
88 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
90 DRE->setType(Fn->getType());
91 }
92 }
93 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
94 CK_FunctionToPointerDecay);
95}
96
97static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
98 bool InOverloadResolution,
100 bool CStyle,
101 bool AllowObjCWritebackConversion);
102
104 QualType &ToType,
105 bool InOverloadResolution,
107 bool CStyle);
109IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
111 OverloadCandidateSet& Conversions,
112 AllowedExplicit AllowExplicit,
113 bool AllowObjCConversionOnExplicit);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
127 const StandardConversionSequence& SCS1,
128 const StandardConversionSequence& SCS2);
129
130/// GetConversionRank - Retrieve the implicit conversion rank
131/// corresponding to the given implicit conversion kind.
133 static const ImplicitConversionRank Rank[] = {
160 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
161 // it was omitted by the patch that added
162 // ICK_Zero_Event_Conversion
163 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Queue_Conversion
172 };
173 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
174 return Rank[(int)Kind];
175}
176
179 ImplicitConversionKind Dimension) {
181 if (Rank == ICR_HLSL_Scalar_Widening) {
182 if (Base == ICR_Promotion)
184 if (Base == ICR_Conversion)
186 }
187 if (Rank == ICR_HLSL_Dimension_Reduction) {
188 if (Base == ICR_Promotion)
190 if (Base == ICR_Conversion)
192 }
193 return Rank;
194}
195
196/// GetImplicitConversionName - Return the name of this kind of
197/// implicit conversion.
199 static const char *const Name[] = {
200 "No conversion",
201 "Lvalue-to-rvalue",
202 "Array-to-pointer",
203 "Function-to-pointer",
204 "Function pointer conversion",
205 "Qualification",
206 "Integral promotion",
207 "Floating point promotion",
208 "Complex promotion",
209 "Integral conversion",
210 "Floating conversion",
211 "Complex conversion",
212 "Floating-integral conversion",
213 "Pointer conversion",
214 "Pointer-to-member conversion",
215 "Boolean conversion",
216 "Compatible-types conversion",
217 "Derived-to-base conversion",
218 "Vector conversion",
219 "SVE Vector conversion",
220 "RVV Vector conversion",
221 "Vector splat",
222 "Complex-real conversion",
223 "Block Pointer conversion",
224 "Transparent Union Conversion",
225 "Writeback conversion",
226 "OpenCL Zero Event Conversion",
227 "OpenCL Zero Queue Conversion",
228 "C specific type conversion",
229 "Incompatible pointer conversion",
230 "Fixed point conversion",
231 "HLSL vector truncation",
232 "Non-decaying array conversion",
233 "HLSL vector splat",
234 };
235 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
236 return Name[Kind];
237}
238
239/// StandardConversionSequence - Set the standard conversion
240/// sequence to the identity conversion.
248 ReferenceBinding = false;
249 DirectBinding = false;
250 IsLvalueReference = true;
251 BindsToFunctionLvalue = false;
252 BindsToRvalue = false;
255 CopyConstructor = nullptr;
256}
257
258/// getRank - Retrieve the rank of this standard conversion sequence
259/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
260/// implicit conversions.
263 if (GetConversionRank(First) > Rank)
264 Rank = GetConversionRank(First);
265 if (GetConversionRank(Second) > Rank)
267 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
269 if (GetConversionRank(Third) > Rank)
270 Rank = GetConversionRank(Third);
271 return Rank;
272}
273
274/// isPointerConversionToBool - Determines whether this conversion is
275/// a conversion of a pointer or pointer-to-member to bool. This is
276/// used as part of the ranking of standard conversion sequences
277/// (C++ 13.3.3.2p4).
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer or function-to-pointer implicit conversions, so
281 // check for their presence as well as checking whether FromType is
282 // a pointer.
283 if (getToType(1)->isBooleanType() &&
284 (getFromType()->isPointerType() ||
285 getFromType()->isMemberPointerType() ||
286 getFromType()->isObjCObjectPointerType() ||
287 getFromType()->isBlockPointerType() ||
289 return true;
290
291 return false;
292}
293
294/// isPointerConversionToVoidPointer - Determines whether this
295/// conversion is a conversion of a pointer to a void pointer. This is
296/// used as part of the ranking of standard conversion sequences (C++
297/// 13.3.3.2p4).
298bool
301 QualType FromType = getFromType();
302 QualType ToType = getToType(1);
303
304 // Note that FromType has not necessarily been transformed by the
305 // array-to-pointer implicit conversion, so check for its presence
306 // and redo the conversion to get a pointer.
308 FromType = Context.getArrayDecayedType(FromType);
309
310 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
311 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
312 return ToPtrType->getPointeeType()->isVoidType();
313
314 return false;
315}
316
317/// Skip any implicit casts which could be either part of a narrowing conversion
318/// or after one in an implicit conversion.
320 const Expr *Converted) {
321 // We can have cleanups wrapping the converted expression; these need to be
322 // preserved so that destructors run if necessary.
323 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
324 Expr *Inner =
325 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
326 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
327 EWC->getObjects());
328 }
329
330 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
331 switch (ICE->getCastKind()) {
332 case CK_NoOp:
333 case CK_IntegralCast:
334 case CK_IntegralToBoolean:
335 case CK_IntegralToFloating:
336 case CK_BooleanToSignedIntegral:
337 case CK_FloatingToIntegral:
338 case CK_FloatingToBoolean:
339 case CK_FloatingCast:
340 Converted = ICE->getSubExpr();
341 continue;
342
343 default:
344 return Converted;
345 }
346 }
347
348 return Converted;
349}
350
351/// Check if this standard conversion sequence represents a narrowing
352/// conversion, according to C++11 [dcl.init.list]p7.
353///
354/// \param Ctx The AST context.
355/// \param Converted The result of applying this standard conversion sequence.
356/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
357/// value of the expression prior to the narrowing conversion.
358/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
359/// type of the expression prior to the narrowing conversion.
360/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
361/// from floating point types to integral types should be ignored.
363 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
364 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
365 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
366 "narrowing check outside C++");
367
368 // C++11 [dcl.init.list]p7:
369 // A narrowing conversion is an implicit conversion ...
370 QualType FromType = getToType(0);
371 QualType ToType = getToType(1);
372
373 // A conversion to an enumeration type is narrowing if the conversion to
374 // the underlying type is narrowing. This only arises for expressions of
375 // the form 'Enum{init}'.
376 if (auto *ET = ToType->getAs<EnumType>())
377 ToType = ET->getDecl()->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
385 goto IntegralConversion;
386 // -- from a pointer type or pointer-to-member type to bool, or
387 return NK_Type_Narrowing;
388
389 // -- from a floating-point type to an integer type, or
390 //
391 // -- from an integer type or unscoped enumeration type to a floating-point
392 // type, except where the source is a constant expression and the actual
393 // value after conversion will fit into the target type and will produce
394 // the original value when converted back to the original type, or
396 FloatingIntegralConversion:
397 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
398 return NK_Type_Narrowing;
399 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
400 ToType->isRealFloatingType()) {
401 if (IgnoreFloatToIntegralConversion)
402 return NK_Not_Narrowing;
403 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 assert(Initializer && "Unknown conversion expression");
405
406 // If it's value-dependent, we can't tell whether it's narrowing.
407 if (Initializer->isValueDependent())
409
410 if (std::optional<llvm::APSInt> IntConstantValue =
411 Initializer->getIntegerConstantExpr(Ctx)) {
412 // Convert the integer to the floating type.
413 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
414 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
415 llvm::APFloat::rmNearestTiesToEven);
416 // And back.
417 llvm::APSInt ConvertedValue = *IntConstantValue;
418 bool ignored;
419 Result.convertToInteger(ConvertedValue,
420 llvm::APFloat::rmTowardZero, &ignored);
421 // If the resulting value is different, this was a narrowing conversion.
422 if (*IntConstantValue != ConvertedValue) {
423 ConstantValue = APValue(*IntConstantValue);
424 ConstantType = Initializer->getType();
426 }
427 } else {
428 // Variables are always narrowings.
430 }
431 }
432 return NK_Not_Narrowing;
433
434 // -- from long double to double or float, or from double to float, except
435 // where the source is a constant expression and the actual value after
436 // conversion is within the range of values that can be represented (even
437 // if it cannot be represented exactly), or
439 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
440 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
441 // FromType is larger than ToType.
442 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
443
444 // If it's value-dependent, we can't tell whether it's narrowing.
445 if (Initializer->isValueDependent())
447
449 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
450 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
451 // Constant!
452 if (Ctx.getLangOpts().C23)
453 ConstantValue = R.Val;
454 assert(ConstantValue.isFloat());
455 llvm::APFloat FloatVal = ConstantValue.getFloat();
456 // Convert the source value into the target type.
457 bool ignored;
458 llvm::APFloat Converted = FloatVal;
459 llvm::APFloat::opStatus ConvertStatus =
460 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
461 llvm::APFloat::rmNearestTiesToEven, &ignored);
462 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
463 llvm::APFloat::rmNearestTiesToEven, &ignored);
464 if (Ctx.getLangOpts().C23) {
465 if (FloatVal.isNaN() && Converted.isNaN() &&
466 !FloatVal.isSignaling() && !Converted.isSignaling()) {
467 // Quiet NaNs are considered the same value, regardless of
468 // payloads.
469 return NK_Not_Narrowing;
470 }
471 // For normal values, check exact equality.
472 if (!Converted.bitwiseIsEqual(FloatVal)) {
473 ConstantType = Initializer->getType();
475 }
476 } else {
477 // If there was no overflow, the source value is within the range of
478 // values that can be represented.
479 if (ConvertStatus & llvm::APFloat::opOverflow) {
480 ConstantType = Initializer->getType();
482 }
483 }
484 } else {
486 }
487 }
488 return NK_Not_Narrowing;
489
490 // -- from an integer type or unscoped enumeration type to an integer type
491 // that cannot represent all the values of the original type, except where
492 // the source is a constant expression and the actual value after
493 // conversion will fit into the target type and will produce the original
494 // value when converted back to the original type.
496 IntegralConversion: {
497 assert(FromType->isIntegralOrUnscopedEnumerationType());
498 assert(ToType->isIntegralOrUnscopedEnumerationType());
499 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
500 const unsigned FromWidth = Ctx.getIntWidth(FromType);
501 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
502 const unsigned ToWidth = Ctx.getIntWidth(ToType);
503
504 if (FromWidth > ToWidth ||
505 (FromWidth == ToWidth && FromSigned != ToSigned) ||
506 (FromSigned && !ToSigned)) {
507 // Not all values of FromType can be represented in ToType.
508 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
509
510 // If it's value-dependent, we can't tell whether it's narrowing.
511 if (Initializer->isValueDependent())
513
514 std::optional<llvm::APSInt> OptInitializerValue;
515 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
516 // Such conversions on variables are always narrowing.
518 }
519 llvm::APSInt &InitializerValue = *OptInitializerValue;
520 bool Narrowing = false;
521 if (FromWidth < ToWidth) {
522 // Negative -> unsigned is narrowing. Otherwise, more bits is never
523 // narrowing.
524 if (InitializerValue.isSigned() && InitializerValue.isNegative())
525 Narrowing = true;
526 } else {
527 // Add a bit to the InitializerValue so we don't have to worry about
528 // signed vs. unsigned comparisons.
529 InitializerValue = InitializerValue.extend(
530 InitializerValue.getBitWidth() + 1);
531 // Convert the initializer to and from the target width and signed-ness.
532 llvm::APSInt ConvertedValue = InitializerValue;
533 ConvertedValue = ConvertedValue.trunc(ToWidth);
534 ConvertedValue.setIsSigned(ToSigned);
535 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
536 ConvertedValue.setIsSigned(InitializerValue.isSigned());
537 // If the result is different, this was a narrowing conversion.
538 if (ConvertedValue != InitializerValue)
539 Narrowing = true;
540 }
541 if (Narrowing) {
542 ConstantType = Initializer->getType();
543 ConstantValue = APValue(InitializerValue);
545 }
546 }
547 return NK_Not_Narrowing;
548 }
549 case ICK_Complex_Real:
550 if (FromType->isComplexType() && !ToType->isComplexType())
551 return NK_Type_Narrowing;
552 return NK_Not_Narrowing;
553
555 if (Ctx.getLangOpts().C23) {
556 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
558 if (Initializer->EvaluateAsRValue(R, Ctx)) {
559 ConstantValue = R.Val;
560 assert(ConstantValue.isFloat());
561 llvm::APFloat FloatVal = ConstantValue.getFloat();
562 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
563 // value, the unqualified versions of the type of the initializer and
564 // the corresponding real type of the object declared shall be
565 // compatible.
566 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
567 ConstantType = Initializer->getType();
569 }
570 }
571 }
572 return NK_Not_Narrowing;
573 default:
574 // Other kinds of conversions are not narrowings.
575 return NK_Not_Narrowing;
576 }
577}
578
579/// dump - Print this standard conversion sequence to standard
580/// error. Useful for debugging overloading issues.
581LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
582 raw_ostream &OS = llvm::errs();
583 bool PrintedSomething = false;
584 if (First != ICK_Identity) {
586 PrintedSomething = true;
587 }
588
589 if (Second != ICK_Identity) {
590 if (PrintedSomething) {
591 OS << " -> ";
592 }
594
595 if (CopyConstructor) {
596 OS << " (by copy constructor)";
597 } else if (DirectBinding) {
598 OS << " (direct reference binding)";
599 } else if (ReferenceBinding) {
600 OS << " (reference binding)";
601 }
602 PrintedSomething = true;
603 }
604
605 if (Third != ICK_Identity) {
606 if (PrintedSomething) {
607 OS << " -> ";
608 }
610 PrintedSomething = true;
611 }
612
613 if (!PrintedSomething) {
614 OS << "No conversions required";
615 }
616}
617
618/// dump - Print this user-defined conversion sequence to standard
619/// error. Useful for debugging overloading issues.
621 raw_ostream &OS = llvm::errs();
622 if (Before.First || Before.Second || Before.Third) {
623 Before.dump();
624 OS << " -> ";
625 }
627 OS << '\'' << *ConversionFunction << '\'';
628 else
629 OS << "aggregate initialization";
630 if (After.First || After.Second || After.Third) {
631 OS << " -> ";
632 After.dump();
633 }
634}
635
636/// dump - Print this implicit conversion sequence to standard
637/// error. Useful for debugging overloading issues.
639 raw_ostream &OS = llvm::errs();
641 OS << "Worst list element conversion: ";
642 switch (ConversionKind) {
644 OS << "Standard conversion: ";
645 Standard.dump();
646 break;
648 OS << "User-defined conversion: ";
650 break;
652 OS << "Ellipsis conversion";
653 break;
655 OS << "Ambiguous conversion";
656 break;
657 case BadConversion:
658 OS << "Bad conversion";
659 break;
660 }
661
662 OS << "\n";
663}
664
666 new (&conversions()) ConversionSet();
667}
668
670 conversions().~ConversionSet();
671}
672
673void
678}
679
680namespace {
681 // Structure used by DeductionFailureInfo to store
682 // template argument information.
683 struct DFIArguments {
684 TemplateArgument FirstArg;
685 TemplateArgument SecondArg;
686 };
687 // Structure used by DeductionFailureInfo to store
688 // template parameter and template argument information.
689 struct DFIParamWithArguments : DFIArguments {
690 TemplateParameter Param;
691 };
692 // Structure used by DeductionFailureInfo to store template argument
693 // information and the index of the problematic call argument.
694 struct DFIDeducedMismatchArgs : DFIArguments {
695 TemplateArgumentList *TemplateArgs;
696 unsigned CallArgIndex;
697 };
698 // Structure used by DeductionFailureInfo to store information about
699 // unsatisfied constraints.
700 struct CNSInfo {
701 TemplateArgumentList *TemplateArgs;
702 ConstraintSatisfaction Satisfaction;
703 };
704}
705
706/// Convert from Sema's representation of template deduction information
707/// to the form used in overload-candidate information.
711 TemplateDeductionInfo &Info) {
713 Result.Result = static_cast<unsigned>(TDK);
714 Result.HasDiagnostic = false;
715 switch (TDK) {
722 Result.Data = nullptr;
723 break;
724
727 Result.Data = Info.Param.getOpaqueValue();
728 break;
729
732 // FIXME: Should allocate from normal heap so that we can free this later.
733 auto *Saved = new (Context) DFIDeducedMismatchArgs;
734 Saved->FirstArg = Info.FirstArg;
735 Saved->SecondArg = Info.SecondArg;
736 Saved->TemplateArgs = Info.takeSugared();
737 Saved->CallArgIndex = Info.CallArgIndex;
738 Result.Data = Saved;
739 break;
740 }
741
743 // FIXME: Should allocate from normal heap so that we can free this later.
744 DFIArguments *Saved = new (Context) DFIArguments;
745 Saved->FirstArg = Info.FirstArg;
746 Saved->SecondArg = Info.SecondArg;
747 Result.Data = Saved;
748 break;
749 }
750
752 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
755 // FIXME: Should allocate from normal heap so that we can free this later.
756 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
757 Saved->Param = Info.Param;
758 Saved->FirstArg = Info.FirstArg;
759 Saved->SecondArg = Info.SecondArg;
760 Result.Data = Saved;
761 break;
762 }
763
765 Result.Data = Info.takeSugared();
766 if (Info.hasSFINAEDiagnostic()) {
770 Result.HasDiagnostic = true;
771 }
772 break;
773
775 CNSInfo *Saved = new (Context) CNSInfo;
776 Saved->TemplateArgs = Info.takeSugared();
777 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
778 Result.Data = Saved;
779 break;
780 }
781
785 llvm_unreachable("not a deduction failure");
786 }
787
788 return Result;
789}
790
792 switch (static_cast<TemplateDeductionResult>(Result)) {
802 break;
803
810 // FIXME: Destroy the data?
811 Data = nullptr;
812 break;
813
815 // FIXME: Destroy the template argument list?
816 Data = nullptr;
818 Diag->~PartialDiagnosticAt();
819 HasDiagnostic = false;
820 }
821 break;
822
824 // FIXME: Destroy the template argument list?
825 Data = nullptr;
827 Diag->~PartialDiagnosticAt();
828 HasDiagnostic = false;
829 }
830 break;
831
832 // Unhandled
835 break;
836 }
837}
838
840 if (HasDiagnostic)
841 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
842 return nullptr;
843}
844
846 switch (static_cast<TemplateDeductionResult>(Result)) {
859 return TemplateParameter();
860
863 return TemplateParameter::getFromOpaqueValue(Data);
864
868 return static_cast<DFIParamWithArguments*>(Data)->Param;
869
870 // Unhandled
873 break;
874 }
875
876 return TemplateParameter();
877}
878
880 switch (static_cast<TemplateDeductionResult>(Result)) {
894 return nullptr;
895
898 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
899
901 return static_cast<TemplateArgumentList*>(Data);
902
904 return static_cast<CNSInfo*>(Data)->TemplateArgs;
905
906 // Unhandled
909 break;
910 }
911
912 return nullptr;
913}
914
916 switch (static_cast<TemplateDeductionResult>(Result)) {
928 return nullptr;
929
936 return &static_cast<DFIArguments*>(Data)->FirstArg;
937
938 // Unhandled
941 break;
942 }
943
944 return nullptr;
945}
946
948 switch (static_cast<TemplateDeductionResult>(Result)) {
961 return nullptr;
962
968 return &static_cast<DFIArguments*>(Data)->SecondArg;
969
970 // Unhandled
973 break;
974 }
975
976 return nullptr;
977}
978
979std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
980 switch (static_cast<TemplateDeductionResult>(Result)) {
983 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
984
985 default:
986 return std::nullopt;
987 }
988}
989
991 const FunctionDecl *Y) {
992 if (!X || !Y)
993 return false;
994 if (X->getNumParams() != Y->getNumParams())
995 return false;
996 // FIXME: when do rewritten comparison operators
997 // with explicit object parameters correspond?
998 // https://cplusplus.github.io/CWG/issues/2797.html
999 for (unsigned I = 0; I < X->getNumParams(); ++I)
1000 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1001 Y->getParamDecl(I)->getType()))
1002 return false;
1003 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1004 auto *FTY = Y->getDescribedFunctionTemplate();
1005 if (!FTY)
1006 return false;
1007 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1008 FTY->getTemplateParameters()))
1009 return false;
1010 }
1011 return true;
1012}
1013
1015 Expr *FirstOperand, FunctionDecl *EqFD) {
1016 assert(EqFD->getOverloadedOperator() ==
1017 OverloadedOperatorKind::OO_EqualEqual);
1018 // C++2a [over.match.oper]p4:
1019 // A non-template function or function template F named operator== is a
1020 // rewrite target with first operand o unless a search for the name operator!=
1021 // in the scope S from the instantiation context of the operator expression
1022 // finds a function or function template that would correspond
1023 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1024 // scope of the class type of o if F is a class member, and the namespace
1025 // scope of which F is a member otherwise. A function template specialization
1026 // named operator== is a rewrite target if its function template is a rewrite
1027 // target.
1029 OverloadedOperatorKind::OO_ExclaimEqual);
1030 if (isa<CXXMethodDecl>(EqFD)) {
1031 // If F is a class member, search scope is class type of first operand.
1032 QualType RHS = FirstOperand->getType();
1033 auto *RHSRec = RHS->getAs<RecordType>();
1034 if (!RHSRec)
1035 return true;
1036 LookupResult Members(S, NotEqOp, OpLoc,
1038 S.LookupQualifiedName(Members, RHSRec->getDecl());
1039 Members.suppressAccessDiagnostics();
1040 for (NamedDecl *Op : Members)
1041 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1042 return false;
1043 return true;
1044 }
1045 // Otherwise the search scope is the namespace scope of which F is a member.
1046 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1047 auto *NotEqFD = Op->getAsFunction();
1048 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1049 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1050 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1052 cast<Decl>(Op->getLexicalDeclContext())))
1053 return false;
1054 }
1055 return true;
1056}
1057
1061 return false;
1062 return Op == OO_EqualEqual || Op == OO_Spaceship;
1063}
1064
1066 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1067 auto Op = FD->getOverloadedOperator();
1068 if (!allowsReversed(Op))
1069 return false;
1070 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1071 assert(OriginalArgs.size() == 2);
1073 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1074 return false;
1075 }
1076 // Don't bother adding a reversed candidate that can never be a better
1077 // match than the non-reversed version.
1078 return FD->getNumNonObjectParams() != 2 ||
1080 FD->getParamDecl(1)->getType()) ||
1081 FD->hasAttr<EnableIfAttr>();
1082}
1083
1084void OverloadCandidateSet::destroyCandidates() {
1085 for (iterator i = begin(), e = end(); i != e; ++i) {
1086 for (auto &C : i->Conversions)
1087 C.~ImplicitConversionSequence();
1088 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1089 i->DeductionFailure.Destroy();
1090 }
1091}
1092
1094 destroyCandidates();
1095 SlabAllocator.Reset();
1096 NumInlineBytesUsed = 0;
1097 Candidates.clear();
1098 Functions.clear();
1099 Kind = CSK;
1100}
1101
1102namespace {
1103 class UnbridgedCastsSet {
1104 struct Entry {
1105 Expr **Addr;
1106 Expr *Saved;
1107 };
1108 SmallVector<Entry, 2> Entries;
1109
1110 public:
1111 void save(Sema &S, Expr *&E) {
1112 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1113 Entry entry = { &E, E };
1114 Entries.push_back(entry);
1116 }
1117
1118 void restore() {
1120 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1121 *i->Addr = i->Saved;
1122 }
1123 };
1124}
1125
1126/// checkPlaceholderForOverload - Do any interesting placeholder-like
1127/// preprocessing on the given expression.
1128///
1129/// \param unbridgedCasts a collection to which to add unbridged casts;
1130/// without this, they will be immediately diagnosed as errors
1131///
1132/// Return true on unrecoverable error.
1133static bool
1135 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1136 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1137 // We can't handle overloaded expressions here because overload
1138 // resolution might reasonably tweak them.
1139 if (placeholder->getKind() == BuiltinType::Overload) return false;
1140
1141 // If the context potentially accepts unbridged ARC casts, strip
1142 // the unbridged cast and add it to the collection for later restoration.
1143 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1144 unbridgedCasts) {
1145 unbridgedCasts->save(S, E);
1146 return false;
1147 }
1148
1149 // Go ahead and check everything else.
1150 ExprResult result = S.CheckPlaceholderExpr(E);
1151 if (result.isInvalid())
1152 return true;
1153
1154 E = result.get();
1155 return false;
1156 }
1157
1158 // Nothing to do.
1159 return false;
1160}
1161
1162/// checkArgPlaceholdersForOverload - Check a set of call operands for
1163/// placeholders.
1165 UnbridgedCastsSet &unbridged) {
1166 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1167 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1168 return true;
1169
1170 return false;
1171}
1172
1175 NamedDecl *&Match, bool NewIsUsingDecl) {
1176 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1177 I != E; ++I) {
1178 NamedDecl *OldD = *I;
1179
1180 bool OldIsUsingDecl = false;
1181 if (isa<UsingShadowDecl>(OldD)) {
1182 OldIsUsingDecl = true;
1183
1184 // We can always introduce two using declarations into the same
1185 // context, even if they have identical signatures.
1186 if (NewIsUsingDecl) continue;
1187
1188 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1189 }
1190
1191 // A using-declaration does not conflict with another declaration
1192 // if one of them is hidden.
1193 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1194 continue;
1195
1196 // If either declaration was introduced by a using declaration,
1197 // we'll need to use slightly different rules for matching.
1198 // Essentially, these rules are the normal rules, except that
1199 // function templates hide function templates with different
1200 // return types or template parameter lists.
1201 bool UseMemberUsingDeclRules =
1202 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1203 !New->getFriendObjectKind();
1204
1205 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1206 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1207 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1208 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1209 continue;
1210 }
1211
1212 if (!isa<FunctionTemplateDecl>(OldD) &&
1213 !shouldLinkPossiblyHiddenDecl(*I, New))
1214 continue;
1215
1216 Match = *I;
1217 return Ovl_Match;
1218 }
1219
1220 // Builtins that have custom typechecking or have a reference should
1221 // not be overloadable or redeclarable.
1222 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1223 Match = *I;
1224 return Ovl_NonFunction;
1225 }
1226 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1227 // We can overload with these, which can show up when doing
1228 // redeclaration checks for UsingDecls.
1229 assert(Old.getLookupKind() == LookupUsingDeclName);
1230 } else if (isa<TagDecl>(OldD)) {
1231 // We can always overload with tags by hiding them.
1232 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1233 // Optimistically assume that an unresolved using decl will
1234 // overload; if it doesn't, we'll have to diagnose during
1235 // template instantiation.
1236 //
1237 // Exception: if the scope is dependent and this is not a class
1238 // member, the using declaration can only introduce an enumerator.
1239 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1240 Match = *I;
1241 return Ovl_NonFunction;
1242 }
1243 } else {
1244 // (C++ 13p1):
1245 // Only function declarations can be overloaded; object and type
1246 // declarations cannot be overloaded.
1247 Match = *I;
1248 return Ovl_NonFunction;
1249 }
1250 }
1251
1252 // C++ [temp.friend]p1:
1253 // For a friend function declaration that is not a template declaration:
1254 // -- if the name of the friend is a qualified or unqualified template-id,
1255 // [...], otherwise
1256 // -- if the name of the friend is a qualified-id and a matching
1257 // non-template function is found in the specified class or namespace,
1258 // the friend declaration refers to that function, otherwise,
1259 // -- if the name of the friend is a qualified-id and a matching function
1260 // template is found in the specified class or namespace, the friend
1261 // declaration refers to the deduced specialization of that function
1262 // template, otherwise
1263 // -- the name shall be an unqualified-id [...]
1264 // If we get here for a qualified friend declaration, we've just reached the
1265 // third bullet. If the type of the friend is dependent, skip this lookup
1266 // until instantiation.
1267 if (New->getFriendObjectKind() && New->getQualifier() &&
1270 !New->getType()->isDependentType()) {
1271 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1272 TemplateSpecResult.addAllDecls(Old);
1273 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1274 /*QualifiedFriend*/true)) {
1275 New->setInvalidDecl();
1276 return Ovl_Overload;
1277 }
1278
1279 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1280 return Ovl_Match;
1281 }
1282
1283 return Ovl_Overload;
1284}
1285
1286static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1287 FunctionDecl *Old,
1288 bool UseMemberUsingDeclRules,
1289 bool ConsiderCudaAttrs,
1290 bool UseOverrideRules = false) {
1291 // C++ [basic.start.main]p2: This function shall not be overloaded.
1292 if (New->isMain())
1293 return false;
1294
1295 // MSVCRT user defined entry points cannot be overloaded.
1296 if (New->isMSVCRTEntryPoint())
1297 return false;
1298
1299 NamedDecl *OldDecl = Old;
1300 NamedDecl *NewDecl = New;
1303
1304 // C++ [temp.fct]p2:
1305 // A function template can be overloaded with other function templates
1306 // and with normal (non-template) functions.
1307 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1308 return true;
1309
1310 // Is the function New an overload of the function Old?
1311 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1312 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1313
1314 // Compare the signatures (C++ 1.3.10) of the two functions to
1315 // determine whether they are overloads. If we find any mismatch
1316 // in the signature, they are overloads.
1317
1318 // If either of these functions is a K&R-style function (no
1319 // prototype), then we consider them to have matching signatures.
1320 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1321 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1322 return false;
1323
1324 const auto *OldType = cast<FunctionProtoType>(OldQType);
1325 const auto *NewType = cast<FunctionProtoType>(NewQType);
1326
1327 // The signature of a function includes the types of its
1328 // parameters (C++ 1.3.10), which includes the presence or absence
1329 // of the ellipsis; see C++ DR 357).
1330 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1331 return true;
1332
1333 // For member-like friends, the enclosing class is part of the signature.
1334 if ((New->isMemberLikeConstrainedFriend() ||
1337 return true;
1338
1339 // Compare the parameter lists.
1340 // This can only be done once we have establish that friend functions
1341 // inhabit the same context, otherwise we might tried to instantiate
1342 // references to non-instantiated entities during constraint substitution.
1343 // GH78101.
1344 if (NewTemplate) {
1345 OldDecl = OldTemplate;
1346 NewDecl = NewTemplate;
1347 // C++ [temp.over.link]p4:
1348 // The signature of a function template consists of its function
1349 // signature, its return type and its template parameter list. The names
1350 // of the template parameters are significant only for establishing the
1351 // relationship between the template parameters and the rest of the
1352 // signature.
1353 //
1354 // We check the return type and template parameter lists for function
1355 // templates first; the remaining checks follow.
1356 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1357 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1358 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1359 bool SameReturnType = SemaRef.Context.hasSameType(
1361 // FIXME(GH58571): Match template parameter list even for non-constrained
1362 // template heads. This currently ensures that the code prior to C++20 is
1363 // not newly broken.
1364 bool ConstraintsInTemplateHead =
1367 // C++ [namespace.udecl]p11:
1368 // The set of declarations named by a using-declarator that inhabits a
1369 // class C does not include member functions and member function
1370 // templates of a base class that "correspond" to (and thus would
1371 // conflict with) a declaration of a function or function template in
1372 // C.
1373 // Comparing return types is not required for the "correspond" check to
1374 // decide whether a member introduced by a shadow declaration is hidden.
1375 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1376 !SameTemplateParameterList)
1377 return true;
1378 if (!UseMemberUsingDeclRules &&
1379 (!SameTemplateParameterList || !SameReturnType))
1380 return true;
1381 }
1382
1383 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1384 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1385
1386 int OldParamsOffset = 0;
1387 int NewParamsOffset = 0;
1388
1389 // When determining if a method is an overload from a base class, act as if
1390 // the implicit object parameter are of the same type.
1391
1392 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1394 return Q;
1395
1396 // We do not allow overloading based off of '__restrict'.
1397 Q.removeRestrict();
1398
1399 // We may not have applied the implicit const for a constexpr member
1400 // function yet (because we haven't yet resolved whether this is a static
1401 // or non-static member function). Add it now, on the assumption that this
1402 // is a redeclaration of OldMethod.
1403 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1404 (M->isConstexpr() || M->isConsteval()) &&
1405 !isa<CXXConstructorDecl>(NewMethod))
1406 Q.addConst();
1407 return Q;
1408 };
1409
1410 auto CompareType = [&](QualType Base, QualType D) {
1411 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1412 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1413
1414 auto DS = D.getNonReferenceType().getCanonicalType().split();
1415 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1416
1417 if (BS.Quals != DS.Quals)
1418 return false;
1419
1420 if (OldMethod->isImplicitObjectMemberFunction() &&
1421 OldMethod->getParent() != NewMethod->getParent()) {
1422 QualType ParentType =
1423 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1425 if (ParentType.getTypePtr() != BS.Ty)
1426 return false;
1427 BS.Ty = DS.Ty;
1428 }
1429
1430 // FIXME: should we ignore some type attributes here?
1431 if (BS.Ty != DS.Ty)
1432 return false;
1433
1434 if (Base->isLValueReferenceType())
1435 return D->isLValueReferenceType();
1436 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1437 };
1438
1439 // If the function is a class member, its signature includes the
1440 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1441 auto DiagnoseInconsistentRefQualifiers = [&]() {
1442 if (SemaRef.LangOpts.CPlusPlus23)
1443 return false;
1444 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1445 return false;
1446 if (OldMethod->isExplicitObjectMemberFunction() ||
1447 NewMethod->isExplicitObjectMemberFunction())
1448 return false;
1449 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1450 NewMethod->getRefQualifier() == RQ_None)) {
1451 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1452 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1453 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1454 return true;
1455 }
1456 return false;
1457 };
1458
1459 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1460 OldParamsOffset++;
1461 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1462 NewParamsOffset++;
1463
1464 if (OldType->getNumParams() - OldParamsOffset !=
1465 NewType->getNumParams() - NewParamsOffset ||
1467 {OldType->param_type_begin() + OldParamsOffset,
1468 OldType->param_type_end()},
1469 {NewType->param_type_begin() + NewParamsOffset,
1470 NewType->param_type_end()},
1471 nullptr)) {
1472 return true;
1473 }
1474
1475 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1476 !NewMethod->isStatic()) {
1477 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1478 const CXXMethodDecl *New) {
1479 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1480 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1481
1482 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1483 return F->getRefQualifier() == RQ_None &&
1484 !F->isExplicitObjectMemberFunction();
1485 };
1486
1487 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1488 CompareType(OldObjectType.getNonReferenceType(),
1489 NewObjectType.getNonReferenceType()))
1490 return true;
1491 return CompareType(OldObjectType, NewObjectType);
1492 }(OldMethod, NewMethod);
1493
1494 if (!HaveCorrespondingObjectParameters) {
1495 if (DiagnoseInconsistentRefQualifiers())
1496 return true;
1497 // CWG2554
1498 // and, if at least one is an explicit object member function, ignoring
1499 // object parameters
1500 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1501 !OldMethod->isExplicitObjectMemberFunction()))
1502 return true;
1503 }
1504 }
1505
1506 if (!UseOverrideRules &&
1508 Expr *NewRC = New->getTrailingRequiresClause(),
1509 *OldRC = Old->getTrailingRequiresClause();
1510 if ((NewRC != nullptr) != (OldRC != nullptr))
1511 return true;
1512 if (NewRC &&
1513 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1514 return true;
1515 }
1516
1517 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1518 NewMethod->isImplicitObjectMemberFunction()) {
1519 if (DiagnoseInconsistentRefQualifiers())
1520 return true;
1521 }
1522
1523 // Though pass_object_size is placed on parameters and takes an argument, we
1524 // consider it to be a function-level modifier for the sake of function
1525 // identity. Either the function has one or more parameters with
1526 // pass_object_size or it doesn't.
1529 return true;
1530
1531 // enable_if attributes are an order-sensitive part of the signature.
1533 NewI = New->specific_attr_begin<EnableIfAttr>(),
1534 NewE = New->specific_attr_end<EnableIfAttr>(),
1535 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1536 OldE = Old->specific_attr_end<EnableIfAttr>();
1537 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1538 if (NewI == NewE || OldI == OldE)
1539 return true;
1540 llvm::FoldingSetNodeID NewID, OldID;
1541 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1542 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1543 if (NewID != OldID)
1544 return true;
1545 }
1546
1547 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1548 // Don't allow overloading of destructors. (In theory we could, but it
1549 // would be a giant change to clang.)
1550 if (!isa<CXXDestructorDecl>(New)) {
1551 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1552 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1553 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1554 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1555 "Unexpected invalid target.");
1556
1557 // Allow overloading of functions with same signature and different CUDA
1558 // target attributes.
1559 if (NewTarget != OldTarget)
1560 return true;
1561 }
1562 }
1563 }
1564
1565 // The signatures match; this is not an overload.
1566 return false;
1567}
1568
1570 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1571 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1572 ConsiderCudaAttrs);
1573}
1574
1576 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1577 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1578 /*UseMemberUsingDeclRules=*/false,
1579 /*ConsiderCudaAttrs=*/true,
1580 /*UseOverrideRules=*/true);
1581}
1582
1583/// Tries a user-defined conversion from From to ToType.
1584///
1585/// Produces an implicit conversion sequence for when a standard conversion
1586/// is not an option. See TryImplicitConversion for more information.
1589 bool SuppressUserConversions,
1590 AllowedExplicit AllowExplicit,
1591 bool InOverloadResolution,
1592 bool CStyle,
1593 bool AllowObjCWritebackConversion,
1594 bool AllowObjCConversionOnExplicit) {
1596
1597 if (SuppressUserConversions) {
1598 // We're not in the case above, so there is no conversion that
1599 // we can perform.
1601 return ICS;
1602 }
1603
1604 // Attempt user-defined conversion.
1605 OverloadCandidateSet Conversions(From->getExprLoc(),
1607 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1608 Conversions, AllowExplicit,
1609 AllowObjCConversionOnExplicit)) {
1610 case OR_Success:
1611 case OR_Deleted:
1612 ICS.setUserDefined();
1613 // C++ [over.ics.user]p4:
1614 // A conversion of an expression of class type to the same class
1615 // type is given Exact Match rank, and a conversion of an
1616 // expression of class type to a base class of that type is
1617 // given Conversion rank, in spite of the fact that a copy
1618 // constructor (i.e., a user-defined conversion function) is
1619 // called for those cases.
1620 if (CXXConstructorDecl *Constructor
1621 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1622 QualType FromCanon
1624 QualType ToCanon
1626 if (Constructor->isCopyConstructor() &&
1627 (FromCanon == ToCanon ||
1628 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1629 // Turn this into a "standard" conversion sequence, so that it
1630 // gets ranked with standard conversion sequences.
1632 ICS.setStandard();
1634 ICS.Standard.setFromType(From->getType());
1635 ICS.Standard.setAllToTypes(ToType);
1636 ICS.Standard.CopyConstructor = Constructor;
1638 if (ToCanon != FromCanon)
1640 }
1641 }
1642 break;
1643
1644 case OR_Ambiguous:
1645 ICS.setAmbiguous();
1646 ICS.Ambiguous.setFromType(From->getType());
1647 ICS.Ambiguous.setToType(ToType);
1648 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1649 Cand != Conversions.end(); ++Cand)
1650 if (Cand->Best)
1651 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1652 break;
1653
1654 // Fall through.
1657 break;
1658 }
1659
1660 return ICS;
1661}
1662
1663/// TryImplicitConversion - Attempt to perform an implicit conversion
1664/// from the given expression (Expr) to the given type (ToType). This
1665/// function returns an implicit conversion sequence that can be used
1666/// to perform the initialization. Given
1667///
1668/// void f(float f);
1669/// void g(int i) { f(i); }
1670///
1671/// this routine would produce an implicit conversion sequence to
1672/// describe the initialization of f from i, which will be a standard
1673/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1674/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1675//
1676/// Note that this routine only determines how the conversion can be
1677/// performed; it does not actually perform the conversion. As such,
1678/// it will not produce any diagnostics if no conversion is available,
1679/// but will instead return an implicit conversion sequence of kind
1680/// "BadConversion".
1681///
1682/// If @p SuppressUserConversions, then user-defined conversions are
1683/// not permitted.
1684/// If @p AllowExplicit, then explicit user-defined conversions are
1685/// permitted.
1686///
1687/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1688/// writeback conversion, which allows __autoreleasing id* parameters to
1689/// be initialized with __strong id* or __weak id* arguments.
1692 bool SuppressUserConversions,
1693 AllowedExplicit AllowExplicit,
1694 bool InOverloadResolution,
1695 bool CStyle,
1696 bool AllowObjCWritebackConversion,
1697 bool AllowObjCConversionOnExplicit) {
1699 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1700 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1701 ICS.setStandard();
1702 return ICS;
1703 }
1704
1705 if (!S.getLangOpts().CPlusPlus) {
1707 return ICS;
1708 }
1709
1710 // C++ [over.ics.user]p4:
1711 // A conversion of an expression of class type to the same class
1712 // type is given Exact Match rank, and a conversion of an
1713 // expression of class type to a base class of that type is
1714 // given Conversion rank, in spite of the fact that a copy/move
1715 // constructor (i.e., a user-defined conversion function) is
1716 // called for those cases.
1717 QualType FromType = From->getType();
1718 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1719 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1720 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1721 ICS.setStandard();
1723 ICS.Standard.setFromType(FromType);
1724 ICS.Standard.setAllToTypes(ToType);
1725
1726 // We don't actually check at this point whether there is a valid
1727 // copy/move constructor, since overloading just assumes that it
1728 // exists. When we actually perform initialization, we'll find the
1729 // appropriate constructor to copy the returned object, if needed.
1730 ICS.Standard.CopyConstructor = nullptr;
1731
1732 // Determine whether this is considered a derived-to-base conversion.
1733 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1735
1736 return ICS;
1737 }
1738
1739 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1740 AllowExplicit, InOverloadResolution, CStyle,
1741 AllowObjCWritebackConversion,
1742 AllowObjCConversionOnExplicit);
1743}
1744
1747 bool SuppressUserConversions,
1748 AllowedExplicit AllowExplicit,
1749 bool InOverloadResolution,
1750 bool CStyle,
1751 bool AllowObjCWritebackConversion) {
1752 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1753 AllowExplicit, InOverloadResolution, CStyle,
1754 AllowObjCWritebackConversion,
1755 /*AllowObjCConversionOnExplicit=*/false);
1756}
1757
1759 AssignmentAction Action,
1760 bool AllowExplicit) {
1761 if (checkPlaceholderForOverload(*this, From))
1762 return ExprError();
1763
1764 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1765 bool AllowObjCWritebackConversion
1766 = getLangOpts().ObjCAutoRefCount &&
1767 (Action == AA_Passing || Action == AA_Sending);
1768 if (getLangOpts().ObjC)
1769 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1770 From->getType(), From);
1772 *this, From, ToType,
1773 /*SuppressUserConversions=*/false,
1774 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1775 /*InOverloadResolution=*/false,
1776 /*CStyle=*/false, AllowObjCWritebackConversion,
1777 /*AllowObjCConversionOnExplicit=*/false);
1778 return PerformImplicitConversion(From, ToType, ICS, Action);
1779}
1780
1782 QualType &ResultTy) {
1783 if (Context.hasSameUnqualifiedType(FromType, ToType))
1784 return false;
1785
1786 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1787 // or F(t noexcept) -> F(t)
1788 // where F adds one of the following at most once:
1789 // - a pointer
1790 // - a member pointer
1791 // - a block pointer
1792 // Changes here need matching changes in FindCompositePointerType.
1793 CanQualType CanTo = Context.getCanonicalType(ToType);
1794 CanQualType CanFrom = Context.getCanonicalType(FromType);
1795 Type::TypeClass TyClass = CanTo->getTypeClass();
1796 if (TyClass != CanFrom->getTypeClass()) return false;
1797 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1798 if (TyClass == Type::Pointer) {
1799 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1800 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1801 } else if (TyClass == Type::BlockPointer) {
1802 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1803 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1804 } else if (TyClass == Type::MemberPointer) {
1805 auto ToMPT = CanTo.castAs<MemberPointerType>();
1806 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1807 // A function pointer conversion cannot change the class of the function.
1808 if (ToMPT->getClass() != FromMPT->getClass())
1809 return false;
1810 CanTo = ToMPT->getPointeeType();
1811 CanFrom = FromMPT->getPointeeType();
1812 } else {
1813 return false;
1814 }
1815
1816 TyClass = CanTo->getTypeClass();
1817 if (TyClass != CanFrom->getTypeClass()) return false;
1818 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1819 return false;
1820 }
1821
1822 const auto *FromFn = cast<FunctionType>(CanFrom);
1823 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1824
1825 const auto *ToFn = cast<FunctionType>(CanTo);
1826 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1827
1828 bool Changed = false;
1829
1830 // Drop 'noreturn' if not present in target type.
1831 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1832 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1833 Changed = true;
1834 }
1835
1836 // Drop 'noexcept' if not present in target type.
1837 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1838 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1839 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1840 FromFn = cast<FunctionType>(
1841 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1842 EST_None)
1843 .getTypePtr());
1844 Changed = true;
1845 }
1846
1847 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1848 // only if the ExtParameterInfo lists of the two function prototypes can be
1849 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1851 bool CanUseToFPT, CanUseFromFPT;
1852 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1853 CanUseFromFPT, NewParamInfos) &&
1854 CanUseToFPT && !CanUseFromFPT) {
1855 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1856 ExtInfo.ExtParameterInfos =
1857 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1858 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1859 FromFPT->getParamTypes(), ExtInfo);
1860 FromFn = QT->getAs<FunctionType>();
1861 Changed = true;
1862 }
1863
1864 // For C, when called from checkPointerTypesForAssignment,
1865 // we need to not alter FromFn, or else even an innocuous cast
1866 // like dropping effects will fail. In C++ however we do want to
1867 // alter FromFn (because of the way PerformImplicitConversion works).
1868 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1869 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1870
1871 // Transparently add/drop effects; here we are concerned with
1872 // language rules/canonicalization. Adding/dropping effects is a warning.
1873 const auto FromFX = FromFPT->getFunctionEffects();
1874 const auto ToFX = ToFPT->getFunctionEffects();
1875 if (FromFX != ToFX) {
1876 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1877 ExtInfo.FunctionEffects = ToFX;
1878 QualType QT = Context.getFunctionType(
1879 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1880 FromFn = QT->getAs<FunctionType>();
1881 Changed = true;
1882 }
1883 }
1884 }
1885
1886 if (!Changed)
1887 return false;
1888
1889 assert(QualType(FromFn, 0).isCanonical());
1890 if (QualType(FromFn, 0) != CanTo) return false;
1891
1892 ResultTy = ToType;
1893 return true;
1894}
1895
1896/// Determine whether the conversion from FromType to ToType is a valid
1897/// floating point conversion.
1898///
1899static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1900 QualType ToType) {
1901 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1902 return false;
1903 // FIXME: disable conversions between long double, __ibm128 and __float128
1904 // if their representation is different until there is back end support
1905 // We of course allow this conversion if long double is really double.
1906
1907 // Conversions between bfloat16 and float16 are currently not supported.
1908 if ((FromType->isBFloat16Type() &&
1909 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1910 (ToType->isBFloat16Type() &&
1911 (FromType->isFloat16Type() || FromType->isHalfType())))
1912 return false;
1913
1914 // Conversions between IEEE-quad and IBM-extended semantics are not
1915 // permitted.
1916 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1917 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1918 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1919 &ToSem == &llvm::APFloat::IEEEquad()) ||
1920 (&FromSem == &llvm::APFloat::IEEEquad() &&
1921 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1922 return false;
1923 return true;
1924}
1925
1926static bool IsVectorElementConversion(Sema &S, QualType FromType,
1927 QualType ToType,
1928 ImplicitConversionKind &ICK, Expr *From) {
1929 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1930 return true;
1931
1932 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1934 return true;
1935 }
1936
1937 if (IsFloatingPointConversion(S, FromType, ToType)) {
1939 return true;
1940 }
1941
1942 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1944 return true;
1945 }
1946
1947 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1949 ToType->isRealFloatingType())) {
1951 return true;
1952 }
1953
1954 if (S.IsIntegralPromotion(From, FromType, ToType)) {
1956 return true;
1957 }
1958
1959 if (FromType->isIntegralOrUnscopedEnumerationType() &&
1960 ToType->isIntegralType(S.Context)) {
1962 return true;
1963 }
1964
1965 return false;
1966}
1967
1968/// Determine whether the conversion from FromType to ToType is a valid
1969/// vector conversion.
1970///
1971/// \param ICK Will be set to the vector conversion kind, if this is a vector
1972/// conversion.
1973static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1975 ImplicitConversionKind &ElConv, Expr *From,
1976 bool InOverloadResolution, bool CStyle) {
1977 // We need at least one of these types to be a vector type to have a vector
1978 // conversion.
1979 if (!ToType->isVectorType() && !FromType->isVectorType())
1980 return false;
1981
1982 // Identical types require no conversions.
1983 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1984 return false;
1985
1986 // There are no conversions between extended vector types, only identity.
1987 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
1988 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
1989 // HLSL allows implicit truncation of vector types.
1990 if (S.getLangOpts().HLSL) {
1991 unsigned FromElts = FromExtType->getNumElements();
1992 unsigned ToElts = ToExtType->getNumElements();
1993 if (FromElts < ToElts)
1994 return false;
1995 if (FromElts == ToElts)
1996 ElConv = ICK_Identity;
1997 else
1999
2000 QualType FromElTy = FromExtType->getElementType();
2001 QualType ToElTy = ToExtType->getElementType();
2002 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2003 return true;
2004 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2005 }
2006 // There are no conversions between extended vector types other than the
2007 // identity conversion.
2008 return false;
2009 }
2010
2011 // Vector splat from any arithmetic type to a vector.
2012 if (FromType->isArithmeticType()) {
2013 if (S.getLangOpts().HLSL) {
2014 ElConv = ICK_HLSL_Vector_Splat;
2015 QualType ToElTy = ToExtType->getElementType();
2016 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2017 }
2018 ICK = ICK_Vector_Splat;
2019 return true;
2020 }
2021 }
2022
2023 if (ToType->isSVESizelessBuiltinType() ||
2024 FromType->isSVESizelessBuiltinType())
2025 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2026 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2028 return true;
2029 }
2030
2031 if (ToType->isRVVSizelessBuiltinType() ||
2032 FromType->isRVVSizelessBuiltinType())
2033 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2034 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2036 return true;
2037 }
2038
2039 // We can perform the conversion between vector types in the following cases:
2040 // 1)vector types are equivalent AltiVec and GCC vector types
2041 // 2)lax vector conversions are permitted and the vector types are of the
2042 // same size
2043 // 3)the destination type does not have the ARM MVE strict-polymorphism
2044 // attribute, which inhibits lax vector conversion for overload resolution
2045 // only
2046 if (ToType->isVectorType() && FromType->isVectorType()) {
2047 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2048 (S.isLaxVectorConversion(FromType, ToType) &&
2049 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2050 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2051 S.isLaxVectorConversion(FromType, ToType) &&
2052 S.anyAltivecTypes(FromType, ToType) &&
2053 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2054 !InOverloadResolution && !CStyle) {
2055 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2056 << FromType << ToType;
2057 }
2059 return true;
2060 }
2061 }
2062
2063 return false;
2064}
2065
2066static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2067 bool InOverloadResolution,
2069 bool CStyle);
2070
2071/// IsStandardConversion - Determines whether there is a standard
2072/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2073/// expression From to the type ToType. Standard conversion sequences
2074/// only consider non-class types; for conversions that involve class
2075/// types, use TryImplicitConversion. If a conversion exists, SCS will
2076/// contain the standard conversion sequence required to perform this
2077/// conversion and this routine will return true. Otherwise, this
2078/// routine will return false and the value of SCS is unspecified.
2079static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2080 bool InOverloadResolution,
2082 bool CStyle,
2083 bool AllowObjCWritebackConversion) {
2084 QualType FromType = From->getType();
2085
2086 // Standard conversions (C++ [conv])
2088 SCS.IncompatibleObjC = false;
2089 SCS.setFromType(FromType);
2090 SCS.CopyConstructor = nullptr;
2091
2092 // There are no standard conversions for class types in C++, so
2093 // abort early. When overloading in C, however, we do permit them.
2094 if (S.getLangOpts().CPlusPlus &&
2095 (FromType->isRecordType() || ToType->isRecordType()))
2096 return false;
2097
2098 // The first conversion can be an lvalue-to-rvalue conversion,
2099 // array-to-pointer conversion, or function-to-pointer conversion
2100 // (C++ 4p1).
2101
2102 if (FromType == S.Context.OverloadTy) {
2103 DeclAccessPair AccessPair;
2104 if (FunctionDecl *Fn
2105 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2106 AccessPair)) {
2107 // We were able to resolve the address of the overloaded function,
2108 // so we can convert to the type of that function.
2109 FromType = Fn->getType();
2110 SCS.setFromType(FromType);
2111
2112 // we can sometimes resolve &foo<int> regardless of ToType, so check
2113 // if the type matches (identity) or we are converting to bool
2115 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2116 QualType resultTy;
2117 // if the function type matches except for [[noreturn]], it's ok
2118 if (!S.IsFunctionConversion(FromType,
2119 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2120 // otherwise, only a boolean conversion is standard
2121 if (!ToType->isBooleanType())
2122 return false;
2123 }
2124
2125 // Check if the "from" expression is taking the address of an overloaded
2126 // function and recompute the FromType accordingly. Take advantage of the
2127 // fact that non-static member functions *must* have such an address-of
2128 // expression.
2129 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2130 if (Method && !Method->isStatic() &&
2131 !Method->isExplicitObjectMemberFunction()) {
2132 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2133 "Non-unary operator on non-static member address");
2134 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2135 == UO_AddrOf &&
2136 "Non-address-of operator on non-static member address");
2137 const Type *ClassType
2139 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2140 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2141 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2142 UO_AddrOf &&
2143 "Non-address-of operator for overloaded function expression");
2144 FromType = S.Context.getPointerType(FromType);
2145 }
2146 } else {
2147 return false;
2148 }
2149 }
2150 // Lvalue-to-rvalue conversion (C++11 4.1):
2151 // A glvalue (3.10) of a non-function, non-array type T can
2152 // be converted to a prvalue.
2153 bool argIsLValue = From->isGLValue();
2154 if (argIsLValue && !FromType->canDecayToPointerType() &&
2155 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2157
2158 // C11 6.3.2.1p2:
2159 // ... if the lvalue has atomic type, the value has the non-atomic version
2160 // of the type of the lvalue ...
2161 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2162 FromType = Atomic->getValueType();
2163
2164 // If T is a non-class type, the type of the rvalue is the
2165 // cv-unqualified version of T. Otherwise, the type of the rvalue
2166 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2167 // just strip the qualifiers because they don't matter.
2168 FromType = FromType.getUnqualifiedType();
2169 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2170 ToType->isArrayParameterType()) {
2171 // HLSL constant array parameters do not decay, so if the argument is a
2172 // constant array and the parameter is an ArrayParameterType we have special
2173 // handling here.
2174 FromType = S.Context.getArrayParameterType(FromType);
2175 if (S.Context.getCanonicalType(FromType) !=
2176 S.Context.getCanonicalType(ToType))
2177 return false;
2178
2180 SCS.setAllToTypes(ToType);
2181 return true;
2182 } else if (FromType->isArrayType()) {
2183 // Array-to-pointer conversion (C++ 4.2)
2185
2186 // An lvalue or rvalue of type "array of N T" or "array of unknown
2187 // bound of T" can be converted to an rvalue of type "pointer to
2188 // T" (C++ 4.2p1).
2189 FromType = S.Context.getArrayDecayedType(FromType);
2190
2191 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2192 // This conversion is deprecated in C++03 (D.4)
2194
2195 // For the purpose of ranking in overload resolution
2196 // (13.3.3.1.1), this conversion is considered an
2197 // array-to-pointer conversion followed by a qualification
2198 // conversion (4.4). (C++ 4.2p2)
2199 SCS.Second = ICK_Identity;
2202 SCS.setAllToTypes(FromType);
2203 return true;
2204 }
2205 } else if (FromType->isFunctionType() && argIsLValue) {
2206 // Function-to-pointer conversion (C++ 4.3).
2208
2209 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2210 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2212 return false;
2213
2214 // An lvalue of function type T can be converted to an rvalue of
2215 // type "pointer to T." The result is a pointer to the
2216 // function. (C++ 4.3p1).
2217 FromType = S.Context.getPointerType(FromType);
2218 } else {
2219 // We don't require any conversions for the first step.
2220 SCS.First = ICK_Identity;
2221 }
2222 SCS.setToType(0, FromType);
2223
2224 // The second conversion can be an integral promotion, floating
2225 // point promotion, integral conversion, floating point conversion,
2226 // floating-integral conversion, pointer conversion,
2227 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2228 // For overloading in C, this can also be a "compatible-type"
2229 // conversion.
2230 bool IncompatibleObjC = false;
2232 ImplicitConversionKind DimensionICK = ICK_Identity;
2233 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2234 // The unqualified versions of the types are the same: there's no
2235 // conversion to do.
2236 SCS.Second = ICK_Identity;
2237 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2238 // Integral promotion (C++ 4.5).
2240 FromType = ToType.getUnqualifiedType();
2241 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2242 // Floating point promotion (C++ 4.6).
2244 FromType = ToType.getUnqualifiedType();
2245 } else if (S.IsComplexPromotion(FromType, ToType)) {
2246 // Complex promotion (Clang extension)
2248 FromType = ToType.getUnqualifiedType();
2249 } else if (ToType->isBooleanType() &&
2250 (FromType->isArithmeticType() ||
2251 FromType->isAnyPointerType() ||
2252 FromType->isBlockPointerType() ||
2253 FromType->isMemberPointerType())) {
2254 // Boolean conversions (C++ 4.12).
2256 FromType = S.Context.BoolTy;
2257 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2258 ToType->isIntegralType(S.Context)) {
2259 // Integral conversions (C++ 4.7).
2261 FromType = ToType.getUnqualifiedType();
2262 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2263 // Complex conversions (C99 6.3.1.6)
2265 FromType = ToType.getUnqualifiedType();
2266 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2267 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2268 // Complex-real conversions (C99 6.3.1.7)
2270 FromType = ToType.getUnqualifiedType();
2271 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2272 // Floating point conversions (C++ 4.8).
2274 FromType = ToType.getUnqualifiedType();
2275 } else if ((FromType->isRealFloatingType() &&
2276 ToType->isIntegralType(S.Context)) ||
2278 ToType->isRealFloatingType())) {
2279
2280 // Floating-integral conversions (C++ 4.9).
2282 FromType = ToType.getUnqualifiedType();
2283 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2285 } else if (AllowObjCWritebackConversion &&
2286 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2288 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2289 FromType, IncompatibleObjC)) {
2290 // Pointer conversions (C++ 4.10).
2292 SCS.IncompatibleObjC = IncompatibleObjC;
2293 FromType = FromType.getUnqualifiedType();
2294 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2295 InOverloadResolution, FromType)) {
2296 // Pointer to member conversions (4.11).
2298 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2299 From, InOverloadResolution, CStyle)) {
2300 SCS.Second = SecondICK;
2301 SCS.Dimension = DimensionICK;
2302 FromType = ToType.getUnqualifiedType();
2303 } else if (!S.getLangOpts().CPlusPlus &&
2304 S.Context.typesAreCompatible(ToType, FromType)) {
2305 // Compatible conversions (Clang extension for C function overloading)
2307 FromType = ToType.getUnqualifiedType();
2309 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2311 FromType = ToType;
2312 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2313 CStyle)) {
2314 // tryAtomicConversion has updated the standard conversion sequence
2315 // appropriately.
2316 return true;
2317 } else if (ToType->isEventT() &&
2319 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2321 FromType = ToType;
2322 } else if (ToType->isQueueT() &&
2324 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2326 FromType = ToType;
2327 } else if (ToType->isSamplerT() &&
2330 FromType = ToType;
2331 } else if ((ToType->isFixedPointType() &&
2332 FromType->isConvertibleToFixedPointType()) ||
2333 (FromType->isFixedPointType() &&
2334 ToType->isConvertibleToFixedPointType())) {
2336 FromType = ToType;
2337 } else {
2338 // No second conversion required.
2339 SCS.Second = ICK_Identity;
2340 }
2341 SCS.setToType(1, FromType);
2342
2343 // The third conversion can be a function pointer conversion or a
2344 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2345 bool ObjCLifetimeConversion;
2346 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2347 // Function pointer conversions (removing 'noexcept') including removal of
2348 // 'noreturn' (Clang extension).
2350 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2351 ObjCLifetimeConversion)) {
2353 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2354 FromType = ToType;
2355 } else {
2356 // No conversion required
2357 SCS.Third = ICK_Identity;
2358 }
2359
2360 // C++ [over.best.ics]p6:
2361 // [...] Any difference in top-level cv-qualification is
2362 // subsumed by the initialization itself and does not constitute
2363 // a conversion. [...]
2364 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2365 QualType CanonTo = S.Context.getCanonicalType(ToType);
2366 if (CanonFrom.getLocalUnqualifiedType()
2367 == CanonTo.getLocalUnqualifiedType() &&
2368 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2369 FromType = ToType;
2370 CanonFrom = CanonTo;
2371 }
2372
2373 SCS.setToType(2, FromType);
2374
2375 if (CanonFrom == CanonTo)
2376 return true;
2377
2378 // If we have not converted the argument type to the parameter type,
2379 // this is a bad conversion sequence, unless we're resolving an overload in C.
2380 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2381 return false;
2382
2383 ExprResult ER = ExprResult{From};
2386 /*Diagnose=*/false,
2387 /*DiagnoseCFAudited=*/false,
2388 /*ConvertRHS=*/false);
2389 ImplicitConversionKind SecondConv;
2390 switch (Conv) {
2391 case Sema::Compatible:
2392 SecondConv = ICK_C_Only_Conversion;
2393 break;
2394 // For our purposes, discarding qualifiers is just as bad as using an
2395 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2396 // qualifiers, as well.
2401 break;
2402 default:
2403 return false;
2404 }
2405
2406 // First can only be an lvalue conversion, so we pretend that this was the
2407 // second conversion. First should already be valid from earlier in the
2408 // function.
2409 SCS.Second = SecondConv;
2410 SCS.setToType(1, ToType);
2411
2412 // Third is Identity, because Second should rank us worse than any other
2413 // conversion. This could also be ICK_Qualification, but it's simpler to just
2414 // lump everything in with the second conversion, and we don't gain anything
2415 // from making this ICK_Qualification.
2416 SCS.Third = ICK_Identity;
2417 SCS.setToType(2, ToType);
2418 return true;
2419}
2420
2421static bool
2423 QualType &ToType,
2424 bool InOverloadResolution,
2426 bool CStyle) {
2427
2428 const RecordType *UT = ToType->getAsUnionType();
2429 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2430 return false;
2431 // The field to initialize within the transparent union.
2432 RecordDecl *UD = UT->getDecl();
2433 // It's compatible if the expression matches any of the fields.
2434 for (const auto *it : UD->fields()) {
2435 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2436 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2437 ToType = it->getType();
2438 return true;
2439 }
2440 }
2441 return false;
2442}
2443
2444bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2445 const BuiltinType *To = ToType->getAs<BuiltinType>();
2446 // All integers are built-in.
2447 if (!To) {
2448 return false;
2449 }
2450
2451 // An rvalue of type char, signed char, unsigned char, short int, or
2452 // unsigned short int can be converted to an rvalue of type int if
2453 // int can represent all the values of the source type; otherwise,
2454 // the source rvalue can be converted to an rvalue of type unsigned
2455 // int (C++ 4.5p1).
2456 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2457 !FromType->isEnumeralType()) {
2458 if ( // We can promote any signed, promotable integer type to an int
2459 (FromType->isSignedIntegerType() ||
2460 // We can promote any unsigned integer type whose size is
2461 // less than int to an int.
2462 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2463 return To->getKind() == BuiltinType::Int;
2464 }
2465
2466 return To->getKind() == BuiltinType::UInt;
2467 }
2468
2469 // C++11 [conv.prom]p3:
2470 // A prvalue of an unscoped enumeration type whose underlying type is not
2471 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2472 // following types that can represent all the values of the enumeration
2473 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2474 // unsigned int, long int, unsigned long int, long long int, or unsigned
2475 // long long int. If none of the types in that list can represent all the
2476 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2477 // type can be converted to an rvalue a prvalue of the extended integer type
2478 // with lowest integer conversion rank (4.13) greater than the rank of long
2479 // long in which all the values of the enumeration can be represented. If
2480 // there are two such extended types, the signed one is chosen.
2481 // C++11 [conv.prom]p4:
2482 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2483 // can be converted to a prvalue of its underlying type. Moreover, if
2484 // integral promotion can be applied to its underlying type, a prvalue of an
2485 // unscoped enumeration type whose underlying type is fixed can also be
2486 // converted to a prvalue of the promoted underlying type.
2487 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2488 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2489 // provided for a scoped enumeration.
2490 if (FromEnumType->getDecl()->isScoped())
2491 return false;
2492
2493 // We can perform an integral promotion to the underlying type of the enum,
2494 // even if that's not the promoted type. Note that the check for promoting
2495 // the underlying type is based on the type alone, and does not consider
2496 // the bitfield-ness of the actual source expression.
2497 if (FromEnumType->getDecl()->isFixed()) {
2498 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2499 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2500 IsIntegralPromotion(nullptr, Underlying, ToType);
2501 }
2502
2503 // We have already pre-calculated the promotion type, so this is trivial.
2504 if (ToType->isIntegerType() &&
2505 isCompleteType(From->getBeginLoc(), FromType))
2506 return Context.hasSameUnqualifiedType(
2507 ToType, FromEnumType->getDecl()->getPromotionType());
2508
2509 // C++ [conv.prom]p5:
2510 // If the bit-field has an enumerated type, it is treated as any other
2511 // value of that type for promotion purposes.
2512 //
2513 // ... so do not fall through into the bit-field checks below in C++.
2514 if (getLangOpts().CPlusPlus)
2515 return false;
2516 }
2517
2518 // C++0x [conv.prom]p2:
2519 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2520 // to an rvalue a prvalue of the first of the following types that can
2521 // represent all the values of its underlying type: int, unsigned int,
2522 // long int, unsigned long int, long long int, or unsigned long long int.
2523 // If none of the types in that list can represent all the values of its
2524 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2525 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2526 // type.
2527 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2528 ToType->isIntegerType()) {
2529 // Determine whether the type we're converting from is signed or
2530 // unsigned.
2531 bool FromIsSigned = FromType->isSignedIntegerType();
2532 uint64_t FromSize = Context.getTypeSize(FromType);
2533
2534 // The types we'll try to promote to, in the appropriate
2535 // order. Try each of these types.
2536 QualType PromoteTypes[6] = {
2537 Context.IntTy, Context.UnsignedIntTy,
2538 Context.LongTy, Context.UnsignedLongTy ,
2539 Context.LongLongTy, Context.UnsignedLongLongTy
2540 };
2541 for (int Idx = 0; Idx < 6; ++Idx) {
2542 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2543 if (FromSize < ToSize ||
2544 (FromSize == ToSize &&
2545 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2546 // We found the type that we can promote to. If this is the
2547 // type we wanted, we have a promotion. Otherwise, no
2548 // promotion.
2549 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2550 }
2551 }
2552 }
2553
2554 // An rvalue for an integral bit-field (9.6) can be converted to an
2555 // rvalue of type int if int can represent all the values of the
2556 // bit-field; otherwise, it can be converted to unsigned int if
2557 // unsigned int can represent all the values of the bit-field. If
2558 // the bit-field is larger yet, no integral promotion applies to
2559 // it. If the bit-field has an enumerated type, it is treated as any
2560 // other value of that type for promotion purposes (C++ 4.5p3).
2561 // FIXME: We should delay checking of bit-fields until we actually perform the
2562 // conversion.
2563 //
2564 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2565 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2566 // bit-fields and those whose underlying type is larger than int) for GCC
2567 // compatibility.
2568 if (From) {
2569 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2570 std::optional<llvm::APSInt> BitWidth;
2571 if (FromType->isIntegralType(Context) &&
2572 (BitWidth =
2573 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2574 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2575 ToSize = Context.getTypeSize(ToType);
2576
2577 // Are we promoting to an int from a bitfield that fits in an int?
2578 if (*BitWidth < ToSize ||
2579 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2580 return To->getKind() == BuiltinType::Int;
2581 }
2582
2583 // Are we promoting to an unsigned int from an unsigned bitfield
2584 // that fits into an unsigned int?
2585 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2586 return To->getKind() == BuiltinType::UInt;
2587 }
2588
2589 return false;
2590 }
2591 }
2592 }
2593
2594 // An rvalue of type bool can be converted to an rvalue of type int,
2595 // with false becoming zero and true becoming one (C++ 4.5p4).
2596 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2597 return true;
2598 }
2599
2600 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2601 // integral type.
2602 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2603 ToType->isIntegerType())
2604 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2605
2606 return false;
2607}
2608
2610 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2611 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2612 /// An rvalue of type float can be converted to an rvalue of type
2613 /// double. (C++ 4.6p1).
2614 if (FromBuiltin->getKind() == BuiltinType::Float &&
2615 ToBuiltin->getKind() == BuiltinType::Double)
2616 return true;
2617
2618 // C99 6.3.1.5p1:
2619 // When a float is promoted to double or long double, or a
2620 // double is promoted to long double [...].
2621 if (!getLangOpts().CPlusPlus &&
2622 (FromBuiltin->getKind() == BuiltinType::Float ||
2623 FromBuiltin->getKind() == BuiltinType::Double) &&
2624 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2625 ToBuiltin->getKind() == BuiltinType::Float128 ||
2626 ToBuiltin->getKind() == BuiltinType::Ibm128))
2627 return true;
2628
2629 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2630 // or not native half types are enabled.
2631 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2632 (ToBuiltin->getKind() == BuiltinType::Float ||
2633 ToBuiltin->getKind() == BuiltinType::Double))
2634 return true;
2635
2636 // Half can be promoted to float.
2637 if (!getLangOpts().NativeHalfType &&
2638 FromBuiltin->getKind() == BuiltinType::Half &&
2639 ToBuiltin->getKind() == BuiltinType::Float)
2640 return true;
2641 }
2642
2643 return false;
2644}
2645
2647 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2648 if (!FromComplex)
2649 return false;
2650
2651 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2652 if (!ToComplex)
2653 return false;
2654
2655 return IsFloatingPointPromotion(FromComplex->getElementType(),
2656 ToComplex->getElementType()) ||
2657 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2658 ToComplex->getElementType());
2659}
2660
2661/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2662/// the pointer type FromPtr to a pointer to type ToPointee, with the
2663/// same type qualifiers as FromPtr has on its pointee type. ToType,
2664/// if non-empty, will be a pointer to ToType that may or may not have
2665/// the right set of qualifiers on its pointee.
2666///
2667static QualType
2669 QualType ToPointee, QualType ToType,
2670 ASTContext &Context,
2671 bool StripObjCLifetime = false) {
2672 assert((FromPtr->getTypeClass() == Type::Pointer ||
2673 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2674 "Invalid similarly-qualified pointer type");
2675
2676 /// Conversions to 'id' subsume cv-qualifier conversions.
2677 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2678 return ToType.getUnqualifiedType();
2679
2680 QualType CanonFromPointee
2681 = Context.getCanonicalType(FromPtr->getPointeeType());
2682 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2683 Qualifiers Quals = CanonFromPointee.getQualifiers();
2684
2685 if (StripObjCLifetime)
2686 Quals.removeObjCLifetime();
2687
2688 // Exact qualifier match -> return the pointer type we're converting to.
2689 if (CanonToPointee.getLocalQualifiers() == Quals) {
2690 // ToType is exactly what we need. Return it.
2691 if (!ToType.isNull())
2692 return ToType.getUnqualifiedType();
2693
2694 // Build a pointer to ToPointee. It has the right qualifiers
2695 // already.
2696 if (isa<ObjCObjectPointerType>(ToType))
2697 return Context.getObjCObjectPointerType(ToPointee);
2698 return Context.getPointerType(ToPointee);
2699 }
2700
2701 // Just build a canonical type that has the right qualifiers.
2702 QualType QualifiedCanonToPointee
2703 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2704
2705 if (isa<ObjCObjectPointerType>(ToType))
2706 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2707 return Context.getPointerType(QualifiedCanonToPointee);
2708}
2709
2711 bool InOverloadResolution,
2712 ASTContext &Context) {
2713 // Handle value-dependent integral null pointer constants correctly.
2714 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2715 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2717 return !InOverloadResolution;
2718
2719 return Expr->isNullPointerConstant(Context,
2720 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2722}
2723
2725 bool InOverloadResolution,
2726 QualType& ConvertedType,
2727 bool &IncompatibleObjC) {
2728 IncompatibleObjC = false;
2729 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2730 IncompatibleObjC))
2731 return true;
2732
2733 // Conversion from a null pointer constant to any Objective-C pointer type.
2734 if (ToType->isObjCObjectPointerType() &&
2735 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2736 ConvertedType = ToType;
2737 return true;
2738 }
2739
2740 // Blocks: Block pointers can be converted to void*.
2741 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2742 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2743 ConvertedType = ToType;
2744 return true;
2745 }
2746 // Blocks: A null pointer constant can be converted to a block
2747 // pointer type.
2748 if (ToType->isBlockPointerType() &&
2749 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2750 ConvertedType = ToType;
2751 return true;
2752 }
2753
2754 // If the left-hand-side is nullptr_t, the right side can be a null
2755 // pointer constant.
2756 if (ToType->isNullPtrType() &&
2757 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2758 ConvertedType = ToType;
2759 return true;
2760 }
2761
2762 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2763 if (!ToTypePtr)
2764 return false;
2765
2766 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2767 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2768 ConvertedType = ToType;
2769 return true;
2770 }
2771
2772 // Beyond this point, both types need to be pointers
2773 // , including objective-c pointers.
2774 QualType ToPointeeType = ToTypePtr->getPointeeType();
2775 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2776 !getLangOpts().ObjCAutoRefCount) {
2777 ConvertedType = BuildSimilarlyQualifiedPointerType(
2778 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2779 Context);
2780 return true;
2781 }
2782 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2783 if (!FromTypePtr)
2784 return false;
2785
2786 QualType FromPointeeType = FromTypePtr->getPointeeType();
2787
2788 // If the unqualified pointee types are the same, this can't be a
2789 // pointer conversion, so don't do all of the work below.
2790 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2791 return false;
2792
2793 // An rvalue of type "pointer to cv T," where T is an object type,
2794 // can be converted to an rvalue of type "pointer to cv void" (C++
2795 // 4.10p2).
2796 if (FromPointeeType->isIncompleteOrObjectType() &&
2797 ToPointeeType->isVoidType()) {
2798 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2799 ToPointeeType,
2800 ToType, Context,
2801 /*StripObjCLifetime=*/true);
2802 return true;
2803 }
2804
2805 // MSVC allows implicit function to void* type conversion.
2806 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2807 ToPointeeType->isVoidType()) {
2808 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2809 ToPointeeType,
2810 ToType, Context);
2811 return true;
2812 }
2813
2814 // When we're overloading in C, we allow a special kind of pointer
2815 // conversion for compatible-but-not-identical pointee types.
2816 if (!getLangOpts().CPlusPlus &&
2817 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2818 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2819 ToPointeeType,
2820 ToType, Context);
2821 return true;
2822 }
2823
2824 // C++ [conv.ptr]p3:
2825 //
2826 // An rvalue of type "pointer to cv D," where D is a class type,
2827 // can be converted to an rvalue of type "pointer to cv B," where
2828 // B is a base class (clause 10) of D. If B is an inaccessible
2829 // (clause 11) or ambiguous (10.2) base class of D, a program that
2830 // necessitates this conversion is ill-formed. The result of the
2831 // conversion is a pointer to the base class sub-object of the
2832 // derived class object. The null pointer value is converted to
2833 // the null pointer value of the destination type.
2834 //
2835 // Note that we do not check for ambiguity or inaccessibility
2836 // here. That is handled by CheckPointerConversion.
2837 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2838 ToPointeeType->isRecordType() &&
2839 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2840 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2841 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2842 ToPointeeType,
2843 ToType, Context);
2844 return true;
2845 }
2846
2847 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2848 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2849 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2850 ToPointeeType,
2851 ToType, Context);
2852 return true;
2853 }
2854
2855 return false;
2856}
2857
2858/// Adopt the given qualifiers for the given type.
2860 Qualifiers TQs = T.getQualifiers();
2861
2862 // Check whether qualifiers already match.
2863 if (TQs == Qs)
2864 return T;
2865
2866 if (Qs.compatiblyIncludes(TQs))
2867 return Context.getQualifiedType(T, Qs);
2868
2869 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2870}
2871
2873 QualType& ConvertedType,
2874 bool &IncompatibleObjC) {
2875 if (!getLangOpts().ObjC)
2876 return false;
2877
2878 // The set of qualifiers on the type we're converting from.
2879 Qualifiers FromQualifiers = FromType.getQualifiers();
2880
2881 // First, we handle all conversions on ObjC object pointer types.
2882 const ObjCObjectPointerType* ToObjCPtr =
2883 ToType->getAs<ObjCObjectPointerType>();
2884 const ObjCObjectPointerType *FromObjCPtr =
2885 FromType->getAs<ObjCObjectPointerType>();
2886
2887 if (ToObjCPtr && FromObjCPtr) {
2888 // If the pointee types are the same (ignoring qualifications),
2889 // then this is not a pointer conversion.
2890 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2891 FromObjCPtr->getPointeeType()))
2892 return false;
2893
2894 // Conversion between Objective-C pointers.
2895 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2896 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2897 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2898 if (getLangOpts().CPlusPlus && LHS && RHS &&
2900 FromObjCPtr->getPointeeType()))
2901 return false;
2902 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2903 ToObjCPtr->getPointeeType(),
2904 ToType, Context);
2905 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2906 return true;
2907 }
2908
2909 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2910 // Okay: this is some kind of implicit downcast of Objective-C
2911 // interfaces, which is permitted. However, we're going to
2912 // complain about it.
2913 IncompatibleObjC = true;
2914 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2915 ToObjCPtr->getPointeeType(),
2916 ToType, Context);
2917 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2918 return true;
2919 }
2920 }
2921 // Beyond this point, both types need to be C pointers or block pointers.
2922 QualType ToPointeeType;
2923 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2924 ToPointeeType = ToCPtr->getPointeeType();
2925 else if (const BlockPointerType *ToBlockPtr =
2926 ToType->getAs<BlockPointerType>()) {
2927 // Objective C++: We're able to convert from a pointer to any object
2928 // to a block pointer type.
2929 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2930 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2931 return true;
2932 }
2933 ToPointeeType = ToBlockPtr->getPointeeType();
2934 }
2935 else if (FromType->getAs<BlockPointerType>() &&
2936 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2937 // Objective C++: We're able to convert from a block pointer type to a
2938 // pointer to any object.
2939 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2940 return true;
2941 }
2942 else
2943 return false;
2944
2945 QualType FromPointeeType;
2946 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2947 FromPointeeType = FromCPtr->getPointeeType();
2948 else if (const BlockPointerType *FromBlockPtr =
2949 FromType->getAs<BlockPointerType>())
2950 FromPointeeType = FromBlockPtr->getPointeeType();
2951 else
2952 return false;
2953
2954 // If we have pointers to pointers, recursively check whether this
2955 // is an Objective-C conversion.
2956 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2957 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2958 IncompatibleObjC)) {
2959 // We always complain about this conversion.
2960 IncompatibleObjC = true;
2961 ConvertedType = Context.getPointerType(ConvertedType);
2962 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2963 return true;
2964 }
2965 // Allow conversion of pointee being objective-c pointer to another one;
2966 // as in I* to id.
2967 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2968 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2969 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2970 IncompatibleObjC)) {
2971
2972 ConvertedType = Context.getPointerType(ConvertedType);
2973 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2974 return true;
2975 }
2976
2977 // If we have pointers to functions or blocks, check whether the only
2978 // differences in the argument and result types are in Objective-C
2979 // pointer conversions. If so, we permit the conversion (but
2980 // complain about it).
2981 const FunctionProtoType *FromFunctionType
2982 = FromPointeeType->getAs<FunctionProtoType>();
2983 const FunctionProtoType *ToFunctionType
2984 = ToPointeeType->getAs<FunctionProtoType>();
2985 if (FromFunctionType && ToFunctionType) {
2986 // If the function types are exactly the same, this isn't an
2987 // Objective-C pointer conversion.
2988 if (Context.getCanonicalType(FromPointeeType)
2989 == Context.getCanonicalType(ToPointeeType))
2990 return false;
2991
2992 // Perform the quick checks that will tell us whether these
2993 // function types are obviously different.
2994 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2995 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2996 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2997 return false;
2998
2999 bool HasObjCConversion = false;
3000 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3001 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3002 // Okay, the types match exactly. Nothing to do.
3003 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3004 ToFunctionType->getReturnType(),
3005 ConvertedType, IncompatibleObjC)) {
3006 // Okay, we have an Objective-C pointer conversion.
3007 HasObjCConversion = true;
3008 } else {
3009 // Function types are too different. Abort.
3010 return false;
3011 }
3012
3013 // Check argument types.
3014 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3015 ArgIdx != NumArgs; ++ArgIdx) {
3016 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3017 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3018 if (Context.getCanonicalType(FromArgType)
3019 == Context.getCanonicalType(ToArgType)) {
3020 // Okay, the types match exactly. Nothing to do.
3021 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3022 ConvertedType, IncompatibleObjC)) {
3023 // Okay, we have an Objective-C pointer conversion.
3024 HasObjCConversion = true;
3025 } else {
3026 // Argument types are too different. Abort.
3027 return false;
3028 }
3029 }
3030
3031 if (HasObjCConversion) {
3032 // We had an Objective-C conversion. Allow this pointer
3033 // conversion, but complain about it.
3034 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3035 IncompatibleObjC = true;
3036 return true;
3037 }
3038 }
3039
3040 return false;
3041}
3042
3044 QualType& ConvertedType) {
3045 QualType ToPointeeType;
3046 if (const BlockPointerType *ToBlockPtr =
3047 ToType->getAs<BlockPointerType>())
3048 ToPointeeType = ToBlockPtr->getPointeeType();
3049 else
3050 return false;
3051
3052 QualType FromPointeeType;
3053 if (const BlockPointerType *FromBlockPtr =
3054 FromType->getAs<BlockPointerType>())
3055 FromPointeeType = FromBlockPtr->getPointeeType();
3056 else
3057 return false;
3058 // We have pointer to blocks, check whether the only
3059 // differences in the argument and result types are in Objective-C
3060 // pointer conversions. If so, we permit the conversion.
3061
3062 const FunctionProtoType *FromFunctionType
3063 = FromPointeeType->getAs<FunctionProtoType>();
3064 const FunctionProtoType *ToFunctionType
3065 = ToPointeeType->getAs<FunctionProtoType>();
3066
3067 if (!FromFunctionType || !ToFunctionType)
3068 return false;
3069
3070 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3071 return true;
3072
3073 // Perform the quick checks that will tell us whether these
3074 // function types are obviously different.
3075 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3076 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3077 return false;
3078
3079 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3080 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3081 if (FromEInfo != ToEInfo)
3082 return false;
3083
3084 bool IncompatibleObjC = false;
3085 if (Context.hasSameType(FromFunctionType->getReturnType(),
3086 ToFunctionType->getReturnType())) {
3087 // Okay, the types match exactly. Nothing to do.
3088 } else {
3089 QualType RHS = FromFunctionType->getReturnType();
3090 QualType LHS = ToFunctionType->getReturnType();
3091 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3092 !RHS.hasQualifiers() && LHS.hasQualifiers())
3093 LHS = LHS.getUnqualifiedType();
3094
3095 if (Context.hasSameType(RHS,LHS)) {
3096 // OK exact match.
3097 } else if (isObjCPointerConversion(RHS, LHS,
3098 ConvertedType, IncompatibleObjC)) {
3099 if (IncompatibleObjC)
3100 return false;
3101 // Okay, we have an Objective-C pointer conversion.
3102 }
3103 else
3104 return false;
3105 }
3106
3107 // Check argument types.
3108 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3109 ArgIdx != NumArgs; ++ArgIdx) {
3110 IncompatibleObjC = false;
3111 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3112 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3113 if (Context.hasSameType(FromArgType, ToArgType)) {
3114 // Okay, the types match exactly. Nothing to do.
3115 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3116 ConvertedType, IncompatibleObjC)) {
3117 if (IncompatibleObjC)
3118 return false;
3119 // Okay, we have an Objective-C pointer conversion.
3120 } else
3121 // Argument types are too different. Abort.
3122 return false;
3123 }
3124
3126 bool CanUseToFPT, CanUseFromFPT;
3127 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3128 CanUseToFPT, CanUseFromFPT,
3129 NewParamInfos))
3130 return false;
3131
3132 ConvertedType = ToType;
3133 return true;
3134}
3135
3136enum {
3145
3146/// Attempts to get the FunctionProtoType from a Type. Handles
3147/// MemberFunctionPointers properly.
3149 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3150 return FPT;
3151
3152 if (auto *MPT = FromType->getAs<MemberPointerType>())
3153 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3154
3155 return nullptr;
3156}
3157
3159 QualType FromType, QualType ToType) {
3160 // If either type is not valid, include no extra info.
3161 if (FromType.isNull() || ToType.isNull()) {
3162 PDiag << ft_default;
3163 return;
3164 }
3165
3166 // Get the function type from the pointers.
3167 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3168 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3169 *ToMember = ToType->castAs<MemberPointerType>();
3170 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3171 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3172 << QualType(FromMember->getClass(), 0);
3173 return;
3174 }
3175 FromType = FromMember->getPointeeType();
3176 ToType = ToMember->getPointeeType();
3177 }
3178
3179 if (FromType->isPointerType())
3180 FromType = FromType->getPointeeType();
3181 if (ToType->isPointerType())
3182 ToType = ToType->getPointeeType();
3183
3184 // Remove references.
3185 FromType = FromType.getNonReferenceType();
3186 ToType = ToType.getNonReferenceType();
3187
3188 // Don't print extra info for non-specialized template functions.
3189 if (FromType->isInstantiationDependentType() &&
3190 !FromType->getAs<TemplateSpecializationType>()) {
3191 PDiag << ft_default;
3192 return;
3193 }
3194
3195 // No extra info for same types.
3196 if (Context.hasSameType(FromType, ToType)) {
3197 PDiag << ft_default;
3198 return;
3199 }
3200
3201 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3202 *ToFunction = tryGetFunctionProtoType(ToType);
3203
3204 // Both types need to be function types.
3205 if (!FromFunction || !ToFunction) {
3206 PDiag << ft_default;
3207 return;
3208 }
3209
3210 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3211 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3212 << FromFunction->getNumParams();
3213 return;
3214 }
3215
3216 // Handle different parameter types.
3217 unsigned ArgPos;
3218 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3219 PDiag << ft_parameter_mismatch << ArgPos + 1
3220 << ToFunction->getParamType(ArgPos)
3221 << FromFunction->getParamType(ArgPos);
3222 return;
3223 }
3224
3225 // Handle different return type.
3226 if (!Context.hasSameType(FromFunction->getReturnType(),
3227 ToFunction->getReturnType())) {
3228 PDiag << ft_return_type << ToFunction->getReturnType()
3229 << FromFunction->getReturnType();
3230 return;
3231 }
3232
3233 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3234 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3235 << FromFunction->getMethodQuals();
3236 return;
3237 }
3238
3239 // Handle exception specification differences on canonical type (in C++17
3240 // onwards).
3241 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3242 ->isNothrow() !=
3243 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3244 ->isNothrow()) {
3245 PDiag << ft_noexcept;
3246 return;
3247 }
3248
3249 // Unable to find a difference, so add no extra info.
3250 PDiag << ft_default;
3251}
3252
3254 ArrayRef<QualType> New, unsigned *ArgPos,
3255 bool Reversed) {
3256 assert(llvm::size(Old) == llvm::size(New) &&
3257 "Can't compare parameters of functions with different number of "
3258 "parameters!");
3259
3260 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3261 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3262 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3263
3264 // Ignore address spaces in pointee type. This is to disallow overloading
3265 // on __ptr32/__ptr64 address spaces.
3266 QualType OldType =
3267 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3268 QualType NewType =
3269 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3270
3271 if (!Context.hasSameType(OldType, NewType)) {
3272 if (ArgPos)
3273 *ArgPos = Idx;
3274 return false;
3275 }
3276 }
3277 return true;
3278}
3279
3281 const FunctionProtoType *NewType,
3282 unsigned *ArgPos, bool Reversed) {
3283 return FunctionParamTypesAreEqual(OldType->param_types(),
3284 NewType->param_types(), ArgPos, Reversed);
3285}
3286
3288 const FunctionDecl *NewFunction,
3289 unsigned *ArgPos,
3290 bool Reversed) {
3291
3292 if (OldFunction->getNumNonObjectParams() !=
3293 NewFunction->getNumNonObjectParams())
3294 return false;
3295
3296 unsigned OldIgnore =
3298 unsigned NewIgnore =
3300
3301 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3302 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3303
3304 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3305 NewPT->param_types().slice(NewIgnore),
3306 ArgPos, Reversed);
3307}
3308
3310 CastKind &Kind,
3311 CXXCastPath& BasePath,
3312 bool IgnoreBaseAccess,
3313 bool Diagnose) {
3314 QualType FromType = From->getType();
3315 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3316
3317 Kind = CK_BitCast;
3318
3319 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3322 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3323 DiagRuntimeBehavior(From->getExprLoc(), From,
3324 PDiag(diag::warn_impcast_bool_to_null_pointer)
3325 << ToType << From->getSourceRange());
3326 else if (!isUnevaluatedContext())
3327 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3328 << ToType << From->getSourceRange();
3329 }
3330 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3331 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3332 QualType FromPointeeType = FromPtrType->getPointeeType(),
3333 ToPointeeType = ToPtrType->getPointeeType();
3334
3335 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3336 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3337 // We must have a derived-to-base conversion. Check an
3338 // ambiguous or inaccessible conversion.
3339 unsigned InaccessibleID = 0;
3340 unsigned AmbiguousID = 0;
3341 if (Diagnose) {
3342 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3343 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3344 }
3345 if (CheckDerivedToBaseConversion(
3346 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3347 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3348 &BasePath, IgnoreBaseAccess))
3349 return true;
3350
3351 // The conversion was successful.
3352 Kind = CK_DerivedToBase;
3353 }
3354
3355 if (Diagnose && !IsCStyleOrFunctionalCast &&
3356 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3357 assert(getLangOpts().MSVCCompat &&
3358 "this should only be possible with MSVCCompat!");
3359 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3360 << From->getSourceRange();
3361 }
3362 }
3363 } else if (const ObjCObjectPointerType *ToPtrType =
3364 ToType->getAs<ObjCObjectPointerType>()) {
3365 if (const ObjCObjectPointerType *FromPtrType =
3366 FromType->getAs<ObjCObjectPointerType>()) {
3367 // Objective-C++ conversions are always okay.
3368 // FIXME: We should have a different class of conversions for the
3369 // Objective-C++ implicit conversions.
3370 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3371 return false;
3372 } else if (FromType->isBlockPointerType()) {
3373 Kind = CK_BlockPointerToObjCPointerCast;
3374 } else {
3375 Kind = CK_CPointerToObjCPointerCast;
3376 }
3377 } else if (ToType->isBlockPointerType()) {
3378 if (!FromType->isBlockPointerType())
3379 Kind = CK_AnyPointerToBlockPointerCast;
3380 }
3381
3382 // We shouldn't fall into this case unless it's valid for other
3383 // reasons.
3385 Kind = CK_NullToPointer;
3386
3387 return false;
3388}
3389
3391 QualType ToType,
3392 bool InOverloadResolution,
3393 QualType &ConvertedType) {
3394 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3395 if (!ToTypePtr)
3396 return false;
3397
3398 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3399 if (From->isNullPointerConstant(Context,
3400 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3402 ConvertedType = ToType;
3403 return true;
3404 }
3405
3406 // Otherwise, both types have to be member pointers.
3407 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3408 if (!FromTypePtr)
3409 return false;
3410
3411 // A pointer to member of B can be converted to a pointer to member of D,
3412 // where D is derived from B (C++ 4.11p2).
3413 QualType FromClass(FromTypePtr->getClass(), 0);
3414 QualType ToClass(ToTypePtr->getClass(), 0);
3415
3416 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3417 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3418 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3419 ToClass.getTypePtr());
3420 return true;
3421 }
3422
3423 return false;
3424}
3425
3427 CastKind &Kind,
3428 CXXCastPath &BasePath,
3429 bool IgnoreBaseAccess) {
3430 QualType FromType = From->getType();
3431 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3432 if (!FromPtrType) {
3433 // This must be a null pointer to member pointer conversion
3434 assert(From->isNullPointerConstant(Context,
3436 "Expr must be null pointer constant!");
3437 Kind = CK_NullToMemberPointer;
3438 return false;
3439 }
3440
3441 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3442 assert(ToPtrType && "No member pointer cast has a target type "
3443 "that is not a member pointer.");
3444
3445 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3446 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3447
3448 // FIXME: What about dependent types?
3449 assert(FromClass->isRecordType() && "Pointer into non-class.");
3450 assert(ToClass->isRecordType() && "Pointer into non-class.");
3451
3452 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3453 /*DetectVirtual=*/true);
3454 bool DerivationOkay =
3455 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3456 assert(DerivationOkay &&
3457 "Should not have been called if derivation isn't OK.");
3458 (void)DerivationOkay;
3459
3460 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3461 getUnqualifiedType())) {
3462 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3463 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3464 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3465 return true;
3466 }
3467
3468 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3469 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3470 << FromClass << ToClass << QualType(VBase, 0)
3471 << From->getSourceRange();
3472 return true;
3473 }
3474
3475 if (!IgnoreBaseAccess)
3476 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3477 Paths.front(),
3478 diag::err_downcast_from_inaccessible_base);
3479
3480 // Must be a base to derived member conversion.
3481 BuildBasePathArray(Paths, BasePath);
3482 Kind = CK_BaseToDerivedMemberPointer;
3483 return false;
3484}
3485
3486/// Determine whether the lifetime conversion between the two given
3487/// qualifiers sets is nontrivial.
3489 Qualifiers ToQuals) {
3490 // Converting anything to const __unsafe_unretained is trivial.
3491 if (ToQuals.hasConst() &&
3493 return false;
3494
3495 return true;
3496}
3497
3498/// Perform a single iteration of the loop for checking if a qualification
3499/// conversion is valid.
3500///
3501/// Specifically, check whether any change between the qualifiers of \p
3502/// FromType and \p ToType is permissible, given knowledge about whether every
3503/// outer layer is const-qualified.
3505 bool CStyle, bool IsTopLevel,
3506 bool &PreviousToQualsIncludeConst,
3507 bool &ObjCLifetimeConversion) {
3508 Qualifiers FromQuals = FromType.getQualifiers();
3509 Qualifiers ToQuals = ToType.getQualifiers();
3510
3511 // Ignore __unaligned qualifier.
3512 FromQuals.removeUnaligned();
3513
3514 // Objective-C ARC:
3515 // Check Objective-C lifetime conversions.
3516 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3517 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3518 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3519 ObjCLifetimeConversion = true;
3520 FromQuals.removeObjCLifetime();
3521 ToQuals.removeObjCLifetime();
3522 } else {
3523 // Qualification conversions cannot cast between different
3524 // Objective-C lifetime qualifiers.
3525 return false;
3526 }
3527 }
3528
3529 // Allow addition/removal of GC attributes but not changing GC attributes.
3530 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3531 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3532 FromQuals.removeObjCGCAttr();
3533 ToQuals.removeObjCGCAttr();
3534 }
3535
3536 // -- for every j > 0, if const is in cv 1,j then const is in cv
3537 // 2,j, and similarly for volatile.
3538 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3539 return false;
3540
3541 // If address spaces mismatch:
3542 // - in top level it is only valid to convert to addr space that is a
3543 // superset in all cases apart from C-style casts where we allow
3544 // conversions between overlapping address spaces.
3545 // - in non-top levels it is not a valid conversion.
3546 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3547 (!IsTopLevel ||
3548 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3549 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3550 return false;
3551
3552 // -- if the cv 1,j and cv 2,j are different, then const is in
3553 // every cv for 0 < k < j.
3554 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3555 !PreviousToQualsIncludeConst)
3556 return false;
3557
3558 // The following wording is from C++20, where the result of the conversion
3559 // is T3, not T2.
3560 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3561 // "array of unknown bound of"
3562 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3563 return false;
3564
3565 // -- if the resulting P3,i is different from P1,i [...], then const is
3566 // added to every cv 3_k for 0 < k < i.
3567 if (!CStyle && FromType->isConstantArrayType() &&
3568 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3569 return false;
3570
3571 // Keep track of whether all prior cv-qualifiers in the "to" type
3572 // include const.
3573 PreviousToQualsIncludeConst =
3574 PreviousToQualsIncludeConst && ToQuals.hasConst();
3575 return true;
3576}
3577
3578bool
3580 bool CStyle, bool &ObjCLifetimeConversion) {
3581 FromType = Context.getCanonicalType(FromType);
3582 ToType = Context.getCanonicalType(ToType);
3583 ObjCLifetimeConversion = false;
3584
3585 // If FromType and ToType are the same type, this is not a
3586 // qualification conversion.
3587 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3588 return false;
3589
3590 // (C++ 4.4p4):
3591 // A conversion can add cv-qualifiers at levels other than the first
3592 // in multi-level pointers, subject to the following rules: [...]
3593 bool PreviousToQualsIncludeConst = true;
3594 bool UnwrappedAnyPointer = false;
3595 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3597 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3598 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3599 return false;
3600 UnwrappedAnyPointer = true;
3601 }
3602
3603 // We are left with FromType and ToType being the pointee types
3604 // after unwrapping the original FromType and ToType the same number
3605 // of times. If we unwrapped any pointers, and if FromType and
3606 // ToType have the same unqualified type (since we checked
3607 // qualifiers above), then this is a qualification conversion.
3608 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3609}
3610
3611/// - Determine whether this is a conversion from a scalar type to an
3612/// atomic type.
3613///
3614/// If successful, updates \c SCS's second and third steps in the conversion
3615/// sequence to finish the conversion.
3616static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3617 bool InOverloadResolution,
3619 bool CStyle) {
3620 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3621 if (!ToAtomic)
3622 return false;
3623
3625 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3626 InOverloadResolution, InnerSCS,
3627 CStyle, /*AllowObjCWritebackConversion=*/false))
3628 return false;
3629
3630 SCS.Second = InnerSCS.Second;
3631 SCS.setToType(1, InnerSCS.getToType(1));
3632 SCS.Third = InnerSCS.Third;
3635 SCS.setToType(2, InnerSCS.getToType(2));
3636 return true;
3637}
3638
3640 CXXConstructorDecl *Constructor,
3641 QualType Type) {
3642 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3643 if (CtorType->getNumParams() > 0) {
3644 QualType FirstArg = CtorType->getParamType(0);
3645 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3646 return true;
3647 }
3648 return false;
3649}
3650
3651static OverloadingResult
3653 CXXRecordDecl *To,
3655 OverloadCandidateSet &CandidateSet,
3656 bool AllowExplicit) {
3658 for (auto *D : S.LookupConstructors(To)) {
3659 auto Info = getConstructorInfo(D);
3660 if (!Info)
3661 continue;
3662
3663 bool Usable = !Info.Constructor->isInvalidDecl() &&
3664 S.isInitListConstructor(Info.Constructor);
3665 if (Usable) {
3666 bool SuppressUserConversions = false;
3667 if (Info.ConstructorTmpl)
3668 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3669 /*ExplicitArgs*/ nullptr, From,
3670 CandidateSet, SuppressUserConversions,
3671 /*PartialOverloading*/ false,
3672 AllowExplicit);
3673 else
3674 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3675 CandidateSet, SuppressUserConversions,
3676 /*PartialOverloading*/ false, AllowExplicit);
3677 }
3678 }
3679
3680 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3681
3683 switch (auto Result =
3684 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3685 case OR_Deleted:
3686 case OR_Success: {
3687 // Record the standard conversion we used and the conversion function.
3688 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3689 QualType ThisType = Constructor->getFunctionObjectParameterType();
3690 // Initializer lists don't have conversions as such.
3692 User.HadMultipleCandidates = HadMultipleCandidates;
3693 User.ConversionFunction = Constructor;
3694 User.FoundConversionFunction = Best->FoundDecl;
3696 User.After.setFromType(ThisType);
3697 User.After.setAllToTypes(ToType);
3698 return Result;
3699 }
3700
3702 return OR_No_Viable_Function;
3703 case OR_Ambiguous:
3704 return OR_Ambiguous;
3705 }
3706
3707 llvm_unreachable("Invalid OverloadResult!");
3708}
3709
3710/// Determines whether there is a user-defined conversion sequence
3711/// (C++ [over.ics.user]) that converts expression From to the type
3712/// ToType. If such a conversion exists, User will contain the
3713/// user-defined conversion sequence that performs such a conversion
3714/// and this routine will return true. Otherwise, this routine returns
3715/// false and User is unspecified.
3716///
3717/// \param AllowExplicit true if the conversion should consider C++0x
3718/// "explicit" conversion functions as well as non-explicit conversion
3719/// functions (C++0x [class.conv.fct]p2).
3720///
3721/// \param AllowObjCConversionOnExplicit true if the conversion should
3722/// allow an extra Objective-C pointer conversion on uses of explicit
3723/// constructors. Requires \c AllowExplicit to also be set.
3724static OverloadingResult
3727 OverloadCandidateSet &CandidateSet,
3728 AllowedExplicit AllowExplicit,
3729 bool AllowObjCConversionOnExplicit) {
3730 assert(AllowExplicit != AllowedExplicit::None ||
3731 !AllowObjCConversionOnExplicit);
3733
3734 // Whether we will only visit constructors.
3735 bool ConstructorsOnly = false;
3736
3737 // If the type we are conversion to is a class type, enumerate its
3738 // constructors.
3739 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3740 // C++ [over.match.ctor]p1:
3741 // When objects of class type are direct-initialized (8.5), or
3742 // copy-initialized from an expression of the same or a
3743 // derived class type (8.5), overload resolution selects the
3744 // constructor. [...] For copy-initialization, the candidate
3745 // functions are all the converting constructors (12.3.1) of
3746 // that class. The argument list is the expression-list within
3747 // the parentheses of the initializer.
3748 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3749 (From->getType()->getAs<RecordType>() &&
3750 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3751 ConstructorsOnly = true;
3752
3753 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3754 // We're not going to find any constructors.
3755 } else if (CXXRecordDecl *ToRecordDecl
3756 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3757
3758 Expr **Args = &From;
3759 unsigned NumArgs = 1;
3760 bool ListInitializing = false;
3761 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3762 // But first, see if there is an init-list-constructor that will work.
3764 S, From, ToType, ToRecordDecl, User, CandidateSet,
3765 AllowExplicit == AllowedExplicit::All);
3767 return Result;
3768 // Never mind.
3769 CandidateSet.clear(
3771
3772 // If we're list-initializing, we pass the individual elements as
3773 // arguments, not the entire list.
3774 Args = InitList->getInits();
3775 NumArgs = InitList->getNumInits();
3776 ListInitializing = true;
3777 }
3778
3779 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3780 auto Info = getConstructorInfo(D);
3781 if (!Info)
3782 continue;
3783
3784 bool Usable = !Info.Constructor->isInvalidDecl();
3785 if (!ListInitializing)
3786 Usable = Usable && Info.Constructor->isConvertingConstructor(
3787 /*AllowExplicit*/ true);
3788 if (Usable) {
3789 bool SuppressUserConversions = !ConstructorsOnly;
3790 // C++20 [over.best.ics.general]/4.5:
3791 // if the target is the first parameter of a constructor [of class
3792 // X] and the constructor [...] is a candidate by [...] the second
3793 // phase of [over.match.list] when the initializer list has exactly
3794 // one element that is itself an initializer list, [...] and the
3795 // conversion is to X or reference to cv X, user-defined conversion
3796 // sequences are not cnosidered.
3797 if (SuppressUserConversions && ListInitializing) {
3798 SuppressUserConversions =
3799 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3800 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3801 ToType);
3802 }
3803 if (Info.ConstructorTmpl)
3805 Info.ConstructorTmpl, Info.FoundDecl,
3806 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3807 CandidateSet, SuppressUserConversions,
3808 /*PartialOverloading*/ false,
3809 AllowExplicit == AllowedExplicit::All);
3810 else
3811 // Allow one user-defined conversion when user specifies a
3812 // From->ToType conversion via an static cast (c-style, etc).
3813 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3814 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3815 SuppressUserConversions,
3816 /*PartialOverloading*/ false,
3817 AllowExplicit == AllowedExplicit::All);
3818 }
3819 }
3820 }
3821 }
3822
3823 // Enumerate conversion functions, if we're allowed to.
3824 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3825 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3826 // No conversion functions from incomplete types.
3827 } else if (const RecordType *FromRecordType =
3828 From->getType()->getAs<RecordType>()) {
3829 if (CXXRecordDecl *FromRecordDecl
3830 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3831 // Add all of the conversion functions as candidates.
3832 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3833 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3834 DeclAccessPair FoundDecl = I.getPair();
3835 NamedDecl *D = FoundDecl.getDecl();
3836 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3837 if (isa<UsingShadowDecl>(D))
3838 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3839
3840 CXXConversionDecl *Conv;
3841 FunctionTemplateDecl *ConvTemplate;
3842 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3843 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3844 else
3845 Conv = cast<CXXConversionDecl>(D);
3846
3847 if (ConvTemplate)
3849 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3850 CandidateSet, AllowObjCConversionOnExplicit,
3851 AllowExplicit != AllowedExplicit::None);
3852 else
3853 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3854 CandidateSet, AllowObjCConversionOnExplicit,
3855 AllowExplicit != AllowedExplicit::None);
3856 }
3857 }
3858 }
3859
3860 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3861
3863 switch (auto Result =
3864 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3865 case OR_Success:
3866 case OR_Deleted:
3867 // Record the standard conversion we used and the conversion function.
3868 if (CXXConstructorDecl *Constructor
3869 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3870 // C++ [over.ics.user]p1:
3871 // If the user-defined conversion is specified by a
3872 // constructor (12.3.1), the initial standard conversion
3873 // sequence converts the source type to the type required by
3874 // the argument of the constructor.
3875 //
3876 if (isa<InitListExpr>(From)) {
3877 // Initializer lists don't have conversions as such.
3879 } else {
3880 if (Best->Conversions[0].isEllipsis())
3881 User.EllipsisConversion = true;
3882 else {
3883 User.Before = Best->Conversions[0].Standard;
3884 User.EllipsisConversion = false;
3885 }
3886 }
3887 User.HadMultipleCandidates = HadMultipleCandidates;
3888 User.ConversionFunction = Constructor;
3889 User.FoundConversionFunction = Best->FoundDecl;
3891 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3892 User.After.setAllToTypes(ToType);
3893 return Result;
3894 }
3895 if (CXXConversionDecl *Conversion
3896 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3897 // C++ [over.ics.user]p1:
3898 //
3899 // [...] If the user-defined conversion is specified by a
3900 // conversion function (12.3.2), the initial standard
3901 // conversion sequence converts the source type to the
3902 // implicit object parameter of the conversion function.
3903 User.Before = Best->Conversions[0].Standard;
3904 User.HadMultipleCandidates = HadMultipleCandidates;
3905 User.ConversionFunction = Conversion;
3906 User.FoundConversionFunction = Best->FoundDecl;
3907 User.EllipsisConversion = false;
3908
3909 // C++ [over.ics.user]p2:
3910 // The second standard conversion sequence converts the
3911 // result of the user-defined conversion to the target type
3912 // for the sequence. Since an implicit conversion sequence
3913 // is an initialization, the special rules for
3914 // initialization by user-defined conversion apply when
3915 // selecting the best user-defined conversion for a
3916 // user-defined conversion sequence (see 13.3.3 and
3917 // 13.3.3.1).
3918 User.After = Best->FinalConversion;
3919 return Result;
3920 }
3921 llvm_unreachable("Not a constructor or conversion function?");
3922
3924 return OR_No_Viable_Function;
3925
3926 case OR_Ambiguous:
3927 return OR_Ambiguous;
3928 }
3929
3930 llvm_unreachable("Invalid OverloadResult!");
3931}
3932
3933bool
3936 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3938 OverloadingResult OvResult =
3939 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3940 CandidateSet, AllowedExplicit::None, false);
3941
3942 if (!(OvResult == OR_Ambiguous ||
3943 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3944 return false;
3945
3946 auto Cands = CandidateSet.CompleteCandidates(
3947 *this,
3949 From);
3950 if (OvResult == OR_Ambiguous)
3951 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3952 << From->getType() << ToType << From->getSourceRange();
3953 else { // OR_No_Viable_Function && !CandidateSet.empty()
3954 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3955 diag::err_typecheck_nonviable_condition_incomplete,
3956 From->getType(), From->getSourceRange()))
3957 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3958 << false << From->getType() << From->getSourceRange() << ToType;
3959 }
3960
3961 CandidateSet.NoteCandidates(
3962 *this, From, Cands);
3963 return true;
3964}
3965
3966// Helper for compareConversionFunctions that gets the FunctionType that the
3967// conversion-operator return value 'points' to, or nullptr.
3968static const FunctionType *
3970 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3971 const PointerType *RetPtrTy =
3972 ConvFuncTy->getReturnType()->getAs<PointerType>();
3973
3974 if (!RetPtrTy)
3975 return nullptr;
3976
3977 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3978}
3979
3980/// Compare the user-defined conversion functions or constructors
3981/// of two user-defined conversion sequences to determine whether any ordering
3982/// is possible.
3985 FunctionDecl *Function2) {
3986 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3987 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3988 if (!Conv1 || !Conv2)
3990
3991 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3993
3994 // Objective-C++:
3995 // If both conversion functions are implicitly-declared conversions from
3996 // a lambda closure type to a function pointer and a block pointer,
3997 // respectively, always prefer the conversion to a function pointer,
3998 // because the function pointer is more lightweight and is more likely
3999 // to keep code working.
4000 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4001 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4002 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4003 if (Block1 != Block2)
4004 return Block1 ? ImplicitConversionSequence::Worse
4006 }
4007
4008 // In order to support multiple calling conventions for the lambda conversion
4009 // operator (such as when the free and member function calling convention is
4010 // different), prefer the 'free' mechanism, followed by the calling-convention
4011 // of operator(). The latter is in place to support the MSVC-like solution of
4012 // defining ALL of the possible conversions in regards to calling-convention.
4013 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4014 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4015
4016 if (Conv1FuncRet && Conv2FuncRet &&
4017 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4018 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4019 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4020
4021 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4022 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4023
4024 CallingConv CallOpCC =
4025 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4027 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4029 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4030
4031 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4032 for (CallingConv CC : PrefOrder) {
4033 if (Conv1CC == CC)
4035 if (Conv2CC == CC)
4037 }
4038 }
4039
4041}
4042
4044 const ImplicitConversionSequence &ICS) {
4046 (ICS.isUserDefined() &&
4048}
4049
4050/// CompareImplicitConversionSequences - Compare two implicit
4051/// conversion sequences to determine whether one is better than the
4052/// other or if they are indistinguishable (C++ 13.3.3.2).
4055 const ImplicitConversionSequence& ICS1,
4056 const ImplicitConversionSequence& ICS2)
4057{
4058 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4059 // conversion sequences (as defined in 13.3.3.1)
4060 // -- a standard conversion sequence (13.3.3.1.1) is a better
4061 // conversion sequence than a user-defined conversion sequence or
4062 // an ellipsis conversion sequence, and
4063 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4064 // conversion sequence than an ellipsis conversion sequence
4065 // (13.3.3.1.3).
4066 //
4067 // C++0x [over.best.ics]p10:
4068 // For the purpose of ranking implicit conversion sequences as
4069 // described in 13.3.3.2, the ambiguous conversion sequence is
4070 // treated as a user-defined sequence that is indistinguishable
4071 // from any other user-defined conversion sequence.
4072
4073 // String literal to 'char *' conversion has been deprecated in C++03. It has
4074 // been removed from C++11. We still accept this conversion, if it happens at
4075 // the best viable function. Otherwise, this conversion is considered worse
4076 // than ellipsis conversion. Consider this as an extension; this is not in the
4077 // standard. For example:
4078 //
4079 // int &f(...); // #1
4080 // void f(char*); // #2
4081 // void g() { int &r = f("foo"); }
4082 //
4083 // In C++03, we pick #2 as the best viable function.
4084 // In C++11, we pick #1 as the best viable function, because ellipsis
4085 // conversion is better than string-literal to char* conversion (since there
4086 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4087 // convert arguments, #2 would be the best viable function in C++11.
4088 // If the best viable function has this conversion, a warning will be issued
4089 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4090
4091 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4094 // Ill-formedness must not differ
4095 ICS1.isBad() == ICS2.isBad())
4099
4100 if (ICS1.getKindRank() < ICS2.getKindRank())
4102 if (ICS2.getKindRank() < ICS1.getKindRank())
4104
4105 // The following checks require both conversion sequences to be of
4106 // the same kind.
4107 if (ICS1.getKind() != ICS2.getKind())
4109
4112
4113 // Two implicit conversion sequences of the same form are
4114 // indistinguishable conversion sequences unless one of the
4115 // following rules apply: (C++ 13.3.3.2p3):
4116
4117 // List-initialization sequence L1 is a better conversion sequence than
4118 // list-initialization sequence L2 if:
4119 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4120 // if not that,
4121 // — L1 and L2 convert to arrays of the same element type, and either the
4122 // number of elements n_1 initialized by L1 is less than the number of
4123 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4124 // an array of unknown bound and L1 does not,
4125 // even if one of the other rules in this paragraph would otherwise apply.
4126 if (!ICS1.isBad()) {
4127 bool StdInit1 = false, StdInit2 = false;
4130 nullptr);
4133 nullptr);
4134 if (StdInit1 != StdInit2)
4135 return StdInit1 ? ImplicitConversionSequence::Better
4137
4140 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4142 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4144 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4145 CAT2->getElementType())) {
4146 // Both to arrays of the same element type
4147 if (CAT1->getSize() != CAT2->getSize())
4148 // Different sized, the smaller wins
4149 return CAT1->getSize().ult(CAT2->getSize())
4154 // One is incomplete, it loses
4158 }
4159 }
4160 }
4161
4162 if (ICS1.isStandard())
4163 // Standard conversion sequence S1 is a better conversion sequence than
4164 // standard conversion sequence S2 if [...]
4166 ICS1.Standard, ICS2.Standard);
4167 else if (ICS1.isUserDefined()) {
4168 // User-defined conversion sequence U1 is a better conversion
4169 // sequence than another user-defined conversion sequence U2 if
4170 // they contain the same user-defined conversion function or
4171 // constructor and if the second standard conversion sequence of
4172 // U1 is better than the second standard conversion sequence of
4173 // U2 (C++ 13.3.3.2p3).
4177 ICS1.UserDefined.After,
4178 ICS2.UserDefined.After);
4179 else
4183 }
4184
4185 return Result;
4186}
4187
4188// Per 13.3.3.2p3, compare the given standard conversion sequences to
4189// determine if one is a proper subset of the other.
4192 const StandardConversionSequence& SCS1,
4193 const StandardConversionSequence& SCS2) {
4196
4197 // the identity conversion sequence is considered to be a subsequence of
4198 // any non-identity conversion sequence
4199 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4201 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4203
4204 if (SCS1.Second != SCS2.Second) {
4205 if (SCS1.Second == ICK_Identity)
4207 else if (SCS2.Second == ICK_Identity)
4209 else
4211 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4213
4214 if (SCS1.Third == SCS2.Third) {
4215 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4217 }
4218
4219 if (SCS1.Third == ICK_Identity)
4223
4224 if (SCS2.Third == ICK_Identity)
4228
4230}
4231
4232/// Determine whether one of the given reference bindings is better
4233/// than the other based on what kind of bindings they are.
4234static bool
4236 const StandardConversionSequence &SCS2) {
4237 // C++0x [over.ics.rank]p3b4:
4238 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4239 // implicit object parameter of a non-static member function declared
4240 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4241 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4242 // lvalue reference to a function lvalue and S2 binds an rvalue
4243 // reference*.
4244 //
4245 // FIXME: Rvalue references. We're going rogue with the above edits,
4246 // because the semantics in the current C++0x working paper (N3225 at the
4247 // time of this writing) break the standard definition of std::forward
4248 // and std::reference_wrapper when dealing with references to functions.
4249 // Proposed wording changes submitted to CWG for consideration.
4252 return false;
4253
4254 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4255 SCS2.IsLvalueReference) ||
4258}
4259
4261 None,
4264};
4265
4266/// Returns kind of fixed enum promotion the \a SCS uses.
4267static FixedEnumPromotion
4269
4270 if (SCS.Second != ICK_Integral_Promotion)
4271 return FixedEnumPromotion::None;
4272
4273 QualType FromType = SCS.getFromType();
4274 if (!FromType->isEnumeralType())
4275 return FixedEnumPromotion::None;
4276
4277 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4278 if (!Enum->isFixed())
4279 return FixedEnumPromotion::None;
4280
4281 QualType UnderlyingType = Enum->getIntegerType();
4282 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4283 return FixedEnumPromotion::ToUnderlyingType;
4284
4285 return FixedEnumPromotion::ToPromotedUnderlyingType;
4286}
4287
4288/// CompareStandardConversionSequences - Compare two standard
4289/// conversion sequences to determine whether one is better than the
4290/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4293 const StandardConversionSequence& SCS1,
4294 const StandardConversionSequence& SCS2)
4295{
4296 // Standard conversion sequence S1 is a better conversion sequence
4297 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4298
4299 // -- S1 is a proper subsequence of S2 (comparing the conversion
4300 // sequences in the canonical form defined by 13.3.3.1.1,
4301 // excluding any Lvalue Transformation; the identity conversion
4302 // sequence is considered to be a subsequence of any
4303 // non-identity conversion sequence) or, if not that,
4306 return CK;
4307
4308 // -- the rank of S1 is better than the rank of S2 (by the rules
4309 // defined below), or, if not that,
4310 ImplicitConversionRank Rank1 = SCS1.getRank();
4311 ImplicitConversionRank Rank2 = SCS2.getRank();
4312 if (Rank1 < Rank2)
4314 else if (Rank2 < Rank1)
4316
4317 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4318 // are indistinguishable unless one of the following rules
4319 // applies:
4320
4321 // A conversion that is not a conversion of a pointer, or
4322 // pointer to member, to bool is better than another conversion
4323 // that is such a conversion.
4325 return SCS2.isPointerConversionToBool()
4328
4329 // C++14 [over.ics.rank]p4b2:
4330 // This is retroactively applied to C++11 by CWG 1601.
4331 //
4332 // A conversion that promotes an enumeration whose underlying type is fixed
4333 // to its underlying type is better than one that promotes to the promoted
4334 // underlying type, if the two are different.
4337 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4338 FEP1 != FEP2)
4339 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4342
4343 // C++ [over.ics.rank]p4b2:
4344 //
4345 // If class B is derived directly or indirectly from class A,
4346 // conversion of B* to A* is better than conversion of B* to
4347 // void*, and conversion of A* to void* is better than conversion
4348 // of B* to void*.
4349 bool SCS1ConvertsToVoid
4351 bool SCS2ConvertsToVoid
4353 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4354 // Exactly one of the conversion sequences is a conversion to
4355 // a void pointer; it's the worse conversion.
4356 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4358 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4359 // Neither conversion sequence converts to a void pointer; compare
4360 // their derived-to-base conversions.
4362 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4363 return DerivedCK;
4364 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4365 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4366 // Both conversion sequences are conversions to void
4367 // pointers. Compare the source types to determine if there's an
4368 // inheritance relationship in their sources.
4369 QualType FromType1 = SCS1.getFromType();
4370 QualType FromType2 = SCS2.getFromType();
4371
4372 // Adjust the types we're converting from via the array-to-pointer
4373 // conversion, if we need to.
4374 if (SCS1.First == ICK_Array_To_Pointer)
4375 FromType1 = S.Context.getArrayDecayedType(FromType1);
4376 if (SCS2.First == ICK_Array_To_Pointer)
4377 FromType2 = S.Context.getArrayDecayedType(FromType2);
4378
4379 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4380 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4381
4382 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4384 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4386
4387 // Objective-C++: If one interface is more specific than the
4388 // other, it is the better one.
4389 const ObjCObjectPointerType* FromObjCPtr1
4390 = FromType1->getAs<ObjCObjectPointerType>();
4391 const ObjCObjectPointerType* FromObjCPtr2
4392 = FromType2->getAs<ObjCObjectPointerType>();
4393 if (FromObjCPtr1 && FromObjCPtr2) {
4394 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4395 FromObjCPtr2);
4396 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4397 FromObjCPtr1);
4398 if (AssignLeft != AssignRight) {
4399 return AssignLeft? ImplicitConversionSequence::Better
4401 }
4402 }
4403 }
4404
4405 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4406 // Check for a better reference binding based on the kind of bindings.
4407 if (isBetterReferenceBindingKind(SCS1, SCS2))
4409 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4411 }
4412
4413 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4414 // bullet 3).
4416 = CompareQualificationConversions(S, SCS1, SCS2))
4417 return QualCK;
4418
4419 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4420 // C++ [over.ics.rank]p3b4:
4421 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4422 // which the references refer are the same type except for
4423 // top-level cv-qualifiers, and the type to which the reference
4424 // initialized by S2 refers is more cv-qualified than the type
4425 // to which the reference initialized by S1 refers.
4426 QualType T1 = SCS1.getToType(2);
4427 QualType T2 = SCS2.getToType(2);
4428 T1 = S.Context.getCanonicalType(T1);
4429 T2 = S.Context.getCanonicalType(T2);
4430 Qualifiers T1Quals, T2Quals;
4431 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4432 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4433 if (UnqualT1 == UnqualT2) {
4434 // Objective-C++ ARC: If the references refer to objects with different
4435 // lifetimes, prefer bindings that don't change lifetime.
4441 }
4442
4443 // If the type is an array type, promote the element qualifiers to the
4444 // type for comparison.
4445 if (isa<ArrayType>(T1) && T1Quals)
4446 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4447 if (isa<ArrayType>(T2) && T2Quals)
4448 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4449 if (T2.isMoreQualifiedThan(T1))
4451 if (T1.isMoreQualifiedThan(T2))
4453 }
4454 }
4455
4456 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4457 // floating-to-integral conversion if the integral conversion
4458 // is between types of the same size.
4459 // For example:
4460 // void f(float);
4461 // void f(int);
4462 // int main {
4463 // long a;
4464 // f(a);
4465 // }
4466 // Here, MSVC will call f(int) instead of generating a compile error
4467 // as clang will do in standard mode.
4468 if (S.getLangOpts().MSVCCompat &&
4471 SCS2.Second == ICK_Floating_Integral &&
4472 S.Context.getTypeSize(SCS1.getFromType()) ==
4473 S.Context.getTypeSize(SCS1.getToType(2)))
4475
4476 // Prefer a compatible vector conversion over a lax vector conversion
4477 // For example:
4478 //
4479 // typedef float __v4sf __attribute__((__vector_size__(16)));
4480 // void f(vector float);
4481 // void f(vector signed int);
4482 // int main() {
4483 // __v4sf a;
4484 // f(a);
4485 // }
4486 // Here, we'd like to choose f(vector float) and not
4487 // report an ambiguous call error
4488 if (SCS1.Second == ICK_Vector_Conversion &&
4489 SCS2.Second == ICK_Vector_Conversion) {
4490 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4491 SCS1.getFromType(), SCS1.getToType(2));
4492 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4493 SCS2.getFromType(), SCS2.getToType(2));
4494
4495 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4496 return SCS1IsCompatibleVectorConversion
4499 }
4500
4501 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4503 bool SCS1IsCompatibleSVEVectorConversion =
4505 bool SCS2IsCompatibleSVEVectorConversion =
4507
4508 if (SCS1IsCompatibleSVEVectorConversion !=
4509 SCS2IsCompatibleSVEVectorConversion)
4510 return SCS1IsCompatibleSVEVectorConversion
4513 }
4514
4515 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4517 bool SCS1IsCompatibleRVVVectorConversion =
4519 bool SCS2IsCompatibleRVVVectorConversion =
4521
4522 if (SCS1IsCompatibleRVVVectorConversion !=
4523 SCS2IsCompatibleRVVVectorConversion)
4524 return SCS1IsCompatibleRVVVectorConversion
4527 }
4529}
4530
4531/// CompareQualificationConversions - Compares two standard conversion
4532/// sequences to determine whether they can be ranked based on their
4533/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4536 const StandardConversionSequence& SCS1,
4537 const StandardConversionSequence& SCS2) {
4538 // C++ [over.ics.rank]p3:
4539 // -- S1 and S2 differ only in their qualification conversion and
4540 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4541 // [C++98]
4542 // [...] and the cv-qualification signature of type T1 is a proper subset
4543 // of the cv-qualification signature of type T2, and S1 is not the
4544 // deprecated string literal array-to-pointer conversion (4.2).
4545 // [C++2a]
4546 // [...] where T1 can be converted to T2 by a qualification conversion.
4547 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4548 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4550
4551 // FIXME: the example in the standard doesn't use a qualification
4552 // conversion (!)
4553 QualType T1 = SCS1.getToType(2);
4554 QualType T2 = SCS2.getToType(2);
4555 T1 = S.Context.getCanonicalType(T1);
4556 T2 = S.Context.getCanonicalType(T2);
4557 assert(!T1->isReferenceType() && !T2->isReferenceType());
4558 Qualifiers T1Quals, T2Quals;
4559 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4560 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4561
4562 // If the types are the same, we won't learn anything by unwrapping
4563 // them.
4564 if (UnqualT1 == UnqualT2)
4566
4567 // Don't ever prefer a standard conversion sequence that uses the deprecated
4568 // string literal array to pointer conversion.
4569 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4570 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4571
4572 // Objective-C++ ARC:
4573 // Prefer qualification conversions not involving a change in lifetime
4574 // to qualification conversions that do change lifetime.
4577 CanPick1 = false;
4580 CanPick2 = false;
4581
4582 bool ObjCLifetimeConversion;
4583 if (CanPick1 &&
4584 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4585 CanPick1 = false;
4586 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4587 // directions, so we can't short-cut this second check in general.
4588 if (CanPick2 &&
4589 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4590 CanPick2 = false;
4591
4592 if (CanPick1 != CanPick2)
4593 return CanPick1 ? ImplicitConversionSequence::Better
4596}
4597
4598/// CompareDerivedToBaseConversions - Compares two standard conversion
4599/// sequences to determine whether they can be ranked based on their
4600/// various kinds of derived-to-base conversions (C++
4601/// [over.ics.rank]p4b3). As part of these checks, we also look at
4602/// conversions between Objective-C interface types.
4605 const StandardConversionSequence& SCS1,
4606 const StandardConversionSequence& SCS2) {
4607 QualType FromType1 = SCS1.getFromType();
4608 QualType ToType1 = SCS1.getToType(1);
4609 QualType FromType2 = SCS2.getFromType();
4610 QualType ToType2 = SCS2.getToType(1);
4611
4612 // Adjust the types we're converting from via the array-to-pointer
4613 // conversion, if we need to.
4614 if (SCS1.First == ICK_Array_To_Pointer)
4615 FromType1 = S.Context.getArrayDecayedType(FromType1);
4616 if (SCS2.First == ICK_Array_To_Pointer)
4617 FromType2 = S.Context.getArrayDecayedType(FromType2);
4618
4619 // Canonicalize all of the types.
4620 FromType1 = S.Context.getCanonicalType(FromType1);
4621 ToType1 = S.Context.getCanonicalType(ToType1);
4622 FromType2 = S.Context.getCanonicalType(FromType2);
4623 ToType2 = S.Context.getCanonicalType(ToType2);
4624
4625 // C++ [over.ics.rank]p4b3:
4626 //
4627 // If class B is derived directly or indirectly from class A and
4628 // class C is derived directly or indirectly from B,
4629 //
4630 // Compare based on pointer conversions.
4631 if (SCS1.Second == ICK_Pointer_Conversion &&
4633 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4634 FromType1->isPointerType() && FromType2->isPointerType() &&
4635 ToType1->isPointerType() && ToType2->isPointerType()) {
4636 QualType FromPointee1 =
4638 QualType ToPointee1 =
4640 QualType FromPointee2 =
4642 QualType ToPointee2 =
4644
4645 // -- conversion of C* to B* is better than conversion of C* to A*,
4646 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4647 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4649 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4651 }
4652
4653 // -- conversion of B* to A* is better than conversion of C* to A*,
4654 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4655 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4657 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4659 }
4660 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4662 const ObjCObjectPointerType *FromPtr1
4663 = FromType1->getAs<ObjCObjectPointerType>();
4664 const ObjCObjectPointerType *FromPtr2
4665 = FromType2->getAs<ObjCObjectPointerType>();
4666 const ObjCObjectPointerType *ToPtr1
4667 = ToType1->getAs<ObjCObjectPointerType>();
4668 const ObjCObjectPointerType *ToPtr2
4669 = ToType2->getAs<ObjCObjectPointerType>();
4670
4671 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4672 // Apply the same conversion ranking rules for Objective-C pointer types
4673 // that we do for C++ pointers to class types. However, we employ the
4674 // Objective-C pseudo-subtyping relationship used for assignment of
4675 // Objective-C pointer types.
4676 bool FromAssignLeft
4677 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4678 bool FromAssignRight
4679 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4680 bool ToAssignLeft
4681 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4682 bool ToAssignRight
4683 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4684
4685 // A conversion to an a non-id object pointer type or qualified 'id'
4686 // type is better than a conversion to 'id'.
4687 if (ToPtr1->isObjCIdType() &&
4688 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4690 if (ToPtr2->isObjCIdType() &&
4691 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4693
4694 // A conversion to a non-id object pointer type is better than a
4695 // conversion to a qualified 'id' type
4696 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4698 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4700
4701 // A conversion to an a non-Class object pointer type or qualified 'Class'
4702 // type is better than a conversion to 'Class'.
4703 if (ToPtr1->isObjCClassType() &&
4704 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4706 if (ToPtr2->isObjCClassType() &&
4707 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4709
4710 // A conversion to a non-Class object pointer type is better than a
4711 // conversion to a qualified 'Class' type.
4712 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4714 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4716
4717 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4718 if (S.Context.hasSameType(FromType1, FromType2) &&
4719 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4720 (ToAssignLeft != ToAssignRight)) {
4721 if (FromPtr1->isSpecialized()) {
4722 // "conversion of B<A> * to B * is better than conversion of B * to
4723 // C *.
4724 bool IsFirstSame =
4725 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4726 bool IsSecondSame =
4727 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4728 if (IsFirstSame) {
4729 if (!IsSecondSame)
4731 } else if (IsSecondSame)
4733 }
4734 return ToAssignLeft? ImplicitConversionSequence::Worse
4736 }
4737
4738 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4739 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4740 (FromAssignLeft != FromAssignRight))
4741 return FromAssignLeft? ImplicitConversionSequence::Better
4743 }
4744 }
4745
4746 // Ranking of member-pointer types.
4747 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4748 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4749 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4750 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4751 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4752 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4753 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4754 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4755 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4756 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4757 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4758 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4759 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4760 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4761 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4762 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4763 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4764 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4766 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4768 }
4769 // conversion of B::* to C::* is better than conversion of A::* to C::*
4770 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4771 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4773 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4775 }
4776 }
4777
4778 if (SCS1.Second == ICK_Derived_To_Base) {
4779 // -- conversion of C to B is better than conversion of C to A,
4780 // -- binding of an expression of type C to a reference of type
4781 // B& is better than binding an expression of type C to a
4782 // reference of type A&,
4783 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4784 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4785 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4787 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4789 }
4790
4791 // -- conversion of B to A is better than conversion of C to A.
4792 // -- binding of an expression of type B to a reference of type
4793 // A& is better than binding an expression of type C to a
4794 // reference of type A&,
4795 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4796 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4797 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4799 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4801 }
4802 }
4803
4805}
4806
4808 if (!T.getQualifiers().hasUnaligned())
4809 return T;
4810
4811 Qualifiers Q;
4812 T = Ctx.getUnqualifiedArrayType(T, Q);
4813 Q.removeUnaligned();
4814 return Ctx.getQualifiedType(T, Q);
4815}
4816
4819 QualType OrigT1, QualType OrigT2,
4820 ReferenceConversions *ConvOut) {
4821 assert(!OrigT1->isReferenceType() &&
4822 "T1 must be the pointee type of the reference type");
4823 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4824
4825 QualType T1 = Context.getCanonicalType(OrigT1);
4826 QualType T2 = Context.getCanonicalType(OrigT2);
4827 Qualifiers T1Quals, T2Quals;
4828 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4829 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4830
4831 ReferenceConversions ConvTmp;
4832 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4833 Conv = ReferenceConversions();
4834
4835 // C++2a [dcl.init.ref]p4:
4836 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4837 // reference-related to "cv2 T2" if T1 is similar to T2, or
4838 // T1 is a base class of T2.
4839 // "cv1 T1" is reference-compatible with "cv2 T2" if
4840 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4841 // "pointer to cv1 T1" via a standard conversion sequence.
4842
4843 // Check for standard conversions we can apply to pointers: derived-to-base
4844 // conversions, ObjC pointer conversions, and function pointer conversions.
4845 // (Qualification conversions are checked last.)
4846 QualType ConvertedT2;
4847 if (UnqualT1 == UnqualT2) {
4848 // Nothing to do.
4849 } else if (isCompleteType(Loc, OrigT2) &&
4850 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4851 Conv |= ReferenceConversions::DerivedToBase;
4852 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4853 UnqualT2->isObjCObjectOrInterfaceType() &&
4854 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4855 Conv |= ReferenceConversions::ObjC;
4856 else if (UnqualT2->isFunctionType() &&
4857 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4858 Conv |= ReferenceConversions::Function;
4859 // No need to check qualifiers; function types don't have them.
4860 return Ref_Compatible;
4861 }
4862 bool ConvertedReferent = Conv != 0;
4863
4864 // We can have a qualification conversion. Compute whether the types are
4865 // similar at the same time.
4866 bool PreviousToQualsIncludeConst = true;
4867 bool TopLevel = true;
4868 do {
4869 if (T1 == T2)
4870 break;
4871
4872 // We will need a qualification conversion.
4873 Conv |= ReferenceConversions::Qualification;
4874
4875 // Track whether we performed a qualification conversion anywhere other
4876 // than the top level. This matters for ranking reference bindings in
4877 // overload resolution.
4878 if (!TopLevel)
4879 Conv |= ReferenceConversions::NestedQualification;
4880
4881 // MS compiler ignores __unaligned qualifier for references; do the same.
4882 T1 = withoutUnaligned(Context, T1);
4883 T2 = withoutUnaligned(Context, T2);
4884
4885 // If we find a qualifier mismatch, the types are not reference-compatible,
4886 // but are still be reference-related if they're similar.
4887 bool ObjCLifetimeConversion = false;
4888 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4889 PreviousToQualsIncludeConst,
4890 ObjCLifetimeConversion))
4891 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4892 ? Ref_Related
4893 : Ref_Incompatible;
4894
4895 // FIXME: Should we track this for any level other than the first?
4896 if (ObjCLifetimeConversion)
4897 Conv |= ReferenceConversions::ObjCLifetime;
4898
4899 TopLevel = false;
4900 } while (Context.UnwrapSimilarTypes(T1, T2));
4901
4902 // At this point, if the types are reference-related, we must either have the
4903 // same inner type (ignoring qualifiers), or must have already worked out how
4904 // to convert the referent.
4905 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4906 ? Ref_Compatible
4907 : Ref_Incompatible;
4908}
4909
4910/// Look for a user-defined conversion to a value reference-compatible
4911/// with DeclType. Return true if something definite is found.
4912static bool
4914 QualType DeclType, SourceLocation DeclLoc,
4915 Expr *Init, QualType T2, bool AllowRvalues,
4916 bool AllowExplicit) {
4917 assert(T2->isRecordType() && "Can only find conversions of record types.");
4918 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4919
4920 OverloadCandidateSet CandidateSet(
4922 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4923 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4924 NamedDecl *D = *I;
4925 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4926 if (isa<UsingShadowDecl>(D))
4927 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4928
4929 FunctionTemplateDecl *ConvTemplate
4930 = dyn_cast<FunctionTemplateDecl>(D);
4931 CXXConversionDecl *Conv;
4932 if (ConvTemplate)
4933 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4934 else
4935 Conv = cast<CXXConversionDecl>(D);
4936
4937 if (AllowRvalues) {
4938 // If we are initializing an rvalue reference, don't permit conversion
4939 // functions that return lvalues.
4940 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4941 const ReferenceType *RefType
4943 if (RefType && !RefType->getPointeeType()->isFunctionType())
4944 continue;
4945 }
4946
4947 if (!ConvTemplate &&
4949 DeclLoc,
4950 Conv->getConversionType()
4955 continue;
4956 } else {
4957 // If the conversion function doesn't return a reference type,
4958 // it can't be considered for this conversion. An rvalue reference
4959 // is only acceptable if its referencee is a function type.
4960
4961 const ReferenceType *RefType =
4963 if (!RefType ||
4964 (!RefType->isLValueReferenceType() &&
4965 !RefType->getPointeeType()->isFunctionType()))
4966 continue;
4967 }
4968
4969 if (ConvTemplate)
4971 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4972 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4973 else
4975 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4976 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4977 }
4978
4979 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4980
4982 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4983 case OR_Success:
4984 // C++ [over.ics.ref]p1:
4985 //
4986 // [...] If the parameter binds directly to the result of
4987 // applying a conversion function to the argument
4988 // expression, the implicit conversion sequence is a
4989 // user-defined conversion sequence (13.3.3.1.2), with the
4990 // second standard conversion sequence either an identity
4991 // conversion or, if the conversion function returns an
4992 // entity of a type that is a derived class of the parameter
4993 // type, a derived-to-base Conversion.
4994 if (!Best->FinalConversion.DirectBinding)
4995 return false;
4996
4997 ICS.setUserDefined();
4998 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4999 ICS.UserDefined.After = Best->FinalConversion;
5000 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5001 ICS.UserDefined.ConversionFunction = Best->Function;
5002 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5003 ICS.UserDefined.EllipsisConversion = false;
5004 assert(ICS.UserDefined.After.ReferenceBinding &&
5006 "Expected a direct reference binding!");
5007 return true;
5008
5009 case OR_Ambiguous:
5010 ICS.setAmbiguous();
5011 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5012 Cand != CandidateSet.end(); ++Cand)
5013 if (Cand->Best)
5014 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5015 return true;
5016
5018 case OR_Deleted:
5019 // There was no suitable conversion, or we found a deleted
5020 // conversion; continue with other checks.
5021 return false;
5022 }
5023
5024 llvm_unreachable("Invalid OverloadResult!");
5025}
5026
5027/// Compute an implicit conversion sequence for reference
5028/// initialization.
5031 SourceLocation DeclLoc,
5032 bool SuppressUserConversions,
5033 bool AllowExplicit) {
5034 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5035
5036 // Most paths end in a failed conversion.
5039
5040 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5041 QualType T2 = Init->getType();
5042
5043 // If the initializer is the address of an overloaded function, try
5044 // to resolve the overloaded function. If all goes well, T2 is the
5045 // type of the resulting function.
5046 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5049 false, Found))
5050 T2 = Fn->getType();
5051 }
5052
5053 // Compute some basic properties of the types and the initializer.
5054 bool isRValRef = DeclType->isRValueReferenceType();
5055 Expr::Classification InitCategory = Init->Classify(S.Context);
5056
5058 Sema::ReferenceCompareResult RefRelationship =
5059 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5060
5061 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5062 ICS.setStandard();
5064 // FIXME: A reference binding can be a function conversion too. We should
5065 // consider that when ordering reference-to-function bindings.
5066 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5068 : (RefConv & Sema::ReferenceConversions::ObjC)
5070 : ICK_Identity;
5072 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5073 // a reference binding that performs a non-top-level qualification
5074 // conversion as a qualification conversion, not as an identity conversion.
5075 ICS.Standard.Third = (RefConv &
5076 Sema::ReferenceConversions::NestedQualification)
5078 : ICK_Identity;
5079 ICS.Standard.setFromType(T2);
5080 ICS.Standard.setToType(0, T2);
5081 ICS.Standard.setToType(1, T1);
5082 ICS.Standard.setToType(2, T1);
5083 ICS.Standard.ReferenceBinding = true;
5084 ICS.Standard.DirectBinding = BindsDirectly;
5085 ICS.Standard.IsLvalueReference = !isRValRef;
5087 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5090 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5091 ICS.Standard.CopyConstructor = nullptr;
5093 };
5094
5095 // C++0x [dcl.init.ref]p5:
5096 // A reference to type "cv1 T1" is initialized by an expression
5097 // of type "cv2 T2" as follows:
5098
5099 // -- If reference is an lvalue reference and the initializer expression
5100 if (!isRValRef) {
5101 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5102 // reference-compatible with "cv2 T2," or
5103 //
5104 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5105 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5106 // C++ [over.ics.ref]p1:
5107 // When a parameter of reference type binds directly (8.5.3)
5108 // to an argument expression, the implicit conversion sequence
5109 // is the identity conversion, unless the argument expression
5110 // has a type that is a derived class of the parameter type,
5111 // in which case the implicit conversion sequence is a
5112 // derived-to-base Conversion (13.3.3.1).
5113 SetAsReferenceBinding(/*BindsDirectly=*/true);
5114
5115 // Nothing more to do: the inaccessibility/ambiguity check for
5116 // derived-to-base conversions is suppressed when we're
5117 // computing the implicit conversion sequence (C++
5118 // [over.best.ics]p2).
5119 return ICS;
5120 }
5121
5122 // -- has a class type (i.e., T2 is a class type), where T1 is
5123 // not reference-related to T2, and can be implicitly
5124 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5125 // is reference-compatible with "cv3 T3" 92) (this
5126 // conversion is selected by enumerating the applicable
5127 // conversion functions (13.3.1.6) and choosing the best
5128 // one through overload resolution (13.3)),
5129 if (!SuppressUserConversions && T2->isRecordType() &&
5130 S.isCompleteType(DeclLoc, T2) &&
5131 RefRelationship == Sema::Ref_Incompatible) {
5132 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5133 Init, T2, /*AllowRvalues=*/false,
5134 AllowExplicit))
5135 return ICS;
5136 }
5137 }
5138
5139 // -- Otherwise, the reference shall be an lvalue reference to a
5140 // non-volatile const type (i.e., cv1 shall be const), or the reference
5141 // shall be an rvalue reference.
5142 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5143 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5145 return ICS;
5146 }
5147
5148 // -- If the initializer expression
5149 //
5150 // -- is an xvalue, class prvalue, array prvalue or function
5151 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5152 if (RefRelationship == Sema::Ref_Compatible &&
5153 (InitCategory.isXValue() ||
5154 (InitCategory.isPRValue() &&
5155 (T2->isRecordType() || T2->isArrayType())) ||
5156 (InitCategory.isLValue() && T2->isFunctionType()))) {
5157 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5158 // binding unless we're binding to a class prvalue.
5159 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5160 // allow the use of rvalue references in C++98/03 for the benefit of
5161 // standard library implementors; therefore, we need the xvalue check here.
5162 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5163 !(InitCategory.isPRValue() || T2->isRecordType()));
5164 return ICS;
5165 }
5166
5167 // -- has a class type (i.e., T2 is a class type), where T1 is not
5168 // reference-related to T2, and can be implicitly converted to
5169 // an xvalue, class prvalue, or function lvalue of type
5170 // "cv3 T3", where "cv1 T1" is reference-compatible with
5171 // "cv3 T3",
5172 //
5173 // then the reference is bound to the value of the initializer
5174 // expression in the first case and to the result of the conversion
5175 // in the second case (or, in either case, to an appropriate base
5176 // class subobject).
5177 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5178 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5179 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5180 Init, T2, /*AllowRvalues=*/true,
5181 AllowExplicit)) {
5182 // In the second case, if the reference is an rvalue reference
5183 // and the second standard conversion sequence of the
5184 // user-defined conversion sequence includes an lvalue-to-rvalue
5185 // conversion, the program is ill-formed.
5186 if (ICS.isUserDefined() && isRValRef &&
5189
5190 return ICS;
5191 }
5192
5193 // A temporary of function type cannot be created; don't even try.
5194 if (T1->isFunctionType())
5195 return ICS;
5196
5197 // -- Otherwise, a temporary of type "cv1 T1" is created and
5198 // initialized from the initializer expression using the
5199 // rules for a non-reference copy initialization (8.5). The
5200 // reference is then bound to the temporary. If T1 is
5201 // reference-related to T2, cv1 must be the same
5202 // cv-qualification as, or greater cv-qualification than,
5203 // cv2; otherwise, the program is ill-formed.
5204 if (RefRelationship == Sema::Ref_Related) {
5205 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5206 // we would be reference-compatible or reference-compatible with
5207 // added qualification. But that wasn't the case, so the reference
5208 // initialization fails.
5209 //
5210 // Note that we only want to check address spaces and cvr-qualifiers here.
5211 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5212 Qualifiers T1Quals = T1.getQualifiers();
5213 Qualifiers T2Quals = T2.getQualifiers();
5214 T1Quals.removeObjCGCAttr();
5215 T1Quals.removeObjCLifetime();
5216 T2Quals.removeObjCGCAttr();
5217 T2Quals.removeObjCLifetime();
5218 // MS compiler ignores __unaligned qualifier for references; do the same.
5219 T1Quals.removeUnaligned();
5220 T2Quals.removeUnaligned();
5221 if (!T1Quals.compatiblyIncludes(T2Quals))
5222 return ICS;
5223 }
5224
5225 // If at least one of the types is a class type, the types are not
5226 // related, and we aren't allowed any user conversions, the
5227 // reference binding fails. This case is important for breaking
5228 // recursion, since TryImplicitConversion below will attempt to
5229 // create a temporary through the use of a copy constructor.
5230 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5231 (T1->isRecordType() || T2->isRecordType()))
5232 return ICS;
5233
5234 // If T1 is reference-related to T2 and the reference is an rvalue
5235 // reference, the initializer expression shall not be an lvalue.
5236 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5237 Init->Classify(S.Context).isLValue()) {
5239 return ICS;
5240 }
5241
5242 // C++ [over.ics.ref]p2:
5243 // When a parameter of reference type is not bound directly to
5244 // an argument expression, the conversion sequence is the one
5245 // required to convert the argument expression to the
5246 // underlying type of the reference according to
5247 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5248 // to copy-initializing a temporary of the underlying type with
5249 // the argument expression. Any difference in top-level
5250 // cv-qualification is subsumed by the initialization itself
5251 // and does not constitute a conversion.
5252 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5253 AllowedExplicit::None,
5254 /*InOverloadResolution=*/false,
5255 /*CStyle=*/false,
5256 /*AllowObjCWritebackConversion=*/false,
5257 /*AllowObjCConversionOnExplicit=*/false);
5258
5259 // Of course, that's still a reference binding.
5260 if (ICS.isStandard()) {
5261 ICS.Standard.ReferenceBinding = true;
5262 ICS.Standard.IsLvalueReference = !isRValRef;
5263 ICS.Standard.BindsToFunctionLvalue = false;
5264 ICS.Standard.BindsToRvalue = true;
5267 } else if (ICS.isUserDefined()) {
5268 const ReferenceType *LValRefType =
5271
5272 // C++ [over.ics.ref]p3:
5273 // Except for an implicit object parameter, for which see 13.3.1, a
5274 // standard conversion sequence cannot be formed if it requires [...]
5275 // binding an rvalue reference to an lvalue other than a function
5276 // lvalue.
5277 // Note that the function case is not possible here.
5278 if (isRValRef && LValRefType) {
5280 return ICS;
5281 }
5282
5284 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5286 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5289 }
5290
5291 return ICS;
5292}
5293
5295TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5296 bool SuppressUserConversions,
5297 bool InOverloadResolution,
5298 bool AllowObjCWritebackConversion,
5299 bool AllowExplicit = false);
5300
5301/// TryListConversion - Try to copy-initialize a value of type ToType from the
5302/// initializer list From.
5305 bool SuppressUserConversions,
5306 bool InOverloadResolution,
5307 bool AllowObjCWritebackConversion) {
5308 // C++11 [over.ics.list]p1:
5309 // When an argument is an initializer list, it is not an expression and
5310 // special rules apply for converting it to a parameter type.
5311
5313 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5314
5315 // We need a complete type for what follows. With one C++20 exception,
5316 // incomplete types can never be initialized from init lists.
5317 QualType InitTy = ToType;
5318 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5319 if (AT && S.getLangOpts().CPlusPlus20)
5320 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5321 // C++20 allows list initialization of an incomplete array type.
5322 InitTy = IAT->getElementType();
5323 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5324 return Result;
5325
5326 // C++20 [over.ics.list]/2:
5327 // If the initializer list is a designated-initializer-list, a conversion
5328 // is only possible if the parameter has an aggregate type
5329 //
5330 // FIXME: The exception for reference initialization here is not part of the
5331 // language rules, but follow other compilers in adding it as a tentative DR
5332 // resolution.
5333 bool IsDesignatedInit = From->hasDesignatedInit();
5334 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5335 IsDesignatedInit)
5336 return Result;
5337
5338 // Per DR1467:
5339 // If the parameter type is a class X and the initializer list has a single
5340 // element of type cv U, where U is X or a class derived from X, the
5341 // implicit conversion sequence is the one required to convert the element
5342 // to the parameter type.
5343 //
5344 // Otherwise, if the parameter type is a character array [... ]
5345 // and the initializer list has a single element that is an
5346 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5347 // implicit conversion sequence is the identity conversion.
5348 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5349 if (ToType->isRecordType()) {
5350 QualType InitType = From->getInit(0)->getType();
5351 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5352 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5353 return TryCopyInitialization(S, From->getInit(0), ToType,
5354 SuppressUserConversions,
5355 InOverloadResolution,
5356 AllowObjCWritebackConversion);
5357 }
5358
5359 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5360 InitializedEntity Entity =
5362 /*Consumed=*/false);
5363 if (S.CanPerformCopyInitialization(Entity, From)) {
5364 Result.setStandard();
5365 Result.Standard.setAsIdentityConversion();
5366 Result.Standard.setFromType(ToType);
5367 Result.Standard.setAllToTypes(ToType);
5368 return Result;
5369 }
5370 }
5371 }
5372
5373 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5374 // C++11 [over.ics.list]p2:
5375 // If the parameter type is std::initializer_list<X> or "array of X" and
5376 // all the elements can be implicitly converted to X, the implicit
5377 // conversion sequence is the worst conversion necessary to convert an
5378 // element of the list to X.
5379 //
5380 // C++14 [over.ics.list]p3:
5381 // Otherwise, if the parameter type is "array of N X", if the initializer
5382 // list has exactly N elements or if it has fewer than N elements and X is
5383 // default-constructible, and if all the elements of the initializer list
5384 // can be implicitly converted to X, the implicit conversion sequence is
5385 // the worst conversion necessary to convert an element of the list to X.
5386 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5387 unsigned e = From->getNumInits();
5390 QualType());
5391 QualType ContTy = ToType;
5392 bool IsUnbounded = false;
5393 if (AT) {
5394 InitTy = AT->getElementType();
5395 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5396 if (CT->getSize().ult(e)) {
5397 // Too many inits, fatally bad
5399 ToType);
5400 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5401 return Result;
5402 }
5403 if (CT->getSize().ugt(e)) {
5404 // Need an init from empty {}, is there one?
5405 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5406 From->getEndLoc());
5407 EmptyList.setType(S.Context.VoidTy);
5408 DfltElt = TryListConversion(
5409 S, &EmptyList, InitTy, SuppressUserConversions,
5410 InOverloadResolution, AllowObjCWritebackConversion);
5411 if (DfltElt.isBad()) {
5412 // No {} init, fatally bad
5414 ToType);
5415 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5416 return Result;
5417 }
5418 }
5419 } else {
5420 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5421 IsUnbounded = true;
5422 if (!e) {
5423 // Cannot convert to zero-sized.
5425 ToType);
5426 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5427 return Result;
5428 }
5429 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5430 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5432 }
5433 }
5434
5435 Result.setStandard();
5436 Result.Standard.setAsIdentityConversion();
5437 Result.Standard.setFromType(InitTy);
5438 Result.Standard.setAllToTypes(InitTy);
5439 for (unsigned i = 0; i < e; ++i) {
5440 Expr *Init = From->getInit(i);
5442 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5443 AllowObjCWritebackConversion);
5444
5445 // Keep the worse conversion seen so far.
5446 // FIXME: Sequences are not totally ordered, so 'worse' can be
5447 // ambiguous. CWG has been informed.
5449 Result) ==
5451 Result = ICS;
5452 // Bail as soon as we find something unconvertible.
5453 if (Result.isBad()) {
5454 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5455 return Result;
5456 }
5457 }
5458 }
5459
5460 // If we needed any implicit {} initialization, compare that now.
5461 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5462 // has been informed that this might not be the best thing.
5463 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5464 S, From->getEndLoc(), DfltElt, Result) ==
5466 Result = DfltElt;
5467 // Record the type being initialized so that we may compare sequences
5468 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5469 return Result;
5470 }
5471
5472 // C++14 [over.ics.list]p4:
5473 // C++11 [over.ics.list]p3:
5474 // Otherwise, if the parameter is a non-aggregate class X and overload
5475 // resolution chooses a single best constructor [...] the implicit
5476 // conversion sequence is a user-defined conversion sequence. If multiple
5477 // constructors are viable but none is better than the others, the
5478 // implicit conversion sequence is a user-defined conversion sequence.
5479 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5480 // This function can deal with initializer lists.
5481 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5482 AllowedExplicit::None,
5483 InOverloadResolution, /*CStyle=*/false,
5484 AllowObjCWritebackConversion,
5485 /*AllowObjCConversionOnExplicit=*/false);
5486 }
5487
5488 // C++14 [over.ics.list]p5:
5489 // C++11 [over.ics.list]p4:
5490 // Otherwise, if the parameter has an aggregate type which can be
5491 // initialized from the initializer list [...] the implicit conversion
5492 // sequence is a user-defined conversion sequence.
5493 if (ToType->isAggregateType()) {
5494 // Type is an aggregate, argument is an init list. At this point it comes
5495 // down to checking whether the initialization works.
5496 // FIXME: Find out whether this parameter is consumed or not.
5497 InitializedEntity Entity =
5499 /*Consumed=*/false);
5501 From)) {
5502 Result.setUserDefined();
5503 Result.UserDefined.Before.setAsIdentityConversion();
5504 // Initializer lists don't have a type.
5505 Result.UserDefined.Before.setFromType(QualType());
5506 Result.UserDefined.Before.setAllToTypes(QualType());
5507
5508 Result.UserDefined.After.setAsIdentityConversion();
5509 Result.UserDefined.After.setFromType(ToType);
5510 Result.UserDefined.After.setAllToTypes(ToType);
5511 Result.UserDefined.ConversionFunction = nullptr;
5512 }
5513 return Result;
5514 }
5515
5516 // C++14 [over.ics.list]p6:
5517 // C++11 [over.ics.list]p5:
5518 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5519 if (ToType->isReferenceType()) {
5520 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5521 // mention initializer lists in any way. So we go by what list-
5522 // initialization would do and try to extrapolate from that.
5523
5524 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5525
5526 // If the initializer list has a single element that is reference-related
5527 // to the parameter type, we initialize the reference from that.
5528 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5529 Expr *Init = From->getInit(0);
5530
5531 QualType T2 = Init->getType();
5532
5533 // If the initializer is the address of an overloaded function, try
5534 // to resolve the overloaded function. If all goes well, T2 is the
5535 // type of the resulting function.
5536 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5539 Init, ToType, false, Found))
5540 T2 = Fn->getType();
5541 }
5542
5543 // Compute some basic properties of the types and the initializer.
5544 Sema::ReferenceCompareResult RefRelationship =
5545 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5546
5547 if (RefRelationship >= Sema::Ref_Related) {
5548 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5549 SuppressUserConversions,
5550 /*AllowExplicit=*/false);
5551 }
5552 }
5553
5554 // Otherwise, we bind the reference to a temporary created from the
5555 // initializer list.
5556 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5557 InOverloadResolution,
5558 AllowObjCWritebackConversion);
5559 if (Result.isFailure())
5560 return Result;
5561 assert(!Result.isEllipsis() &&
5562 "Sub-initialization cannot result in ellipsis conversion.");
5563
5564 // Can we even bind to a temporary?
5565 if (ToType->isRValueReferenceType() ||
5566 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5567 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5568 Result.UserDefined.After;
5569 SCS.ReferenceBinding = true;
5571 SCS.BindsToRvalue = true;
5572 SCS.BindsToFunctionLvalue = false;
5575 } else
5577 From, ToType);
5578 return Result;
5579 }
5580
5581 // C++14 [over.ics.list]p7:
5582 // C++11 [over.ics.list]p6:
5583 // Otherwise, if the parameter type is not a class:
5584 if (!ToType->isRecordType()) {
5585 // - if the initializer list has one element that is not itself an
5586 // initializer list, the implicit conversion sequence is the one
5587 // required to convert the element to the parameter type.
5588 unsigned NumInits = From->getNumInits();
5589 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5590 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5591 SuppressUserConversions,
5592 InOverloadResolution,
5593 AllowObjCWritebackConversion);
5594 // - if the initializer list has no elements, the implicit conversion
5595 // sequence is the identity conversion.
5596 else if (NumInits == 0) {
5597 Result.setStandard();
5598 Result.Standard.setAsIdentityConversion();
5599 Result.Standard.setFromType(ToType);
5600 Result.Standard.setAllToTypes(ToType);
5601 }
5602 return Result;
5603 }
5604
5605 // C++14 [over.ics.list]p8:
5606 // C++11 [over.ics.list]p7:
5607 // In all cases other than those enumerated above, no conversion is possible
5608 return Result;
5609}
5610
5611/// TryCopyInitialization - Try to copy-initialize a value of type
5612/// ToType from the expression From. Return the implicit conversion
5613/// sequence required to pass this argument, which may be a bad
5614/// conversion sequence (meaning that the argument cannot be passed to
5615/// a parameter of this type). If @p SuppressUserConversions, then we
5616/// do not permit any user-defined conversion sequences.
5619 bool SuppressUserConversions,
5620 bool InOverloadResolution,
5621 bool AllowObjCWritebackConversion,
5622 bool AllowExplicit) {
5623 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5624 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5625 InOverloadResolution,AllowObjCWritebackConversion);
5626
5627 if (ToType->isReferenceType())
5628 return TryReferenceInit(S, From, ToType,
5629 /*FIXME:*/ From->getBeginLoc(),
5630 SuppressUserConversions, AllowExplicit);
5631
5632 return TryImplicitConversion(S, From, ToType,
5633 SuppressUserConversions,
5634 AllowedExplicit::None,
5635 InOverloadResolution,
5636 /*CStyle=*/false,
5637 AllowObjCWritebackConversion,
5638 /*AllowObjCConversionOnExplicit=*/false);
5639}
5640
5641static bool TryCopyInitialization(const CanQualType FromQTy,
5642 const CanQualType ToQTy,
5643 Sema &S,
5644 SourceLocation Loc,
5645 ExprValueKind FromVK) {
5646 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5648 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5649
5650 return !ICS.isBad();
5651}
5652
5653/// TryObjectArgumentInitialization - Try to initialize the object
5654/// parameter of the given member function (@c Method) from the
5655/// expression @p From.
5657 Sema &S, SourceLocation Loc, QualType FromType,
5658 Expr::Classification FromClassification, CXXMethodDecl *Method,
5659 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5660 QualType ExplicitParameterType = QualType(),
5661 bool SuppressUserConversion = false) {
5662
5663 // We need to have an object of class type.
5664 if (const auto *PT = FromType->getAs<PointerType>()) {
5665 FromType = PT->getPointeeType();
5666
5667 // When we had a pointer, it's implicitly dereferenced, so we
5668 // better have an lvalue.
5669 assert(FromClassification.isLValue());
5670 }
5671
5672 auto ValueKindFromClassification = [](Expr::Classification C) {
5673 if (C.isPRValue())
5674 return clang::VK_PRValue;
5675 if (C.isXValue())
5676 return VK_XValue;
5677 return clang::VK_LValue;
5678 };
5679
5680 if (Method->isExplicitObjectMemberFunction()) {
5681 if (ExplicitParameterType.isNull())
5682 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5683 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5684 ValueKindFromClassification(FromClassification));
5686 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5687 /*InOverloadResolution=*/true, false);
5688 if (ICS.isBad())
5689 ICS.Bad.FromExpr = nullptr;
5690 return ICS;
5691 }
5692
5693 assert(FromType->isRecordType());
5694
5695 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5696 // C++98 [class.dtor]p2:
5697 // A destructor can be invoked for a const, volatile or const volatile
5698 // object.
5699 // C++98 [over.match.funcs]p4:
5700 // For static member functions, the implicit object parameter is considered
5701 // to match any object (since if the function is selected, the object is
5702 // discarded).
5703 Qualifiers Quals = Method->getMethodQualifiers();
5704 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5705 Quals.addConst();
5706 Quals.addVolatile();
5707 }
5708
5709 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5710
5711 // Set up the conversion sequence as a "bad" conversion, to allow us
5712 // to exit early.
5714
5715 // C++0x [over.match.funcs]p4:
5716 // For non-static member functions, the type of the implicit object
5717 // parameter is
5718 //
5719 // - "lvalue reference to cv X" for functions declared without a
5720 // ref-qualifier or with the & ref-qualifier
5721 // - "rvalue reference to cv X" for functions declared with the &&
5722 // ref-qualifier
5723 //
5724 // where X is the class of which the function is a member and cv is the
5725 // cv-qualification on the member function declaration.
5726 //
5727 // However, when finding an implicit conversion sequence for the argument, we
5728 // are not allowed to perform user-defined conversions
5729 // (C++ [over.match.funcs]p5). We perform a simplified version of
5730 // reference binding here, that allows class rvalues to bind to
5731 // non-constant references.
5732
5733 // First check the qualifiers.
5734 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5735 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5736 if (ImplicitParamType.getCVRQualifiers() !=
5737 FromTypeCanon.getLocalCVRQualifiers() &&
5738 !ImplicitParamType.isAtLeastAsQualifiedAs(
5739 withoutUnaligned(S.Context, FromTypeCanon))) {
5741 FromType, ImplicitParamType);
5742 return ICS;
5743 }
5744
5745 if (FromTypeCanon.hasAddressSpace()) {
5746 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5747 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5748 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5750 FromType, ImplicitParamType);
5751 return ICS;
5752 }
5753 }
5754
5755 // Check that we have either the same type or a derived type. It
5756 // affects the conversion rank.
5757 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5758 ImplicitConversionKind SecondKind;
5759 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5760 SecondKind = ICK_Identity;
5761 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5762 SecondKind = ICK_Derived_To_Base;
5763 } else if (!Method->isExplicitObjectMemberFunction()) {
5765 FromType, ImplicitParamType);
5766 return ICS;
5767 }
5768
5769 // Check the ref-qualifier.
5770 switch (Method->getRefQualifier()) {
5771 case RQ_None:
5772 // Do nothing; we don't care about lvalueness or rvalueness.
5773 break;
5774
5775 case RQ_LValue:
5776 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5777 // non-const lvalue reference cannot bind to an rvalue
5779 ImplicitParamType);
5780 return ICS;
5781 }
5782 break;
5783
5784 case RQ_RValue:
5785 if (!FromClassification.isRValue()) {
5786 // rvalue reference cannot bind to an lvalue
5788 ImplicitParamType);
5789 return ICS;
5790 }
5791 break;
5792 }
5793
5794 // Success. Mark this as a reference binding.
5795 ICS.setStandard();
5797 ICS.Standard.Second = SecondKind;
5798 ICS.Standard.setFromType(FromType);
5799 ICS.Standard.setAllToTypes(ImplicitParamType);
5800 ICS.Standard.ReferenceBinding = true;
5801 ICS.Standard.DirectBinding = true;
5803 ICS.Standard.BindsToFunctionLvalue = false;
5804 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5806 = (Method->getRefQualifier() == RQ_None);
5807 return ICS;
5808}
5809
5810/// PerformObjectArgumentInitialization - Perform initialization of
5811/// the implicit object parameter for the given Method with the given
5812/// expression.
5814 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5815 CXXMethodDecl *Method) {
5816 QualType FromRecordType, DestType;
5817 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5818
5819 Expr::Classification FromClassification;
5820 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5821 FromRecordType = PT->getPointeeType();
5822 DestType = Method->getThisType();
5823 FromClassification = Expr::Classification::makeSimpleLValue();
5824 } else {
5825 FromRecordType = From->getType();
5826 DestType = ImplicitParamRecordType;
5827 FromClassification = From->Classify(Context);
5828
5829 // When performing member access on a prvalue, materialize a temporary.
5830 if (From->isPRValue()) {
5831 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5832 Method->getRefQualifier() !=
5834 }
5835 }
5836
5837 // Note that we always use the true parent context when performing
5838 // the actual argument initialization.
5840 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5841 Method->getParent());
5842 if (ICS.isBad()) {
5843 switch (ICS.Bad.Kind) {
5845 Qualifiers FromQs = FromRecordType.getQualifiers();
5846 Qualifiers ToQs = DestType.getQualifiers();
5847 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5848 if (CVR) {
5849 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5850 << Method->getDeclName() << FromRecordType << (CVR - 1)
5851 << From->getSourceRange();
5852 Diag(Method->getLocation(), diag::note_previous_decl)
5853 << Method->getDeclName();
5854 return ExprError();
5855 }
5856 break;
5857 }
5858
5861 bool IsRValueQualified =
5863 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5864 << Method->getDeclName() << FromClassification.isRValue()
5865 << IsRValueQualified;
5866 Diag(Method->getLocation(), diag::note_previous_decl)
5867 << Method->getDeclName();
5868 return ExprError();
5869 }
5870
5873 break;
5874
5877 llvm_unreachable("Lists are not objects");
5878 }
5879
5880 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5881 << ImplicitParamRecordType << FromRecordType
5882 << From->getSourceRange();
5883 }
5884
5885 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5886 ExprResult FromRes =
5887 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5888 if (FromRes.isInvalid())
5889 return ExprError();
5890 From = FromRes.get();
5891 }
5892
5893 if (!Context.hasSameType(From->getType(), DestType)) {
5894 CastKind CK;
5895 QualType PteeTy = DestType->getPointeeType();
5896 LangAS DestAS =
5897 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5898 if (FromRecordType.getAddressSpace() != DestAS)
5899 CK = CK_AddressSpaceConversion;
5900 else
5901 CK = CK_NoOp;
5902 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5903 }
5904 return From;
5905}
5906
5907/// TryContextuallyConvertToBool - Attempt to contextually convert the
5908/// expression From to bool (C++0x [conv]p3).
5911 // C++ [dcl.init]/17.8:
5912 // - Otherwise, if the initialization is direct-initialization, the source
5913 // type is std::nullptr_t, and the destination type is bool, the initial
5914 // value of the object being initialized is false.
5915 if (From->getType()->isNullPtrType())
5917 S.Context.BoolTy,
5918 From->isGLValue());
5919
5920 // All other direct-initialization of bool is equivalent to an implicit
5921 // conversion to bool in which explicit conversions are permitted.
5922 return TryImplicitConversion(S, From, S.Context.BoolTy,
5923 /*SuppressUserConversions=*/false,
5924 AllowedExplicit::Conversions,
5925 /*InOverloadResolution=*/false,
5926 /*CStyle=*/false,
5927 /*AllowObjCWritebackConversion=*/false,
5928 /*AllowObjCConversionOnExplicit=*/false);
5929}
5930
5932 if (checkPlaceholderForOverload(*this, From))
5933 return ExprError();
5934
5936 if (!ICS.isBad())
5937 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5938
5939 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5940 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5941 << From->getType() << From->getSourceRange();
5942 return ExprError();
5943}
5944
5945/// Check that the specified conversion is permitted in a converted constant
5946/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5947/// is acceptable.
5950 // Since we know that the target type is an integral or unscoped enumeration
5951 // type, most conversion kinds are impossible. All possible First and Third
5952 // conversions are fine.
5953 switch (SCS.Second) {
5954 case ICK_Identity:
5956 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5958 return true;
5959
5961 // Conversion from an integral or unscoped enumeration type to bool is
5962 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5963 // conversion, so we allow it in a converted constant expression.
5964 //
5965 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5966 // a lot of popular code. We should at least add a warning for this
5967 // (non-conforming) extension.
5969 SCS.getToType(2)->isBooleanType();
5970
5972 case ICK_Pointer_Member:
5973 // C++1z: null pointer conversions and null member pointer conversions are
5974 // only permitted if the source type is std::nullptr_t.
5975 return SCS.getFromType()->isNullPtrType();
5976
5988 case ICK_Vector_Splat:
5989 case ICK_Complex_Real:
5998 return false;
5999
6004 llvm_unreachable("found a first conversion kind in Second");
6005
6007 case ICK_Qualification:
6008 llvm_unreachable("found a third conversion kind in Second");
6009
6011 break;
6012 }
6013
6014 llvm_unreachable("unknown conversion kind");
6015}
6016
6017/// BuildConvertedConstantExpression - Check that the expression From is a
6018/// converted constant expression of type T, perform the conversion but
6019/// does not evaluate the expression
6021 QualType T,
6022 Sema::CCEKind CCE,
6023 NamedDecl *Dest,
6024 APValue &PreNarrowingValue) {
6025 assert(S.getLangOpts().CPlusPlus11 &&
6026 "converted constant expression outside C++11");
6027
6028 if (checkPlaceholderForOverload(S, From))
6029 return ExprError();
6030
6031 // C++1z [expr.const]p3:
6032 // A converted constant expression of type T is an expression,
6033 // implicitly converted to type T, where the converted
6034 // expression is a constant expression and the implicit conversion
6035 // sequence contains only [... list of conversions ...].
6039 : TryCopyInitialization(S, From, T,
6040 /*SuppressUserConversions=*/false,
6041 /*InOverloadResolution=*/false,
6042 /*AllowObjCWritebackConversion=*/false,
6043 /*AllowExplicit=*/false);
6044 StandardConversionSequence *SCS = nullptr;
6045 switch (ICS.getKind()) {
6047 SCS = &ICS.Standard;
6048 break;
6050 if (T->isRecordType())
6051 SCS = &ICS.UserDefined.Before;
6052 else
6053 SCS = &ICS.UserDefined.After;
6054 break;
6058 return S.Diag(From->getBeginLoc(),
6059 diag::err_typecheck_converted_constant_expression)
6060 << From->getType() << From->getSourceRange() << T;
6061 return ExprError();
6062
6065 llvm_unreachable("bad conversion in converted constant expression");
6066 }
6067
6068 // Check that we would only use permitted conversions.
6069 if (!CheckConvertedConstantConversions(S, *SCS)) {
6070 return S.Diag(From->getBeginLoc(),
6071 diag::err_typecheck_converted_constant_expression_disallowed)
6072 << From->getType() << From->getSourceRange() << T;
6073 }
6074 // [...] and where the reference binding (if any) binds directly.
6075 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6076 return S.Diag(From->getBeginLoc(),
6077 diag::err_typecheck_converted_constant_expression_indirect)
6078 << From->getType() << From->getSourceRange() << T;
6079 }
6080 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6081 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6082 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6083 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6084 // case explicitly.
6085 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6086 return S.Diag(From->getBeginLoc(),
6087 diag::err_reference_bind_to_bitfield_in_cce)
6088 << From->getSourceRange();
6089 }
6090
6091 // Usually we can simply apply the ImplicitConversionSequence we formed
6092 // earlier, but that's not guaranteed to work when initializing an object of
6093 // class type.
6095 if (T->isRecordType()) {
6096 assert(CCE == Sema::CCEK_TemplateArg &&
6097 "unexpected class type converted constant expr");
6100 T, cast<NonTypeTemplateParmDecl>(Dest)),
6101 SourceLocation(), From);
6102 } else {
6104 }
6105 if (Result.isInvalid())
6106 return Result;
6107
6108 // C++2a [intro.execution]p5:
6109 // A full-expression is [...] a constant-expression [...]
6110 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6111 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6113 if (Result.isInvalid())
6114 return Result;
6115
6116 // Check for a narrowing implicit conversion.
6117 bool ReturnPreNarrowingValue = false;
6118 QualType PreNarrowingType;
6119 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6120 PreNarrowingType)) {
6122 // Implicit conversion to a narrower type, but the expression is
6123 // value-dependent so we can't tell whether it's actually narrowing.
6125 // Implicit conversion to a narrower type, and the value is not a constant
6126 // expression. We'll diagnose this in a moment.
6127 case NK_Not_Narrowing:
6128 break;
6129
6131 if (CCE == Sema::CCEK_ArrayBound &&
6132 PreNarrowingType->isIntegralOrEnumerationType() &&
6133 PreNarrowingValue.isInt()) {
6134 // Don't diagnose array bound narrowing here; we produce more precise
6135 // errors by allowing the un-narrowed value through.
6136 ReturnPreNarrowingValue = true;
6137 break;
6138 }
6139 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6140 << CCE << /*Constant*/ 1
6141 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6142 break;
6143
6144 case NK_Type_Narrowing:
6145 // FIXME: It would be better to diagnose that the expression is not a
6146 // constant expression.
6147 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6148 << CCE << /*Constant*/ 0 << From->getType() << T;
6149 break;
6150 }
6151 if (!ReturnPreNarrowingValue)
6152 PreNarrowingValue = {};
6153
6154 return Result;
6155}
6156
6157/// CheckConvertedConstantExpression - Check that the expression From is a
6158/// converted constant expression of type T, perform the conversion and produce
6159/// the converted expression, per C++11 [expr.const]p3.
6162 Sema::CCEKind CCE,
6163 bool RequireInt,
6164 NamedDecl *Dest) {
6165
6166 APValue PreNarrowingValue;
6168 PreNarrowingValue);
6169 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6170 Value = APValue();
6171 return Result;
6172 }
6173 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6174 RequireInt, PreNarrowingValue);
6175}
6176
6178 CCEKind CCE,
6179 NamedDecl *Dest) {
6180 APValue PreNarrowingValue;
6181 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6182 PreNarrowingValue);
6183}
6184
6186 APValue &Value, CCEKind CCE,
6187 NamedDecl *Dest) {
6188 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6189 Dest);
6190}
6191
6193 llvm::APSInt &Value,
6194 CCEKind CCE) {
6195 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6196
6197 APValue V;
6198 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6199 /*Dest=*/nullptr);
6200 if (!R.isInvalid() && !R.get()->isValueDependent())
6201 Value = V.getInt();
6202 return R;
6203}
6204
6207 Sema::CCEKind CCE, bool RequireInt,
6208 const APValue &PreNarrowingValue) {
6209
6211 // Check the expression is a constant expression.
6213 Expr::EvalResult Eval;
6214 Eval.Diag = &Notes;
6215
6216 ConstantExprKind Kind;
6217 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6218 Kind = ConstantExprKind::ClassTemplateArgument;
6219 else if (CCE == Sema::CCEK_TemplateArg)
6220 Kind = ConstantExprKind::NonClassTemplateArgument;
6221 else
6222 Kind = ConstantExprKind::Normal;
6223
6224 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6225 (RequireInt && !Eval.Val.isInt())) {
6226 // The expression can't be folded, so we can't keep it at this position in
6227 // the AST.
6228 Result = ExprError();
6229 } else {
6230 Value = Eval.Val;
6231
6232 if (Notes.empty()) {
6233 // It's a constant expression.
6234 Expr *E = Result.get();
6235 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6236 // We expect a ConstantExpr to have a value associated with it
6237 // by this point.
6238 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6239 "ConstantExpr has no value associated with it");
6240 (void)CE;
6241 } else {
6242 E = ConstantExpr::Create(Context, Result.get(), Value);
6243 }
6244 if (!PreNarrowingValue.isAbsent())
6245 Value = std::move(PreNarrowingValue);
6246 return E;
6247 }
6248 }
6249
6250 // It's not a constant expression. Produce an appropriate diagnostic.
6251 if (Notes.size() == 1 &&
6252 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6253 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6254 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6255 diag::note_constexpr_invalid_template_arg) {
6256 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6257 for (unsigned I = 0; I < Notes.size(); ++I)
6258 Diag(Notes[I].first, Notes[I].second);
6259 } else {
6260 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6261 << CCE << E->getSourceRange();
6262 for (unsigned I = 0; I < Notes.size(); ++I)
6263 Diag(Notes[I].first, Notes[I].second);
6264 }
6265 return ExprError();
6266}
6267
6268/// dropPointerConversions - If the given standard conversion sequence
6269/// involves any pointer conversions, remove them. This may change
6270/// the result type of the conversion sequence.
6272 if (SCS.Second == ICK_Pointer_Conversion) {
6273 SCS.Second = ICK_Identity;
6274 SCS.Dimension = ICK_Identity;
6275 SCS.Third = ICK_Identity;
6276 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6277 }
6278}
6279
6280/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6281/// convert the expression From to an Objective-C pointer type.
6284 // Do an implicit conversion to 'id'.
6287 = TryImplicitConversion(S, From, Ty,
6288 // FIXME: Are these flags correct?
6289 /*SuppressUserConversions=*/false,
6290 AllowedExplicit::Conversions,
6291 /*InOverloadResolution=*/false,
6292 /*CStyle=*/false,
6293 /*AllowObjCWritebackConversion=*/false,
6294 /*AllowObjCConversionOnExplicit=*/true);
6295
6296 // Strip off any final conversions to 'id'.
6297 switch (ICS.getKind()) {
6302 break;
6303
6306 break;
6307
6310 break;
6311 }
6312
6313 return ICS;
6314}
6315
6317 if (checkPlaceholderForOverload(*this, From))
6318 return ExprError();
6319
6320 QualType Ty = Context.getObjCIdType();
6323 if (!ICS.isBad())
6324 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6325 return ExprResult();
6326}
6327
6328static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6329 const Expr *Base = nullptr;
6330 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6331 "expected a member expression");
6332
6333 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6334 M && !M->isImplicitAccess())
6335 Base = M->getBase();
6336 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6337 M && !M->isImplicitAccess())
6338 Base = M->getBase();
6339
6340 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6341
6342 if (T->isPointerType())
6343 T = T->getPointeeType();
6344
6345 return T;
6346}
6347
6349 const FunctionDecl *Fun) {
6350 QualType ObjType = Obj->getType();
6351 if (ObjType->isPointerType()) {
6352 ObjType = ObjType->getPointeeType();
6353 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6355 /*CanOverflow=*/false, FPOptionsOverride());
6356 }
6357 if (Obj->Classify(S.getASTContext()).isPRValue()) {
6359 ObjType, Obj,
6361 }
6362 return Obj;
6363}
6364
6366 FunctionDecl *Fun) {
6367 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6370 Obj->getExprLoc(), Obj);
6371}
6372
6374 Expr *Object, MultiExprArg &Args,
6375 SmallVectorImpl<Expr *> &NewArgs) {
6376 assert(Method->isExplicitObjectMemberFunction() &&
6377 "Method is not an explicit member function");
6378 assert(NewArgs.empty() && "NewArgs should be empty");
6379
6380 NewArgs.reserve(Args.size() + 1);
6381 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6382 NewArgs.push_back(This);
6383 NewArgs.append(Args.begin(), Args.end());
6384 Args = NewArgs;
6386 Method, Object->getBeginLoc());
6387}
6388
6389/// Determine whether the provided type is an integral type, or an enumeration
6390/// type of a permitted flavor.
6392 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6394}
6395
6396static ExprResult
6399 QualType T, UnresolvedSetImpl &ViableConversions) {
6400
6401 if (Converter.Suppress)
6402 return ExprError();
6403
6404 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6405 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6406 CXXConversionDecl *Conv =
6407 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6409 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6410 }
6411 return From;
6412}
6413
6414static bool
6417 QualType T, bool HadMultipleCandidates,
6418 UnresolvedSetImpl &ExplicitConversions) {
6419 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6420 DeclAccessPair Found = ExplicitConversions[0];
6421 CXXConversionDecl *Conversion =
6422 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6423
6424 // The user probably meant to invoke the given explicit
6425 // conversion; use it.
6426 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6427 std::string TypeStr;
6428 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6429
6430 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6432 "static_cast<" + TypeStr + ">(")
6434 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6435 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6436
6437 // If we aren't in a SFINAE context, build a call to the
6438 // explicit conversion function.
6439 if (SemaRef.isSFINAEContext())
6440 return true;
6441
6442 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6443 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6444 HadMultipleCandidates);
6445 if (Result.isInvalid())
6446 return true;
6447
6448 // Replace the conversion with a RecoveryExpr, so we don't try to
6449 // instantiate it later, but can further diagnose here.
6450 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6451 From, Result.get()->getType());
6452 if (Result.isInvalid())
6453 return true;
6454 From = Result.get();
6455 }
6456 return false;
6457}
6458
6459static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6461 QualType T, bool HadMultipleCandidates,
6463 CXXConversionDecl *Conversion =
6464 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6465 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6466
6467 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6468 if (!Converter.SuppressConversion) {
6469 if (SemaRef.isSFINAEContext())
6470 return true;
6471
6472 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6473 << From->getSourceRange();
6474 }
6475
6476 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6477 HadMultipleCandidates);
6478 if (Result.isInvalid())
6479 return true;
6480 // Record usage of conversion in an implicit cast.
6481 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6482 CK_UserDefinedConversion, Result.get(),
6483 nullptr, Result.get()->getValueKind(),
6484 SemaRef.CurFPFeatureOverrides());
6485 return false;
6486}
6487
6489 Sema &SemaRef, SourceLocation Loc, Expr *From,
6491 if (!Converter.match(From->getType()) && !Converter.Suppress)
6492 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6493 << From->getSourceRange();
6494
6495 return SemaRef.DefaultLvalueConversion(From);
6496}
6497
6498static void
6500 UnresolvedSetImpl &ViableConversions,
6501 OverloadCandidateSet &CandidateSet) {
6502 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6503 DeclAccessPair FoundDecl = ViableConversions[I];
6504 NamedDecl *D = FoundDecl.getDecl();
6505 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6506 if (isa<UsingShadowDecl>(D))
6507 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6508
6509 CXXConversionDecl *Conv;
6510 FunctionTemplateDecl *ConvTemplate;
6511 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6512 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6513 else
6514 Conv = cast<CXXConversionDecl>(D);
6515
6516 if (ConvTemplate)
6518 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6519 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6520 else
6521 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6522 ToType, CandidateSet,
6523 /*AllowObjCConversionOnExplicit=*/false,
6524 /*AllowExplicit*/ true);
6525 }
6526}
6527
6528/// Attempt to convert the given expression to a type which is accepted
6529/// by the given converter.
6530///
6531/// This routine will attempt to convert an expression of class type to a
6532/// type accepted by the specified converter. In C++11 and before, the class
6533/// must have a single non-explicit conversion function converting to a matching
6534/// type. In C++1y, there can be multiple such conversion functions, but only
6535/// one target type.
6536///
6537/// \param Loc The source location of the construct that requires the
6538/// conversion.
6539///
6540/// \param From The expression we're converting from.
6541///
6542/// \param Converter Used to control and diagnose the conversion process.
6543///
6544/// \returns The expression, converted to an integral or enumeration type if
6545/// successful.
6547 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6548 // We can't perform any more checking for type-dependent expressions.
6549 if (From->isTypeDependent())
6550 return From;
6551
6552 // Process placeholders immediately.
6553 if (From->hasPlaceholderType()) {
6554 ExprResult result = CheckPlaceholderExpr(From);
6555 if (result.isInvalid())
6556 return result;
6557 From = result.get();
6558 }
6559
6560 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6561 ExprResult Converted = DefaultLvalueConversion(From);
6562 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6563 // If the expression already has a matching type, we're golden.
6564 if (Converter.match(T))
6565 return Converted;
6566
6567 // FIXME: Check for missing '()' if T is a function type?
6568
6569 // We can only perform contextual implicit conversions on objects of class
6570 // type.
6571 const RecordType *RecordTy = T->getAs<RecordType>();
6572 if (!RecordTy || !getLangOpts().CPlusPlus) {
6573 if (!Converter.Suppress)
6574 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6575 return From;
6576 }
6577
6578 // We must have a complete class type.
6579 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6580 ContextualImplicitConverter &Converter;
6581 Expr *From;
6582
6583 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6584 : Converter(Converter), From(From) {}
6585
6586 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6587 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6588 }
6589 } IncompleteDiagnoser(Converter, From);
6590
6591 if (Converter.Suppress ? !isCompleteType(Loc, T)
6592 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6593 return From;
6594
6595 // Look for a conversion to an integral or enumeration type.
6597 ViableConversions; // These are *potentially* viable in C++1y.
6598 UnresolvedSet<4> ExplicitConversions;
6599 const auto &Conversions =
6600 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6601
6602 bool HadMultipleCandidates =
6603 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6604
6605 // To check that there is only one target type, in C++1y:
6606 QualType ToType;
6607 bool HasUniqueTargetType = true;
6608
6609 // Collect explicit or viable (potentially in C++1y) conversions.
6610 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6611 NamedDecl *D = (*I)->getUnderlyingDecl();
6612 CXXConversionDecl *Conversion;
6613 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6614 if (ConvTemplate) {
6615 if (getLangOpts().CPlusPlus14)
6616 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6617 else
6618 continue; // C++11 does not consider conversion operator templates(?).
6619 } else
6620 Conversion = cast<CXXConversionDecl>(D);
6621
6622 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6623 "Conversion operator templates are considered potentially "
6624 "viable in C++1y");
6625
6626 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6627 if (Converter.match(CurToType) || ConvTemplate) {
6628
6629 if (Conversion->isExplicit()) {
6630 // FIXME: For C++1y, do we need this restriction?
6631 // cf. diagnoseNoViableConversion()
6632 if (!ConvTemplate)
6633 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6634 } else {
6635 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6636 if (ToType.isNull())
6637 ToType = CurToType.getUnqualifiedType();
6638 else if (HasUniqueTargetType &&
6639 (CurToType.getUnqualifiedType() != ToType))
6640 HasUniqueTargetType = false;
6641 }
6642 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6643 }
6644 }
6645 }
6646
6647 if (getLangOpts().CPlusPlus14) {
6648 // C++1y [conv]p6:
6649 // ... An expression e of class type E appearing in such a context
6650 // is said to be contextually implicitly converted to a specified
6651 // type T and is well-formed if and only if e can be implicitly
6652 // converted to a type T that is determined as follows: E is searched
6653 // for conversion functions whose return type is cv T or reference to
6654 // cv T such that T is allowed by the context. There shall be
6655 // exactly one such T.
6656
6657 // If no unique T is found:
6658 if (ToType.isNull()) {
6659 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6660 HadMultipleCandidates,
6661 ExplicitConversions))
6662 return ExprError();
6663 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6664 }
6665
6666 // If more than one unique Ts are found:
6667 if (!HasUniqueTargetType)
6668 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6669 ViableConversions);
6670
6671 // If one unique T is found:
6672 // First, build a candidate set from the previously recorded
6673 // potentially viable conversions.
6675 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6676 CandidateSet);
6677
6678 // Then, perform overload resolution over the candidate set.
6680 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6681 case OR_Success: {
6682 // Apply this conversion.
6684 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6685 if (recordConversion(*this, Loc, From, Converter, T,
6686 HadMultipleCandidates, Found))
6687 return ExprError();
6688 break;
6689 }
6690 case OR_Ambiguous:
6691 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6692 ViableConversions);
6694 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6695 HadMultipleCandidates,
6696 ExplicitConversions))
6697 return ExprError();
6698 [[fallthrough]];
6699 case OR_Deleted:
6700 // We'll complain below about a non-integral condition type.
6701 break;
6702 }
6703 } else {
6704 switch (ViableConversions.size()) {
6705 case 0: {
6706 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6707 HadMultipleCandidates,
6708 ExplicitConversions))
6709 return ExprError();
6710
6711 // We'll complain below about a non-integral condition type.
6712 break;
6713 }
6714 case 1: {
6715 // Apply this conversion.
6716 DeclAccessPair Found = ViableConversions[0];
6717 if (recordConversion(*this, Loc, From, Converter, T,
6718 HadMultipleCandidates, Found))
6719 return ExprError();
6720 break;
6721 }
6722 default:
6723 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6724 ViableConversions);
6725 }
6726 }
6727
6728 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6729}
6730
6731/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6732/// an acceptable non-member overloaded operator for a call whose
6733/// arguments have types T1 (and, if non-empty, T2). This routine
6734/// implements the check in C++ [over.match.oper]p3b2 concerning
6735/// enumeration types.
6737 FunctionDecl *Fn,
6738 ArrayRef<Expr *> Args) {
6739 QualType T1 = Args[0]->getType();
6740 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6741
6742 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6743 return true;
6744
6745 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6746 return true;
6747
6748 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6749 if (Proto->getNumParams() < 1)
6750 return false;
6751
6752 if (T1->isEnumeralType()) {
6753 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6754 if (Context.hasSameUnqualifiedType(T1, ArgType))
6755 return true;
6756 }
6757
6758 if (Proto->getNumParams() < 2)
6759 return false;
6760
6761 if (!T2.isNull() && T2->isEnumeralType()) {
6762 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6763 if (Context.hasSameUnqualifiedType(T2, ArgType))
6764 return true;
6765 }
6766
6767 return false;
6768}
6769
6772 return false;
6773
6774 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6775 return FD->isTargetMultiVersion();
6776
6777 if (!FD->isMultiVersion())
6778 return false;
6779
6780 // Among multiple target versions consider either the default,
6781 // or the first non-default in the absence of default version.
6782 unsigned SeenAt = 0;
6783 unsigned I = 0;
6784 bool HasDefault = false;
6786 FD, [&](const FunctionDecl *CurFD) {
6787 if (FD == CurFD)
6788 SeenAt = I;
6789 else if (CurFD->isTargetMultiVersionDefault())
6790 HasDefault = true;
6791 ++I;
6792 });
6793 return HasDefault || SeenAt != 0;
6794}
6795
6798 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6799 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6800 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6801 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6802 const FunctionProtoType *Proto
6803 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6804 assert(Proto && "Functions without a prototype cannot be overloaded");
6805 assert(!Function->getDescribedFunctionTemplate() &&
6806 "Use AddTemplateOverloadCandidate for function templates");
6807
6808 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6809 if (!isa<CXXConstructorDecl>(Method)) {
6810 // If we get here, it's because we're calling a member function
6811 // that is named without a member access expression (e.g.,
6812 // "this->f") that was either written explicitly or created
6813 // implicitly. This can happen with a qualified call to a member
6814 // function, e.g., X::f(). We use an empty type for the implied
6815 // object argument (C++ [over.call.func]p3), and the acting context
6816 // is irrelevant.
6817 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6819 CandidateSet, SuppressUserConversions,
6820 PartialOverloading, EarlyConversions, PO);
6821 return;
6822 }
6823 // We treat a constructor like a non-member function, since its object
6824 // argument doesn't participate in overload resolution.
6825 }
6826
6827 if (!CandidateSet.isNewCandidate(Function, PO))
6828 return;
6829
6830 // C++11 [class.copy]p11: [DR1402]
6831 // A defaulted move constructor that is defined as deleted is ignored by
6832 // overload resolution.
6833 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6834 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6835 Constructor->isMoveConstructor())
6836 return;
6837
6838 // Overload resolution is always an unevaluated context.
6841
6842 // C++ [over.match.oper]p3:
6843 // if no operand has a class type, only those non-member functions in the
6844 // lookup set that have a first parameter of type T1 or "reference to
6845 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6846 // is a right operand) a second parameter of type T2 or "reference to
6847 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6848 // candidate functions.
6849 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6851 return;
6852
6853 // Add this candidate
6854 OverloadCandidate &Candidate =
6855 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6856 Candidate.FoundDecl = FoundDecl;
6857 Candidate.Function = Function;
6858 Candidate.Viable = true;
6859 Candidate.RewriteKind =
6860 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6861 Candidate.IsADLCandidate = IsADLCandidate;
6862 Candidate.ExplicitCallArguments = Args.size();
6863
6864 // Explicit functions are not actually candidates at all if we're not
6865 // allowing them in this context, but keep them around so we can point
6866 // to them in diagnostics.
6867 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6868 Candidate.Viable = false;
6869 Candidate.FailureKind = ovl_fail_explicit;
6870 return;
6871 }
6872
6873 // Functions with internal linkage are only viable in the same module unit.
6874 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6875 /// FIXME: Currently, the semantics of linkage in clang is slightly
6876 /// different from the semantics in C++ spec. In C++ spec, only names
6877 /// have linkage. So that all entities of the same should share one
6878 /// linkage. But in clang, different entities of the same could have
6879 /// different linkage.
6880 NamedDecl *ND = Function;
6881 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6882 ND = SpecInfo->getTemplate();
6883
6884 if (ND->getFormalLinkage() == Linkage::Internal) {
6885 Candidate.Viable = false;
6887 return;
6888 }
6889 }
6890
6892 Candidate.Viable = false;
6894 return;
6895 }
6896
6897 if (Constructor) {
6898 // C++ [class.copy]p3:
6899 // A member function template is never instantiated to perform the copy
6900 // of a class object to an object of its class type.
6901 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6902 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6903 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6904 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6905 ClassType))) {
6906 Candidate.Viable = false;
6908 return;
6909 }
6910
6911 // C++ [over.match.funcs]p8: (proposed DR resolution)
6912 // A constructor inherited from class type C that has a first parameter
6913 // of type "reference to P" (including such a constructor instantiated
6914 // from a template) is excluded from the set of candidate functions when
6915 // constructing an object of type cv D if the argument list has exactly
6916 // one argument and D is reference-related to P and P is reference-related
6917 // to C.
6918 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6919 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6920 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6921 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6922 QualType C = Context.getRecordType(Constructor->getParent());
6923 QualType D = Context.getRecordType(Shadow->getParent());
6924 SourceLocation Loc = Args.front()->getExprLoc();
6925 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6926 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6927 Candidate.Viable = false;
6929 return;
6930 }
6931 }
6932
6933 // Check that the constructor is capable of constructing an object in the
6934 // destination address space.
6936 Constructor->getMethodQualifiers().getAddressSpace(),
6937 CandidateSet.getDestAS())) {
6938 Candidate.Viable = false;
6940 }
6941 }
6942
6943 unsigned NumParams = Proto->getNumParams();
6944
6945 // (C++ 13.3.2p2): A candidate function having fewer than m
6946 // parameters is viable only if it has an ellipsis in its parameter
6947 // list (8.3.5).
6948 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6949 !Proto->isVariadic() &&
6950 shouldEnforceArgLimit(PartialOverloading, Function)) {
6951 Candidate.Viable = false;
6953 return;
6954 }
6955
6956 // (C++ 13.3.2p2): A candidate function having more than m parameters
6957 // is viable only if the (m+1)st parameter has a default argument
6958 // (8.3.6). For the purposes of overload resolution, the
6959 // parameter list is truncated on the right, so that there are
6960 // exactly m parameters.
6961 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6962 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
6963 !PartialOverloading) {
6964 // Not enough arguments.
6965 Candidate.Viable = false;
6967 return;
6968 }
6969
6970 // (CUDA B.1): Check for invalid calls between targets.
6971 if (getLangOpts().CUDA) {
6972 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
6973 // Skip the check for callers that are implicit members, because in this
6974 // case we may not yet know what the member's target is; the target is
6975 // inferred for the member automatically, based on the bases and fields of
6976 // the class.
6977 if (!(Caller && Caller->isImplicit()) &&
6978 !CUDA().IsAllowedCall(Caller, Function)) {
6979 Candidate.Viable = false;
6980 Candidate.FailureKind = ovl_fail_bad_target;
6981 return;
6982 }
6983 }
6984
6985 if (Function->getTrailingRequiresClause()) {
6986 ConstraintSatisfaction Satisfaction;
6987 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
6988 /*ForOverloadResolution*/ true) ||
6989 !Satisfaction.IsSatisfied) {
6990 Candidate.Viable = false;
6992 return;
6993 }
6994 }
6995
6996 // Determine the implicit conversion sequences for each of the
6997 // arguments.
6998 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6999 unsigned ConvIdx =
7000 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7001 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7002 // We already formed a conversion sequence for this parameter during
7003 // template argument deduction.
7004 } else if (ArgIdx < NumParams) {
7005 // (C++ 13.3.2p3): for F to be a viable function, there shall
7006 // exist for each argument an implicit conversion sequence
7007 // (13.3.3.1) that converts that argument to the corresponding
7008 // parameter of F.
7009 QualType ParamType = Proto->getParamType(ArgIdx);
7010 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7011 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7012 /*InOverloadResolution=*/true,
7013 /*AllowObjCWritebackConversion=*/
7014 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7015 if (Candidate.Conversions[ConvIdx].isBad()) {
7016 Candidate.Viable = false;
7018 return;
7019 }
7020 } else {
7021 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7022 // argument for which there is no corresponding parameter is
7023 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7024 Candidate.Conversions[ConvIdx].setEllipsis();
7025 }
7026 }
7027
7028 if (EnableIfAttr *FailedAttr =
7029 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7030 Candidate.Viable = false;
7031 Candidate.FailureKind = ovl_fail_enable_if;
7032 Candidate.DeductionFailure.Data = FailedAttr;
7033 return;
7034 }
7035}
7036
7040 if (Methods.size() <= 1)
7041 return nullptr;
7042
7043 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7044 bool Match = true;
7045 ObjCMethodDecl *Method = Methods[b];
7046 unsigned NumNamedArgs = Sel.getNumArgs();
7047 // Method might have more arguments than selector indicates. This is due
7048 // to addition of c-style arguments in method.
7049 if (Method->param_size() > NumNamedArgs)
7050 NumNamedArgs = Method->param_size();
7051 if (Args.size() < NumNamedArgs)
7052 continue;
7053
7054 for (unsigned i = 0; i < NumNamedArgs; i++) {
7055 // We can't do any type-checking on a type-dependent argument.
7056 if (Args[i]->isTypeDependent()) {
7057 Match = false;
7058 break;
7059 }
7060
7061 ParmVarDecl *param = Method->parameters()[i];
7062 Expr *argExpr = Args[i];
7063 assert(argExpr && "SelectBestMethod(): missing expression");
7064
7065 // Strip the unbridged-cast placeholder expression off unless it's
7066 // a consumed argument.
7067 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7068 !param->hasAttr<CFConsumedAttr>())
7069 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7070
7071 // If the parameter is __unknown_anytype, move on to the next method.
7072 if (param->getType() == Context.UnknownAnyTy) {
7073 Match = false;
7074 break;
7075 }
7076
7077 ImplicitConversionSequence ConversionState
7078 = TryCopyInitialization(*this, argExpr, param->getType(),
7079 /*SuppressUserConversions*/false,
7080 /*InOverloadResolution=*/true,
7081 /*AllowObjCWritebackConversion=*/
7082 getLangOpts().ObjCAutoRefCount,
7083 /*AllowExplicit*/false);
7084 // This function looks for a reasonably-exact match, so we consider
7085 // incompatible pointer conversions to be a failure here.
7086 if (ConversionState.isBad() ||
7087 (ConversionState.isStandard() &&
7088 ConversionState.Standard.Second ==
7090 Match = false;
7091 break;
7092 }
7093 }
7094 // Promote additional arguments to variadic methods.
7095 if (Match && Method->isVariadic()) {
7096 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7097 if (Args[i]->isTypeDependent()) {
7098 Match = false;
7099 break;
7100 }
7101 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7102 nullptr);
7103 if (Arg.isInvalid()) {
7104 Match = false;
7105 break;
7106 }
7107 }
7108 } else {
7109 // Check for extra arguments to non-variadic methods.
7110 if (Args.size() != NumNamedArgs)
7111 Match = false;
7112 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7113 // Special case when selectors have no argument. In this case, select
7114 // one with the most general result type of 'id'.
7115 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7116 QualType ReturnT = Methods[b]->getReturnType();
7117 if (ReturnT->isObjCIdType())
7118 return Methods[b];
7119 }
7120 }
7121 }
7122
7123 if (Match)
7124 return Method;
7125 }
7126 return nullptr;
7127}
7128
7130 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7131 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7132 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7133 if (ThisArg) {
7134 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7135 assert(!isa<CXXConstructorDecl>(Method) &&
7136 "Shouldn't have `this` for ctors!");
7137 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7139 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7140 if (R.isInvalid())
7141 return false;
7142 ConvertedThis = R.get();
7143 } else {
7144 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7145 (void)MD;
7146 assert((MissingImplicitThis || MD->isStatic() ||
7147 isa<CXXConstructorDecl>(MD)) &&
7148 "Expected `this` for non-ctor instance methods");
7149 }
7150 ConvertedThis = nullptr;
7151 }
7152
7153 // Ignore any variadic arguments. Converting them is pointless, since the
7154 // user can't refer to them in the function condition.
7155 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7156
7157 // Convert the arguments.
7158 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7159 ExprResult R;
7161 S.Context, Function->getParamDecl(I)),
7162 SourceLocation(), Args[I]);
7163
7164 if (R.isInvalid())
7165 return false;
7166
7167 ConvertedArgs.push_back(R.get());
7168 }
7169
7170 if (Trap.hasErrorOccurred())
7171 return false;
7172
7173 // Push default arguments if needed.
7174 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7175 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7176 ParmVarDecl *P = Function->getParamDecl(i);
7177 if (!P->hasDefaultArg())
7178 return false;
7180 if (R.isInvalid())
7181 return false;
7182 ConvertedArgs.push_back(R.get());
7183 }
7184
7185 if (Trap.hasErrorOccurred())
7186 return false;
7187 }
7188 return true;
7189}
7190
7192 SourceLocation CallLoc,
7193 ArrayRef<Expr *> Args,
7194 bool MissingImplicitThis) {
7195 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7196 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7197 return nullptr;
7198
7199 SFINAETrap Trap(*this);
7200 SmallVector<Expr *, 16> ConvertedArgs;
7201 // FIXME: We should look into making enable_if late-parsed.
7202 Expr *DiscardedThis;
7204 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7205 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7206 return *EnableIfAttrs.begin();
7207
7208 for (auto *EIA : EnableIfAttrs) {
7210 // FIXME: This doesn't consider value-dependent cases, because doing so is
7211 // very difficult. Ideally, we should handle them more gracefully.
7212 if (EIA->getCond()->isValueDependent() ||
7213 !EIA->getCond()->EvaluateWithSubstitution(
7214 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7215 return EIA;
7216
7217 if (!Result.isInt() || !Result.getInt().getBoolValue())
7218 return EIA;
7219 }
7220 return nullptr;
7221}
7222
7223template <typename CheckFn>
7225 bool ArgDependent, SourceLocation Loc,
7226 CheckFn &&IsSuccessful) {
7228 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7229 if (ArgDependent == DIA->getArgDependent())
7230 Attrs.push_back(DIA);
7231 }
7232
7233 // Common case: No diagnose_if attributes, so we can quit early.
7234 if (Attrs.empty())
7235 return false;
7236
7237 auto WarningBegin = std::stable_partition(
7238 Attrs.begin(), Attrs.end(),
7239 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7240
7241 // Note that diagnose_if attributes are late-parsed, so they appear in the
7242 // correct order (unlike enable_if attributes).
7243 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7244 IsSuccessful);
7245 if (ErrAttr != WarningBegin) {
7246 const DiagnoseIfAttr *DIA = *ErrAttr;
7247 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7248 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7249 << DIA->getParent() << DIA->getCond()->getSourceRange();
7250 return true;
7251 }
7252
7253 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7254 if (IsSuccessful(DIA)) {
7255 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7256 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7257 << DIA->getParent() << DIA->getCond()->getSourceRange();
7258 }
7259
7260 return false;
7261}
7262
7264 const Expr *ThisArg,
7266 SourceLocation Loc) {
7268 *this, Function, /*ArgDependent=*/true, Loc,
7269 [&](const DiagnoseIfAttr *DIA) {
7271 // It's sane to use the same Args for any redecl of this function, since
7272 // EvaluateWithSubstitution only cares about the position of each
7273 // argument in the arg list, not the ParmVarDecl* it maps to.
7274 if (!DIA->getCond()->EvaluateWithSubstitution(
7275 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7276 return false;
7277 return Result.isInt() && Result.getInt().getBoolValue();
7278 });
7279}
7280
7282 SourceLocation Loc) {
7284 *this, ND, /*ArgDependent=*/false, Loc,
7285 [&](const DiagnoseIfAttr *DIA) {
7286 bool Result;
7287 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7288 Result;
7289 });
7290}
7291
7293 ArrayRef<Expr *> Args,
7294 OverloadCandidateSet &CandidateSet,
7295 TemplateArgumentListInfo *ExplicitTemplateArgs,
7296 bool SuppressUserConversions,
7297 bool PartialOverloading,
7298 bool FirstArgumentIsBase) {
7299 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7300 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7301 ArrayRef<Expr *> FunctionArgs = Args;
7302
7303 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7304 FunctionDecl *FD =
7305 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7306
7307 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7308 QualType ObjectType;
7309 Expr::Classification ObjectClassification;
7310 if (Args.size() > 0) {
7311 if (Expr *E = Args[0]) {
7312 // Use the explicit base to restrict the lookup:
7313 ObjectType = E->getType();
7314 // Pointers in the object arguments are implicitly dereferenced, so we
7315 // always classify them as l-values.
7316 if (!ObjectType.isNull() && ObjectType->isPointerType())
7317 ObjectClassification = Expr::Classification::makeSimpleLValue();
7318 else
7319 ObjectClassification = E->Classify(Context);
7320 } // .. else there is an implicit base.
7321 FunctionArgs = Args.slice(1);
7322 }
7323 if (FunTmpl) {
7324 AddMethodTemplateCandidate(
7325 FunTmpl, F.getPair(),
7326 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7327 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7328 FunctionArgs, CandidateSet, SuppressUserConversions,
7329 PartialOverloading);
7330 } else {
7331 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7332 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7333 ObjectClassification, FunctionArgs, CandidateSet,
7334 SuppressUserConversions, PartialOverloading);
7335 }
7336 } else {
7337 // This branch handles both standalone functions and static methods.
7338
7339 // Slice the first argument (which is the base) when we access
7340 // static method as non-static.
7341 if (Args.size() > 0 &&
7342 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7343 !isa<CXXConstructorDecl>(FD)))) {
7344 assert(cast<CXXMethodDecl>(FD)->isStatic());
7345 FunctionArgs = Args.slice(1);
7346 }
7347 if (FunTmpl) {
7348 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7349 ExplicitTemplateArgs, FunctionArgs,
7350 CandidateSet, SuppressUserConversions,
7351 PartialOverloading);
7352 } else {
7353 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7354 SuppressUserConversions, PartialOverloading);
7355 }
7356 }
7357 }
7358}
7359
7361 Expr::Classification ObjectClassification,
7362 ArrayRef<Expr *> Args,
7363 OverloadCandidateSet &CandidateSet,
7364 bool SuppressUserConversions,
7366 NamedDecl *Decl = FoundDecl.getDecl();
7367 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7368
7369 if (isa<UsingShadowDecl>(Decl))
7370 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7371
7372 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7373 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7374 "Expected a member function template");
7375 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7376 /*ExplicitArgs*/ nullptr, ObjectType,
7377 ObjectClassification, Args, CandidateSet,
7378 SuppressUserConversions, false, PO);
7379 } else {
7380 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7381 ObjectType, ObjectClassification, Args, CandidateSet,
7382 SuppressUserConversions, false, std::nullopt, PO);
7383 }
7384}
7385
7386void
7388 CXXRecordDecl *ActingContext, QualType ObjectType,
7389 Expr::Classification ObjectClassification,
7390 ArrayRef<Expr *> Args,
7391 OverloadCandidateSet &CandidateSet,
7392 bool SuppressUserConversions,
7393 bool PartialOverloading,
7394 ConversionSequenceList EarlyConversions,
7396 const FunctionProtoType *Proto
7397 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7398 assert(Proto && "Methods without a prototype cannot be overloaded");
7399 assert(!isa<CXXConstructorDecl>(Method) &&
7400 "Use AddOverloadCandidate for constructors");
7401
7402 if (!CandidateSet.isNewCandidate(Method, PO))
7403 return;
7404
7405 // C++11 [class.copy]p23: [DR1402]
7406 // A defaulted move assignment operator that is defined as deleted is
7407 // ignored by overload resolution.
7408 if (Method->isDefaulted() && Method->isDeleted() &&
7409 Method->isMoveAssignmentOperator())
7410 return;
7411
7412 // Overload resolution is always an unevaluated context.
7415
7416 // Add this candidate
7417 OverloadCandidate &Candidate =
7418 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7419 Candidate.FoundDecl = FoundDecl;
7420 Candidate.Function = Method;
7421 Candidate.RewriteKind =
7422 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7423 Candidate.TookAddressOfOverload =
7425 Candidate.ExplicitCallArguments = Args.size();
7426
7427 bool IgnoreExplicitObject =
7428 (Method->isExplicitObjectMemberFunction() &&
7429 CandidateSet.getKind() ==
7431 bool ImplicitObjectMethodTreatedAsStatic =
7432 CandidateSet.getKind() ==
7435
7436 unsigned ExplicitOffset =
7437 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7438
7439 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7440 int(ImplicitObjectMethodTreatedAsStatic);
7441
7442 // (C++ 13.3.2p2): A candidate function having fewer than m
7443 // parameters is viable only if it has an ellipsis in its parameter
7444 // list (8.3.5).
7445 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7446 !Proto->isVariadic() &&
7447 shouldEnforceArgLimit(PartialOverloading, Method)) {
7448 Candidate.Viable = false;
7450 return;
7451 }
7452
7453 // (C++ 13.3.2p2): A candidate function having more than m parameters
7454 // is viable only if the (m+1)st parameter has a default argument
7455 // (8.3.6). For the purposes of overload resolution, the
7456 // parameter list is truncated on the right, so that there are
7457 // exactly m parameters.
7458 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7459 ExplicitOffset +
7460 int(ImplicitObjectMethodTreatedAsStatic);
7461
7462 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7463 // Not enough arguments.
7464 Candidate.Viable = false;
7466 return;
7467 }
7468
7469 Candidate.Viable = true;
7470
7471 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7472 if (ObjectType.isNull())
7473 Candidate.IgnoreObjectArgument = true;
7474 else if (Method->isStatic()) {
7475 // [over.best.ics.general]p8
7476 // When the parameter is the implicit object parameter of a static member
7477 // function, the implicit conversion sequence is a standard conversion
7478 // sequence that is neither better nor worse than any other standard
7479 // conversion sequence.
7480 //
7481 // This is a rule that was introduced in C++23 to support static lambdas. We
7482 // apply it retroactively because we want to support static lambdas as an
7483 // extension and it doesn't hurt previous code.
7484 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7485 } else {
7486 // Determine the implicit conversion sequence for the object
7487 // parameter.
7488 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7489 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7490 Method, ActingContext, /*InOverloadResolution=*/true);
7491 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7492 Candidate.Viable = false;
7494 return;
7495 }
7496 }
7497
7498 // (CUDA B.1): Check for invalid calls between targets.
7499 if (getLangOpts().CUDA)
7500 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7501 Method)) {
7502 Candidate.Viable = false;
7503 Candidate.FailureKind = ovl_fail_bad_target;
7504 return;
7505 }
7506
7507 if (Method->getTrailingRequiresClause()) {
7508 ConstraintSatisfaction Satisfaction;
7509 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7510 /*ForOverloadResolution*/ true) ||
7511 !Satisfaction.IsSatisfied) {
7512 Candidate.Viable = false;
7514 return;
7515 }
7516 }
7517
7518 // Determine the implicit conversion sequences for each of the
7519 // arguments.
7520 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7521 unsigned ConvIdx =
7522 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7523 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7524 // We already formed a conversion sequence for this parameter during
7525 // template argument deduction.
7526 } else if (ArgIdx < NumParams) {
7527 // (C++ 13.3.2p3): for F to be a viable function, there shall
7528 // exist for each argument an implicit conversion sequence
7529 // (13.3.3.1) that converts that argument to the corresponding
7530 // parameter of F.
7531 QualType ParamType;
7532 if (ImplicitObjectMethodTreatedAsStatic) {
7533 ParamType = ArgIdx == 0
7535 : Proto->getParamType(ArgIdx - 1);
7536 } else {
7537 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7538 }
7539 Candidate.Conversions[ConvIdx]
7540 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7541 SuppressUserConversions,
7542 /*InOverloadResolution=*/true,
7543 /*AllowObjCWritebackConversion=*/
7544 getLangOpts().ObjCAutoRefCount);
7545 if (Candidate.Conversions[ConvIdx].isBad()) {
7546 Candidate.Viable = false;
7548 return;
7549 }
7550 } else {
7551 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7552 // argument for which there is no corresponding parameter is
7553 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7554 Candidate.Conversions[ConvIdx].setEllipsis();
7555 }
7556 }
7557
7558 if (EnableIfAttr *FailedAttr =
7559 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7560 Candidate.Viable = false;
7561 Candidate.FailureKind = ovl_fail_enable_if;
7562 Candidate.DeductionFailure.Data = FailedAttr;
7563 return;
7564 }
7565
7566 if (isNonViableMultiVersionOverload(Method)) {
7567 Candidate.Viable = false;
7569 }
7570}
7571
7573 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7574 CXXRecordDecl *ActingContext,
7575 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7576 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7577 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7578 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7579 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7580 return;
7581
7582 // C++ [over.match.funcs]p7:
7583 // In each case where a candidate is a function template, candidate
7584 // function template specializations are generated using template argument
7585 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7586 // candidate functions in the usual way.113) A given name can refer to one
7587 // or more function templates and also to a set of overloaded non-template
7588 // functions. In such a case, the candidate functions generated from each
7589 // function template are combined with the set of non-template candidate
7590 // functions.
7591 TemplateDeductionInfo Info(CandidateSet.getLocation());
7592 FunctionDecl *Specialization = nullptr;
7593 ConversionSequenceList Conversions;
7595 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7596 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7597 ObjectClassification,
7598 [&](ArrayRef<QualType> ParamTypes) {
7599 return CheckNonDependentConversions(
7600 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7601 SuppressUserConversions, ActingContext, ObjectType,
7602 ObjectClassification, PO);
7603 });
7605 OverloadCandidate &Candidate =
7606 CandidateSet.addCandidate(Conversions.size(), Conversions);
7607 Candidate.FoundDecl = FoundDecl;
7608 Candidate.Function = MethodTmpl->getTemplatedDecl();
7609 Candidate.Viable = false;
7610 Candidate.RewriteKind =
7611 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7612 Candidate.IsSurrogate = false;
7613 Candidate.IgnoreObjectArgument =
7614 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7615 ObjectType.isNull();
7616 Candidate.ExplicitCallArguments = Args.size();
7619 else {
7622 Info);
7623 }
7624 return;
7625 }
7626
7627 // Add the function template specialization produced by template argument
7628 // deduction as a candidate.
7629 assert(Specialization && "Missing member function template specialization?");
7630 assert(isa<CXXMethodDecl>(Specialization) &&
7631 "Specialization is not a member function?");
7632 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7633 ActingContext, ObjectType, ObjectClassification, Args,
7634 CandidateSet, SuppressUserConversions, PartialOverloading,
7635 Conversions, PO);
7636}
7637
7638/// Determine whether a given function template has a simple explicit specifier
7639/// or a non-value-dependent explicit-specification that evaluates to true.
7642}
7643
7645 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7646 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7647 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7648 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7649 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7650 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7651 return;
7652
7653 // If the function template has a non-dependent explicit specification,
7654 // exclude it now if appropriate; we are not permitted to perform deduction
7655 // and substitution in this case.
7656 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7657 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7658 Candidate.FoundDecl = FoundDecl;
7659 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7660 Candidate.Viable = false;
7661 Candidate.FailureKind = ovl_fail_explicit;
7662 return;
7663 }
7664
7665 // C++ [over.match.funcs]p7:
7666 // In each case where a candidate is a function template, candidate
7667 // function template specializations are generated using template argument
7668 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7669 // candidate functions in the usual way.113) A given name can refer to one
7670 // or more function templates and also to a set of overloaded non-template
7671 // functions. In such a case, the candidate functions generated from each
7672 // function template are combined with the set of non-template candidate
7673 // functions.
7674 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7675 FunctionTemplate->getTemplateDepth());
7676 FunctionDecl *Specialization = nullptr;
7677 ConversionSequenceList Conversions;
7679 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7680 PartialOverloading, AggregateCandidateDeduction,
7681 /*ObjectType=*/QualType(),
7682 /*ObjectClassification=*/Expr::Classification(),
7683 [&](ArrayRef<QualType> ParamTypes) {
7684 return CheckNonDependentConversions(
7685 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7686 SuppressUserConversions, nullptr, QualType(), {}, PO);
7687 });
7689 OverloadCandidate &Candidate =
7690 CandidateSet.addCandidate(Conversions.size(), Conversions);
7691 Candidate.FoundDecl = FoundDecl;
7692 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7693 Candidate.Viable = false;
7694 Candidate.RewriteKind =
7695 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7696 Candidate.IsSurrogate = false;
7697 Candidate.IsADLCandidate = IsADLCandidate;
7698 // Ignore the object argument if there is one, since we don't have an object
7699 // type.
7700 Candidate.IgnoreObjectArgument =
7701 isa<CXXMethodDecl>(Candidate.Function) &&
7702 !isa<CXXConstructorDecl>(Candidate.Function);
7703 Candidate.ExplicitCallArguments = Args.size();
7706 else {
7709 Info);
7710 }
7711 return;
7712 }
7713
7714 // Add the function template specialization produced by template argument
7715 // deduction as a candidate.
7716 assert(Specialization && "Missing function template specialization?");
7717 AddOverloadCandidate(
7718 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7719 PartialOverloading, AllowExplicit,
7720 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7722}
7723
7725 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7726 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7727 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7728 CXXRecordDecl *ActingContext, QualType ObjectType,
7729 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7730 // FIXME: The cases in which we allow explicit conversions for constructor
7731 // arguments never consider calling a constructor template. It's not clear
7732 // that is correct.
7733 const bool AllowExplicit = false;
7734
7735 auto *FD = FunctionTemplate->getTemplatedDecl();
7736 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7737 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7738 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7739
7740 Conversions =
7741 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7742
7743 // Overload resolution is always an unevaluated context.
7746
7747 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7748 // require that, but this check should never result in a hard error, and
7749 // overload resolution is permitted to sidestep instantiations.
7750 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7751 !ObjectType.isNull()) {
7752 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7753 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7754 !ParamTypes[0]->isDependentType()) {
7755 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7756 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7757 Method, ActingContext, /*InOverloadResolution=*/true,
7758 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7759 : QualType());
7760 if (Conversions[ConvIdx].isBad())
7761 return true;
7762 }
7763 }
7764
7765 unsigned Offset =
7766 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7767
7768 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7769 I != N; ++I) {
7770 QualType ParamType = ParamTypes[I + Offset];
7771 if (!ParamType->isDependentType()) {
7772 unsigned ConvIdx;
7774 ConvIdx = Args.size() - 1 - I;
7775 assert(Args.size() + ThisConversions == 2 &&
7776 "number of args (including 'this') must be exactly 2 for "
7777 "reversed order");
7778 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7779 // would also be 0. 'this' got ConvIdx = 1 previously.
7780 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7781 } else {
7782 // For members, 'this' got ConvIdx = 0 previously.
7783 ConvIdx = ThisConversions + I;
7784 }
7785 Conversions[ConvIdx]
7786 = TryCopyInitialization(*this, Args[I], ParamType,
7787 SuppressUserConversions,
7788 /*InOverloadResolution=*/true,
7789 /*AllowObjCWritebackConversion=*/
7790 getLangOpts().ObjCAutoRefCount,
7791 AllowExplicit);
7792 if (Conversions[ConvIdx].isBad())
7793 return true;
7794 }
7795 }
7796
7797 return false;
7798}
7799
7800/// Determine whether this is an allowable conversion from the result
7801/// of an explicit conversion operator to the expected type, per C++
7802/// [over.match.conv]p1 and [over.match.ref]p1.
7803///
7804/// \param ConvType The return type of the conversion function.
7805///
7806/// \param ToType The type we are converting to.
7807///
7808/// \param AllowObjCPointerConversion Allow a conversion from one
7809/// Objective-C pointer to another.
7810///
7811/// \returns true if the conversion is allowable, false otherwise.
7813 QualType ConvType, QualType ToType,
7814 bool AllowObjCPointerConversion) {
7815 QualType ToNonRefType = ToType.getNonReferenceType();
7816
7817 // Easy case: the types are the same.
7818 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7819 return true;
7820
7821 // Allow qualification conversions.
7822 bool ObjCLifetimeConversion;
7823 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7824 ObjCLifetimeConversion))
7825 return true;
7826
7827 // If we're not allowed to consider Objective-C pointer conversions,
7828 // we're done.
7829 if (!AllowObjCPointerConversion)
7830 return false;
7831
7832 // Is this an Objective-C pointer conversion?
7833 bool IncompatibleObjC = false;
7834 QualType ConvertedType;
7835 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7836 IncompatibleObjC);
7837}
7838
7840 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7841 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7842 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7843 bool AllowExplicit, bool AllowResultConversion) {
7844 assert(!Conversion->getDescribedFunctionTemplate() &&
7845 "Conversion function templates use AddTemplateConversionCandidate");
7846 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7847 if (!CandidateSet.isNewCandidate(Conversion))
7848 return;
7849
7850 // If the conversion function has an undeduced return type, trigger its
7851 // deduction now.
7852 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7853 if (DeduceReturnType(Conversion, From->getExprLoc()))
7854 return;
7855 ConvType = Conversion->getConversionType().getNonReferenceType();
7856 }
7857
7858 // If we don't allow any conversion of the result type, ignore conversion
7859 // functions that don't convert to exactly (possibly cv-qualified) T.
7860 if (!AllowResultConversion &&
7861 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7862 return;
7863
7864 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7865 // operator is only a candidate if its return type is the target type or
7866 // can be converted to the target type with a qualification conversion.
7867 //
7868 // FIXME: Include such functions in the candidate list and explain why we
7869 // can't select them.
7870 if (Conversion->isExplicit() &&
7871 !isAllowableExplicitConversion(*this, ConvType, ToType,
7872 AllowObjCConversionOnExplicit))
7873 return;
7874
7875 // Overload resolution is always an unevaluated context.
7878
7879 // Add this candidate
7880 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7881 Candidate.FoundDecl = FoundDecl;
7882 Candidate.Function = Conversion;
7884 Candidate.FinalConversion.setFromType(ConvType);
7885 Candidate.FinalConversion.setAllToTypes(ToType);
7886 Candidate.Viable = true;
7887 Candidate.ExplicitCallArguments = 1;
7888
7889 // Explicit functions are not actually candidates at all if we're not
7890 // allowing them in this context, but keep them around so we can point
7891 // to them in diagnostics.
7892 if (!AllowExplicit && Conversion->isExplicit()) {
7893 Candidate.Viable = false;
7894 Candidate.FailureKind = ovl_fail_explicit;
7895 return;
7896 }
7897
7898 // C++ [over.match.funcs]p4:
7899 // For conversion functions, the function is considered to be a member of
7900 // the class of the implicit implied object argument for the purpose of
7901 // defining the type of the implicit object parameter.
7902 //
7903 // Determine the implicit conversion sequence for the implicit
7904 // object parameter.
7905 QualType ObjectType = From->getType();
7906 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
7907 ObjectType = FromPtrType->getPointeeType();
7908 const auto *ConversionContext =
7909 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
7910
7911 // C++23 [over.best.ics.general]
7912 // However, if the target is [...]
7913 // - the object parameter of a user-defined conversion function
7914 // [...] user-defined conversion sequences are not considered.
7916 *this, CandidateSet.getLocation(), From->getType(),
7917 From->Classify(Context), Conversion, ConversionContext,
7918 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
7919 /*SuppressUserConversion*/ true);
7920
7921 if (Candidate.Conversions[0].isBad()) {
7922 Candidate.Viable = false;
7924 return;
7925 }
7926
7927 if (Conversion->getTrailingRequiresClause()) {
7928 ConstraintSatisfaction Satisfaction;
7929 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7930 !Satisfaction.IsSatisfied) {
7931 Candidate.Viable = false;
7933 return;
7934 }
7935 }
7936
7937 // We won't go through a user-defined type conversion function to convert a
7938 // derived to base as such conversions are given Conversion Rank. They only
7939 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7940 QualType FromCanon
7941 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7942 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7943 if (FromCanon == ToCanon ||
7944 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7945 Candidate.Viable = false;
7947 return;
7948 }
7949
7950 // To determine what the conversion from the result of calling the
7951 // conversion function to the type we're eventually trying to
7952 // convert to (ToType), we need to synthesize a call to the
7953 // conversion function and attempt copy initialization from it. This
7954 // makes sure that we get the right semantics with respect to
7955 // lvalues/rvalues and the type. Fortunately, we can allocate this
7956 // call on the stack and we don't need its arguments to be
7957 // well-formed.
7958 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7959 VK_LValue, From->getBeginLoc());
7961 Context.getPointerType(Conversion->getType()),
7962 CK_FunctionToPointerDecay, &ConversionRef,
7964
7965 QualType ConversionType = Conversion->getConversionType();
7966 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7967 Candidate.Viable = false;
7969 return;
7970 }
7971
7972 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7973
7974 // Note that it is safe to allocate CallExpr on the stack here because
7975 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7976 // allocator).
7977 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7978
7979 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7980 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7981 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7982
7984 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7985 /*SuppressUserConversions=*/true,
7986 /*InOverloadResolution=*/false,
7987 /*AllowObjCWritebackConversion=*/false);
7988
7989 switch (ICS.getKind()) {
7991 Candidate.FinalConversion = ICS.Standard;
7992
7993 // C++ [over.ics.user]p3:
7994 // If the user-defined conversion is specified by a specialization of a
7995 // conversion function template, the second standard conversion sequence
7996 // shall have exact match rank.
7997 if (Conversion->getPrimaryTemplate() &&
7999 Candidate.Viable = false;
8001 return;
8002 }
8003
8004 // C++0x [dcl.init.ref]p5:
8005 // In the second case, if the reference is an rvalue reference and
8006 // the second standard conversion sequence of the user-defined
8007 // conversion sequence includes an lvalue-to-rvalue conversion, the
8008 // program is ill-formed.
8009 if (ToType->isRValueReferenceType() &&
8011 Candidate.Viable = false;
8013 return;
8014 }
8015 break;
8016
8018 Candidate.Viable = false;
8020 return;
8021
8022 default:
8023 llvm_unreachable(
8024 "Can only end up with a standard conversion sequence or failure");
8025 }
8026
8027 if (EnableIfAttr *FailedAttr =
8028 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8029 Candidate.Viable = false;
8030 Candidate.FailureKind = ovl_fail_enable_if;
8031 Candidate.DeductionFailure.Data = FailedAttr;
8032 return;
8033 }
8034
8035 if (isNonViableMultiVersionOverload(Conversion)) {
8036 Candidate.Viable = false;
8038 }
8039}
8040
8042 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8043 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8044 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8045 bool AllowExplicit, bool AllowResultConversion) {
8046 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8047 "Only conversion function templates permitted here");
8048
8049 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8050 return;
8051
8052 // If the function template has a non-dependent explicit specification,
8053 // exclude it now if appropriate; we are not permitted to perform deduction
8054 // and substitution in this case.
8055 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8056 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8057 Candidate.FoundDecl = FoundDecl;
8058 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8059 Candidate.Viable = false;
8060 Candidate.FailureKind = ovl_fail_explicit;
8061 return;
8062 }
8063
8064 QualType ObjectType = From->getType();
8065 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8066
8067 TemplateDeductionInfo Info(CandidateSet.getLocation());
8070 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8071 Specialization, Info);
8073 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8074 Candidate.FoundDecl = FoundDecl;
8075 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8076 Candidate.Viable = false;
8078 Candidate.ExplicitCallArguments = 1;
8080 Info);
8081 return;
8082 }
8083
8084 // Add the conversion function template specialization produced by
8085 // template argument deduction as a candidate.
8086 assert(Specialization && "Missing function template specialization?");
8087 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8088 CandidateSet, AllowObjCConversionOnExplicit,
8089 AllowExplicit, AllowResultConversion);
8090}
8091
8093 DeclAccessPair FoundDecl,
8094 CXXRecordDecl *ActingContext,
8095 const FunctionProtoType *Proto,
8096 Expr *Object,
8097 ArrayRef<Expr *> Args,
8098 OverloadCandidateSet& CandidateSet) {
8099 if (!CandidateSet.isNewCandidate(Conversion))
8100 return;
8101
8102 // Overload resolution is always an unevaluated context.
8105
8106 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8107 Candidate.FoundDecl = FoundDecl;
8108 Candidate.Function = nullptr;
8109 Candidate.Surrogate = Conversion;
8110 Candidate.IsSurrogate = true;
8111 Candidate.Viable = true;
8112 Candidate.ExplicitCallArguments = Args.size();
8113
8114 // Determine the implicit conversion sequence for the implicit
8115 // object parameter.
8116 ImplicitConversionSequence ObjectInit;
8117 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8118 ObjectInit = TryCopyInitialization(*this, Object,
8119 Conversion->getParamDecl(0)->getType(),
8120 /*SuppressUserConversions=*/false,
8121 /*InOverloadResolution=*/true, false);
8122 } else {
8124 *this, CandidateSet.getLocation(), Object->getType(),
8125 Object->Classify(Context), Conversion, ActingContext);
8126 }
8127
8128 if (ObjectInit.isBad()) {
8129 Candidate.Viable = false;
8131 Candidate.Conversions[0] = ObjectInit;
8132 return;
8133 }
8134
8135 // The first conversion is actually a user-defined conversion whose
8136 // first conversion is ObjectInit's standard conversion (which is
8137 // effectively a reference binding). Record it as such.
8138 Candidate.Conversions[0].setUserDefined();
8139 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8140 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8141 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8142 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8143 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8144 Candidate.Conversions[0].UserDefined.After
8145 = Candidate.Conversions[0].UserDefined.Before;
8146 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8147
8148 // Find the
8149 unsigned NumParams = Proto->getNumParams();
8150
8151 // (C++ 13.3.2p2): A candidate function having fewer than m
8152 // parameters is viable only if it has an ellipsis in its parameter
8153 // list (8.3.5).
8154 if (Args.size() > NumParams && !Proto->isVariadic()) {
8155 Candidate.Viable = false;
8157 return;
8158 }
8159
8160 // Function types don't have any default arguments, so just check if
8161 // we have enough arguments.
8162 if (Args.size() < NumParams) {
8163 // Not enough arguments.
8164 Candidate.Viable = false;
8166 return;
8167 }
8168
8169 // Determine the implicit conversion sequences for each of the
8170 // arguments.
8171 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8172 if (ArgIdx < NumParams) {
8173 // (C++ 13.3.2p3): for F to be a viable function, there shall
8174 // exist for each argument an implicit conversion sequence
8175 // (13.3.3.1) that converts that argument to the corresponding
8176 // parameter of F.
8177 QualType ParamType = Proto->getParamType(ArgIdx);
8178 Candidate.Conversions[ArgIdx + 1]
8179 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8180 /*SuppressUserConversions=*/false,
8181 /*InOverloadResolution=*/false,
8182 /*AllowObjCWritebackConversion=*/
8183 getLangOpts().ObjCAutoRefCount);
8184 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8185 Candidate.Viable = false;
8187 return;
8188 }
8189 } else {
8190 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8191 // argument for which there is no corresponding parameter is
8192 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8193 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8194 }
8195 }
8196
8197 if (Conversion->getTrailingRequiresClause()) {
8198 ConstraintSatisfaction Satisfaction;
8199 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8200 /*ForOverloadResolution*/ true) ||
8201 !Satisfaction.IsSatisfied) {
8202 Candidate.Viable = false;
8204 return;
8205 }
8206 }
8207
8208 if (EnableIfAttr *FailedAttr =
8209 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8210 Candidate.Viable = false;
8211 Candidate.FailureKind = ovl_fail_enable_if;
8212 Candidate.DeductionFailure.Data = FailedAttr;
8213 return;
8214 }
8215}
8216
8218 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8219 OverloadCandidateSet &CandidateSet,
8220 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8221 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8222 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8223 ArrayRef<Expr *> FunctionArgs = Args;
8224
8225 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8226 FunctionDecl *FD =
8227 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8228
8229 // Don't consider rewritten functions if we're not rewriting.
8230 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8231 continue;
8232
8233 assert(!isa<CXXMethodDecl>(FD) &&
8234 "unqualified operator lookup found a member function");
8235
8236 if (FunTmpl) {
8237 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8238 FunctionArgs, CandidateSet);
8239 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8240 AddTemplateOverloadCandidate(
8241 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8242 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8243 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8244 } else {
8245 if (ExplicitTemplateArgs)
8246 continue;
8247 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8248 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8249 AddOverloadCandidate(
8250 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8251 false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8253 }
8254 }
8255}
8256
8258 SourceLocation OpLoc,
8259 ArrayRef<Expr *> Args,
8260 OverloadCandidateSet &CandidateSet,
8263
8264 // C++ [over.match.oper]p3:
8265 // For a unary operator @ with an operand of a type whose
8266 // cv-unqualified version is T1, and for a binary operator @ with
8267 // a left operand of a type whose cv-unqualified version is T1 and
8268 // a right operand of a type whose cv-unqualified version is T2,
8269 // three sets of candidate functions, designated member
8270 // candidates, non-member candidates and built-in candidates, are
8271 // constructed as follows:
8272 QualType T1 = Args[0]->getType();
8273
8274 // -- If T1 is a complete class type or a class currently being
8275 // defined, the set of member candidates is the result of the
8276 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8277 // the set of member candidates is empty.
8278 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8279 // Complete the type if it can be completed.
8280 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8281 return;
8282 // If the type is neither complete nor being defined, bail out now.
8283 if (!T1Rec->getDecl()->getDefinition())
8284 return;
8285
8286 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8287 LookupQualifiedName(Operators, T1Rec->getDecl());
8288 Operators.suppressAccessDiagnostics();
8289
8290 for (LookupResult::iterator Oper = Operators.begin(),
8291 OperEnd = Operators.end();
8292 Oper != OperEnd; ++Oper) {
8293 if (Oper->getAsFunction() &&
8295 !CandidateSet.getRewriteInfo().shouldAddReversed(
8296 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8297 continue;
8298 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8299 Args[0]->Classify(Context), Args.slice(1),
8300 CandidateSet, /*SuppressUserConversion=*/false, PO);
8301 }
8302 }
8303}
8304
8306 OverloadCandidateSet& CandidateSet,
8307 bool IsAssignmentOperator,
8308 unsigned NumContextualBoolArguments) {
8309 // Overload resolution is always an unevaluated context.
8312
8313 // Add this candidate
8314 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8315 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8316 Candidate.Function = nullptr;
8317 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8318
8319 // Determine the implicit conversion sequences for each of the
8320 // arguments.
8321 Candidate.Viable = true;
8322 Candidate.ExplicitCallArguments = Args.size();
8323 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8324 // C++ [over.match.oper]p4:
8325 // For the built-in assignment operators, conversions of the
8326 // left operand are restricted as follows:
8327 // -- no temporaries are introduced to hold the left operand, and
8328 // -- no user-defined conversions are applied to the left
8329 // operand to achieve a type match with the left-most
8330 // parameter of a built-in candidate.
8331 //
8332 // We block these conversions by turning off user-defined
8333 // conversions, since that is the only way that initialization of
8334 // a reference to a non-class type can occur from something that
8335 // is not of the same type.
8336 if (ArgIdx < NumContextualBoolArguments) {
8337 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8338 "Contextual conversion to bool requires bool type");
8339 Candidate.Conversions[ArgIdx]
8340 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8341 } else {
8342 Candidate.Conversions[ArgIdx]
8343 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8344 ArgIdx == 0 && IsAssignmentOperator,
8345 /*InOverloadResolution=*/false,
8346 /*AllowObjCWritebackConversion=*/
8347 getLangOpts().ObjCAutoRefCount);
8348 }
8349 if (Candidate.Conversions[ArgIdx].isBad()) {
8350 Candidate.Viable = false;
8352 break;
8353 }
8354 }
8355}
8356
8357namespace {
8358
8359/// BuiltinCandidateTypeSet - A set of types that will be used for the
8360/// candidate operator functions for built-in operators (C++
8361/// [over.built]). The types are separated into pointer types and
8362/// enumeration types.
8363class BuiltinCandidateTypeSet {
8364 /// TypeSet - A set of types.
8365 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8366
8367 /// PointerTypes - The set of pointer types that will be used in the
8368 /// built-in candidates.
8369 TypeSet PointerTypes;
8370
8371 /// MemberPointerTypes - The set of member pointer types that will be
8372 /// used in the built-in candidates.
8373 TypeSet MemberPointerTypes;
8374
8375 /// EnumerationTypes - The set of enumeration types that will be
8376 /// used in the built-in candidates.
8377 TypeSet EnumerationTypes;
8378
8379 /// The set of vector types that will be used in the built-in
8380 /// candidates.
8381 TypeSet VectorTypes;
8382
8383 /// The set of matrix types that will be used in the built-in
8384 /// candidates.
8385 TypeSet MatrixTypes;
8386
8387 /// The set of _BitInt types that will be used in the built-in candidates.
8388 TypeSet BitIntTypes;
8389
8390 /// A flag indicating non-record types are viable candidates
8391 bool HasNonRecordTypes;
8392
8393 /// A flag indicating whether either arithmetic or enumeration types
8394 /// were present in the candidate set.
8395 bool HasArithmeticOrEnumeralTypes;
8396
8397 /// A flag indicating whether the nullptr type was present in the
8398 /// candidate set.
8399 bool HasNullPtrType;
8400
8401 /// Sema - The semantic analysis instance where we are building the
8402 /// candidate type set.
8403 Sema &SemaRef;
8404
8405 /// Context - The AST context in which we will build the type sets.
8406 ASTContext &Context;
8407
8408 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8409 const Qualifiers &VisibleQuals);
8410 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8411
8412public:
8413 /// iterator - Iterates through the types that are part of the set.
8414 typedef TypeSet::iterator iterator;
8415
8416 BuiltinCandidateTypeSet(Sema &SemaRef)
8417 : HasNonRecordTypes(false),
8418 HasArithmeticOrEnumeralTypes(false),
8419 HasNullPtrType(false),
8420 SemaRef(SemaRef),
8421 Context(SemaRef.Context) { }
8422
8423 void AddTypesConvertedFrom(QualType Ty,
8425 bool AllowUserConversions,
8426 bool AllowExplicitConversions,
8427 const Qualifiers &VisibleTypeConversionsQuals);
8428
8429 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8430 llvm::iterator_range<iterator> member_pointer_types() {
8431 return MemberPointerTypes;
8432 }
8433 llvm::iterator_range<iterator> enumeration_types() {
8434 return EnumerationTypes;
8435 }
8436 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8437 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8438 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8439
8440 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8441 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8442 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8443 bool hasNullPtrType() const { return HasNullPtrType; }
8444};
8445
8446} // end anonymous namespace
8447
8448/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8449/// the set of pointer types along with any more-qualified variants of
8450/// that type. For example, if @p Ty is "int const *", this routine
8451/// will add "int const *", "int const volatile *", "int const
8452/// restrict *", and "int const volatile restrict *" to the set of
8453/// pointer types. Returns true if the add of @p Ty itself succeeded,
8454/// false otherwise.
8455///
8456/// FIXME: what to do about extended qualifiers?
8457bool
8458BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8459 const Qualifiers &VisibleQuals) {
8460
8461 // Insert this type.
8462 if (!PointerTypes.insert(Ty))
8463 return false;
8464
8465 QualType PointeeTy;
8466 const PointerType *PointerTy = Ty->getAs<PointerType>();
8467 bool buildObjCPtr = false;
8468 if (!PointerTy) {
8470 PointeeTy = PTy->getPointeeType();
8471 buildObjCPtr = true;
8472 } else {
8473 PointeeTy = PointerTy->getPointeeType();
8474 }
8475
8476 // Don't add qualified variants of arrays. For one, they're not allowed
8477 // (the qualifier would sink to the element type), and for another, the
8478 // only overload situation where it matters is subscript or pointer +- int,
8479 // and those shouldn't have qualifier variants anyway.
8480 if (PointeeTy->isArrayType())
8481 return true;
8482
8483 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8484 bool hasVolatile = VisibleQuals.hasVolatile();
8485 bool hasRestrict = VisibleQuals.hasRestrict();
8486
8487 // Iterate through all strict supersets of BaseCVR.
8488 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8489 if ((CVR | BaseCVR) != CVR) continue;
8490 // Skip over volatile if no volatile found anywhere in the types.
8491 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8492
8493 // Skip over restrict if no restrict found anywhere in the types, or if
8494 // the type cannot be restrict-qualified.
8495 if ((CVR & Qualifiers::Restrict) &&
8496 (!hasRestrict ||
8497 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8498 continue;
8499
8500 // Build qualified pointee type.
8501 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8502
8503 // Build qualified pointer type.
8504 QualType QPointerTy;
8505 if (!buildObjCPtr)
8506 QPointerTy = Context.getPointerType(QPointeeTy);
8507 else
8508 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8509
8510 // Insert qualified pointer type.
8511 PointerTypes.insert(QPointerTy);
8512 }
8513
8514 return true;
8515}
8516
8517/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8518/// to the set of pointer types along with any more-qualified variants of
8519/// that type. For example, if @p Ty is "int const *", this routine
8520/// will add "int const *", "int const volatile *", "int const
8521/// restrict *", and "int const volatile restrict *" to the set of
8522/// pointer types. Returns true if the add of @p Ty itself succeeded,
8523/// false otherwise.
8524///
8525/// FIXME: what to do about extended qualifiers?
8526bool
8527BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8528 QualType Ty) {
8529 // Insert this type.
8530 if (!MemberPointerTypes.insert(Ty))
8531 return false;
8532
8533 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8534 assert(PointerTy && "type was not a member pointer type!");
8535
8536 QualType PointeeTy = PointerTy->getPointeeType();
8537 // Don't add qualified variants of arrays. For one, they're not allowed
8538 // (the qualifier would sink to the element type), and for another, the
8539 // only overload situation where it matters is subscript or pointer +- int,
8540 // and those shouldn't have qualifier variants anyway.
8541 if (PointeeTy->isArrayType())
8542 return true;
8543 const Type *ClassTy = PointerTy->getClass();
8544
8545 // Iterate through all strict supersets of the pointee type's CVR
8546 // qualifiers.
8547 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8548 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8549 if ((CVR | BaseCVR) != CVR) continue;
8550
8551 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8552 MemberPointerTypes.insert(
8553 Context.getMemberPointerType(QPointeeTy, ClassTy));
8554 }
8555
8556 return true;
8557}
8558
8559/// AddTypesConvertedFrom - Add each of the types to which the type @p
8560/// Ty can be implicit converted to the given set of @p Types. We're
8561/// primarily interested in pointer types and enumeration types. We also
8562/// take member pointer types, for the conditional operator.
8563/// AllowUserConversions is true if we should look at the conversion
8564/// functions of a class type, and AllowExplicitConversions if we
8565/// should also include the explicit conversion functions of a class
8566/// type.
8567void
8568BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8569 SourceLocation Loc,
8570 bool AllowUserConversions,
8571 bool AllowExplicitConversions,
8572 const Qualifiers &VisibleQuals) {
8573 // Only deal with canonical types.
8574 Ty = Context.getCanonicalType(Ty);
8575
8576 // Look through reference types; they aren't part of the type of an
8577 // expression for the purposes of conversions.
8578 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8579 Ty = RefTy->getPointeeType();
8580
8581 // If we're dealing with an array type, decay to the pointer.
8582 if (Ty->isArrayType())
8583 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8584
8585 // Otherwise, we don't care about qualifiers on the type.
8586 Ty = Ty.getLocalUnqualifiedType();
8587
8588 // Flag if we ever add a non-record type.
8589 const RecordType *TyRec = Ty->getAs<RecordType>();
8590 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8591
8592 // Flag if we encounter an arithmetic type.
8593 HasArithmeticOrEnumeralTypes =
8594 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8595
8596 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8597 PointerTypes.insert(Ty);
8598 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8599 // Insert our type, and its more-qualified variants, into the set
8600 // of types.
8601 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8602 return;
8603 } else if (Ty->isMemberPointerType()) {
8604 // Member pointers are far easier, since the pointee can't be converted.
8605 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8606 return;
8607 } else if (Ty->isEnumeralType()) {
8608 HasArithmeticOrEnumeralTypes = true;
8609 EnumerationTypes.insert(Ty);
8610 } else if (Ty->isBitIntType()) {
8611 HasArithmeticOrEnumeralTypes = true;
8612 BitIntTypes.insert(Ty);
8613 } else if (Ty->isVectorType()) {
8614 // We treat vector types as arithmetic types in many contexts as an
8615 // extension.
8616 HasArithmeticOrEnumeralTypes = true;
8617 VectorTypes.insert(Ty);
8618 } else if (Ty->isMatrixType()) {
8619 // Similar to vector types, we treat vector types as arithmetic types in
8620 // many contexts as an extension.
8621 HasArithmeticOrEnumeralTypes = true;
8622 MatrixTypes.insert(Ty);
8623 } else if (Ty->isNullPtrType()) {
8624 HasNullPtrType = true;
8625 } else if (AllowUserConversions && TyRec) {
8626 // No conversion functions in incomplete types.
8627 if (!SemaRef.isCompleteType(Loc, Ty))
8628 return;
8629
8630 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8631 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8632 if (isa<UsingShadowDecl>(D))
8633 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8634
8635 // Skip conversion function templates; they don't tell us anything
8636 // about which builtin types we can convert to.
8637 if (isa<FunctionTemplateDecl>(D))
8638 continue;
8639
8640 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8641 if (AllowExplicitConversions || !Conv->isExplicit()) {
8642 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8643 VisibleQuals);
8644 }
8645 }
8646 }
8647}
8648/// Helper function for adjusting address spaces for the pointer or reference
8649/// operands of builtin operators depending on the argument.
8651 Expr *Arg) {
8653}
8654
8655/// Helper function for AddBuiltinOperatorCandidates() that adds
8656/// the volatile- and non-volatile-qualified assignment operators for the
8657/// given type to the candidate set.
8659 QualType T,
8660 ArrayRef<Expr *> Args,
8661 OverloadCandidateSet &CandidateSet) {
8662 QualType ParamTypes[2];
8663
8664 // T& operator=(T&, T)
8665 ParamTypes[0] = S.Context.getLValueReferenceType(
8667 ParamTypes[1] = T;
8668 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8669 /*IsAssignmentOperator=*/true);
8670
8672 // volatile T& operator=(volatile T&, T)
8673 ParamTypes[0] = S.Context.getLValueReferenceType(
8675 Args[0]));
8676 ParamTypes[1] = T;
8677 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8678 /*IsAssignmentOperator=*/true);
8679 }
8680}
8681
8682/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8683/// if any, found in visible type conversion functions found in ArgExpr's type.
8684static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8685 Qualifiers VRQuals;
8686 const RecordType *TyRec;
8687 if (const MemberPointerType *RHSMPType =
8688 ArgExpr->getType()->getAs<MemberPointerType>())
8689 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8690 else
8691 TyRec = ArgExpr->getType()->getAs<RecordType>();
8692 if (!TyRec) {
8693 // Just to be safe, assume the worst case.
8694 VRQuals.addVolatile();
8695 VRQuals.addRestrict();
8696 return VRQuals;
8697 }
8698
8699 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8700 if (!ClassDecl->hasDefinition())
8701 return VRQuals;
8702
8703 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8704 if (isa<UsingShadowDecl>(D))
8705 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8706 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8707 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8708 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8709 CanTy = ResTypeRef->getPointeeType();
8710 // Need to go down the pointer/mempointer chain and add qualifiers
8711 // as see them.
8712 bool done = false;
8713 while (!done) {
8714 if (CanTy.isRestrictQualified())
8715 VRQuals.addRestrict();
8716 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8717 CanTy = ResTypePtr->getPointeeType();
8718 else if (const MemberPointerType *ResTypeMPtr =
8719 CanTy->getAs<MemberPointerType>())
8720 CanTy = ResTypeMPtr->getPointeeType();
8721 else
8722 done = true;
8723 if (CanTy.isVolatileQualified())
8724 VRQuals.addVolatile();
8725 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8726 return VRQuals;
8727 }
8728 }
8729 }
8730 return VRQuals;
8731}
8732
8733// Note: We're currently only handling qualifiers that are meaningful for the
8734// LHS of compound assignment overloading.
8736 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8737 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8738 // _Atomic
8739 if (Available.hasAtomic()) {
8740 Available.removeAtomic();
8741 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8742 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8743 return;
8744 }
8745
8746 // volatile
8747 if (Available.hasVolatile()) {
8748 Available.removeVolatile();
8749 assert(!Applied.hasVolatile());
8750 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8751 Callback);
8752 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8753 return;
8754 }
8755
8756 Callback(Applied);
8757}
8758
8760 QualifiersAndAtomic Quals,
8761 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8763 Callback);
8764}
8765
8767 QualifiersAndAtomic Quals,
8768 Sema &S) {
8769 if (Quals.hasAtomic())
8771 if (Quals.hasVolatile())
8774}
8775
8776namespace {
8777
8778/// Helper class to manage the addition of builtin operator overload
8779/// candidates. It provides shared state and utility methods used throughout
8780/// the process, as well as a helper method to add each group of builtin
8781/// operator overloads from the standard to a candidate set.
8782class BuiltinOperatorOverloadBuilder {
8783 // Common instance state available to all overload candidate addition methods.
8784 Sema &S;
8785 ArrayRef<Expr *> Args;
8786 QualifiersAndAtomic VisibleTypeConversionsQuals;
8787 bool HasArithmeticOrEnumeralCandidateType;
8789 OverloadCandidateSet &CandidateSet;
8790
8791 static constexpr int ArithmeticTypesCap = 26;
8793
8794 // Define some indices used to iterate over the arithmetic types in
8795 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8796 // types are that preserved by promotion (C++ [over.built]p2).
8797 unsigned FirstIntegralType,
8798 LastIntegralType;
8799 unsigned FirstPromotedIntegralType,
8800 LastPromotedIntegralType;
8801 unsigned FirstPromotedArithmeticType,
8802 LastPromotedArithmeticType;
8803 unsigned NumArithmeticTypes;
8804
8805 void InitArithmeticTypes() {
8806 // Start of promoted types.
8807 FirstPromotedArithmeticType = 0;
8808 ArithmeticTypes.push_back(S.Context.FloatTy);
8809 ArithmeticTypes.push_back(S.Context.DoubleTy);
8810 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8812 ArithmeticTypes.push_back(S.Context.Float128Ty);
8814 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8815
8816 // Start of integral types.
8817 FirstIntegralType = ArithmeticTypes.size();
8818 FirstPromotedIntegralType = ArithmeticTypes.size();
8819 ArithmeticTypes.push_back(S.Context.IntTy);
8820 ArithmeticTypes.push_back(S.Context.LongTy);
8821 ArithmeticTypes.push_back(S.Context.LongLongTy);
8825 ArithmeticTypes.push_back(S.Context.Int128Ty);
8826 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8827 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8828 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8832 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8833
8834 /// We add candidates for the unique, unqualified _BitInt types present in
8835 /// the candidate type set. The candidate set already handled ensuring the
8836 /// type is unqualified and canonical, but because we're adding from N
8837 /// different sets, we need to do some extra work to unique things. Insert
8838 /// the candidates into a unique set, then move from that set into the list
8839 /// of arithmetic types.
8840 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8841 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8842 BuiltinCandidateTypeSet &Candidate) {
8843 for (QualType BitTy : Candidate.bitint_types())
8844 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8845 });
8846 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8847 LastPromotedIntegralType = ArithmeticTypes.size();
8848 LastPromotedArithmeticType = ArithmeticTypes.size();
8849 // End of promoted types.
8850
8851 ArithmeticTypes.push_back(S.Context.BoolTy);
8852 ArithmeticTypes.push_back(S.Context.CharTy);
8853 ArithmeticTypes.push_back(S.Context.WCharTy);
8854 if (S.Context.getLangOpts().Char8)
8855 ArithmeticTypes.push_back(S.Context.Char8Ty);
8856 ArithmeticTypes.push_back(S.Context.Char16Ty);
8857 ArithmeticTypes.push_back(S.Context.Char32Ty);
8858 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8859 ArithmeticTypes.push_back(S.Context.ShortTy);
8860 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8861 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8862 LastIntegralType = ArithmeticTypes.size();
8863 NumArithmeticTypes = ArithmeticTypes.size();
8864 // End of integral types.
8865 // FIXME: What about complex? What about half?
8866
8867 // We don't know for sure how many bit-precise candidates were involved, so
8868 // we subtract those from the total when testing whether we're under the
8869 // cap or not.
8870 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
8871 ArithmeticTypesCap &&
8872 "Enough inline storage for all arithmetic types.");
8873 }
8874
8875 /// Helper method to factor out the common pattern of adding overloads
8876 /// for '++' and '--' builtin operators.
8877 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8878 bool HasVolatile,
8879 bool HasRestrict) {
8880 QualType ParamTypes[2] = {
8881 S.Context.getLValueReferenceType(CandidateTy),
8882 S.Context.IntTy
8883 };
8884
8885 // Non-volatile version.
8886 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8887
8888 // Use a heuristic to reduce number of builtin candidates in the set:
8889 // add volatile version only if there are conversions to a volatile type.
8890 if (HasVolatile) {
8891 ParamTypes[0] =
8893 S.Context.getVolatileType(CandidateTy));
8894 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8895 }
8896
8897 // Add restrict version only if there are conversions to a restrict type
8898 // and our candidate type is a non-restrict-qualified pointer.
8899 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8900 !CandidateTy.isRestrictQualified()) {
8901 ParamTypes[0]
8904 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8905
8906 if (HasVolatile) {
8907 ParamTypes[0]
8909 S.Context.getCVRQualifiedType(CandidateTy,
8912 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8913 }
8914 }
8915
8916 }
8917
8918 /// Helper to add an overload candidate for a binary builtin with types \p L
8919 /// and \p R.
8920 void AddCandidate(QualType L, QualType R) {
8921 QualType LandR[2] = {L, R};
8922 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8923 }
8924
8925public:
8926 BuiltinOperatorOverloadBuilder(
8927 Sema &S, ArrayRef<Expr *> Args,
8928 QualifiersAndAtomic VisibleTypeConversionsQuals,
8929 bool HasArithmeticOrEnumeralCandidateType,
8931 OverloadCandidateSet &CandidateSet)
8932 : S(S), Args(Args),
8933 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8934 HasArithmeticOrEnumeralCandidateType(
8935 HasArithmeticOrEnumeralCandidateType),
8936 CandidateTypes(CandidateTypes),
8937 CandidateSet(CandidateSet) {
8938
8939 InitArithmeticTypes();
8940 }
8941
8942 // Increment is deprecated for bool since C++17.
8943 //
8944 // C++ [over.built]p3:
8945 //
8946 // For every pair (T, VQ), where T is an arithmetic type other
8947 // than bool, and VQ is either volatile or empty, there exist
8948 // candidate operator functions of the form
8949 //
8950 // VQ T& operator++(VQ T&);
8951 // T operator++(VQ T&, int);
8952 //
8953 // C++ [over.built]p4:
8954 //
8955 // For every pair (T, VQ), where T is an arithmetic type other
8956 // than bool, and VQ is either volatile or empty, there exist
8957 // candidate operator functions of the form
8958 //
8959 // VQ T& operator--(VQ T&);
8960 // T operator--(VQ T&, int);
8961 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8962 if (!HasArithmeticOrEnumeralCandidateType)
8963 return;
8964
8965 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8966 const auto TypeOfT = ArithmeticTypes[Arith];
8967 if (TypeOfT == S.Context.BoolTy) {
8968 if (Op == OO_MinusMinus)
8969 continue;
8970 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8971 continue;
8972 }
8973 addPlusPlusMinusMinusStyleOverloads(
8974 TypeOfT,
8975 VisibleTypeConversionsQuals.hasVolatile(),
8976 VisibleTypeConversionsQuals.hasRestrict());
8977 }
8978 }
8979
8980 // C++ [over.built]p5:
8981 //
8982 // For every pair (T, VQ), where T is a cv-qualified or
8983 // cv-unqualified object type, and VQ is either volatile or
8984 // empty, there exist candidate operator functions of the form
8985 //
8986 // T*VQ& operator++(T*VQ&);
8987 // T*VQ& operator--(T*VQ&);
8988 // T* operator++(T*VQ&, int);
8989 // T* operator--(T*VQ&, int);
8990 void addPlusPlusMinusMinusPointerOverloads() {
8991 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8992 // Skip pointer types that aren't pointers to object types.
8993 if (!PtrTy->getPointeeType()->isObjectType())
8994 continue;
8995
8996 addPlusPlusMinusMinusStyleOverloads(
8997 PtrTy,
8998 (!PtrTy.isVolatileQualified() &&
8999 VisibleTypeConversionsQuals.hasVolatile()),
9000 (!PtrTy.isRestrictQualified() &&
9001 VisibleTypeConversionsQuals.hasRestrict()));
9002 }
9003 }
9004
9005 // C++ [over.built]p6:
9006 // For every cv-qualified or cv-unqualified object type T, there
9007 // exist candidate operator functions of the form
9008 //
9009 // T& operator*(T*);
9010 //
9011 // C++ [over.built]p7:
9012 // For every function type T that does not have cv-qualifiers or a
9013 // ref-qualifier, there exist candidate operator functions of the form
9014 // T& operator*(T*);
9015 void addUnaryStarPointerOverloads() {
9016 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9017 QualType PointeeTy = ParamTy->getPointeeType();
9018 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9019 continue;
9020
9021 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9022 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9023 continue;
9024
9025 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9026 }
9027 }
9028
9029 // C++ [over.built]p9:
9030 // For every promoted arithmetic type T, there exist candidate
9031 // operator functions of the form
9032 //
9033 // T operator+(T);
9034 // T operator-(T);
9035 void addUnaryPlusOrMinusArithmeticOverloads() {
9036 if (!HasArithmeticOrEnumeralCandidateType)
9037 return;
9038
9039 for (unsigned Arith = FirstPromotedArithmeticType;
9040 Arith < LastPromotedArithmeticType; ++Arith) {
9041 QualType ArithTy = ArithmeticTypes[Arith];
9042 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9043 }
9044
9045 // Extension: We also add these operators for vector types.
9046 for (QualType VecTy : CandidateTypes[0].vector_types())
9047 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9048 }
9049
9050 // C++ [over.built]p8:
9051 // For every type T, there exist candidate operator functions of
9052 // the form
9053 //
9054 // T* operator+(T*);
9055 void addUnaryPlusPointerOverloads() {
9056 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9057 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9058 }
9059
9060 // C++ [over.built]p10:
9061 // For every promoted integral type T, there exist candidate
9062 // operator functions of the form
9063 //
9064 // T operator~(T);
9065 void addUnaryTildePromotedIntegralOverloads() {
9066 if (!HasArithmeticOrEnumeralCandidateType)
9067 return;
9068
9069 for (unsigned Int = FirstPromotedIntegralType;
9070 Int < LastPromotedIntegralType; ++Int) {
9071 QualType IntTy = ArithmeticTypes[Int];
9072 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9073 }
9074
9075 // Extension: We also add this operator for vector types.
9076 for (QualType VecTy : CandidateTypes[0].vector_types())
9077 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9078 }
9079
9080 // C++ [over.match.oper]p16:
9081 // For every pointer to member type T or type std::nullptr_t, there
9082 // exist candidate operator functions of the form
9083 //
9084 // bool operator==(T,T);
9085 // bool operator!=(T,T);
9086 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9087 /// Set of (canonical) types that we've already handled.
9089
9090 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9091 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9092 // Don't add the same builtin candidate twice.
9093 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9094 continue;
9095
9096 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9097 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9098 }
9099
9100 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9102 if (AddedTypes.insert(NullPtrTy).second) {
9103 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9104 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9105 }
9106 }
9107 }
9108 }
9109
9110 // C++ [over.built]p15:
9111 //
9112 // For every T, where T is an enumeration type or a pointer type,
9113 // there exist candidate operator functions of the form
9114 //
9115 // bool operator<(T, T);
9116 // bool operator>(T, T);
9117 // bool operator<=(T, T);
9118 // bool operator>=(T, T);
9119 // bool operator==(T, T);
9120 // bool operator!=(T, T);
9121 // R operator<=>(T, T)
9122 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9123 // C++ [over.match.oper]p3:
9124 // [...]the built-in candidates include all of the candidate operator
9125 // functions defined in 13.6 that, compared to the given operator, [...]
9126 // do not have the same parameter-type-list as any non-template non-member
9127 // candidate.
9128 //
9129 // Note that in practice, this only affects enumeration types because there
9130 // aren't any built-in candidates of record type, and a user-defined operator
9131 // must have an operand of record or enumeration type. Also, the only other
9132 // overloaded operator with enumeration arguments, operator=,
9133 // cannot be overloaded for enumeration types, so this is the only place
9134 // where we must suppress candidates like this.
9136 UserDefinedBinaryOperators;
9137
9138 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9139 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9140 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9141 CEnd = CandidateSet.end();
9142 C != CEnd; ++C) {
9143 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9144 continue;
9145
9146 if (C->Function->isFunctionTemplateSpecialization())
9147 continue;
9148
9149 // We interpret "same parameter-type-list" as applying to the
9150 // "synthesized candidate, with the order of the two parameters
9151 // reversed", not to the original function.
9152 bool Reversed = C->isReversed();
9153 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9154 ->getType()
9155 .getUnqualifiedType();
9156 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9157 ->getType()
9158 .getUnqualifiedType();
9159
9160 // Skip if either parameter isn't of enumeral type.
9161 if (!FirstParamType->isEnumeralType() ||
9162 !SecondParamType->isEnumeralType())
9163 continue;
9164
9165 // Add this operator to the set of known user-defined operators.
9166 UserDefinedBinaryOperators.insert(
9167 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9168 S.Context.getCanonicalType(SecondParamType)));
9169 }
9170 }
9171 }
9172
9173 /// Set of (canonical) types that we've already handled.
9175
9176 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9177 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9178 // Don't add the same builtin candidate twice.
9179 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9180 continue;
9181 if (IsSpaceship && PtrTy->isFunctionPointerType())
9182 continue;
9183
9184 QualType ParamTypes[2] = {PtrTy, PtrTy};
9185 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9186 }
9187 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9188 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9189
9190 // Don't add the same builtin candidate twice, or if a user defined
9191 // candidate exists.
9192 if (!AddedTypes.insert(CanonType).second ||
9193 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9194 CanonType)))
9195 continue;
9196 QualType ParamTypes[2] = {EnumTy, EnumTy};
9197 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9198 }
9199 }
9200 }
9201
9202 // C++ [over.built]p13:
9203 //
9204 // For every cv-qualified or cv-unqualified object type T
9205 // there exist candidate operator functions of the form
9206 //
9207 // T* operator+(T*, ptrdiff_t);
9208 // T& operator[](T*, ptrdiff_t); [BELOW]
9209 // T* operator-(T*, ptrdiff_t);
9210 // T* operator+(ptrdiff_t, T*);
9211 // T& operator[](ptrdiff_t, T*); [BELOW]
9212 //
9213 // C++ [over.built]p14:
9214 //
9215 // For every T, where T is a pointer to object type, there
9216 // exist candidate operator functions of the form
9217 //
9218 // ptrdiff_t operator-(T, T);
9219 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9220 /// Set of (canonical) types that we've already handled.
9222
9223 for (int Arg = 0; Arg < 2; ++Arg) {
9224 QualType AsymmetricParamTypes[2] = {
9227 };
9228 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9229 QualType PointeeTy = PtrTy->getPointeeType();
9230 if (!PointeeTy->isObjectType())
9231 continue;
9232
9233 AsymmetricParamTypes[Arg] = PtrTy;
9234 if (Arg == 0 || Op == OO_Plus) {
9235 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9236 // T* operator+(ptrdiff_t, T*);
9237 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9238 }
9239 if (Op == OO_Minus) {
9240 // ptrdiff_t operator-(T, T);
9241 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9242 continue;
9243
9244 QualType ParamTypes[2] = {PtrTy, PtrTy};
9245 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9246 }
9247 }
9248 }
9249 }
9250
9251 // C++ [over.built]p12:
9252 //
9253 // For every pair of promoted arithmetic types L and R, there
9254 // exist candidate operator functions of the form
9255 //
9256 // LR operator*(L, R);
9257 // LR operator/(L, R);
9258 // LR operator+(L, R);
9259 // LR operator-(L, R);
9260 // bool operator<(L, R);
9261 // bool operator>(L, R);
9262 // bool operator<=(L, R);
9263 // bool operator>=(L, R);
9264 // bool operator==(L, R);
9265 // bool operator!=(L, R);
9266 //
9267 // where LR is the result of the usual arithmetic conversions
9268 // between types L and R.
9269 //
9270 // C++ [over.built]p24:
9271 //
9272 // For every pair of promoted arithmetic types L and R, there exist
9273 // candidate operator functions of the form
9274 //
9275 // LR operator?(bool, L, R);
9276 //
9277 // where LR is the result of the usual arithmetic conversions
9278 // between types L and R.
9279 // Our candidates ignore the first parameter.
9280 void addGenericBinaryArithmeticOverloads() {
9281 if (!HasArithmeticOrEnumeralCandidateType)
9282 return;
9283
9284 for (unsigned Left = FirstPromotedArithmeticType;
9285 Left < LastPromotedArithmeticType; ++Left) {
9286 for (unsigned Right = FirstPromotedArithmeticType;
9287 Right < LastPromotedArithmeticType; ++Right) {
9288 QualType LandR[2] = { ArithmeticTypes[Left],
9289 ArithmeticTypes[Right] };
9290 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9291 }
9292 }
9293
9294 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9295 // conditional operator for vector types.
9296 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9297 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9298 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9299 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9300 }
9301 }
9302
9303 /// Add binary operator overloads for each candidate matrix type M1, M2:
9304 /// * (M1, M1) -> M1
9305 /// * (M1, M1.getElementType()) -> M1
9306 /// * (M2.getElementType(), M2) -> M2
9307 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9308 void addMatrixBinaryArithmeticOverloads() {
9309 if (!HasArithmeticOrEnumeralCandidateType)
9310 return;
9311
9312 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9313 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9314 AddCandidate(M1, M1);
9315 }
9316
9317 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9318 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9319 if (!CandidateTypes[0].containsMatrixType(M2))
9320 AddCandidate(M2, M2);
9321 }
9322 }
9323
9324 // C++2a [over.built]p14:
9325 //
9326 // For every integral type T there exists a candidate operator function
9327 // of the form
9328 //
9329 // std::strong_ordering operator<=>(T, T)
9330 //
9331 // C++2a [over.built]p15:
9332 //
9333 // For every pair of floating-point types L and R, there exists a candidate
9334 // operator function of the form
9335 //
9336 // std::partial_ordering operator<=>(L, R);
9337 //
9338 // FIXME: The current specification for integral types doesn't play nice with
9339 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9340 // comparisons. Under the current spec this can lead to ambiguity during
9341 // overload resolution. For example:
9342 //
9343 // enum A : int {a};
9344 // auto x = (a <=> (long)42);
9345 //
9346 // error: call is ambiguous for arguments 'A' and 'long'.
9347 // note: candidate operator<=>(int, int)
9348 // note: candidate operator<=>(long, long)
9349 //
9350 // To avoid this error, this function deviates from the specification and adds
9351 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9352 // arithmetic types (the same as the generic relational overloads).
9353 //
9354 // For now this function acts as a placeholder.
9355 void addThreeWayArithmeticOverloads() {
9356 addGenericBinaryArithmeticOverloads();
9357 }
9358
9359 // C++ [over.built]p17:
9360 //
9361 // For every pair of promoted integral types L and R, there
9362 // exist candidate operator functions of the form
9363 //
9364 // LR operator%(L, R);
9365 // LR operator&(L, R);
9366 // LR operator^(L, R);
9367 // LR operator|(L, R);
9368 // L operator<<(L, R);
9369 // L operator>>(L, R);
9370 //
9371 // where LR is the result of the usual arithmetic conversions
9372 // between types L and R.
9373 void addBinaryBitwiseArithmeticOverloads() {
9374 if (!HasArithmeticOrEnumeralCandidateType)
9375 return;
9376
9377 for (unsigned Left = FirstPromotedIntegralType;
9378 Left < LastPromotedIntegralType; ++Left) {
9379 for (unsigned Right = FirstPromotedIntegralType;
9380 Right < LastPromotedIntegralType; ++Right) {
9381 QualType LandR[2] = { ArithmeticTypes[Left],
9382 ArithmeticTypes[Right] };
9383 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9384 }
9385 }
9386 }
9387
9388 // C++ [over.built]p20:
9389 //
9390 // For every pair (T, VQ), where T is an enumeration or
9391 // pointer to member type and VQ is either volatile or
9392 // empty, there exist candidate operator functions of the form
9393 //
9394 // VQ T& operator=(VQ T&, T);
9395 void addAssignmentMemberPointerOrEnumeralOverloads() {
9396 /// Set of (canonical) types that we've already handled.
9398
9399 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9400 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9401 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9402 continue;
9403
9404 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9405 }
9406
9407 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9408 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9409 continue;
9410
9411 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9412 }
9413 }
9414 }
9415
9416 // C++ [over.built]p19:
9417 //
9418 // For every pair (T, VQ), where T is any type and VQ is either
9419 // volatile or empty, there exist candidate operator functions
9420 // of the form
9421 //
9422 // T*VQ& operator=(T*VQ&, T*);
9423 //
9424 // C++ [over.built]p21:
9425 //
9426 // For every pair (T, VQ), where T is a cv-qualified or
9427 // cv-unqualified object type and VQ is either volatile or
9428 // empty, there exist candidate operator functions of the form
9429 //
9430 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9431 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9432 void addAssignmentPointerOverloads(bool isEqualOp) {
9433 /// Set of (canonical) types that we've already handled.
9435
9436 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9437 // If this is operator=, keep track of the builtin candidates we added.
9438 if (isEqualOp)
9439 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9440 else if (!PtrTy->getPointeeType()->isObjectType())
9441 continue;
9442
9443 // non-volatile version
9444 QualType ParamTypes[2] = {
9446 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9447 };
9448 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9449 /*IsAssignmentOperator=*/ isEqualOp);
9450
9451 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9452 VisibleTypeConversionsQuals.hasVolatile();
9453 if (NeedVolatile) {
9454 // volatile version
9455 ParamTypes[0] =
9457 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9458 /*IsAssignmentOperator=*/isEqualOp);
9459 }
9460
9461 if (!PtrTy.isRestrictQualified() &&
9462 VisibleTypeConversionsQuals.hasRestrict()) {
9463 // restrict version
9464 ParamTypes[0] =
9466 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9467 /*IsAssignmentOperator=*/isEqualOp);
9468
9469 if (NeedVolatile) {
9470 // volatile restrict version
9471 ParamTypes[0] =
9474 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9475 /*IsAssignmentOperator=*/isEqualOp);
9476 }
9477 }
9478 }
9479
9480 if (isEqualOp) {
9481 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9482 // Make sure we don't add the same candidate twice.
9483 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9484 continue;
9485
9486 QualType ParamTypes[2] = {
9488 PtrTy,
9489 };
9490
9491 // non-volatile version
9492 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9493 /*IsAssignmentOperator=*/true);
9494
9495 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9496 VisibleTypeConversionsQuals.hasVolatile();
9497 if (NeedVolatile) {
9498 // volatile version
9499 ParamTypes[0] = S.Context.getLValueReferenceType(
9500 S.Context.getVolatileType(PtrTy));
9501 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9502 /*IsAssignmentOperator=*/true);
9503 }
9504
9505 if (!PtrTy.isRestrictQualified() &&
9506 VisibleTypeConversionsQuals.hasRestrict()) {
9507 // restrict version
9508 ParamTypes[0] = S.Context.getLValueReferenceType(
9509 S.Context.getRestrictType(PtrTy));
9510 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9511 /*IsAssignmentOperator=*/true);
9512
9513 if (NeedVolatile) {
9514 // volatile restrict version
9515 ParamTypes[0] =
9518 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9519 /*IsAssignmentOperator=*/true);
9520 }
9521 }
9522 }
9523 }
9524 }
9525
9526 // C++ [over.built]p18:
9527 //
9528 // For every triple (L, VQ, R), where L is an arithmetic type,
9529 // VQ is either volatile or empty, and R is a promoted
9530 // arithmetic type, there exist candidate operator functions of
9531 // the form
9532 //
9533 // VQ L& operator=(VQ L&, R);
9534 // VQ L& operator*=(VQ L&, R);
9535 // VQ L& operator/=(VQ L&, R);
9536 // VQ L& operator+=(VQ L&, R);
9537 // VQ L& operator-=(VQ L&, R);
9538 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9539 if (!HasArithmeticOrEnumeralCandidateType)
9540 return;
9541
9542 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9543 for (unsigned Right = FirstPromotedArithmeticType;
9544 Right < LastPromotedArithmeticType; ++Right) {
9545 QualType ParamTypes[2];
9546 ParamTypes[1] = ArithmeticTypes[Right];
9548 S, ArithmeticTypes[Left], Args[0]);
9549
9551 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9552 ParamTypes[0] =
9553 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9554 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9555 /*IsAssignmentOperator=*/isEqualOp);
9556 });
9557 }
9558 }
9559
9560 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9561 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9562 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9563 QualType ParamTypes[2];
9564 ParamTypes[1] = Vec2Ty;
9565 // Add this built-in operator as a candidate (VQ is empty).
9566 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9568 /*IsAssignmentOperator=*/isEqualOp);
9569
9570 // Add this built-in operator as a candidate (VQ is 'volatile').
9571 if (VisibleTypeConversionsQuals.hasVolatile()) {
9572 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9573 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9574 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9575 /*IsAssignmentOperator=*/isEqualOp);
9576 }
9577 }
9578 }
9579
9580 // C++ [over.built]p22:
9581 //
9582 // For every triple (L, VQ, R), where L is an integral type, VQ
9583 // is either volatile or empty, and R is a promoted integral
9584 // type, there exist candidate operator functions of the form
9585 //
9586 // VQ L& operator%=(VQ L&, R);
9587 // VQ L& operator<<=(VQ L&, R);
9588 // VQ L& operator>>=(VQ L&, R);
9589 // VQ L& operator&=(VQ L&, R);
9590 // VQ L& operator^=(VQ L&, R);
9591 // VQ L& operator|=(VQ L&, R);
9592 void addAssignmentIntegralOverloads() {
9593 if (!HasArithmeticOrEnumeralCandidateType)
9594 return;
9595
9596 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9597 for (unsigned Right = FirstPromotedIntegralType;
9598 Right < LastPromotedIntegralType; ++Right) {
9599 QualType ParamTypes[2];
9600 ParamTypes[1] = ArithmeticTypes[Right];
9602 S, ArithmeticTypes[Left], Args[0]);
9603
9605 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9606 ParamTypes[0] =
9607 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9608 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9609 });
9610 }
9611 }
9612 }
9613
9614 // C++ [over.operator]p23:
9615 //
9616 // There also exist candidate operator functions of the form
9617 //
9618 // bool operator!(bool);
9619 // bool operator&&(bool, bool);
9620 // bool operator||(bool, bool);
9621 void addExclaimOverload() {
9622 QualType ParamTy = S.Context.BoolTy;
9623 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9624 /*IsAssignmentOperator=*/false,
9625 /*NumContextualBoolArguments=*/1);
9626 }
9627 void addAmpAmpOrPipePipeOverload() {
9628 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9629 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9630 /*IsAssignmentOperator=*/false,
9631 /*NumContextualBoolArguments=*/2);
9632 }
9633
9634 // C++ [over.built]p13:
9635 //
9636 // For every cv-qualified or cv-unqualified object type T there
9637 // exist candidate operator functions of the form
9638 //
9639 // T* operator+(T*, ptrdiff_t); [ABOVE]
9640 // T& operator[](T*, ptrdiff_t);
9641 // T* operator-(T*, ptrdiff_t); [ABOVE]
9642 // T* operator+(ptrdiff_t, T*); [ABOVE]
9643 // T& operator[](ptrdiff_t, T*);
9644 void addSubscriptOverloads() {
9645 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9646 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9647 QualType PointeeType = PtrTy->getPointeeType();
9648 if (!PointeeType->isObjectType())
9649 continue;
9650
9651 // T& operator[](T*, ptrdiff_t)
9652 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9653 }
9654
9655 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9656 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9657 QualType PointeeType = PtrTy->getPointeeType();
9658 if (!PointeeType->isObjectType())
9659 continue;
9660
9661 // T& operator[](ptrdiff_t, T*)
9662 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9663 }
9664 }
9665
9666 // C++ [over.built]p11:
9667 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9668 // C1 is the same type as C2 or is a derived class of C2, T is an object
9669 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9670 // there exist candidate operator functions of the form
9671 //
9672 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9673 //
9674 // where CV12 is the union of CV1 and CV2.
9675 void addArrowStarOverloads() {
9676 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9677 QualType C1Ty = PtrTy;
9678 QualType C1;
9680 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9681 if (!isa<RecordType>(C1))
9682 continue;
9683 // heuristic to reduce number of builtin candidates in the set.
9684 // Add volatile/restrict version only if there are conversions to a
9685 // volatile/restrict type.
9686 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9687 continue;
9688 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9689 continue;
9690 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9691 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9692 QualType C2 = QualType(mptr->getClass(), 0);
9693 C2 = C2.getUnqualifiedType();
9694 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9695 break;
9696 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9697 // build CV12 T&
9698 QualType T = mptr->getPointeeType();
9699 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9700 T.isVolatileQualified())
9701 continue;
9702 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9703 T.isRestrictQualified())
9704 continue;
9705 T = Q1.apply(S.Context, T);
9706 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9707 }
9708 }
9709 }
9710
9711 // Note that we don't consider the first argument, since it has been
9712 // contextually converted to bool long ago. The candidates below are
9713 // therefore added as binary.
9714 //
9715 // C++ [over.built]p25:
9716 // For every type T, where T is a pointer, pointer-to-member, or scoped
9717 // enumeration type, there exist candidate operator functions of the form
9718 //
9719 // T operator?(bool, T, T);
9720 //
9721 void addConditionalOperatorOverloads() {
9722 /// Set of (canonical) types that we've already handled.
9724
9725 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9726 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9727 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9728 continue;
9729
9730 QualType ParamTypes[2] = {PtrTy, PtrTy};
9731 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9732 }
9733
9734 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9735 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9736 continue;
9737
9738 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9739 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9740 }
9741
9742 if (S.getLangOpts().CPlusPlus11) {
9743 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9744 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9745 continue;
9746
9747 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9748 continue;
9749
9750 QualType ParamTypes[2] = {EnumTy, EnumTy};
9751 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9752 }
9753 }
9754 }
9755 }
9756};
9757
9758} // end anonymous namespace
9759
9761 SourceLocation OpLoc,
9762 ArrayRef<Expr *> Args,
9763 OverloadCandidateSet &CandidateSet) {
9764 // Find all of the types that the arguments can convert to, but only
9765 // if the operator we're looking at has built-in operator candidates
9766 // that make use of these types. Also record whether we encounter non-record
9767 // candidate types or either arithmetic or enumeral candidate types.
9768 QualifiersAndAtomic VisibleTypeConversionsQuals;
9769 VisibleTypeConversionsQuals.addConst();
9770 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9771 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9772 if (Args[ArgIdx]->getType()->isAtomicType())
9773 VisibleTypeConversionsQuals.addAtomic();
9774 }
9775
9776 bool HasNonRecordCandidateType = false;
9777 bool HasArithmeticOrEnumeralCandidateType = false;
9779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9780 CandidateTypes.emplace_back(*this);
9781 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9782 OpLoc,
9783 true,
9784 (Op == OO_Exclaim ||
9785 Op == OO_AmpAmp ||
9786 Op == OO_PipePipe),
9787 VisibleTypeConversionsQuals);
9788 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9789 CandidateTypes[ArgIdx].hasNonRecordTypes();
9790 HasArithmeticOrEnumeralCandidateType =
9791 HasArithmeticOrEnumeralCandidateType ||
9792 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9793 }
9794
9795 // Exit early when no non-record types have been added to the candidate set
9796 // for any of the arguments to the operator.
9797 //
9798 // We can't exit early for !, ||, or &&, since there we have always have
9799 // 'bool' overloads.
9800 if (!HasNonRecordCandidateType &&
9801 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9802 return;
9803
9804 // Setup an object to manage the common state for building overloads.
9805 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9806 VisibleTypeConversionsQuals,
9807 HasArithmeticOrEnumeralCandidateType,
9808 CandidateTypes, CandidateSet);
9809
9810 // Dispatch over the operation to add in only those overloads which apply.
9811 switch (Op) {
9812 case OO_None:
9814 llvm_unreachable("Expected an overloaded operator");
9815
9816 case OO_New:
9817 case OO_Delete:
9818 case OO_Array_New:
9819 case OO_Array_Delete:
9820 case OO_Call:
9821 llvm_unreachable(
9822 "Special operators don't use AddBuiltinOperatorCandidates");
9823
9824 case OO_Comma:
9825 case OO_Arrow:
9826 case OO_Coawait:
9827 // C++ [over.match.oper]p3:
9828 // -- For the operator ',', the unary operator '&', the
9829 // operator '->', or the operator 'co_await', the
9830 // built-in candidates set is empty.
9831 break;
9832
9833 case OO_Plus: // '+' is either unary or binary
9834 if (Args.size() == 1)
9835 OpBuilder.addUnaryPlusPointerOverloads();
9836 [[fallthrough]];
9837
9838 case OO_Minus: // '-' is either unary or binary
9839 if (Args.size() == 1) {
9840 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9841 } else {
9842 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9843 OpBuilder.addGenericBinaryArithmeticOverloads();
9844 OpBuilder.addMatrixBinaryArithmeticOverloads();
9845 }
9846 break;
9847
9848 case OO_Star: // '*' is either unary or binary
9849 if (Args.size() == 1)
9850 OpBuilder.addUnaryStarPointerOverloads();
9851 else {
9852 OpBuilder.addGenericBinaryArithmeticOverloads();
9853 OpBuilder.addMatrixBinaryArithmeticOverloads();
9854 }
9855 break;
9856
9857 case OO_Slash:
9858 OpBuilder.addGenericBinaryArithmeticOverloads();
9859 break;
9860
9861 case OO_PlusPlus:
9862 case OO_MinusMinus:
9863 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9864 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9865 break;
9866
9867 case OO_EqualEqual:
9868 case OO_ExclaimEqual:
9869 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9870 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9871 OpBuilder.addGenericBinaryArithmeticOverloads();
9872 break;
9873
9874 case OO_Less:
9875 case OO_Greater:
9876 case OO_LessEqual:
9877 case OO_GreaterEqual:
9878 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9879 OpBuilder.addGenericBinaryArithmeticOverloads();
9880 break;
9881
9882 case OO_Spaceship:
9883 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9884 OpBuilder.addThreeWayArithmeticOverloads();
9885 break;
9886
9887 case OO_Percent:
9888 case OO_Caret:
9889 case OO_Pipe:
9890 case OO_LessLess:
9891 case OO_GreaterGreater:
9892 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9893 break;
9894
9895 case OO_Amp: // '&' is either unary or binary
9896 if (Args.size() == 1)
9897 // C++ [over.match.oper]p3:
9898 // -- For the operator ',', the unary operator '&', or the
9899 // operator '->', the built-in candidates set is empty.
9900 break;
9901
9902 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9903 break;
9904
9905 case OO_Tilde:
9906 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9907 break;
9908
9909 case OO_Equal:
9910 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9911 [[fallthrough]];
9912
9913 case OO_PlusEqual:
9914 case OO_MinusEqual:
9915 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9916 [[fallthrough]];
9917
9918 case OO_StarEqual:
9919 case OO_SlashEqual:
9920 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9921 break;
9922
9923 case OO_PercentEqual:
9924 case OO_LessLessEqual:
9925 case OO_GreaterGreaterEqual:
9926 case OO_AmpEqual:
9927 case OO_CaretEqual:
9928 case OO_PipeEqual:
9929 OpBuilder.addAssignmentIntegralOverloads();
9930 break;
9931
9932 case OO_Exclaim:
9933 OpBuilder.addExclaimOverload();
9934 break;
9935
9936 case OO_AmpAmp:
9937 case OO_PipePipe:
9938 OpBuilder.addAmpAmpOrPipePipeOverload();
9939 break;
9940
9941 case OO_Subscript:
9942 if (Args.size() == 2)
9943 OpBuilder.addSubscriptOverloads();
9944 break;
9945
9946 case OO_ArrowStar:
9947 OpBuilder.addArrowStarOverloads();
9948 break;
9949
9950 case OO_Conditional:
9951 OpBuilder.addConditionalOperatorOverloads();
9952 OpBuilder.addGenericBinaryArithmeticOverloads();
9953 break;
9954 }
9955}
9956
9957void
9959 SourceLocation Loc,
9960 ArrayRef<Expr *> Args,
9961 TemplateArgumentListInfo *ExplicitTemplateArgs,
9962 OverloadCandidateSet& CandidateSet,
9963 bool PartialOverloading) {
9964 ADLResult Fns;
9965
9966 // FIXME: This approach for uniquing ADL results (and removing
9967 // redundant candidates from the set) relies on pointer-equality,
9968 // which means we need to key off the canonical decl. However,
9969 // always going back to the canonical decl might not get us the
9970 // right set of default arguments. What default arguments are
9971 // we supposed to consider on ADL candidates, anyway?
9972
9973 // FIXME: Pass in the explicit template arguments?
9974 ArgumentDependentLookup(Name, Loc, Args, Fns);
9975
9976 // Erase all of the candidates we already knew about.
9977 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9978 CandEnd = CandidateSet.end();
9979 Cand != CandEnd; ++Cand)
9980 if (Cand->Function) {
9981 FunctionDecl *Fn = Cand->Function;
9982 Fns.erase(Fn);
9983 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
9984 Fns.erase(FunTmpl);
9985 }
9986
9987 // For each of the ADL candidates we found, add it to the overload
9988 // set.
9989 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9991
9992 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9993 if (ExplicitTemplateArgs)
9994 continue;
9995
9996 AddOverloadCandidate(
9997 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9998 PartialOverloading, /*AllowExplicit=*/true,
9999 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10000 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10001 AddOverloadCandidate(
10002 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10003 /*SuppressUserConversions=*/false, PartialOverloading,
10004 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10005 ADLCallKind::UsesADL, std::nullopt,
10007 }
10008 } else {
10009 auto *FTD = cast<FunctionTemplateDecl>(*I);
10010 AddTemplateOverloadCandidate(
10011 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10012 /*SuppressUserConversions=*/false, PartialOverloading,
10013 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10014 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10015 *this, Args, FTD->getTemplatedDecl())) {
10016 AddTemplateOverloadCandidate(
10017 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10018 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10019 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10021 }
10022 }
10023 }
10024}
10025
10026namespace {
10027enum class Comparison { Equal, Better, Worse };
10028}
10029
10030/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10031/// overload resolution.
10032///
10033/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10034/// Cand1's first N enable_if attributes have precisely the same conditions as
10035/// Cand2's first N enable_if attributes (where N = the number of enable_if
10036/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10037///
10038/// Note that you can have a pair of candidates such that Cand1's enable_if
10039/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10040/// worse than Cand1's.
10041static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10042 const FunctionDecl *Cand2) {
10043 // Common case: One (or both) decls don't have enable_if attrs.
10044 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10045 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10046 if (!Cand1Attr || !Cand2Attr) {
10047 if (Cand1Attr == Cand2Attr)
10048 return Comparison::Equal;
10049 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10050 }
10051
10052 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10053 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10054
10055 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10056 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10057 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10058 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10059
10060 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10061 // has fewer enable_if attributes than Cand2, and vice versa.
10062 if (!Cand1A)
10063 return Comparison::Worse;
10064 if (!Cand2A)
10065 return Comparison::Better;
10066
10067 Cand1ID.clear();
10068 Cand2ID.clear();
10069
10070 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10071 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10072 if (Cand1ID != Cand2ID)
10073 return Comparison::Worse;
10074 }
10075
10076 return Comparison::Equal;
10077}
10078
10079static Comparison
10081 const OverloadCandidate &Cand2) {
10082 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10083 !Cand2.Function->isMultiVersion())
10084 return Comparison::Equal;
10085
10086 // If both are invalid, they are equal. If one of them is invalid, the other
10087 // is better.
10088 if (Cand1.Function->isInvalidDecl()) {
10089 if (Cand2.Function->isInvalidDecl())
10090 return Comparison::Equal;
10091 return Comparison::Worse;
10092 }
10093 if (Cand2.Function->isInvalidDecl())
10094 return Comparison::Better;
10095
10096 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10097 // cpu_dispatch, else arbitrarily based on the identifiers.
10098 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10099 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10100 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10101 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10102
10103 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10104 return Comparison::Equal;
10105
10106 if (Cand1CPUDisp && !Cand2CPUDisp)
10107 return Comparison::Better;
10108 if (Cand2CPUDisp && !Cand1CPUDisp)
10109 return Comparison::Worse;
10110
10111 if (Cand1CPUSpec && Cand2CPUSpec) {
10112 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10113 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10114 ? Comparison::Better
10115 : Comparison::Worse;
10116
10117 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10118 FirstDiff = std::mismatch(
10119 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10120 Cand2CPUSpec->cpus_begin(),
10121 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10122 return LHS->getName() == RHS->getName();
10123 });
10124
10125 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10126 "Two different cpu-specific versions should not have the same "
10127 "identifier list, otherwise they'd be the same decl!");
10128 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10129 ? Comparison::Better
10130 : Comparison::Worse;
10131 }
10132 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10133}
10134
10135/// Compute the type of the implicit object parameter for the given function,
10136/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10137/// null QualType if there is a 'matches anything' implicit object parameter.
10138static std::optional<QualType>
10140 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10141 return std::nullopt;
10142
10143 auto *M = cast<CXXMethodDecl>(F);
10144 // Static member functions' object parameters match all types.
10145 if (M->isStatic())
10146 return QualType();
10147 return M->getFunctionObjectParameterReferenceType();
10148}
10149
10150// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10151// represent the same entity.
10152static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10153 const FunctionDecl *F2) {
10154 if (declaresSameEntity(F1, F2))
10155 return true;
10156 auto PT1 = F1->getPrimaryTemplate();
10157 auto PT2 = F2->getPrimaryTemplate();
10158 if (PT1 && PT2) {
10159 if (declaresSameEntity(PT1, PT2) ||
10160 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10161 PT2->getInstantiatedFromMemberTemplate()))
10162 return true;
10163 }
10164 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10165 // different functions with same params). Consider removing this (as no test
10166 // fail w/o it).
10167 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10168 if (First) {
10169 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10170 return *T;
10171 }
10172 assert(I < F->getNumParams());
10173 return F->getParamDecl(I++)->getType();
10174 };
10175
10176 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10177 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10178
10179 if (F1NumParams != F2NumParams)
10180 return false;
10181
10182 unsigned I1 = 0, I2 = 0;
10183 for (unsigned I = 0; I != F1NumParams; ++I) {
10184 QualType T1 = NextParam(F1, I1, I == 0);
10185 QualType T2 = NextParam(F2, I2, I == 0);
10186 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10187 if (!Context.hasSameUnqualifiedType(T1, T2))
10188 return false;
10189 }
10190 return true;
10191}
10192
10193/// We're allowed to use constraints partial ordering only if the candidates
10194/// have the same parameter types:
10195/// [over.match.best.general]p2.6
10196/// F1 and F2 are non-template functions with the same
10197/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10199 const OverloadCandidate &Cand1,
10200 const OverloadCandidate &Cand2) {
10201 if (!Cand1.Function || !Cand2.Function)
10202 return false;
10203
10204 FunctionDecl *Fn1 = Cand1.Function;
10205 FunctionDecl *Fn2 = Cand2.Function;
10206
10207 if (Fn1->isVariadic() != Fn2->isVariadic())
10208 return false;
10209
10211 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10212 return false;
10213
10214 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10215 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10216 if (Mem1 && Mem2) {
10217 // if they are member functions, both are direct members of the same class,
10218 // and
10219 if (Mem1->getParent() != Mem2->getParent())
10220 return false;
10221 // if both are non-static member functions, they have the same types for
10222 // their object parameters
10223 if (Mem1->isInstance() && Mem2->isInstance() &&
10225 Mem1->getFunctionObjectParameterReferenceType(),
10226 Mem1->getFunctionObjectParameterReferenceType()))
10227 return false;
10228 }
10229 return true;
10230}
10231
10232/// isBetterOverloadCandidate - Determines whether the first overload
10233/// candidate is a better candidate than the second (C++ 13.3.3p1).
10235 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10237 // Define viable functions to be better candidates than non-viable
10238 // functions.
10239 if (!Cand2.Viable)
10240 return Cand1.Viable;
10241 else if (!Cand1.Viable)
10242 return false;
10243
10244 // [CUDA] A function with 'never' preference is marked not viable, therefore
10245 // is never shown up here. The worst preference shown up here is 'wrong side',
10246 // e.g. an H function called by a HD function in device compilation. This is
10247 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10248 // function which is called only by an H function. A deferred diagnostic will
10249 // be triggered if it is emitted. However a wrong-sided function is still
10250 // a viable candidate here.
10251 //
10252 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10253 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10254 // can be emitted, Cand1 is not better than Cand2. This rule should have
10255 // precedence over other rules.
10256 //
10257 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10258 // other rules should be used to determine which is better. This is because
10259 // host/device based overloading resolution is mostly for determining
10260 // viability of a function. If two functions are both viable, other factors
10261 // should take precedence in preference, e.g. the standard-defined preferences
10262 // like argument conversion ranks or enable_if partial-ordering. The
10263 // preference for pass-object-size parameters is probably most similar to a
10264 // type-based-overloading decision and so should take priority.
10265 //
10266 // If other rules cannot determine which is better, CUDA preference will be
10267 // used again to determine which is better.
10268 //
10269 // TODO: Currently IdentifyPreference does not return correct values
10270 // for functions called in global variable initializers due to missing
10271 // correct context about device/host. Therefore we can only enforce this
10272 // rule when there is a caller. We should enforce this rule for functions
10273 // in global variable initializers once proper context is added.
10274 //
10275 // TODO: We can only enable the hostness based overloading resolution when
10276 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10277 // overloading resolution diagnostics.
10278 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10279 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10280 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10281 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10282 bool IsCand1ImplicitHD =
10284 bool IsCand2ImplicitHD =
10286 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10287 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10288 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10289 // The implicit HD function may be a function in a system header which
10290 // is forced by pragma. In device compilation, if we prefer HD candidates
10291 // over wrong-sided candidates, overloading resolution may change, which
10292 // may result in non-deferrable diagnostics. As a workaround, we let
10293 // implicit HD candidates take equal preference as wrong-sided candidates.
10294 // This will preserve the overloading resolution.
10295 // TODO: We still need special handling of implicit HD functions since
10296 // they may incur other diagnostics to be deferred. We should make all
10297 // host/device related diagnostics deferrable and remove special handling
10298 // of implicit HD functions.
10299 auto EmitThreshold =
10300 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10301 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10304 auto Cand1Emittable = P1 > EmitThreshold;
10305 auto Cand2Emittable = P2 > EmitThreshold;
10306 if (Cand1Emittable && !Cand2Emittable)
10307 return true;
10308 if (!Cand1Emittable && Cand2Emittable)
10309 return false;
10310 }
10311 }
10312
10313 // C++ [over.match.best]p1: (Changed in C++23)
10314 //
10315 // -- if F is a static member function, ICS1(F) is defined such
10316 // that ICS1(F) is neither better nor worse than ICS1(G) for
10317 // any function G, and, symmetrically, ICS1(G) is neither
10318 // better nor worse than ICS1(F).
10319 unsigned StartArg = 0;
10320 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10321 StartArg = 1;
10322
10323 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10324 // We don't allow incompatible pointer conversions in C++.
10325 if (!S.getLangOpts().CPlusPlus)
10326 return ICS.isStandard() &&
10327 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10328
10329 // The only ill-formed conversion we allow in C++ is the string literal to
10330 // char* conversion, which is only considered ill-formed after C++11.
10331 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10333 };
10334
10335 // Define functions that don't require ill-formed conversions for a given
10336 // argument to be better candidates than functions that do.
10337 unsigned NumArgs = Cand1.Conversions.size();
10338 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10339 bool HasBetterConversion = false;
10340 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10341 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10342 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10343 if (Cand1Bad != Cand2Bad) {
10344 if (Cand1Bad)
10345 return false;
10346 HasBetterConversion = true;
10347 }
10348 }
10349
10350 if (HasBetterConversion)
10351 return true;
10352
10353 // C++ [over.match.best]p1:
10354 // A viable function F1 is defined to be a better function than another
10355 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10356 // conversion sequence than ICSi(F2), and then...
10357 bool HasWorseConversion = false;
10358 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10360 Cand1.Conversions[ArgIdx],
10361 Cand2.Conversions[ArgIdx])) {
10363 // Cand1 has a better conversion sequence.
10364 HasBetterConversion = true;
10365 break;
10366
10368 if (Cand1.Function && Cand2.Function &&
10369 Cand1.isReversed() != Cand2.isReversed() &&
10370 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10371 // Work around large-scale breakage caused by considering reversed
10372 // forms of operator== in C++20:
10373 //
10374 // When comparing a function against a reversed function, if we have a
10375 // better conversion for one argument and a worse conversion for the
10376 // other, the implicit conversion sequences are treated as being equally
10377 // good.
10378 //
10379 // This prevents a comparison function from being considered ambiguous
10380 // with a reversed form that is written in the same way.
10381 //
10382 // We diagnose this as an extension from CreateOverloadedBinOp.
10383 HasWorseConversion = true;
10384 break;
10385 }
10386
10387 // Cand1 can't be better than Cand2.
10388 return false;
10389
10391 // Do nothing.
10392 break;
10393 }
10394 }
10395
10396 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10397 // ICSj(F2), or, if not that,
10398 if (HasBetterConversion && !HasWorseConversion)
10399 return true;
10400
10401 // -- the context is an initialization by user-defined conversion
10402 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10403 // from the return type of F1 to the destination type (i.e.,
10404 // the type of the entity being initialized) is a better
10405 // conversion sequence than the standard conversion sequence
10406 // from the return type of F2 to the destination type.
10408 Cand1.Function && Cand2.Function &&
10409 isa<CXXConversionDecl>(Cand1.Function) &&
10410 isa<CXXConversionDecl>(Cand2.Function)) {
10411 // First check whether we prefer one of the conversion functions over the
10412 // other. This only distinguishes the results in non-standard, extension
10413 // cases such as the conversion from a lambda closure type to a function
10414 // pointer or block.
10419 Cand1.FinalConversion,
10420 Cand2.FinalConversion);
10421
10424
10425 // FIXME: Compare kind of reference binding if conversion functions
10426 // convert to a reference type used in direct reference binding, per
10427 // C++14 [over.match.best]p1 section 2 bullet 3.
10428 }
10429
10430 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10431 // as combined with the resolution to CWG issue 243.
10432 //
10433 // When the context is initialization by constructor ([over.match.ctor] or
10434 // either phase of [over.match.list]), a constructor is preferred over
10435 // a conversion function.
10436 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10437 Cand1.Function && Cand2.Function &&
10438 isa<CXXConstructorDecl>(Cand1.Function) !=
10439 isa<CXXConstructorDecl>(Cand2.Function))
10440 return isa<CXXConstructorDecl>(Cand1.Function);
10441
10442 // -- F1 is a non-template function and F2 is a function template
10443 // specialization, or, if not that,
10444 bool Cand1IsSpecialization = Cand1.Function &&
10446 bool Cand2IsSpecialization = Cand2.Function &&
10448 if (Cand1IsSpecialization != Cand2IsSpecialization)
10449 return Cand2IsSpecialization;
10450
10451 // -- F1 and F2 are function template specializations, and the function
10452 // template for F1 is more specialized than the template for F2
10453 // according to the partial ordering rules described in 14.5.5.2, or,
10454 // if not that,
10455 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10456 const auto *Obj1Context =
10457 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10458 const auto *Obj2Context =
10459 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10460 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10463 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10464 : TPOC_Call,
10466 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10467 : QualType{},
10468 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10469 : QualType{},
10470 Cand1.isReversed() ^ Cand2.isReversed())) {
10471 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10472 }
10473 }
10474
10475 // -— F1 and F2 are non-template functions with the same
10476 // parameter-type-lists, and F1 is more constrained than F2 [...],
10477 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10478 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10480 Cand1.Function)
10481 return true;
10482
10483 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10484 // class B of D, and for all arguments the corresponding parameters of
10485 // F1 and F2 have the same type.
10486 // FIXME: Implement the "all parameters have the same type" check.
10487 bool Cand1IsInherited =
10488 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10489 bool Cand2IsInherited =
10490 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10491 if (Cand1IsInherited != Cand2IsInherited)
10492 return Cand2IsInherited;
10493 else if (Cand1IsInherited) {
10494 assert(Cand2IsInherited);
10495 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10496 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10497 if (Cand1Class->isDerivedFrom(Cand2Class))
10498 return true;
10499 if (Cand2Class->isDerivedFrom(Cand1Class))
10500 return false;
10501 // Inherited from sibling base classes: still ambiguous.
10502 }
10503
10504 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10505 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10506 // with reversed order of parameters and F1 is not
10507 //
10508 // We rank reversed + different operator as worse than just reversed, but
10509 // that comparison can never happen, because we only consider reversing for
10510 // the maximally-rewritten operator (== or <=>).
10511 if (Cand1.RewriteKind != Cand2.RewriteKind)
10512 return Cand1.RewriteKind < Cand2.RewriteKind;
10513
10514 // Check C++17 tie-breakers for deduction guides.
10515 {
10516 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10517 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10518 if (Guide1 && Guide2) {
10519 // -- F1 is generated from a deduction-guide and F2 is not
10520 if (Guide1->isImplicit() != Guide2->isImplicit())
10521 return Guide2->isImplicit();
10522
10523 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10524 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10525 return true;
10526 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10527 return false;
10528
10529 // --F1 is generated from a non-template constructor and F2 is generated
10530 // from a constructor template
10531 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10532 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10533 if (Constructor1 && Constructor2) {
10534 bool isC1Templated = Constructor1->getTemplatedKind() !=
10536 bool isC2Templated = Constructor2->getTemplatedKind() !=
10538 if (isC1Templated != isC2Templated)
10539 return isC2Templated;
10540 }
10541 }
10542 }
10543
10544 // Check for enable_if value-based overload resolution.
10545 if (Cand1.Function && Cand2.Function) {
10546 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10547 if (Cmp != Comparison::Equal)
10548 return Cmp == Comparison::Better;
10549 }
10550
10551 bool HasPS1 = Cand1.Function != nullptr &&
10553 bool HasPS2 = Cand2.Function != nullptr &&
10555 if (HasPS1 != HasPS2 && HasPS1)
10556 return true;
10557
10558 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10559 if (MV == Comparison::Better)
10560 return true;
10561 if (MV == Comparison::Worse)
10562 return false;
10563
10564 // If other rules cannot determine which is better, CUDA preference is used
10565 // to determine which is better.
10566 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10567 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10568 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10569 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10570 }
10571
10572 // General member function overloading is handled above, so this only handles
10573 // constructors with address spaces.
10574 // This only handles address spaces since C++ has no other
10575 // qualifier that can be used with constructors.
10576 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10577 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10578 if (CD1 && CD2) {
10579 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10580 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10581 if (AS1 != AS2) {
10583 return true;
10585 return false;
10586 }
10587 }
10588
10589 return false;
10590}
10591
10592/// Determine whether two declarations are "equivalent" for the purposes of
10593/// name lookup and overload resolution. This applies when the same internal/no
10594/// linkage entity is defined by two modules (probably by textually including
10595/// the same header). In such a case, we don't consider the declarations to
10596/// declare the same entity, but we also don't want lookups with both
10597/// declarations visible to be ambiguous in some cases (this happens when using
10598/// a modularized libstdc++).
10600 const NamedDecl *B) {
10601 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10602 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10603 if (!VA || !VB)
10604 return false;
10605
10606 // The declarations must be declaring the same name as an internal linkage
10607 // entity in different modules.
10608 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10609 VB->getDeclContext()->getRedeclContext()) ||
10610 getOwningModule(VA) == getOwningModule(VB) ||
10611 VA->isExternallyVisible() || VB->isExternallyVisible())
10612 return false;
10613
10614 // Check that the declarations appear to be equivalent.
10615 //
10616 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10617 // For constants and functions, we should check the initializer or body is
10618 // the same. For non-constant variables, we shouldn't allow it at all.
10619 if (Context.hasSameType(VA->getType(), VB->getType()))
10620 return true;
10621
10622 // Enum constants within unnamed enumerations will have different types, but
10623 // may still be similar enough to be interchangeable for our purposes.
10624 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10625 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10626 // Only handle anonymous enums. If the enumerations were named and
10627 // equivalent, they would have been merged to the same type.
10628 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10629 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10630 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10631 !Context.hasSameType(EnumA->getIntegerType(),
10632 EnumB->getIntegerType()))
10633 return false;
10634 // Allow this only if the value is the same for both enumerators.
10635 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10636 }
10637 }
10638
10639 // Nothing else is sufficiently similar.
10640 return false;
10641}
10642
10645 assert(D && "Unknown declaration");
10646 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10647
10648 Module *M = getOwningModule(D);
10649 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10650 << !M << (M ? M->getFullModuleName() : "");
10651
10652 for (auto *E : Equiv) {
10653 Module *M = getOwningModule(E);
10654 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10655 << !M << (M ? M->getFullModuleName() : "");
10656 }
10657}
10658
10660 return FailureKind == ovl_fail_bad_deduction &&
10661 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10663 static_cast<CNSInfo *>(DeductionFailure.Data)
10664 ->Satisfaction.ContainsErrors;
10665}
10666
10667/// Computes the best viable function (C++ 13.3.3)
10668/// within an overload candidate set.
10669///
10670/// \param Loc The location of the function name (or operator symbol) for
10671/// which overload resolution occurs.
10672///
10673/// \param Best If overload resolution was successful or found a deleted
10674/// function, \p Best points to the candidate function found.
10675///
10676/// \returns The result of overload resolution.
10679 iterator &Best) {
10681 std::transform(begin(), end(), std::back_inserter(Candidates),
10682 [](OverloadCandidate &Cand) { return &Cand; });
10683
10684 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10685 // are accepted by both clang and NVCC. However, during a particular
10686 // compilation mode only one call variant is viable. We need to
10687 // exclude non-viable overload candidates from consideration based
10688 // only on their host/device attributes. Specifically, if one
10689 // candidate call is WrongSide and the other is SameSide, we ignore
10690 // the WrongSide candidate.
10691 // We only need to remove wrong-sided candidates here if
10692 // -fgpu-exclude-wrong-side-overloads is off. When
10693 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10694 // uniformly in isBetterOverloadCandidate.
10695 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10696 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10697 bool ContainsSameSideCandidate =
10698 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10699 // Check viable function only.
10700 return Cand->Viable && Cand->Function &&
10701 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10703 });
10704 if (ContainsSameSideCandidate) {
10705 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10706 // Check viable function only to avoid unnecessary data copying/moving.
10707 return Cand->Viable && Cand->Function &&
10708 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10710 };
10711 llvm::erase_if(Candidates, IsWrongSideCandidate);
10712 }
10713 }
10714
10715 // Find the best viable function.
10716 Best = end();
10717 for (auto *Cand : Candidates) {
10718 Cand->Best = false;
10719 if (Cand->Viable) {
10720 if (Best == end() ||
10721 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10722 Best = Cand;
10723 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10724 // This candidate has constraint that we were unable to evaluate because
10725 // it referenced an expression that contained an error. Rather than fall
10726 // back onto a potentially unintended candidate (made worse by
10727 // subsuming constraints), treat this as 'no viable candidate'.
10728 Best = end();
10729 return OR_No_Viable_Function;
10730 }
10731 }
10732
10733 // If we didn't find any viable functions, abort.
10734 if (Best == end())
10735 return OR_No_Viable_Function;
10736
10738
10740 PendingBest.push_back(&*Best);
10741 Best->Best = true;
10742
10743 // Make sure that this function is better than every other viable
10744 // function. If not, we have an ambiguity.
10745 while (!PendingBest.empty()) {
10746 auto *Curr = PendingBest.pop_back_val();
10747 for (auto *Cand : Candidates) {
10748 if (Cand->Viable && !Cand->Best &&
10749 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10750 PendingBest.push_back(Cand);
10751 Cand->Best = true;
10752
10754 Curr->Function))
10755 EquivalentCands.push_back(Cand->Function);
10756 else
10757 Best = end();
10758 }
10759 }
10760 }
10761
10762 // If we found more than one best candidate, this is ambiguous.
10763 if (Best == end())
10764 return OR_Ambiguous;
10765
10766 // Best is the best viable function.
10767 if (Best->Function && Best->Function->isDeleted())
10768 return OR_Deleted;
10769
10770 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
10771 Kind == CSK_AddressOfOverloadSet && M &&
10772 M->isImplicitObjectMemberFunction()) {
10773 return OR_No_Viable_Function;
10774 }
10775
10776 if (!EquivalentCands.empty())
10778 EquivalentCands);
10779
10780 return OR_Success;
10781}
10782
10783namespace {
10784
10785enum OverloadCandidateKind {
10786 oc_function,
10787 oc_method,
10788 oc_reversed_binary_operator,
10789 oc_constructor,
10790 oc_implicit_default_constructor,
10791 oc_implicit_copy_constructor,
10792 oc_implicit_move_constructor,
10793 oc_implicit_copy_assignment,
10794 oc_implicit_move_assignment,
10795 oc_implicit_equality_comparison,
10796 oc_inherited_constructor
10797};
10798
10799enum OverloadCandidateSelect {
10800 ocs_non_template,
10801 ocs_template,
10802 ocs_described_template,
10803};
10804
10805static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10806ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10807 const FunctionDecl *Fn,
10809 std::string &Description) {
10810
10811 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10812 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10813 isTemplate = true;
10814 Description = S.getTemplateArgumentBindingsText(
10815 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10816 }
10817
10818 OverloadCandidateSelect Select = [&]() {
10819 if (!Description.empty())
10820 return ocs_described_template;
10821 return isTemplate ? ocs_template : ocs_non_template;
10822 }();
10823
10824 OverloadCandidateKind Kind = [&]() {
10825 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10826 return oc_implicit_equality_comparison;
10827
10828 if (CRK & CRK_Reversed)
10829 return oc_reversed_binary_operator;
10830
10831 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10832 if (!Ctor->isImplicit()) {
10833 if (isa<ConstructorUsingShadowDecl>(Found))
10834 return oc_inherited_constructor;
10835 else
10836 return oc_constructor;
10837 }
10838
10839 if (Ctor->isDefaultConstructor())
10840 return oc_implicit_default_constructor;
10841
10842 if (Ctor->isMoveConstructor())
10843 return oc_implicit_move_constructor;
10844
10845 assert(Ctor->isCopyConstructor() &&
10846 "unexpected sort of implicit constructor");
10847 return oc_implicit_copy_constructor;
10848 }
10849
10850 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10851 // This actually gets spelled 'candidate function' for now, but
10852 // it doesn't hurt to split it out.
10853 if (!Meth->isImplicit())
10854 return oc_method;
10855
10856 if (Meth->isMoveAssignmentOperator())
10857 return oc_implicit_move_assignment;
10858
10859 if (Meth->isCopyAssignmentOperator())
10860 return oc_implicit_copy_assignment;
10861
10862 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10863 return oc_method;
10864 }
10865
10866 return oc_function;
10867 }();
10868
10869 return std::make_pair(Kind, Select);
10870}
10871
10872void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10873 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10874 // set.
10875 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10876 S.Diag(FoundDecl->getLocation(),
10877 diag::note_ovl_candidate_inherited_constructor)
10878 << Shadow->getNominatedBaseClass();
10879}
10880
10881} // end anonymous namespace
10882
10884 const FunctionDecl *FD) {
10885 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10886 bool AlwaysTrue;
10887 if (EnableIf->getCond()->isValueDependent() ||
10888 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10889 return false;
10890 if (!AlwaysTrue)
10891 return false;
10892 }
10893 return true;
10894}
10895
10896/// Returns true if we can take the address of the function.
10897///
10898/// \param Complain - If true, we'll emit a diagnostic
10899/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10900/// we in overload resolution?
10901/// \param Loc - The location of the statement we're complaining about. Ignored
10902/// if we're not complaining, or if we're in overload resolution.
10904 bool Complain,
10905 bool InOverloadResolution,
10906 SourceLocation Loc) {
10907 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10908 if (Complain) {
10909 if (InOverloadResolution)
10910 S.Diag(FD->getBeginLoc(),
10911 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10912 else
10913 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10914 }
10915 return false;
10916 }
10917
10918 if (FD->getTrailingRequiresClause()) {
10919 ConstraintSatisfaction Satisfaction;
10920 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10921 return false;
10922 if (!Satisfaction.IsSatisfied) {
10923 if (Complain) {
10924 if (InOverloadResolution) {
10925 SmallString<128> TemplateArgString;
10926 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10927 TemplateArgString += " ";
10928 TemplateArgString += S.getTemplateArgumentBindingsText(
10929 FunTmpl->getTemplateParameters(),
10931 }
10932
10933 S.Diag(FD->getBeginLoc(),
10934 diag::note_ovl_candidate_unsatisfied_constraints)
10935 << TemplateArgString;
10936 } else
10937 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10938 << FD;
10939 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10940 }
10941 return false;
10942 }
10943 }
10944
10945 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10946 return P->hasAttr<PassObjectSizeAttr>();
10947 });
10948 if (I == FD->param_end())
10949 return true;
10950
10951 if (Complain) {
10952 // Add one to ParamNo because it's user-facing
10953 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10954 if (InOverloadResolution)
10955 S.Diag(FD->getLocation(),
10956 diag::note_ovl_candidate_has_pass_object_size_params)
10957 << ParamNo;
10958 else
10959 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10960 << FD << ParamNo;
10961 }
10962 return false;
10963}
10964
10966 const FunctionDecl *FD) {
10967 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10968 /*InOverloadResolution=*/true,
10969 /*Loc=*/SourceLocation());
10970}
10971
10973 bool Complain,
10974 SourceLocation Loc) {
10975 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10976 /*InOverloadResolution=*/false,
10977 Loc);
10978}
10979
10980// Don't print candidates other than the one that matches the calling
10981// convention of the call operator, since that is guaranteed to exist.
10983 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10984
10985 if (!ConvD)
10986 return false;
10987 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10988 if (!RD->isLambda())
10989 return false;
10990
10991 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10992 CallingConv CallOpCC =
10993 CallOp->getType()->castAs<FunctionType>()->getCallConv();
10994 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10995 CallingConv ConvToCC =
10996 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10997
10998 return ConvToCC != CallOpCC;
10999}
11000
11001// Notes the location of an overload candidate.
11003 OverloadCandidateRewriteKind RewriteKind,
11004 QualType DestType, bool TakingAddress) {
11005 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11006 return;
11007 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11008 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11009 return;
11010 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11011 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11012 return;
11014 return;
11015
11016 std::string FnDesc;
11017 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11018 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11019 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11020 << (unsigned)KSPair.first << (unsigned)KSPair.second
11021 << Fn << FnDesc;
11022
11023 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11024 Diag(Fn->getLocation(), PD);
11025 MaybeEmitInheritedConstructorNote(*this, Found);
11026}
11027
11028static void
11030 // Perhaps the ambiguity was caused by two atomic constraints that are
11031 // 'identical' but not equivalent:
11032 //
11033 // void foo() requires (sizeof(T) > 4) { } // #1
11034 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11035 //
11036 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11037 // #2 to subsume #1, but these constraint are not considered equivalent
11038 // according to the subsumption rules because they are not the same
11039 // source-level construct. This behavior is quite confusing and we should try
11040 // to help the user figure out what happened.
11041
11042 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11043 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11044 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11045 if (!I->Function)
11046 continue;
11048 if (auto *Template = I->Function->getPrimaryTemplate())
11049 Template->getAssociatedConstraints(AC);
11050 else
11051 I->Function->getAssociatedConstraints(AC);
11052 if (AC.empty())
11053 continue;
11054 if (FirstCand == nullptr) {
11055 FirstCand = I->Function;
11056 FirstAC = AC;
11057 } else if (SecondCand == nullptr) {
11058 SecondCand = I->Function;
11059 SecondAC = AC;
11060 } else {
11061 // We have more than one pair of constrained functions - this check is
11062 // expensive and we'd rather not try to diagnose it.
11063 return;
11064 }
11065 }
11066 if (!SecondCand)
11067 return;
11068 // The diagnostic can only happen if there are associated constraints on
11069 // both sides (there needs to be some identical atomic constraint).
11070 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11071 SecondCand, SecondAC))
11072 // Just show the user one diagnostic, they'll probably figure it out
11073 // from here.
11074 return;
11075}
11076
11077// Notes the location of all overload candidates designated through
11078// OverloadedExpr
11079void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11080 bool TakingAddress) {
11081 assert(OverloadedExpr->getType() == Context.OverloadTy);
11082
11083 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11084 OverloadExpr *OvlExpr = Ovl.Expression;
11085
11086 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11087 IEnd = OvlExpr->decls_end();
11088 I != IEnd; ++I) {
11089 if (FunctionTemplateDecl *FunTmpl =
11090 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11091 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11092 TakingAddress);
11093 } else if (FunctionDecl *Fun
11094 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11095 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11096 }
11097 }
11098}
11099
11100/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11101/// "lead" diagnostic; it will be given two arguments, the source and
11102/// target types of the conversion.
11104 Sema &S,
11105 SourceLocation CaretLoc,
11106 const PartialDiagnostic &PDiag) const {
11107 S.Diag(CaretLoc, PDiag)
11108 << Ambiguous.getFromType() << Ambiguous.getToType();
11109 unsigned CandsShown = 0;
11111 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11112 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11113 break;
11114 ++CandsShown;
11115 S.NoteOverloadCandidate(I->first, I->second);
11116 }
11117 S.Diags.overloadCandidatesShown(CandsShown);
11118 if (I != E)
11119 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11120}
11121
11123 unsigned I, bool TakingCandidateAddress) {
11124 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11125 assert(Conv.isBad());
11126 assert(Cand->Function && "for now, candidate must be a function");
11127 FunctionDecl *Fn = Cand->Function;
11128
11129 // There's a conversion slot for the object argument if this is a
11130 // non-constructor method. Note that 'I' corresponds the
11131 // conversion-slot index.
11132 bool isObjectArgument = false;
11133 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11134 if (I == 0)
11135 isObjectArgument = true;
11136 else
11137 I--;
11138 }
11139
11140 std::string FnDesc;
11141 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11142 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11143 FnDesc);
11144
11145 Expr *FromExpr = Conv.Bad.FromExpr;
11146 QualType FromTy = Conv.Bad.getFromType();
11147 QualType ToTy = Conv.Bad.getToType();
11148 SourceRange ToParamRange;
11149
11150 // FIXME: In presence of parameter packs we can't determine parameter range
11151 // reliably, as we don't have access to instantiation.
11152 bool HasParamPack =
11153 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11154 return Parm->isParameterPack();
11155 });
11156 if (!isObjectArgument && !HasParamPack)
11157 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11158
11159 if (FromTy == S.Context.OverloadTy) {
11160 assert(FromExpr && "overload set argument came from implicit argument?");
11161 Expr *E = FromExpr->IgnoreParens();
11162 if (isa<UnaryOperator>(E))
11163 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11164 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11165
11166 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11167 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11168 << ToParamRange << ToTy << Name << I + 1;
11169 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11170 return;
11171 }
11172
11173 // Do some hand-waving analysis to see if the non-viability is due
11174 // to a qualifier mismatch.
11175 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11176 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11177 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11178 CToTy = RT->getPointeeType();
11179 else {
11180 // TODO: detect and diagnose the full richness of const mismatches.
11181 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11182 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11183 CFromTy = FromPT->getPointeeType();
11184 CToTy = ToPT->getPointeeType();
11185 }
11186 }
11187
11188 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11189 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11190 Qualifiers FromQs = CFromTy.getQualifiers();
11191 Qualifiers ToQs = CToTy.getQualifiers();
11192
11193 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11194 if (isObjectArgument)
11195 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11196 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11197 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11198 else
11199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11200 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11201 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11202 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11203 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11204 return;
11205 }
11206
11207 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11209 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11210 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11211 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11212 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11213 return;
11214 }
11215
11216 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11218 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11219 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11220 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11221 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11222 return;
11223 }
11224
11225 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11226 assert(CVR && "expected qualifiers mismatch");
11227
11228 if (isObjectArgument) {
11229 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11230 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11231 << FromTy << (CVR - 1);
11232 } else {
11233 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11234 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11235 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11236 }
11237 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11238 return;
11239 }
11240
11243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11244 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11245 << (unsigned)isObjectArgument << I + 1
11247 << ToParamRange;
11248 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11249 return;
11250 }
11251
11252 // Special diagnostic for failure to convert an initializer list, since
11253 // telling the user that it has type void is not useful.
11254 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11255 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11256 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11257 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11260 ? 2
11261 : 0);
11262 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11263 return;
11264 }
11265
11266 // Diagnose references or pointers to incomplete types differently,
11267 // since it's far from impossible that the incompleteness triggered
11268 // the failure.
11269 QualType TempFromTy = FromTy.getNonReferenceType();
11270 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11271 TempFromTy = PTy->getPointeeType();
11272 if (TempFromTy->isIncompleteType()) {
11273 // Emit the generic diagnostic and, optionally, add the hints to it.
11274 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11275 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11276 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11277 << (unsigned)(Cand->Fix.Kind);
11278
11279 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11280 return;
11281 }
11282
11283 // Diagnose base -> derived pointer conversions.
11284 unsigned BaseToDerivedConversion = 0;
11285 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11286 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11287 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11288 FromPtrTy->getPointeeType()) &&
11289 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11290 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11291 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11292 FromPtrTy->getPointeeType()))
11293 BaseToDerivedConversion = 1;
11294 }
11295 } else if (const ObjCObjectPointerType *FromPtrTy
11296 = FromTy->getAs<ObjCObjectPointerType>()) {
11297 if (const ObjCObjectPointerType *ToPtrTy
11298 = ToTy->getAs<ObjCObjectPointerType>())
11299 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11300 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11301 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11302 FromPtrTy->getPointeeType()) &&
11303 FromIface->isSuperClassOf(ToIface))
11304 BaseToDerivedConversion = 2;
11305 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11306 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11307 !FromTy->isIncompleteType() &&
11308 !ToRefTy->getPointeeType()->isIncompleteType() &&
11309 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11310 BaseToDerivedConversion = 3;
11311 }
11312 }
11313
11314 if (BaseToDerivedConversion) {
11315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11316 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11317 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11318 << I + 1;
11319 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11320 return;
11321 }
11322
11323 if (isa<ObjCObjectPointerType>(CFromTy) &&
11324 isa<PointerType>(CToTy)) {
11325 Qualifiers FromQs = CFromTy.getQualifiers();
11326 Qualifiers ToQs = CToTy.getQualifiers();
11327 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11328 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11329 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11330 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11331 << I + 1;
11332 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11333 return;
11334 }
11335 }
11336
11337 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11338 return;
11339
11340 // Emit the generic diagnostic and, optionally, add the hints to it.
11341 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11342 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11343 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11344 << (unsigned)(Cand->Fix.Kind);
11345
11346 // Check that location of Fn is not in system header.
11347 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11348 // If we can fix the conversion, suggest the FixIts.
11349 for (const FixItHint &HI : Cand->Fix.Hints)
11350 FDiag << HI;
11351 }
11352
11353 S.Diag(Fn->getLocation(), FDiag);
11354
11355 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11356}
11357
11358/// Additional arity mismatch diagnosis specific to a function overload
11359/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11360/// over a candidate in any candidate set.
11362 unsigned NumArgs, bool IsAddressOf = false) {
11363 assert(Cand->Function && "Candidate is required to be a function.");
11364 FunctionDecl *Fn = Cand->Function;
11365 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11366 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11367
11368 // With invalid overloaded operators, it's possible that we think we
11369 // have an arity mismatch when in fact it looks like we have the
11370 // right number of arguments, because only overloaded operators have
11371 // the weird behavior of overloading member and non-member functions.
11372 // Just don't report anything.
11373 if (Fn->isInvalidDecl() &&
11374 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11375 return true;
11376
11377 if (NumArgs < MinParams) {
11378 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11380 Cand->DeductionFailure.getResult() ==
11382 } else {
11383 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11385 Cand->DeductionFailure.getResult() ==
11387 }
11388
11389 return false;
11390}
11391
11392/// General arity mismatch diagnosis over a candidate in a candidate set.
11394 unsigned NumFormalArgs,
11395 bool IsAddressOf = false) {
11396 assert(isa<FunctionDecl>(D) &&
11397 "The templated declaration should at least be a function"
11398 " when diagnosing bad template argument deduction due to too many"
11399 " or too few arguments");
11400
11401 FunctionDecl *Fn = cast<FunctionDecl>(D);
11402
11403 // TODO: treat calls to a missing default constructor as a special case
11404 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11405 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11406 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11407
11408 // at least / at most / exactly
11409 bool HasExplicitObjectParam =
11410 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11411
11412 unsigned ParamCount =
11413 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11414 unsigned mode, modeCount;
11415
11416 if (NumFormalArgs < MinParams) {
11417 if (MinParams != ParamCount || FnTy->isVariadic() ||
11418 FnTy->isTemplateVariadic())
11419 mode = 0; // "at least"
11420 else
11421 mode = 2; // "exactly"
11422 modeCount = MinParams;
11423 } else {
11424 if (MinParams != ParamCount)
11425 mode = 1; // "at most"
11426 else
11427 mode = 2; // "exactly"
11428 modeCount = ParamCount;
11429 }
11430
11431 std::string Description;
11432 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11433 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11434
11435 if (modeCount == 1 && !IsAddressOf &&
11436 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11438 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11439 << Description << mode
11440 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11441 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11442 else
11443 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11444 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11445 << Description << mode << modeCount << NumFormalArgs
11446 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11447
11448 MaybeEmitInheritedConstructorNote(S, Found);
11449}
11450
11451/// Arity mismatch diagnosis specific to a function overload candidate.
11453 unsigned NumFormalArgs) {
11454 assert(Cand->Function && "Candidate must be a function");
11455 FunctionDecl *Fn = Cand->Function;
11456 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
11457 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
11458 Cand->TookAddressOfOverload);
11459}
11460
11462 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11463 return TD;
11464 llvm_unreachable("Unsupported: Getting the described template declaration"
11465 " for bad deduction diagnosis");
11466}
11467
11468/// Diagnose a failed template-argument deduction.
11469static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11470 DeductionFailureInfo &DeductionFailure,
11471 unsigned NumArgs,
11472 bool TakingCandidateAddress) {
11473 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11474 NamedDecl *ParamD;
11475 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11476 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11477 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11478 switch (DeductionFailure.getResult()) {
11480 llvm_unreachable(
11481 "TemplateDeductionResult::Success while diagnosing bad deduction");
11483 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11484 "while diagnosing bad deduction");
11487 return;
11488
11490 assert(ParamD && "no parameter found for incomplete deduction result");
11491 S.Diag(Templated->getLocation(),
11492 diag::note_ovl_candidate_incomplete_deduction)
11493 << ParamD->getDeclName();
11494 MaybeEmitInheritedConstructorNote(S, Found);
11495 return;
11496 }
11497
11499 assert(ParamD && "no parameter found for incomplete deduction result");
11500 S.Diag(Templated->getLocation(),
11501 diag::note_ovl_candidate_incomplete_deduction_pack)
11502 << ParamD->getDeclName()
11503 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11504 << *DeductionFailure.getFirstArg();
11505 MaybeEmitInheritedConstructorNote(S, Found);
11506 return;
11507 }
11508
11510 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11511 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11512
11513 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11514
11515 // Param will have been canonicalized, but it should just be a
11516 // qualified version of ParamD, so move the qualifiers to that.
11518 Qs.strip(Param);
11519 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11520 assert(S.Context.hasSameType(Param, NonCanonParam));
11521
11522 // Arg has also been canonicalized, but there's nothing we can do
11523 // about that. It also doesn't matter as much, because it won't
11524 // have any template parameters in it (because deduction isn't
11525 // done on dependent types).
11526 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11527
11528 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11529 << ParamD->getDeclName() << Arg << NonCanonParam;
11530 MaybeEmitInheritedConstructorNote(S, Found);
11531 return;
11532 }
11533
11535 assert(ParamD && "no parameter found for inconsistent deduction result");
11536 int which = 0;
11537 if (isa<TemplateTypeParmDecl>(ParamD))
11538 which = 0;
11539 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11540 // Deduction might have failed because we deduced arguments of two
11541 // different types for a non-type template parameter.
11542 // FIXME: Use a different TDK value for this.
11543 QualType T1 =
11544 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11545 QualType T2 =
11546 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11547 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11548 S.Diag(Templated->getLocation(),
11549 diag::note_ovl_candidate_inconsistent_deduction_types)
11550 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11551 << *DeductionFailure.getSecondArg() << T2;
11552 MaybeEmitInheritedConstructorNote(S, Found);
11553 return;
11554 }
11555
11556 which = 1;
11557 } else {
11558 which = 2;
11559 }
11560
11561 // Tweak the diagnostic if the problem is that we deduced packs of
11562 // different arities. We'll print the actual packs anyway in case that
11563 // includes additional useful information.
11564 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11565 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11566 DeductionFailure.getFirstArg()->pack_size() !=
11567 DeductionFailure.getSecondArg()->pack_size()) {
11568 which = 3;
11569 }
11570
11571 S.Diag(Templated->getLocation(),
11572 diag::note_ovl_candidate_inconsistent_deduction)
11573 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11574 << *DeductionFailure.getSecondArg();
11575 MaybeEmitInheritedConstructorNote(S, Found);
11576 return;
11577 }
11578
11580 assert(ParamD && "no parameter found for invalid explicit arguments");
11581 if (ParamD->getDeclName())
11582 S.Diag(Templated->getLocation(),
11583 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11584 << ParamD->getDeclName();
11585 else {
11586 int index = 0;
11587 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11588 index = TTP->getIndex();
11589 else if (NonTypeTemplateParmDecl *NTTP
11590 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11591 index = NTTP->getIndex();
11592 else
11593 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11594 S.Diag(Templated->getLocation(),
11595 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11596 << (index + 1);
11597 }
11598 MaybeEmitInheritedConstructorNote(S, Found);
11599 return;
11600
11602 // Format the template argument list into the argument string.
11603 SmallString<128> TemplateArgString;
11604 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11605 TemplateArgString = " ";
11606 TemplateArgString += S.getTemplateArgumentBindingsText(
11607 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11608 if (TemplateArgString.size() == 1)
11609 TemplateArgString.clear();
11610 S.Diag(Templated->getLocation(),
11611 diag::note_ovl_candidate_unsatisfied_constraints)
11612 << TemplateArgString;
11613
11615 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11616 return;
11617 }
11620 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11621 return;
11622
11624 S.Diag(Templated->getLocation(),
11625 diag::note_ovl_candidate_instantiation_depth);
11626 MaybeEmitInheritedConstructorNote(S, Found);
11627 return;
11628
11630 // Format the template argument list into the argument string.
11631 SmallString<128> TemplateArgString;
11632 if (TemplateArgumentList *Args =
11633 DeductionFailure.getTemplateArgumentList()) {
11634 TemplateArgString = " ";
11635 TemplateArgString += S.getTemplateArgumentBindingsText(
11636 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11637 if (TemplateArgString.size() == 1)
11638 TemplateArgString.clear();
11639 }
11640
11641 // If this candidate was disabled by enable_if, say so.
11642 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11643 if (PDiag && PDiag->second.getDiagID() ==
11644 diag::err_typename_nested_not_found_enable_if) {
11645 // FIXME: Use the source range of the condition, and the fully-qualified
11646 // name of the enable_if template. These are both present in PDiag.
11647 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11648 << "'enable_if'" << TemplateArgString;
11649 return;
11650 }
11651
11652 // We found a specific requirement that disabled the enable_if.
11653 if (PDiag && PDiag->second.getDiagID() ==
11654 diag::err_typename_nested_not_found_requirement) {
11655 S.Diag(Templated->getLocation(),
11656 diag::note_ovl_candidate_disabled_by_requirement)
11657 << PDiag->second.getStringArg(0) << TemplateArgString;
11658 return;
11659 }
11660
11661 // Format the SFINAE diagnostic into the argument string.
11662 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11663 // formatted message in another diagnostic.
11664 SmallString<128> SFINAEArgString;
11665 SourceRange R;
11666 if (PDiag) {
11667 SFINAEArgString = ": ";
11668 R = SourceRange(PDiag->first, PDiag->first);
11669 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11670 }
11671
11672 S.Diag(Templated->getLocation(),
11673 diag::note_ovl_candidate_substitution_failure)
11674 << TemplateArgString << SFINAEArgString << R;
11675 MaybeEmitInheritedConstructorNote(S, Found);
11676 return;
11677 }
11678
11681 // Format the template argument list into the argument string.
11682 SmallString<128> TemplateArgString;
11683 if (TemplateArgumentList *Args =
11684 DeductionFailure.getTemplateArgumentList()) {
11685 TemplateArgString = " ";
11686 TemplateArgString += S.getTemplateArgumentBindingsText(
11687 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11688 if (TemplateArgString.size() == 1)
11689 TemplateArgString.clear();
11690 }
11691
11692 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11693 << (*DeductionFailure.getCallArgIndex() + 1)
11694 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11695 << TemplateArgString
11696 << (DeductionFailure.getResult() ==
11698 break;
11699 }
11700
11702 // FIXME: Provide a source location to indicate what we couldn't match.
11703 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11704 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11705 if (FirstTA.getKind() == TemplateArgument::Template &&
11706 SecondTA.getKind() == TemplateArgument::Template) {
11707 TemplateName FirstTN = FirstTA.getAsTemplate();
11708 TemplateName SecondTN = SecondTA.getAsTemplate();
11709 if (FirstTN.getKind() == TemplateName::Template &&
11710 SecondTN.getKind() == TemplateName::Template) {
11711 if (FirstTN.getAsTemplateDecl()->getName() ==
11712 SecondTN.getAsTemplateDecl()->getName()) {
11713 // FIXME: This fixes a bad diagnostic where both templates are named
11714 // the same. This particular case is a bit difficult since:
11715 // 1) It is passed as a string to the diagnostic printer.
11716 // 2) The diagnostic printer only attempts to find a better
11717 // name for types, not decls.
11718 // Ideally, this should folded into the diagnostic printer.
11719 S.Diag(Templated->getLocation(),
11720 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11721 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11722 return;
11723 }
11724 }
11725 }
11726
11727 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11728 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11729 return;
11730
11731 // FIXME: For generic lambda parameters, check if the function is a lambda
11732 // call operator, and if so, emit a prettier and more informative
11733 // diagnostic that mentions 'auto' and lambda in addition to
11734 // (or instead of?) the canonical template type parameters.
11735 S.Diag(Templated->getLocation(),
11736 diag::note_ovl_candidate_non_deduced_mismatch)
11737 << FirstTA << SecondTA;
11738 return;
11739 }
11740 // TODO: diagnose these individually, then kill off
11741 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11743 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11744 MaybeEmitInheritedConstructorNote(S, Found);
11745 return;
11747 S.Diag(Templated->getLocation(),
11748 diag::note_cuda_ovl_candidate_target_mismatch);
11749 return;
11750 }
11751}
11752
11753/// Diagnose a failed template-argument deduction, for function calls.
11755 unsigned NumArgs,
11756 bool TakingCandidateAddress) {
11757 assert(Cand->Function && "Candidate must be a function");
11758 FunctionDecl *Fn = Cand->Function;
11762 if (CheckArityMismatch(S, Cand, NumArgs))
11763 return;
11764 }
11765 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
11766 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11767}
11768
11769/// CUDA: diagnose an invalid call across targets.
11771 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11772 assert(Cand->Function && "Candidate must be a Function.");
11773 FunctionDecl *Callee = Cand->Function;
11774
11775 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11776 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11777
11778 std::string FnDesc;
11779 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11780 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11781 Cand->getRewriteKind(), FnDesc);
11782
11783 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11784 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11785 << FnDesc /* Ignored */
11786 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11787
11788 // This could be an implicit constructor for which we could not infer the
11789 // target due to a collsion. Diagnose that case.
11790 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11791 if (Meth != nullptr && Meth->isImplicit()) {
11792 CXXRecordDecl *ParentClass = Meth->getParent();
11794
11795 switch (FnKindPair.first) {
11796 default:
11797 return;
11798 case oc_implicit_default_constructor:
11800 break;
11801 case oc_implicit_copy_constructor:
11803 break;
11804 case oc_implicit_move_constructor:
11806 break;
11807 case oc_implicit_copy_assignment:
11809 break;
11810 case oc_implicit_move_assignment:
11812 break;
11813 };
11814
11815 bool ConstRHS = false;
11816 if (Meth->getNumParams()) {
11817 if (const ReferenceType *RT =
11818 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11819 ConstRHS = RT->getPointeeType().isConstQualified();
11820 }
11821 }
11822
11823 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11824 /* ConstRHS */ ConstRHS,
11825 /* Diagnose */ true);
11826 }
11827}
11828
11830 assert(Cand->Function && "Candidate must be a function");
11831 FunctionDecl *Callee = Cand->Function;
11832 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11833
11834 S.Diag(Callee->getLocation(),
11835 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11836 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11837}
11838
11840 assert(Cand->Function && "Candidate must be a function");
11841 FunctionDecl *Fn = Cand->Function;
11843 assert(ES.isExplicit() && "not an explicit candidate");
11844
11845 unsigned Kind;
11846 switch (Fn->getDeclKind()) {
11847 case Decl::Kind::CXXConstructor:
11848 Kind = 0;
11849 break;
11850 case Decl::Kind::CXXConversion:
11851 Kind = 1;
11852 break;
11853 case Decl::Kind::CXXDeductionGuide:
11854 Kind = Fn->isImplicit() ? 0 : 2;
11855 break;
11856 default:
11857 llvm_unreachable("invalid Decl");
11858 }
11859
11860 // Note the location of the first (in-class) declaration; a redeclaration
11861 // (particularly an out-of-class definition) will typically lack the
11862 // 'explicit' specifier.
11863 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11864 FunctionDecl *First = Fn->getFirstDecl();
11865 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11866 First = Pattern->getFirstDecl();
11867
11868 S.Diag(First->getLocation(),
11869 diag::note_ovl_candidate_explicit)
11870 << Kind << (ES.getExpr() ? 1 : 0)
11871 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11872}
11873
11875 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
11876 if (!DG)
11877 return;
11878 TemplateDecl *OriginTemplate =
11880 // We want to always print synthesized deduction guides for type aliases.
11881 // They would retain the explicit bit of the corresponding constructor.
11882 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
11883 return;
11884 std::string FunctionProto;
11885 llvm::raw_string_ostream OS(FunctionProto);
11886 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
11887 if (!Template) {
11888 // This also could be an instantiation. Find out the primary template.
11889 FunctionDecl *Pattern =
11890 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
11891 if (!Pattern) {
11892 // The implicit deduction guide is built on an explicit non-template
11893 // deduction guide. Currently, this might be the case only for type
11894 // aliases.
11895 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
11896 // gets merged.
11897 assert(OriginTemplate->isTypeAlias() &&
11898 "Non-template implicit deduction guides are only possible for "
11899 "type aliases");
11900 DG->print(OS);
11901 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
11902 << FunctionProto;
11903 return;
11904 }
11905 Template = Pattern->getDescribedFunctionTemplate();
11906 assert(Template && "Cannot find the associated function template of "
11907 "CXXDeductionGuideDecl?");
11908 }
11909 Template->print(OS);
11910 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
11911 << FunctionProto;
11912}
11913
11914/// Generates a 'note' diagnostic for an overload candidate. We've
11915/// already generated a primary error at the call site.
11916///
11917/// It really does need to be a single diagnostic with its caret
11918/// pointed at the candidate declaration. Yes, this creates some
11919/// major challenges of technical writing. Yes, this makes pointing
11920/// out problems with specific arguments quite awkward. It's still
11921/// better than generating twenty screens of text for every failed
11922/// overload.
11923///
11924/// It would be great to be able to express per-candidate problems
11925/// more richly for those diagnostic clients that cared, but we'd
11926/// still have to be just as careful with the default diagnostics.
11927/// \param CtorDestAS Addr space of object being constructed (for ctor
11928/// candidates only).
11930 unsigned NumArgs,
11931 bool TakingCandidateAddress,
11932 LangAS CtorDestAS = LangAS::Default) {
11933 assert(Cand->Function && "Candidate must be a function");
11934 FunctionDecl *Fn = Cand->Function;
11936 return;
11937
11938 // There is no physical candidate declaration to point to for OpenCL builtins.
11939 // Except for failed conversions, the notes are identical for each candidate,
11940 // so do not generate such notes.
11941 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11943 return;
11944
11945 // Skip implicit member functions when trying to resolve
11946 // the address of a an overload set for a function pointer.
11947 if (Cand->TookAddressOfOverload &&
11948 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
11949 return;
11950
11951 // Note deleted candidates, but only if they're viable.
11952 if (Cand->Viable) {
11953 if (Fn->isDeleted()) {
11954 std::string FnDesc;
11955 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11956 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11957 Cand->getRewriteKind(), FnDesc);
11958
11959 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11960 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11961 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11962 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11963 return;
11964 }
11965
11966 // We don't really have anything else to say about viable candidates.
11967 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11968 return;
11969 }
11970
11971 // If this is a synthesized deduction guide we're deducing against, add a note
11972 // for it. These deduction guides are not explicitly spelled in the source
11973 // code, so simply printing a deduction failure note mentioning synthesized
11974 // template parameters or pointing to the header of the surrounding RecordDecl
11975 // would be confusing.
11976 //
11977 // We prefer adding such notes at the end of the deduction failure because
11978 // duplicate code snippets appearing in the diagnostic would likely become
11979 // noisy.
11980 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
11981
11982 switch (Cand->FailureKind) {
11985 return DiagnoseArityMismatch(S, Cand, NumArgs);
11986
11988 return DiagnoseBadDeduction(S, Cand, NumArgs,
11989 TakingCandidateAddress);
11990
11992 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11993 << (Fn->getPrimaryTemplate() ? 1 : 0);
11994 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11995 return;
11996 }
11997
11999 Qualifiers QualsForPrinting;
12000 QualsForPrinting.setAddressSpace(CtorDestAS);
12001 S.Diag(Fn->getLocation(),
12002 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12003 << QualsForPrinting;
12004 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12005 return;
12006 }
12007
12011 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12012
12014 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12015 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12016 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12017 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12018
12019 // FIXME: this currently happens when we're called from SemaInit
12020 // when user-conversion overload fails. Figure out how to handle
12021 // those conditions and diagnose them well.
12022 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12023 }
12024
12026 return DiagnoseBadTarget(S, Cand);
12027
12028 case ovl_fail_enable_if:
12029 return DiagnoseFailedEnableIfAttr(S, Cand);
12030
12031 case ovl_fail_explicit:
12032 return DiagnoseFailedExplicitSpec(S, Cand);
12033
12035 // It's generally not interesting to note copy/move constructors here.
12036 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12037 return;
12038 S.Diag(Fn->getLocation(),
12039 diag::note_ovl_candidate_inherited_constructor_slice)
12040 << (Fn->getPrimaryTemplate() ? 1 : 0)
12041 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12042 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12043 return;
12044
12046 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12047 (void)Available;
12048 assert(!Available);
12049 break;
12050 }
12052 // Do nothing, these should simply be ignored.
12053 break;
12054
12056 std::string FnDesc;
12057 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12058 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12059 Cand->getRewriteKind(), FnDesc);
12060
12061 S.Diag(Fn->getLocation(),
12062 diag::note_ovl_candidate_constraints_not_satisfied)
12063 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12064 << FnDesc /* Ignored */;
12065 ConstraintSatisfaction Satisfaction;
12066 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12067 break;
12068 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12069 }
12070 }
12071}
12072
12075 return;
12076
12077 // Desugar the type of the surrogate down to a function type,
12078 // retaining as many typedefs as possible while still showing
12079 // the function type (and, therefore, its parameter types).
12080 QualType FnType = Cand->Surrogate->getConversionType();
12081 bool isLValueReference = false;
12082 bool isRValueReference = false;
12083 bool isPointer = false;
12084 if (const LValueReferenceType *FnTypeRef =
12085 FnType->getAs<LValueReferenceType>()) {
12086 FnType = FnTypeRef->getPointeeType();
12087 isLValueReference = true;
12088 } else if (const RValueReferenceType *FnTypeRef =
12089 FnType->getAs<RValueReferenceType>()) {
12090 FnType = FnTypeRef->getPointeeType();
12091 isRValueReference = true;
12092 }
12093 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12094 FnType = FnTypePtr->getPointeeType();
12095 isPointer = true;
12096 }
12097 // Desugar down to a function type.
12098 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12099 // Reconstruct the pointer/reference as appropriate.
12100 if (isPointer) FnType = S.Context.getPointerType(FnType);
12101 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12102 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12103
12104 if (!Cand->Viable &&
12106 S.Diag(Cand->Surrogate->getLocation(),
12107 diag::note_ovl_surrogate_constraints_not_satisfied)
12108 << Cand->Surrogate;
12109 ConstraintSatisfaction Satisfaction;
12110 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12111 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12112 } else {
12113 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12114 << FnType;
12115 }
12116}
12117
12118static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12119 SourceLocation OpLoc,
12120 OverloadCandidate *Cand) {
12121 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12122 std::string TypeStr("operator");
12123 TypeStr += Opc;
12124 TypeStr += "(";
12125 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12126 if (Cand->Conversions.size() == 1) {
12127 TypeStr += ")";
12128 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12129 } else {
12130 TypeStr += ", ";
12131 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12132 TypeStr += ")";
12133 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12134 }
12135}
12136
12138 OverloadCandidate *Cand) {
12139 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12140 if (ICS.isBad()) break; // all meaningless after first invalid
12141 if (!ICS.isAmbiguous()) continue;
12142
12144 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12145 }
12146}
12147
12149 if (Cand->Function)
12150 return Cand->Function->getLocation();
12151 if (Cand->IsSurrogate)
12152 return Cand->Surrogate->getLocation();
12153 return SourceLocation();
12154}
12155
12156static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12157 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12161 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12162
12166 return 1;
12167
12170 return 2;
12171
12179 return 3;
12180
12182 return 4;
12183
12185 return 5;
12186
12189 return 6;
12190 }
12191 llvm_unreachable("Unhandled deduction result");
12192}
12193
12194namespace {
12195
12196struct CompareOverloadCandidatesForDisplay {
12197 Sema &S;
12199 size_t NumArgs;
12201
12202 CompareOverloadCandidatesForDisplay(
12203 Sema &S, SourceLocation Loc, size_t NArgs,
12205 : S(S), NumArgs(NArgs), CSK(CSK) {}
12206
12207 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12208 // If there are too many or too few arguments, that's the high-order bit we
12209 // want to sort by, even if the immediate failure kind was something else.
12210 if (C->FailureKind == ovl_fail_too_many_arguments ||
12211 C->FailureKind == ovl_fail_too_few_arguments)
12212 return static_cast<OverloadFailureKind>(C->FailureKind);
12213
12214 if (C->Function) {
12215 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12217 if (NumArgs < C->Function->getMinRequiredArguments())
12219 }
12220
12221 return static_cast<OverloadFailureKind>(C->FailureKind);
12222 }
12223
12224 bool operator()(const OverloadCandidate *L,
12225 const OverloadCandidate *R) {
12226 // Fast-path this check.
12227 if (L == R) return false;
12228
12229 // Order first by viability.
12230 if (L->Viable) {
12231 if (!R->Viable) return true;
12232
12233 if (int Ord = CompareConversions(*L, *R))
12234 return Ord < 0;
12235 // Use other tie breakers.
12236 } else if (R->Viable)
12237 return false;
12238
12239 assert(L->Viable == R->Viable);
12240
12241 // Criteria by which we can sort non-viable candidates:
12242 if (!L->Viable) {
12243 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12244 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12245
12246 // 1. Arity mismatches come after other candidates.
12247 if (LFailureKind == ovl_fail_too_many_arguments ||
12248 LFailureKind == ovl_fail_too_few_arguments) {
12249 if (RFailureKind == ovl_fail_too_many_arguments ||
12250 RFailureKind == ovl_fail_too_few_arguments) {
12251 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12252 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12253 if (LDist == RDist) {
12254 if (LFailureKind == RFailureKind)
12255 // Sort non-surrogates before surrogates.
12256 return !L->IsSurrogate && R->IsSurrogate;
12257 // Sort candidates requiring fewer parameters than there were
12258 // arguments given after candidates requiring more parameters
12259 // than there were arguments given.
12260 return LFailureKind == ovl_fail_too_many_arguments;
12261 }
12262 return LDist < RDist;
12263 }
12264 return false;
12265 }
12266 if (RFailureKind == ovl_fail_too_many_arguments ||
12267 RFailureKind == ovl_fail_too_few_arguments)
12268 return true;
12269
12270 // 2. Bad conversions come first and are ordered by the number
12271 // of bad conversions and quality of good conversions.
12272 if (LFailureKind == ovl_fail_bad_conversion) {
12273 if (RFailureKind != ovl_fail_bad_conversion)
12274 return true;
12275
12276 // The conversion that can be fixed with a smaller number of changes,
12277 // comes first.
12278 unsigned numLFixes = L->Fix.NumConversionsFixed;
12279 unsigned numRFixes = R->Fix.NumConversionsFixed;
12280 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12281 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12282 if (numLFixes != numRFixes) {
12283 return numLFixes < numRFixes;
12284 }
12285
12286 // If there's any ordering between the defined conversions...
12287 if (int Ord = CompareConversions(*L, *R))
12288 return Ord < 0;
12289 } else if (RFailureKind == ovl_fail_bad_conversion)
12290 return false;
12291
12292 if (LFailureKind == ovl_fail_bad_deduction) {
12293 if (RFailureKind != ovl_fail_bad_deduction)
12294 return true;
12295
12297 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12298 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12299 if (LRank != RRank)
12300 return LRank < RRank;
12301 }
12302 } else if (RFailureKind == ovl_fail_bad_deduction)
12303 return false;
12304
12305 // TODO: others?
12306 }
12307
12308 // Sort everything else by location.
12311
12312 // Put candidates without locations (e.g. builtins) at the end.
12313 if (LLoc.isValid() && RLoc.isValid())
12314 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12315 if (LLoc.isValid() && !RLoc.isValid())
12316 return true;
12317 if (RLoc.isValid() && !LLoc.isValid())
12318 return false;
12319 assert(!LLoc.isValid() && !RLoc.isValid());
12320 // For builtins and other functions without locations, fallback to the order
12321 // in which they were added into the candidate set.
12322 return L < R;
12323 }
12324
12325private:
12326 struct ConversionSignals {
12327 unsigned KindRank = 0;
12329
12330 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12331 ConversionSignals Sig;
12332 Sig.KindRank = Seq.getKindRank();
12333 if (Seq.isStandard())
12334 Sig.Rank = Seq.Standard.getRank();
12335 else if (Seq.isUserDefined())
12336 Sig.Rank = Seq.UserDefined.After.getRank();
12337 // We intend StaticObjectArgumentConversion to compare the same as
12338 // StandardConversion with ICR_ExactMatch rank.
12339 return Sig;
12340 }
12341
12342 static ConversionSignals ForObjectArgument() {
12343 // We intend StaticObjectArgumentConversion to compare the same as
12344 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12345 return {};
12346 }
12347 };
12348
12349 // Returns -1 if conversions in L are considered better.
12350 // 0 if they are considered indistinguishable.
12351 // 1 if conversions in R are better.
12352 int CompareConversions(const OverloadCandidate &L,
12353 const OverloadCandidate &R) {
12354 // We cannot use `isBetterOverloadCandidate` because it is defined
12355 // according to the C++ standard and provides a partial order, but we need
12356 // a total order as this function is used in sort.
12357 assert(L.Conversions.size() == R.Conversions.size());
12358 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12359 auto LS = L.IgnoreObjectArgument && I == 0
12360 ? ConversionSignals::ForObjectArgument()
12361 : ConversionSignals::ForSequence(L.Conversions[I]);
12362 auto RS = R.IgnoreObjectArgument
12363 ? ConversionSignals::ForObjectArgument()
12364 : ConversionSignals::ForSequence(R.Conversions[I]);
12365 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12366 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12367 ? -1
12368 : 1;
12369 }
12370 // FIXME: find a way to compare templates for being more or less
12371 // specialized that provides a strict weak ordering.
12372 return 0;
12373 }
12374};
12375}
12376
12377/// CompleteNonViableCandidate - Normally, overload resolution only
12378/// computes up to the first bad conversion. Produces the FixIt set if
12379/// possible.
12380static void
12382 ArrayRef<Expr *> Args,
12384 assert(!Cand->Viable);
12385
12386 // Don't do anything on failures other than bad conversion.
12388 return;
12389
12390 // We only want the FixIts if all the arguments can be corrected.
12391 bool Unfixable = false;
12392 // Use a implicit copy initialization to check conversion fixes.
12394
12395 // Attempt to fix the bad conversion.
12396 unsigned ConvCount = Cand->Conversions.size();
12397 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12398 ++ConvIdx) {
12399 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12400 if (Cand->Conversions[ConvIdx].isInitialized() &&
12401 Cand->Conversions[ConvIdx].isBad()) {
12402 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12403 break;
12404 }
12405 }
12406
12407 // FIXME: this should probably be preserved from the overload
12408 // operation somehow.
12409 bool SuppressUserConversions = false;
12410
12411 unsigned ConvIdx = 0;
12412 unsigned ArgIdx = 0;
12413 ArrayRef<QualType> ParamTypes;
12414 bool Reversed = Cand->isReversed();
12415
12416 if (Cand->IsSurrogate) {
12417 QualType ConvType
12419 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12420 ConvType = ConvPtrType->getPointeeType();
12421 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12422 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12423 ConvIdx = 1;
12424 } else if (Cand->Function) {
12425 ParamTypes =
12426 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12427 if (isa<CXXMethodDecl>(Cand->Function) &&
12428 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12429 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12430 ConvIdx = 1;
12432 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12434 OO_Subscript)
12435 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12436 ArgIdx = 1;
12437 }
12438 } else {
12439 // Builtin operator.
12440 assert(ConvCount <= 3);
12441 ParamTypes = Cand->BuiltinParamTypes;
12442 }
12443
12444 // Fill in the rest of the conversions.
12445 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12446 ConvIdx != ConvCount;
12447 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12448 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12449 if (Cand->Conversions[ConvIdx].isInitialized()) {
12450 // We've already checked this conversion.
12451 } else if (ParamIdx < ParamTypes.size()) {
12452 if (ParamTypes[ParamIdx]->isDependentType())
12453 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12454 Args[ArgIdx]->getType());
12455 else {
12456 Cand->Conversions[ConvIdx] =
12457 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12458 SuppressUserConversions,
12459 /*InOverloadResolution=*/true,
12460 /*AllowObjCWritebackConversion=*/
12461 S.getLangOpts().ObjCAutoRefCount);
12462 // Store the FixIt in the candidate if it exists.
12463 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12464 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12465 }
12466 } else
12467 Cand->Conversions[ConvIdx].setEllipsis();
12468 }
12469}
12470
12473 SourceLocation OpLoc,
12474 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12475 // Sort the candidates by viability and position. Sorting directly would
12476 // be prohibitive, so we make a set of pointers and sort those.
12478 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12479 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12480 if (!Filter(*Cand))
12481 continue;
12482 switch (OCD) {
12483 case OCD_AllCandidates:
12484 if (!Cand->Viable) {
12485 if (!Cand->Function && !Cand->IsSurrogate) {
12486 // This a non-viable builtin candidate. We do not, in general,
12487 // want to list every possible builtin candidate.
12488 continue;
12489 }
12490 CompleteNonViableCandidate(S, Cand, Args, Kind);
12491 }
12492 break;
12493
12495 if (!Cand->Viable)
12496 continue;
12497 break;
12498
12500 if (!Cand->Best)
12501 continue;
12502 break;
12503 }
12504
12505 Cands.push_back(Cand);
12506 }
12507
12508 llvm::stable_sort(
12509 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12510
12511 return Cands;
12512}
12513
12515 SourceLocation OpLoc) {
12516 bool DeferHint = false;
12517 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12518 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12519 // host device candidates.
12520 auto WrongSidedCands =
12521 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12522 return (Cand.Viable == false &&
12523 Cand.FailureKind == ovl_fail_bad_target) ||
12524 (Cand.Function &&
12525 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12526 Cand.Function->template hasAttr<CUDADeviceAttr>());
12527 });
12528 DeferHint = !WrongSidedCands.empty();
12529 }
12530 return DeferHint;
12531}
12532
12533/// When overload resolution fails, prints diagnostic messages containing the
12534/// candidates in the candidate set.
12537 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12538 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12539
12540 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12541
12542 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12543
12544 // In WebAssembly we don't want to emit further diagnostics if a table is
12545 // passed as an argument to a function.
12546 bool NoteCands = true;
12547 for (const Expr *Arg : Args) {
12548 if (Arg->getType()->isWebAssemblyTableType())
12549 NoteCands = false;
12550 }
12551
12552 if (NoteCands)
12553 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12554
12555 if (OCD == OCD_AmbiguousCandidates)
12557}
12558
12561 StringRef Opc, SourceLocation OpLoc) {
12562 bool ReportedAmbiguousConversions = false;
12563
12564 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12565 unsigned CandsShown = 0;
12566 auto I = Cands.begin(), E = Cands.end();
12567 for (; I != E; ++I) {
12568 OverloadCandidate *Cand = *I;
12569
12570 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12571 ShowOverloads == Ovl_Best) {
12572 break;
12573 }
12574 ++CandsShown;
12575
12576 if (Cand->Function)
12577 NoteFunctionCandidate(S, Cand, Args.size(),
12578 /*TakingCandidateAddress=*/false, DestAS);
12579 else if (Cand->IsSurrogate)
12580 NoteSurrogateCandidate(S, Cand);
12581 else {
12582 assert(Cand->Viable &&
12583 "Non-viable built-in candidates are not added to Cands.");
12584 // Generally we only see ambiguities including viable builtin
12585 // operators if overload resolution got screwed up by an
12586 // ambiguous user-defined conversion.
12587 //
12588 // FIXME: It's quite possible for different conversions to see
12589 // different ambiguities, though.
12590 if (!ReportedAmbiguousConversions) {
12591 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12592 ReportedAmbiguousConversions = true;
12593 }
12594
12595 // If this is a viable builtin, print it.
12596 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12597 }
12598 }
12599
12600 // Inform S.Diags that we've shown an overload set with N elements. This may
12601 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12602 S.Diags.overloadCandidatesShown(CandsShown);
12603
12604 if (I != E)
12605 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12606 shouldDeferDiags(S, Args, OpLoc))
12607 << int(E - I);
12608}
12609
12610static SourceLocation
12612 return Cand->Specialization ? Cand->Specialization->getLocation()
12613 : SourceLocation();
12614}
12615
12616namespace {
12617struct CompareTemplateSpecCandidatesForDisplay {
12618 Sema &S;
12619 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12620
12621 bool operator()(const TemplateSpecCandidate *L,
12622 const TemplateSpecCandidate *R) {
12623 // Fast-path this check.
12624 if (L == R)
12625 return false;
12626
12627 // Assuming that both candidates are not matches...
12628
12629 // Sort by the ranking of deduction failures.
12633
12634 // Sort everything else by location.
12637
12638 // Put candidates without locations (e.g. builtins) at the end.
12639 if (LLoc.isInvalid())
12640 return false;
12641 if (RLoc.isInvalid())
12642 return true;
12643
12644 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12645 }
12646};
12647}
12648
12649/// Diagnose a template argument deduction failure.
12650/// We are treating these failures as overload failures due to bad
12651/// deductions.
12653 bool ForTakingAddress) {
12654 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12655 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12656}
12657
12658void TemplateSpecCandidateSet::destroyCandidates() {
12659 for (iterator i = begin(), e = end(); i != e; ++i) {
12660 i->DeductionFailure.Destroy();
12661 }
12662}
12663
12665 destroyCandidates();
12666 Candidates.clear();
12667}
12668
12669/// NoteCandidates - When no template specialization match is found, prints
12670/// diagnostic messages containing the non-matching specializations that form
12671/// the candidate set.
12672/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12673/// OCD == OCD_AllCandidates and Cand->Viable == false.
12675 // Sort the candidates by position (assuming no candidate is a match).
12676 // Sorting directly would be prohibitive, so we make a set of pointers
12677 // and sort those.
12679 Cands.reserve(size());
12680 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12681 if (Cand->Specialization)
12682 Cands.push_back(Cand);
12683 // Otherwise, this is a non-matching builtin candidate. We do not,
12684 // in general, want to list every possible builtin candidate.
12685 }
12686
12687 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12688
12689 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12690 // for generalization purposes (?).
12691 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12692
12694 unsigned CandsShown = 0;
12695 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12696 TemplateSpecCandidate *Cand = *I;
12697
12698 // Set an arbitrary limit on the number of candidates we'll spam
12699 // the user with. FIXME: This limit should depend on details of the
12700 // candidate list.
12701 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12702 break;
12703 ++CandsShown;
12704
12705 assert(Cand->Specialization &&
12706 "Non-matching built-in candidates are not added to Cands.");
12707 Cand->NoteDeductionFailure(S, ForTakingAddress);
12708 }
12709
12710 if (I != E)
12711 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12712}
12713
12714// [PossiblyAFunctionType] --> [Return]
12715// NonFunctionType --> NonFunctionType
12716// R (A) --> R(A)
12717// R (*)(A) --> R (A)
12718// R (&)(A) --> R (A)
12719// R (S::*)(A) --> R (A)
12721 QualType Ret = PossiblyAFunctionType;
12722 if (const PointerType *ToTypePtr =
12723 PossiblyAFunctionType->getAs<PointerType>())
12724 Ret = ToTypePtr->getPointeeType();
12725 else if (const ReferenceType *ToTypeRef =
12726 PossiblyAFunctionType->getAs<ReferenceType>())
12727 Ret = ToTypeRef->getPointeeType();
12728 else if (const MemberPointerType *MemTypePtr =
12729 PossiblyAFunctionType->getAs<MemberPointerType>())
12730 Ret = MemTypePtr->getPointeeType();
12731 Ret =
12732 Context.getCanonicalType(Ret).getUnqualifiedType();
12733 return Ret;
12734}
12735
12737 bool Complain = true) {
12738 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12739 S.DeduceReturnType(FD, Loc, Complain))
12740 return true;
12741
12742 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12743 if (S.getLangOpts().CPlusPlus17 &&
12744 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12745 !S.ResolveExceptionSpec(Loc, FPT))
12746 return true;
12747
12748 return false;
12749}
12750
12751namespace {
12752// A helper class to help with address of function resolution
12753// - allows us to avoid passing around all those ugly parameters
12754class AddressOfFunctionResolver {
12755 Sema& S;
12756 Expr* SourceExpr;
12757 const QualType& TargetType;
12758 QualType TargetFunctionType; // Extracted function type from target type
12759
12760 bool Complain;
12761 //DeclAccessPair& ResultFunctionAccessPair;
12762 ASTContext& Context;
12763
12764 bool TargetTypeIsNonStaticMemberFunction;
12765 bool FoundNonTemplateFunction;
12766 bool StaticMemberFunctionFromBoundPointer;
12767 bool HasComplained;
12768
12769 OverloadExpr::FindResult OvlExprInfo;
12770 OverloadExpr *OvlExpr;
12771 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12773 TemplateSpecCandidateSet FailedCandidates;
12774
12775public:
12776 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12777 const QualType &TargetType, bool Complain)
12778 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12779 Complain(Complain), Context(S.getASTContext()),
12780 TargetTypeIsNonStaticMemberFunction(
12781 !!TargetType->getAs<MemberPointerType>()),
12782 FoundNonTemplateFunction(false),
12783 StaticMemberFunctionFromBoundPointer(false),
12784 HasComplained(false),
12785 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12786 OvlExpr(OvlExprInfo.Expression),
12787 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12788 ExtractUnqualifiedFunctionTypeFromTargetType();
12789
12790 if (TargetFunctionType->isFunctionType()) {
12791 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12792 if (!UME->isImplicitAccess() &&
12794 StaticMemberFunctionFromBoundPointer = true;
12795 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12796 DeclAccessPair dap;
12798 OvlExpr, false, &dap)) {
12799 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12800 if (!Method->isStatic()) {
12801 // If the target type is a non-function type and the function found
12802 // is a non-static member function, pretend as if that was the
12803 // target, it's the only possible type to end up with.
12804 TargetTypeIsNonStaticMemberFunction = true;
12805
12806 // And skip adding the function if its not in the proper form.
12807 // We'll diagnose this due to an empty set of functions.
12808 if (!OvlExprInfo.HasFormOfMemberPointer)
12809 return;
12810 }
12811
12812 Matches.push_back(std::make_pair(dap, Fn));
12813 }
12814 return;
12815 }
12816
12817 if (OvlExpr->hasExplicitTemplateArgs())
12818 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12819
12820 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12821 // C++ [over.over]p4:
12822 // If more than one function is selected, [...]
12823 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12824 if (FoundNonTemplateFunction)
12825 EliminateAllTemplateMatches();
12826 else
12827 EliminateAllExceptMostSpecializedTemplate();
12828 }
12829 }
12830
12831 if (S.getLangOpts().CUDA && Matches.size() > 1)
12832 EliminateSuboptimalCudaMatches();
12833 }
12834
12835 bool hasComplained() const { return HasComplained; }
12836
12837private:
12838 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12839 QualType Discard;
12840 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12841 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12842 }
12843
12844 /// \return true if A is considered a better overload candidate for the
12845 /// desired type than B.
12846 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12847 // If A doesn't have exactly the correct type, we don't want to classify it
12848 // as "better" than anything else. This way, the user is required to
12849 // disambiguate for us if there are multiple candidates and no exact match.
12850 return candidateHasExactlyCorrectType(A) &&
12851 (!candidateHasExactlyCorrectType(B) ||
12852 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12853 }
12854
12855 /// \return true if we were able to eliminate all but one overload candidate,
12856 /// false otherwise.
12857 bool eliminiateSuboptimalOverloadCandidates() {
12858 // Same algorithm as overload resolution -- one pass to pick the "best",
12859 // another pass to be sure that nothing is better than the best.
12860 auto Best = Matches.begin();
12861 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12862 if (isBetterCandidate(I->second, Best->second))
12863 Best = I;
12864
12865 const FunctionDecl *BestFn = Best->second;
12866 auto IsBestOrInferiorToBest = [this, BestFn](
12867 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12868 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12869 };
12870
12871 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12872 // option, so we can potentially give the user a better error
12873 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12874 return false;
12875 Matches[0] = *Best;
12876 Matches.resize(1);
12877 return true;
12878 }
12879
12880 bool isTargetTypeAFunction() const {
12881 return TargetFunctionType->isFunctionType();
12882 }
12883
12884 // [ToType] [Return]
12885
12886 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12887 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12888 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12889 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12890 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12891 }
12892
12893 // return true if any matching specializations were found
12894 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12895 const DeclAccessPair& CurAccessFunPair) {
12896 if (CXXMethodDecl *Method
12897 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12898 // Skip non-static function templates when converting to pointer, and
12899 // static when converting to member pointer.
12900 bool CanConvertToFunctionPointer =
12901 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12902 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12903 return false;
12904 }
12905 else if (TargetTypeIsNonStaticMemberFunction)
12906 return false;
12907
12908 // C++ [over.over]p2:
12909 // If the name is a function template, template argument deduction is
12910 // done (14.8.2.2), and if the argument deduction succeeds, the
12911 // resulting template argument list is used to generate a single
12912 // function template specialization, which is added to the set of
12913 // overloaded functions considered.
12914 FunctionDecl *Specialization = nullptr;
12915 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12917 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
12918 Specialization, Info, /*IsAddressOfFunction*/ true);
12919 Result != TemplateDeductionResult::Success) {
12920 // Make a note of the failed deduction for diagnostics.
12921 FailedCandidates.addCandidate()
12922 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12923 MakeDeductionFailureInfo(Context, Result, Info));
12924 return false;
12925 }
12926
12927 // Template argument deduction ensures that we have an exact match or
12928 // compatible pointer-to-function arguments that would be adjusted by ICS.
12929 // This function template specicalization works.
12931 Context.getCanonicalType(Specialization->getType()),
12932 Context.getCanonicalType(TargetFunctionType)));
12933
12935 return false;
12936
12937 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12938 return true;
12939 }
12940
12941 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12942 const DeclAccessPair& CurAccessFunPair) {
12943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12944 // Skip non-static functions when converting to pointer, and static
12945 // when converting to member pointer.
12946 bool CanConvertToFunctionPointer =
12947 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12948 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12949 return false;
12950 }
12951 else if (TargetTypeIsNonStaticMemberFunction)
12952 return false;
12953
12954 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12955 if (S.getLangOpts().CUDA) {
12956 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12957 if (!(Caller && Caller->isImplicit()) &&
12958 !S.CUDA().IsAllowedCall(Caller, FunDecl))
12959 return false;
12960 }
12961 if (FunDecl->isMultiVersion()) {
12962 const auto *TA = FunDecl->getAttr<TargetAttr>();
12963 if (TA && !TA->isDefaultVersion())
12964 return false;
12965 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
12966 if (TVA && !TVA->isDefaultVersion())
12967 return false;
12968 }
12969
12970 // If any candidate has a placeholder return type, trigger its deduction
12971 // now.
12972 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12973 Complain)) {
12974 HasComplained |= Complain;
12975 return false;
12976 }
12977
12978 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12979 return false;
12980
12981 // If we're in C, we need to support types that aren't exactly identical.
12982 if (!S.getLangOpts().CPlusPlus ||
12983 candidateHasExactlyCorrectType(FunDecl)) {
12984 Matches.push_back(std::make_pair(
12985 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12986 FoundNonTemplateFunction = true;
12987 return true;
12988 }
12989 }
12990
12991 return false;
12992 }
12993
12994 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12995 bool Ret = false;
12996
12997 // If the overload expression doesn't have the form of a pointer to
12998 // member, don't try to convert it to a pointer-to-member type.
12999 if (IsInvalidFormOfPointerToMemberFunction())
13000 return false;
13001
13002 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13003 E = OvlExpr->decls_end();
13004 I != E; ++I) {
13005 // Look through any using declarations to find the underlying function.
13006 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13007
13008 // C++ [over.over]p3:
13009 // Non-member functions and static member functions match
13010 // targets of type "pointer-to-function" or "reference-to-function."
13011 // Nonstatic member functions match targets of
13012 // type "pointer-to-member-function."
13013 // Note that according to DR 247, the containing class does not matter.
13014 if (FunctionTemplateDecl *FunctionTemplate
13015 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13016 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13017 Ret = true;
13018 }
13019 // If we have explicit template arguments supplied, skip non-templates.
13020 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13021 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13022 Ret = true;
13023 }
13024 assert(Ret || Matches.empty());
13025 return Ret;
13026 }
13027
13028 void EliminateAllExceptMostSpecializedTemplate() {
13029 // [...] and any given function template specialization F1 is
13030 // eliminated if the set contains a second function template
13031 // specialization whose function template is more specialized
13032 // than the function template of F1 according to the partial
13033 // ordering rules of 14.5.5.2.
13034
13035 // The algorithm specified above is quadratic. We instead use a
13036 // two-pass algorithm (similar to the one used to identify the
13037 // best viable function in an overload set) that identifies the
13038 // best function template (if it exists).
13039
13040 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13041 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13042 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13043
13044 // TODO: It looks like FailedCandidates does not serve much purpose
13045 // here, since the no_viable diagnostic has index 0.
13047 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13048 SourceExpr->getBeginLoc(), S.PDiag(),
13049 S.PDiag(diag::err_addr_ovl_ambiguous)
13050 << Matches[0].second->getDeclName(),
13051 S.PDiag(diag::note_ovl_candidate)
13052 << (unsigned)oc_function << (unsigned)ocs_described_template,
13053 Complain, TargetFunctionType);
13054
13055 if (Result != MatchesCopy.end()) {
13056 // Make it the first and only element
13057 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13058 Matches[0].second = cast<FunctionDecl>(*Result);
13059 Matches.resize(1);
13060 } else
13061 HasComplained |= Complain;
13062 }
13063
13064 void EliminateAllTemplateMatches() {
13065 // [...] any function template specializations in the set are
13066 // eliminated if the set also contains a non-template function, [...]
13067 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13068 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13069 ++I;
13070 else {
13071 Matches[I] = Matches[--N];
13072 Matches.resize(N);
13073 }
13074 }
13075 }
13076
13077 void EliminateSuboptimalCudaMatches() {
13078 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13079 Matches);
13080 }
13081
13082public:
13083 void ComplainNoMatchesFound() const {
13084 assert(Matches.empty());
13085 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13086 << OvlExpr->getName() << TargetFunctionType
13087 << OvlExpr->getSourceRange();
13088 if (FailedCandidates.empty())
13089 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13090 /*TakingAddress=*/true);
13091 else {
13092 // We have some deduction failure messages. Use them to diagnose
13093 // the function templates, and diagnose the non-template candidates
13094 // normally.
13095 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13096 IEnd = OvlExpr->decls_end();
13097 I != IEnd; ++I)
13098 if (FunctionDecl *Fun =
13099 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13101 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13102 /*TakingAddress=*/true);
13103 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13104 }
13105 }
13106
13107 bool IsInvalidFormOfPointerToMemberFunction() const {
13108 return TargetTypeIsNonStaticMemberFunction &&
13109 !OvlExprInfo.HasFormOfMemberPointer;
13110 }
13111
13112 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13113 // TODO: Should we condition this on whether any functions might
13114 // have matched, or is it more appropriate to do that in callers?
13115 // TODO: a fixit wouldn't hurt.
13116 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13117 << TargetType << OvlExpr->getSourceRange();
13118 }
13119
13120 bool IsStaticMemberFunctionFromBoundPointer() const {
13121 return StaticMemberFunctionFromBoundPointer;
13122 }
13123
13124 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13125 S.Diag(OvlExpr->getBeginLoc(),
13126 diag::err_invalid_form_pointer_member_function)
13127 << OvlExpr->getSourceRange();
13128 }
13129
13130 void ComplainOfInvalidConversion() const {
13131 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13132 << OvlExpr->getName() << TargetType;
13133 }
13134
13135 void ComplainMultipleMatchesFound() const {
13136 assert(Matches.size() > 1);
13137 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13138 << OvlExpr->getName() << OvlExpr->getSourceRange();
13139 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13140 /*TakingAddress=*/true);
13141 }
13142
13143 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13144
13145 int getNumMatches() const { return Matches.size(); }
13146
13147 FunctionDecl* getMatchingFunctionDecl() const {
13148 if (Matches.size() != 1) return nullptr;
13149 return Matches[0].second;
13150 }
13151
13152 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13153 if (Matches.size() != 1) return nullptr;
13154 return &Matches[0].first;
13155 }
13156};
13157}
13158
13161 QualType TargetType,
13162 bool Complain,
13163 DeclAccessPair &FoundResult,
13164 bool *pHadMultipleCandidates) {
13165 assert(AddressOfExpr->getType() == Context.OverloadTy);
13166
13167 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13168 Complain);
13169 int NumMatches = Resolver.getNumMatches();
13170 FunctionDecl *Fn = nullptr;
13171 bool ShouldComplain = Complain && !Resolver.hasComplained();
13172 if (NumMatches == 0 && ShouldComplain) {
13173 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13174 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13175 else
13176 Resolver.ComplainNoMatchesFound();
13177 }
13178 else if (NumMatches > 1 && ShouldComplain)
13179 Resolver.ComplainMultipleMatchesFound();
13180 else if (NumMatches == 1) {
13181 Fn = Resolver.getMatchingFunctionDecl();
13182 assert(Fn);
13183 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13184 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13185 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13186 if (Complain) {
13187 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13188 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13189 else
13190 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13191 }
13192 }
13193
13194 if (pHadMultipleCandidates)
13195 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13196 return Fn;
13197}
13198
13202 OverloadExpr *Ovl = R.Expression;
13203 bool IsResultAmbiguous = false;
13204 FunctionDecl *Result = nullptr;
13205 DeclAccessPair DAP;
13206 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13207
13208 // Return positive for better, negative for worse, 0 for equal preference.
13209 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13210 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13211 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13212 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13213 };
13214
13215 // Don't use the AddressOfResolver because we're specifically looking for
13216 // cases where we have one overload candidate that lacks
13217 // enable_if/pass_object_size/...
13218 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13219 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13220 if (!FD)
13221 return nullptr;
13222
13224 continue;
13225
13226 // If we found a better result, update Result.
13227 auto FoundBetter = [&]() {
13228 IsResultAmbiguous = false;
13229 DAP = I.getPair();
13230 Result = FD;
13231 };
13232
13233 // We have more than one result - see if it is more constrained than the
13234 // previous one.
13235 if (Result) {
13236 // Check CUDA preference first. If the candidates have differennt CUDA
13237 // preference, choose the one with higher CUDA preference. Otherwise,
13238 // choose the one with more constraints.
13239 if (getLangOpts().CUDA) {
13240 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13241 // FD has different preference than Result.
13242 if (PreferenceByCUDA != 0) {
13243 // FD is more preferable than Result.
13244 if (PreferenceByCUDA > 0)
13245 FoundBetter();
13246 continue;
13247 }
13248 }
13249 // FD has the same CUDA prefernece than Result. Continue check
13250 // constraints.
13251 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13252 if (MoreConstrained != FD) {
13253 if (!MoreConstrained) {
13254 IsResultAmbiguous = true;
13255 AmbiguousDecls.push_back(FD);
13256 }
13257 continue;
13258 }
13259 // FD is more constrained - replace Result with it.
13260 }
13261 FoundBetter();
13262 }
13263
13264 if (IsResultAmbiguous)
13265 return nullptr;
13266
13267 if (Result) {
13269 // We skipped over some ambiguous declarations which might be ambiguous with
13270 // the selected result.
13271 for (FunctionDecl *Skipped : AmbiguousDecls) {
13272 // If skipped candidate has different CUDA preference than the result,
13273 // there is no ambiguity. Otherwise check whether they have different
13274 // constraints.
13275 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13276 continue;
13277 if (!getMoreConstrainedFunction(Skipped, Result))
13278 return nullptr;
13279 }
13280 Pair = DAP;
13281 }
13282 return Result;
13283}
13284
13286 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13287 Expr *E = SrcExpr.get();
13288 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13289
13290 DeclAccessPair DAP;
13291 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13292 if (!Found || Found->isCPUDispatchMultiVersion() ||
13293 Found->isCPUSpecificMultiVersion())
13294 return false;
13295
13296 // Emitting multiple diagnostics for a function that is both inaccessible and
13297 // unavailable is consistent with our behavior elsewhere. So, always check
13298 // for both.
13299 DiagnoseUseOfDecl(Found, E->getExprLoc());
13300 CheckAddressOfMemberAccess(E, DAP);
13301 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13302 if (Res.isInvalid())
13303 return false;
13304 Expr *Fixed = Res.get();
13305 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13306 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13307 else
13308 SrcExpr = Fixed;
13309 return true;
13310}
13311
13313 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13314 TemplateSpecCandidateSet *FailedTSC) {
13315 // C++ [over.over]p1:
13316 // [...] [Note: any redundant set of parentheses surrounding the
13317 // overloaded function name is ignored (5.1). ]
13318 // C++ [over.over]p1:
13319 // [...] The overloaded function name can be preceded by the &
13320 // operator.
13321
13322 // If we didn't actually find any template-ids, we're done.
13323 if (!ovl->hasExplicitTemplateArgs())
13324 return nullptr;
13325
13326 TemplateArgumentListInfo ExplicitTemplateArgs;
13327 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13328
13329 // Look through all of the overloaded functions, searching for one
13330 // whose type matches exactly.
13331 FunctionDecl *Matched = nullptr;
13332 for (UnresolvedSetIterator I = ovl->decls_begin(),
13333 E = ovl->decls_end(); I != E; ++I) {
13334 // C++0x [temp.arg.explicit]p3:
13335 // [...] In contexts where deduction is done and fails, or in contexts
13336 // where deduction is not done, if a template argument list is
13337 // specified and it, along with any default template arguments,
13338 // identifies a single function template specialization, then the
13339 // template-id is an lvalue for the function template specialization.
13340 FunctionTemplateDecl *FunctionTemplate
13341 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13342
13343 // C++ [over.over]p2:
13344 // If the name is a function template, template argument deduction is
13345 // done (14.8.2.2), and if the argument deduction succeeds, the
13346 // resulting template argument list is used to generate a single
13347 // function template specialization, which is added to the set of
13348 // overloaded functions considered.
13349 FunctionDecl *Specialization = nullptr;
13350 TemplateDeductionInfo Info(ovl->getNameLoc());
13352 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13353 /*IsAddressOfFunction*/ true);
13355 // Make a note of the failed deduction for diagnostics.
13356 if (FailedTSC)
13357 FailedTSC->addCandidate().set(
13358 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13359 MakeDeductionFailureInfo(Context, Result, Info));
13360 continue;
13361 }
13362
13363 assert(Specialization && "no specialization and no error?");
13364
13365 // Multiple matches; we can't resolve to a single declaration.
13366 if (Matched) {
13367 if (Complain) {
13368 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13369 << ovl->getName();
13370 NoteAllOverloadCandidates(ovl);
13371 }
13372 return nullptr;
13373 }
13374
13375 Matched = Specialization;
13376 if (FoundResult) *FoundResult = I.getPair();
13377 }
13378
13379 if (Matched &&
13380 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13381 return nullptr;
13382
13383 return Matched;
13384}
13385
13387 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13388 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13389 unsigned DiagIDForComplaining) {
13390 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13391
13393
13394 DeclAccessPair found;
13395 ExprResult SingleFunctionExpression;
13396 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13397 ovl.Expression, /*complain*/ false, &found)) {
13398 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13399 SrcExpr = ExprError();
13400 return true;
13401 }
13402
13403 // It is only correct to resolve to an instance method if we're
13404 // resolving a form that's permitted to be a pointer to member.
13405 // Otherwise we'll end up making a bound member expression, which
13406 // is illegal in all the contexts we resolve like this.
13407 if (!ovl.HasFormOfMemberPointer &&
13408 isa<CXXMethodDecl>(fn) &&
13409 cast<CXXMethodDecl>(fn)->isInstance()) {
13410 if (!complain) return false;
13411
13412 Diag(ovl.Expression->getExprLoc(),
13413 diag::err_bound_member_function)
13414 << 0 << ovl.Expression->getSourceRange();
13415
13416 // TODO: I believe we only end up here if there's a mix of
13417 // static and non-static candidates (otherwise the expression
13418 // would have 'bound member' type, not 'overload' type).
13419 // Ideally we would note which candidate was chosen and why
13420 // the static candidates were rejected.
13421 SrcExpr = ExprError();
13422 return true;
13423 }
13424
13425 // Fix the expression to refer to 'fn'.
13426 SingleFunctionExpression =
13427 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13428
13429 // If desired, do function-to-pointer decay.
13430 if (doFunctionPointerConversion) {
13431 SingleFunctionExpression =
13432 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13433 if (SingleFunctionExpression.isInvalid()) {
13434 SrcExpr = ExprError();
13435 return true;
13436 }
13437 }
13438 }
13439
13440 if (!SingleFunctionExpression.isUsable()) {
13441 if (complain) {
13442 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13443 << ovl.Expression->getName()
13444 << DestTypeForComplaining
13445 << OpRangeForComplaining
13447 NoteAllOverloadCandidates(SrcExpr.get());
13448
13449 SrcExpr = ExprError();
13450 return true;
13451 }
13452
13453 return false;
13454 }
13455
13456 SrcExpr = SingleFunctionExpression;
13457 return true;
13458}
13459
13460/// Add a single candidate to the overload set.
13462 DeclAccessPair FoundDecl,
13463 TemplateArgumentListInfo *ExplicitTemplateArgs,
13464 ArrayRef<Expr *> Args,
13465 OverloadCandidateSet &CandidateSet,
13466 bool PartialOverloading,
13467 bool KnownValid) {
13468 NamedDecl *Callee = FoundDecl.getDecl();
13469 if (isa<UsingShadowDecl>(Callee))
13470 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13471
13472 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13473 if (ExplicitTemplateArgs) {
13474 assert(!KnownValid && "Explicit template arguments?");
13475 return;
13476 }
13477 // Prevent ill-formed function decls to be added as overload candidates.
13478 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13479 return;
13480
13481 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13482 /*SuppressUserConversions=*/false,
13483 PartialOverloading);
13484 return;
13485 }
13486
13487 if (FunctionTemplateDecl *FuncTemplate
13488 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13489 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13490 ExplicitTemplateArgs, Args, CandidateSet,
13491 /*SuppressUserConversions=*/false,
13492 PartialOverloading);
13493 return;
13494 }
13495
13496 assert(!KnownValid && "unhandled case in overloaded call candidate");
13497}
13498
13500 ArrayRef<Expr *> Args,
13501 OverloadCandidateSet &CandidateSet,
13502 bool PartialOverloading) {
13503
13504#ifndef NDEBUG
13505 // Verify that ArgumentDependentLookup is consistent with the rules
13506 // in C++0x [basic.lookup.argdep]p3:
13507 //
13508 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13509 // and let Y be the lookup set produced by argument dependent
13510 // lookup (defined as follows). If X contains
13511 //
13512 // -- a declaration of a class member, or
13513 //
13514 // -- a block-scope function declaration that is not a
13515 // using-declaration, or
13516 //
13517 // -- a declaration that is neither a function or a function
13518 // template
13519 //
13520 // then Y is empty.
13521
13522 if (ULE->requiresADL()) {
13524 E = ULE->decls_end(); I != E; ++I) {
13525 assert(!(*I)->getDeclContext()->isRecord());
13526 assert(isa<UsingShadowDecl>(*I) ||
13527 !(*I)->getDeclContext()->isFunctionOrMethod());
13528 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13529 }
13530 }
13531#endif
13532
13533 // It would be nice to avoid this copy.
13534 TemplateArgumentListInfo TABuffer;
13535 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13536 if (ULE->hasExplicitTemplateArgs()) {
13537 ULE->copyTemplateArgumentsInto(TABuffer);
13538 ExplicitTemplateArgs = &TABuffer;
13539 }
13540
13542 E = ULE->decls_end(); I != E; ++I)
13543 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13544 CandidateSet, PartialOverloading,
13545 /*KnownValid*/ true);
13546
13547 if (ULE->requiresADL())
13548 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13549 Args, ExplicitTemplateArgs,
13550 CandidateSet, PartialOverloading);
13551}
13552
13554 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13555 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13556 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13557 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13558 CandidateSet, false, /*KnownValid*/ false);
13559}
13560
13561/// Determine whether a declaration with the specified name could be moved into
13562/// a different namespace.
13564 switch (Name.getCXXOverloadedOperator()) {
13565 case OO_New: case OO_Array_New:
13566 case OO_Delete: case OO_Array_Delete:
13567 return false;
13568
13569 default:
13570 return true;
13571 }
13572}
13573
13574/// Attempt to recover from an ill-formed use of a non-dependent name in a
13575/// template, where the non-dependent name was declared after the template
13576/// was defined. This is common in code written for a compilers which do not
13577/// correctly implement two-stage name lookup.
13578///
13579/// Returns true if a viable candidate was found and a diagnostic was issued.
13581 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13583 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13584 CXXRecordDecl **FoundInClass = nullptr) {
13585 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13586 return false;
13587
13588 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13589 if (DC->isTransparentContext())
13590 continue;
13591
13592 SemaRef.LookupQualifiedName(R, DC);
13593
13594 if (!R.empty()) {
13596
13597 OverloadCandidateSet Candidates(FnLoc, CSK);
13598 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13599 Candidates);
13600
13603 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13604
13605 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13606 // We either found non-function declarations or a best viable function
13607 // at class scope. A class-scope lookup result disables ADL. Don't
13608 // look past this, but let the caller know that we found something that
13609 // either is, or might be, usable in this class.
13610 if (FoundInClass) {
13611 *FoundInClass = RD;
13612 if (OR == OR_Success) {
13613 R.clear();
13614 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13615 R.resolveKind();
13616 }
13617 }
13618 return false;
13619 }
13620
13621 if (OR != OR_Success) {
13622 // There wasn't a unique best function or function template.
13623 return false;
13624 }
13625
13626 // Find the namespaces where ADL would have looked, and suggest
13627 // declaring the function there instead.
13628 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13629 Sema::AssociatedClassSet AssociatedClasses;
13630 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13631 AssociatedNamespaces,
13632 AssociatedClasses);
13633 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13635 DeclContext *Std = SemaRef.getStdNamespace();
13636 for (Sema::AssociatedNamespaceSet::iterator
13637 it = AssociatedNamespaces.begin(),
13638 end = AssociatedNamespaces.end(); it != end; ++it) {
13639 // Never suggest declaring a function within namespace 'std'.
13640 if (Std && Std->Encloses(*it))
13641 continue;
13642
13643 // Never suggest declaring a function within a namespace with a
13644 // reserved name, like __gnu_cxx.
13645 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13646 if (NS &&
13647 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13648 continue;
13649
13650 SuggestedNamespaces.insert(*it);
13651 }
13652 }
13653
13654 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13655 << R.getLookupName();
13656 if (SuggestedNamespaces.empty()) {
13657 SemaRef.Diag(Best->Function->getLocation(),
13658 diag::note_not_found_by_two_phase_lookup)
13659 << R.getLookupName() << 0;
13660 } else if (SuggestedNamespaces.size() == 1) {
13661 SemaRef.Diag(Best->Function->getLocation(),
13662 diag::note_not_found_by_two_phase_lookup)
13663 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13664 } else {
13665 // FIXME: It would be useful to list the associated namespaces here,
13666 // but the diagnostics infrastructure doesn't provide a way to produce
13667 // a localized representation of a list of items.
13668 SemaRef.Diag(Best->Function->getLocation(),
13669 diag::note_not_found_by_two_phase_lookup)
13670 << R.getLookupName() << 2;
13671 }
13672
13673 // Try to recover by calling this function.
13674 return true;
13675 }
13676
13677 R.clear();
13678 }
13679
13680 return false;
13681}
13682
13683/// Attempt to recover from ill-formed use of a non-dependent operator in a
13684/// template, where the non-dependent operator was declared after the template
13685/// was defined.
13686///
13687/// Returns true if a viable candidate was found and a diagnostic was issued.
13688static bool
13690 SourceLocation OpLoc,
13691 ArrayRef<Expr *> Args) {
13692 DeclarationName OpName =
13694 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13695 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13697 /*ExplicitTemplateArgs=*/nullptr, Args);
13698}
13699
13700namespace {
13701class BuildRecoveryCallExprRAII {
13702 Sema &SemaRef;
13704
13705public:
13706 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13707 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13708 SemaRef.IsBuildingRecoveryCallExpr = true;
13709 }
13710
13711 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13712};
13713}
13714
13715/// Attempts to recover from a call where no functions were found.
13716///
13717/// This function will do one of three things:
13718/// * Diagnose, recover, and return a recovery expression.
13719/// * Diagnose, fail to recover, and return ExprError().
13720/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13721/// expected to diagnose as appropriate.
13722static ExprResult
13725 SourceLocation LParenLoc,
13727 SourceLocation RParenLoc,
13728 bool EmptyLookup, bool AllowTypoCorrection) {
13729 // Do not try to recover if it is already building a recovery call.
13730 // This stops infinite loops for template instantiations like
13731 //
13732 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13733 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13734 if (SemaRef.IsBuildingRecoveryCallExpr)
13735 return ExprResult();
13736 BuildRecoveryCallExprRAII RCE(SemaRef);
13737
13738 CXXScopeSpec SS;
13739 SS.Adopt(ULE->getQualifierLoc());
13740 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13741
13742 TemplateArgumentListInfo TABuffer;
13743 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13744 if (ULE->hasExplicitTemplateArgs()) {
13745 ULE->copyTemplateArgumentsInto(TABuffer);
13746 ExplicitTemplateArgs = &TABuffer;
13747 }
13748
13749 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13751 CXXRecordDecl *FoundInClass = nullptr;
13752 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13754 ExplicitTemplateArgs, Args, &FoundInClass)) {
13755 // OK, diagnosed a two-phase lookup issue.
13756 } else if (EmptyLookup) {
13757 // Try to recover from an empty lookup with typo correction.
13758 R.clear();
13759 NoTypoCorrectionCCC NoTypoValidator{};
13760 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13761 ExplicitTemplateArgs != nullptr,
13762 dyn_cast<MemberExpr>(Fn));
13763 CorrectionCandidateCallback &Validator =
13764 AllowTypoCorrection
13765 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13766 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13767 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13768 Args))
13769 return ExprError();
13770 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13771 // We found a usable declaration of the name in a dependent base of some
13772 // enclosing class.
13773 // FIXME: We should also explain why the candidates found by name lookup
13774 // were not viable.
13775 if (SemaRef.DiagnoseDependentMemberLookup(R))
13776 return ExprError();
13777 } else {
13778 // We had viable candidates and couldn't recover; let the caller diagnose
13779 // this.
13780 return ExprResult();
13781 }
13782
13783 // If we get here, we should have issued a diagnostic and formed a recovery
13784 // lookup result.
13785 assert(!R.empty() && "lookup results empty despite recovery");
13786
13787 // If recovery created an ambiguity, just bail out.
13788 if (R.isAmbiguous()) {
13790 return ExprError();
13791 }
13792
13793 // Build an implicit member call if appropriate. Just drop the
13794 // casts and such from the call, we don't really care.
13795 ExprResult NewFn = ExprError();
13796 if ((*R.begin())->isCXXClassMember())
13797 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13798 ExplicitTemplateArgs, S);
13799 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13800 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13801 ExplicitTemplateArgs);
13802 else
13803 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13804
13805 if (NewFn.isInvalid())
13806 return ExprError();
13807
13808 // This shouldn't cause an infinite loop because we're giving it
13809 // an expression with viable lookup results, which should never
13810 // end up here.
13811 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13812 MultiExprArg(Args.data(), Args.size()),
13813 RParenLoc);
13814}
13815
13818 MultiExprArg Args,
13819 SourceLocation RParenLoc,
13820 OverloadCandidateSet *CandidateSet,
13821 ExprResult *Result) {
13822#ifndef NDEBUG
13823 if (ULE->requiresADL()) {
13824 // To do ADL, we must have found an unqualified name.
13825 assert(!ULE->getQualifier() && "qualified name with ADL");
13826
13827 // We don't perform ADL for implicit declarations of builtins.
13828 // Verify that this was correctly set up.
13829 FunctionDecl *F;
13830 if (ULE->decls_begin() != ULE->decls_end() &&
13831 ULE->decls_begin() + 1 == ULE->decls_end() &&
13832 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13833 F->getBuiltinID() && F->isImplicit())
13834 llvm_unreachable("performing ADL for builtin");
13835
13836 // We don't perform ADL in C.
13837 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13838 }
13839#endif
13840
13841 UnbridgedCastsSet UnbridgedCasts;
13842 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13843 *Result = ExprError();
13844 return true;
13845 }
13846
13847 // Add the functions denoted by the callee to the set of candidate
13848 // functions, including those from argument-dependent lookup.
13849 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13850
13851 if (getLangOpts().MSVCCompat &&
13852 CurContext->isDependentContext() && !isSFINAEContext() &&
13853 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13854
13856 if (CandidateSet->empty() ||
13857 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13859 // In Microsoft mode, if we are inside a template class member function
13860 // then create a type dependent CallExpr. The goal is to postpone name
13861 // lookup to instantiation time to be able to search into type dependent
13862 // base classes.
13863 CallExpr *CE =
13864 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13865 RParenLoc, CurFPFeatureOverrides());
13867 *Result = CE;
13868 return true;
13869 }
13870 }
13871
13872 if (CandidateSet->empty())
13873 return false;
13874
13875 UnbridgedCasts.restore();
13876 return false;
13877}
13878
13879// Guess at what the return type for an unresolvable overload should be.
13882 std::optional<QualType> Result;
13883 // Adjust Type after seeing a candidate.
13884 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13885 if (!Candidate.Function)
13886 return;
13887 if (Candidate.Function->isInvalidDecl())
13888 return;
13889 QualType T = Candidate.Function->getReturnType();
13890 if (T.isNull())
13891 return;
13892 if (!Result)
13893 Result = T;
13894 else if (Result != T)
13895 Result = QualType();
13896 };
13897
13898 // Look for an unambiguous type from a progressively larger subset.
13899 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13900 //
13901 // First, consider only the best candidate.
13902 if (Best && *Best != CS.end())
13903 ConsiderCandidate(**Best);
13904 // Next, consider only viable candidates.
13905 if (!Result)
13906 for (const auto &C : CS)
13907 if (C.Viable)
13908 ConsiderCandidate(C);
13909 // Finally, consider all candidates.
13910 if (!Result)
13911 for (const auto &C : CS)
13912 ConsiderCandidate(C);
13913
13914 if (!Result)
13915 return QualType();
13916 auto Value = *Result;
13917 if (Value.isNull() || Value->isUndeducedType())
13918 return QualType();
13919 return Value;
13920}
13921
13922/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13923/// the completed call expression. If overload resolution fails, emits
13924/// diagnostics and returns ExprError()
13927 SourceLocation LParenLoc,
13928 MultiExprArg Args,
13929 SourceLocation RParenLoc,
13930 Expr *ExecConfig,
13931 OverloadCandidateSet *CandidateSet,
13933 OverloadingResult OverloadResult,
13934 bool AllowTypoCorrection) {
13935 switch (OverloadResult) {
13936 case OR_Success: {
13937 FunctionDecl *FDecl = (*Best)->Function;
13938 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13939 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13940 return ExprError();
13941 ExprResult Res =
13942 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13943 if (Res.isInvalid())
13944 return ExprError();
13945 return SemaRef.BuildResolvedCallExpr(
13946 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
13947 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
13948 }
13949
13950 case OR_No_Viable_Function: {
13951 if (*Best != CandidateSet->end() &&
13952 CandidateSet->getKind() ==
13954 if (CXXMethodDecl *M =
13955 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
13957 CandidateSet->NoteCandidates(
13959 Fn->getBeginLoc(),
13960 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
13961 SemaRef, OCD_AmbiguousCandidates, Args);
13962 return ExprError();
13963 }
13964 }
13965
13966 // Try to recover by looking for viable functions which the user might
13967 // have meant to call.
13968 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13969 Args, RParenLoc,
13970 CandidateSet->empty(),
13971 AllowTypoCorrection);
13972 if (Recovery.isInvalid() || Recovery.isUsable())
13973 return Recovery;
13974
13975 // If the user passes in a function that we can't take the address of, we
13976 // generally end up emitting really bad error messages. Here, we attempt to
13977 // emit better ones.
13978 for (const Expr *Arg : Args) {
13979 if (!Arg->getType()->isFunctionType())
13980 continue;
13981 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13982 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13983 if (FD &&
13984 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13985 Arg->getExprLoc()))
13986 return ExprError();
13987 }
13988 }
13989
13990 CandidateSet->NoteCandidates(
13992 Fn->getBeginLoc(),
13993 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13994 << ULE->getName() << Fn->getSourceRange()),
13995 SemaRef, OCD_AllCandidates, Args);
13996 break;
13997 }
13998
13999 case OR_Ambiguous:
14000 CandidateSet->NoteCandidates(
14001 PartialDiagnosticAt(Fn->getBeginLoc(),
14002 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14003 << ULE->getName() << Fn->getSourceRange()),
14004 SemaRef, OCD_AmbiguousCandidates, Args);
14005 break;
14006
14007 case OR_Deleted: {
14008 FunctionDecl *FDecl = (*Best)->Function;
14009 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14010 Fn->getSourceRange(), ULE->getName(),
14011 *CandidateSet, FDecl, Args);
14012
14013 // We emitted an error for the unavailable/deleted function call but keep
14014 // the call in the AST.
14015 ExprResult Res =
14016 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14017 if (Res.isInvalid())
14018 return ExprError();
14019 return SemaRef.BuildResolvedCallExpr(
14020 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14021 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14022 }
14023 }
14024
14025 // Overload resolution failed, try to recover.
14026 SmallVector<Expr *, 8> SubExprs = {Fn};
14027 SubExprs.append(Args.begin(), Args.end());
14028 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14029 chooseRecoveryType(*CandidateSet, Best));
14030}
14031
14034 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14035 if (I->Viable &&
14036 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14037 I->Viable = false;
14038 I->FailureKind = ovl_fail_addr_not_available;
14039 }
14040 }
14041}
14042
14045 SourceLocation LParenLoc,
14046 MultiExprArg Args,
14047 SourceLocation RParenLoc,
14048 Expr *ExecConfig,
14049 bool AllowTypoCorrection,
14050 bool CalleesAddressIsTaken) {
14051 OverloadCandidateSet CandidateSet(
14052 Fn->getExprLoc(), CalleesAddressIsTaken
14055 ExprResult result;
14056
14057 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14058 &result))
14059 return result;
14060
14061 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14062 // functions that aren't addressible are considered unviable.
14063 if (CalleesAddressIsTaken)
14064 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14065
14067 OverloadingResult OverloadResult =
14068 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14069
14070 // Model the case with a call to a templated function whose definition
14071 // encloses the call and whose return type contains a placeholder type as if
14072 // the UnresolvedLookupExpr was type-dependent.
14073 if (OverloadResult == OR_Success) {
14074 const FunctionDecl *FDecl = Best->Function;
14075 if (FDecl && FDecl->isTemplateInstantiation() &&
14076 FDecl->getReturnType()->isUndeducedType()) {
14077 if (const auto *TP =
14078 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14079 TP && TP->willHaveBody()) {
14080 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14081 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14082 }
14083 }
14084 }
14085
14086 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14087 ExecConfig, &CandidateSet, &Best,
14088 OverloadResult, AllowTypoCorrection);
14089}
14090
14094 const UnresolvedSetImpl &Fns,
14095 bool PerformADL) {
14096 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14097 PerformADL, Fns.begin(), Fns.end(),
14098 /*KnownDependent=*/false);
14099}
14100
14102 CXXConversionDecl *Method,
14103 bool HadMultipleCandidates) {
14104 // Convert the expression to match the conversion function's implicit object
14105 // parameter.
14106 ExprResult Exp;
14107 if (Method->isExplicitObjectMemberFunction())
14108 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14109 else
14110 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14111 FoundDecl, Method);
14112 if (Exp.isInvalid())
14113 return true;
14114
14115 if (Method->getParent()->isLambda() &&
14117 // This is a lambda conversion to block pointer; check if the argument
14118 // was a LambdaExpr.
14119 Expr *SubE = E;
14120 auto *CE = dyn_cast<CastExpr>(SubE);
14121 if (CE && CE->getCastKind() == CK_NoOp)
14122 SubE = CE->getSubExpr();
14123 SubE = SubE->IgnoreParens();
14124 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14125 SubE = BE->getSubExpr();
14126 if (isa<LambdaExpr>(SubE)) {
14127 // For the conversion to block pointer on a lambda expression, we
14128 // construct a special BlockLiteral instead; this doesn't really make
14129 // a difference in ARC, but outside of ARC the resulting block literal
14130 // follows the normal lifetime rules for block literals instead of being
14131 // autoreleased.
14132 PushExpressionEvaluationContext(
14133 ExpressionEvaluationContext::PotentiallyEvaluated);
14134 ExprResult BlockExp = BuildBlockForLambdaConversion(
14135 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14136 PopExpressionEvaluationContext();
14137
14138 // FIXME: This note should be produced by a CodeSynthesisContext.
14139 if (BlockExp.isInvalid())
14140 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14141 return BlockExp;
14142 }
14143 }
14144 CallExpr *CE;
14145 QualType ResultType = Method->getReturnType();
14147 ResultType = ResultType.getNonLValueExprType(Context);
14148 if (Method->isExplicitObjectMemberFunction()) {
14149 ExprResult FnExpr =
14150 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14151 HadMultipleCandidates, E->getBeginLoc());
14152 if (FnExpr.isInvalid())
14153 return ExprError();
14154 Expr *ObjectParam = Exp.get();
14155 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14156 ResultType, VK, Exp.get()->getEndLoc(),
14157 CurFPFeatureOverrides());
14158 } else {
14159 MemberExpr *ME =
14160 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14162 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14163 HadMultipleCandidates, DeclarationNameInfo(),
14165
14166 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14167 Exp.get()->getEndLoc(),
14168 CurFPFeatureOverrides());
14169 }
14170
14171 if (CheckFunctionCall(Method, CE,
14172 Method->getType()->castAs<FunctionProtoType>()))
14173 return ExprError();
14174
14175 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14176}
14177
14180 const UnresolvedSetImpl &Fns,
14181 Expr *Input, bool PerformADL) {
14183 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14185 // TODO: provide better source location info.
14186 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14187
14188 if (checkPlaceholderForOverload(*this, Input))
14189 return ExprError();
14190
14191 Expr *Args[2] = { Input, nullptr };
14192 unsigned NumArgs = 1;
14193
14194 // For post-increment and post-decrement, add the implicit '0' as
14195 // the second argument, so that we know this is a post-increment or
14196 // post-decrement.
14197 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14198 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14199 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14200 SourceLocation());
14201 NumArgs = 2;
14202 }
14203
14204 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14205
14206 if (Input->isTypeDependent()) {
14208 // [C++26][expr.unary.op][expr.pre.incr]
14209 // The * operator yields an lvalue of type
14210 // The pre/post increment operators yied an lvalue.
14211 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14212 VK = VK_LValue;
14213
14214 if (Fns.empty())
14215 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14216 OK_Ordinary, OpLoc, false,
14217 CurFPFeatureOverrides());
14218
14219 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14220 ExprResult Fn = CreateUnresolvedLookupExpr(
14221 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14222 if (Fn.isInvalid())
14223 return ExprError();
14224 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14225 Context.DependentTy, VK_PRValue, OpLoc,
14226 CurFPFeatureOverrides());
14227 }
14228
14229 // Build an empty overload set.
14231
14232 // Add the candidates from the given function set.
14233 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14234
14235 // Add operator candidates that are member functions.
14236 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14237
14238 // Add candidates from ADL.
14239 if (PerformADL) {
14240 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14241 /*ExplicitTemplateArgs*/nullptr,
14242 CandidateSet);
14243 }
14244
14245 // Add builtin operator candidates.
14246 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14247
14248 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14249
14250 // Perform overload resolution.
14252 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14253 case OR_Success: {
14254 // We found a built-in operator or an overloaded operator.
14255 FunctionDecl *FnDecl = Best->Function;
14256
14257 if (FnDecl) {
14258 Expr *Base = nullptr;
14259 // We matched an overloaded operator. Build a call to that
14260 // operator.
14261
14262 // Convert the arguments.
14263 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14264 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14265
14266 ExprResult InputInit;
14267 if (Method->isExplicitObjectMemberFunction())
14268 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14269 else
14270 InputInit = PerformImplicitObjectArgumentInitialization(
14271 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14272 if (InputInit.isInvalid())
14273 return ExprError();
14274 Base = Input = InputInit.get();
14275 } else {
14276 // Convert the arguments.
14277 ExprResult InputInit
14278 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14279 Context,
14280 FnDecl->getParamDecl(0)),
14282 Input);
14283 if (InputInit.isInvalid())
14284 return ExprError();
14285 Input = InputInit.get();
14286 }
14287
14288 // Build the actual expression node.
14289 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14290 Base, HadMultipleCandidates,
14291 OpLoc);
14292 if (FnExpr.isInvalid())
14293 return ExprError();
14294
14295 // Determine the result type.
14296 QualType ResultTy = FnDecl->getReturnType();
14298 ResultTy = ResultTy.getNonLValueExprType(Context);
14299
14300 Args[0] = Input;
14302 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14303 CurFPFeatureOverrides(), Best->IsADLCandidate);
14304
14305 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14306 return ExprError();
14307
14308 if (CheckFunctionCall(FnDecl, TheCall,
14309 FnDecl->getType()->castAs<FunctionProtoType>()))
14310 return ExprError();
14311 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14312 } else {
14313 // We matched a built-in operator. Convert the arguments, then
14314 // break out so that we will build the appropriate built-in
14315 // operator node.
14316 ExprResult InputRes = PerformImplicitConversion(
14317 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14319 if (InputRes.isInvalid())
14320 return ExprError();
14321 Input = InputRes.get();
14322 break;
14323 }
14324 }
14325
14327 // This is an erroneous use of an operator which can be overloaded by
14328 // a non-member function. Check for non-member operators which were
14329 // defined too late to be candidates.
14330 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14331 // FIXME: Recover by calling the found function.
14332 return ExprError();
14333
14334 // No viable function; fall through to handling this as a
14335 // built-in operator, which will produce an error message for us.
14336 break;
14337
14338 case OR_Ambiguous:
14339 CandidateSet.NoteCandidates(
14340 PartialDiagnosticAt(OpLoc,
14341 PDiag(diag::err_ovl_ambiguous_oper_unary)
14343 << Input->getType() << Input->getSourceRange()),
14344 *this, OCD_AmbiguousCandidates, ArgsArray,
14345 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14346 return ExprError();
14347
14348 case OR_Deleted: {
14349 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14350 // object whose method was called. Later in NoteCandidates size of ArgsArray
14351 // is passed further and it eventually ends up compared to number of
14352 // function candidate parameters which never includes the object parameter,
14353 // so slice ArgsArray to make sure apples are compared to apples.
14354 StringLiteral *Msg = Best->Function->getDeletedMessage();
14355 CandidateSet.NoteCandidates(
14356 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14358 << (Msg != nullptr)
14359 << (Msg ? Msg->getString() : StringRef())
14360 << Input->getSourceRange()),
14361 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14362 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14363 return ExprError();
14364 }
14365 }
14366
14367 // Either we found no viable overloaded operator or we matched a
14368 // built-in operator. In either case, fall through to trying to
14369 // build a built-in operation.
14370 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14371}
14372
14375 const UnresolvedSetImpl &Fns,
14376 ArrayRef<Expr *> Args, bool PerformADL) {
14377 SourceLocation OpLoc = CandidateSet.getLocation();
14378
14379 OverloadedOperatorKind ExtraOp =
14382 : OO_None;
14383
14384 // Add the candidates from the given function set. This also adds the
14385 // rewritten candidates using these functions if necessary.
14386 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14387
14388 // Add operator candidates that are member functions.
14389 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14390 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14391 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14393
14394 // In C++20, also add any rewritten member candidates.
14395 if (ExtraOp) {
14396 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14397 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14398 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14399 CandidateSet,
14401 }
14402
14403 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14404 // performed for an assignment operator (nor for operator[] nor operator->,
14405 // which don't get here).
14406 if (Op != OO_Equal && PerformADL) {
14408 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14409 /*ExplicitTemplateArgs*/ nullptr,
14410 CandidateSet);
14411 if (ExtraOp) {
14412 DeclarationName ExtraOpName =
14413 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14414 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14415 /*ExplicitTemplateArgs*/ nullptr,
14416 CandidateSet);
14417 }
14418 }
14419
14420 // Add builtin operator candidates.
14421 //
14422 // FIXME: We don't add any rewritten candidates here. This is strictly
14423 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14424 // resulting in our selecting a rewritten builtin candidate. For example:
14425 //
14426 // enum class E { e };
14427 // bool operator!=(E, E) requires false;
14428 // bool k = E::e != E::e;
14429 //
14430 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14431 // it seems unreasonable to consider rewritten builtin candidates. A core
14432 // issue has been filed proposing to removed this requirement.
14433 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14434}
14435
14438 const UnresolvedSetImpl &Fns, Expr *LHS,
14439 Expr *RHS, bool PerformADL,
14440 bool AllowRewrittenCandidates,
14441 FunctionDecl *DefaultedFn) {
14442 Expr *Args[2] = { LHS, RHS };
14443 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14444
14445 if (!getLangOpts().CPlusPlus20)
14446 AllowRewrittenCandidates = false;
14447
14449
14450 // If either side is type-dependent, create an appropriate dependent
14451 // expression.
14452 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14453 if (Fns.empty()) {
14454 // If there are no functions to store, just build a dependent
14455 // BinaryOperator or CompoundAssignment.
14458 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14459 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14460 Context.DependentTy);
14462 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14463 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14464 }
14465
14466 // FIXME: save results of ADL from here?
14467 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14468 // TODO: provide better source location info in DNLoc component.
14470 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14471 ExprResult Fn = CreateUnresolvedLookupExpr(
14472 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14473 if (Fn.isInvalid())
14474 return ExprError();
14475 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14476 Context.DependentTy, VK_PRValue, OpLoc,
14477 CurFPFeatureOverrides());
14478 }
14479
14480 // If this is the .* operator, which is not overloadable, just
14481 // create a built-in binary operator.
14482 if (Opc == BO_PtrMemD) {
14483 auto CheckPlaceholder = [&](Expr *&Arg) {
14484 ExprResult Res = CheckPlaceholderExpr(Arg);
14485 if (Res.isUsable())
14486 Arg = Res.get();
14487 return !Res.isUsable();
14488 };
14489
14490 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14491 // expression that contains placeholders (in either the LHS or RHS).
14492 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14493 return ExprError();
14494 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14495 }
14496
14497 // Always do placeholder-like conversions on the RHS.
14498 if (checkPlaceholderForOverload(*this, Args[1]))
14499 return ExprError();
14500
14501 // Do placeholder-like conversion on the LHS; note that we should
14502 // not get here with a PseudoObject LHS.
14503 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14504 if (checkPlaceholderForOverload(*this, Args[0]))
14505 return ExprError();
14506
14507 // If this is the assignment operator, we only perform overload resolution
14508 // if the left-hand side is a class or enumeration type. This is actually
14509 // a hack. The standard requires that we do overload resolution between the
14510 // various built-in candidates, but as DR507 points out, this can lead to
14511 // problems. So we do it this way, which pretty much follows what GCC does.
14512 // Note that we go the traditional code path for compound assignment forms.
14513 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14514 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14515
14516 // Build the overload set.
14519 Op, OpLoc, AllowRewrittenCandidates));
14520 if (DefaultedFn)
14521 CandidateSet.exclude(DefaultedFn);
14522 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14523
14524 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14525
14526 // Perform overload resolution.
14528 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14529 case OR_Success: {
14530 // We found a built-in operator or an overloaded operator.
14531 FunctionDecl *FnDecl = Best->Function;
14532
14533 bool IsReversed = Best->isReversed();
14534 if (IsReversed)
14535 std::swap(Args[0], Args[1]);
14536
14537 if (FnDecl) {
14538
14539 if (FnDecl->isInvalidDecl())
14540 return ExprError();
14541
14542 Expr *Base = nullptr;
14543 // We matched an overloaded operator. Build a call to that
14544 // operator.
14545
14546 OverloadedOperatorKind ChosenOp =
14548
14549 // C++2a [over.match.oper]p9:
14550 // If a rewritten operator== candidate is selected by overload
14551 // resolution for an operator@, its return type shall be cv bool
14552 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14553 !FnDecl->getReturnType()->isBooleanType()) {
14554 bool IsExtension =
14556 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14557 : diag::err_ovl_rewrite_equalequal_not_bool)
14558 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14559 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14560 Diag(FnDecl->getLocation(), diag::note_declared_at);
14561 if (!IsExtension)
14562 return ExprError();
14563 }
14564
14565 if (AllowRewrittenCandidates && !IsReversed &&
14566 CandidateSet.getRewriteInfo().isReversible()) {
14567 // We could have reversed this operator, but didn't. Check if some
14568 // reversed form was a viable candidate, and if so, if it had a
14569 // better conversion for either parameter. If so, this call is
14570 // formally ambiguous, and allowing it is an extension.
14572 for (OverloadCandidate &Cand : CandidateSet) {
14573 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14574 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14575 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14577 *this, OpLoc, Cand.Conversions[ArgIdx],
14578 Best->Conversions[ArgIdx]) ==
14580 AmbiguousWith.push_back(Cand.Function);
14581 break;
14582 }
14583 }
14584 }
14585 }
14586
14587 if (!AmbiguousWith.empty()) {
14588 bool AmbiguousWithSelf =
14589 AmbiguousWith.size() == 1 &&
14590 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14591 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14593 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14594 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14595 if (AmbiguousWithSelf) {
14596 Diag(FnDecl->getLocation(),
14597 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14598 // Mark member== const or provide matching != to disallow reversed
14599 // args. Eg.
14600 // struct S { bool operator==(const S&); };
14601 // S()==S();
14602 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14603 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14604 !MD->isConst() &&
14605 !MD->hasCXXExplicitFunctionObjectParameter() &&
14606 Context.hasSameUnqualifiedType(
14607 MD->getFunctionObjectParameterType(),
14608 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14609 Context.hasSameUnqualifiedType(
14610 MD->getFunctionObjectParameterType(),
14611 Args[0]->getType()) &&
14612 Context.hasSameUnqualifiedType(
14613 MD->getFunctionObjectParameterType(),
14614 Args[1]->getType()))
14615 Diag(FnDecl->getLocation(),
14616 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14617 } else {
14618 Diag(FnDecl->getLocation(),
14619 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14620 for (auto *F : AmbiguousWith)
14621 Diag(F->getLocation(),
14622 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14623 }
14624 }
14625 }
14626
14627 // Check for nonnull = nullable.
14628 // This won't be caught in the arg's initialization: the parameter to
14629 // the assignment operator is not marked nonnull.
14630 if (Op == OO_Equal)
14631 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14632 Args[1]->getType(), OpLoc);
14633
14634 // Convert the arguments.
14635 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14636 // Best->Access is only meaningful for class members.
14637 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14638
14639 ExprResult Arg0, Arg1;
14640 unsigned ParamIdx = 0;
14641 if (Method->isExplicitObjectMemberFunction()) {
14642 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14643 ParamIdx = 1;
14644 } else {
14645 Arg0 = PerformImplicitObjectArgumentInitialization(
14646 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14647 }
14648 Arg1 = PerformCopyInitialization(
14650 Context, FnDecl->getParamDecl(ParamIdx)),
14651 SourceLocation(), Args[1]);
14652 if (Arg0.isInvalid() || Arg1.isInvalid())
14653 return ExprError();
14654
14655 Base = Args[0] = Arg0.getAs<Expr>();
14656 Args[1] = RHS = Arg1.getAs<Expr>();
14657 } else {
14658 // Convert the arguments.
14659 ExprResult Arg0 = PerformCopyInitialization(
14661 FnDecl->getParamDecl(0)),
14662 SourceLocation(), Args[0]);
14663 if (Arg0.isInvalid())
14664 return ExprError();
14665
14666 ExprResult Arg1 =
14667 PerformCopyInitialization(
14669 FnDecl->getParamDecl(1)),
14670 SourceLocation(), Args[1]);
14671 if (Arg1.isInvalid())
14672 return ExprError();
14673 Args[0] = LHS = Arg0.getAs<Expr>();
14674 Args[1] = RHS = Arg1.getAs<Expr>();
14675 }
14676
14677 // Build the actual expression node.
14678 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14679 Best->FoundDecl, Base,
14680 HadMultipleCandidates, OpLoc);
14681 if (FnExpr.isInvalid())
14682 return ExprError();
14683
14684 // Determine the result type.
14685 QualType ResultTy = FnDecl->getReturnType();
14687 ResultTy = ResultTy.getNonLValueExprType(Context);
14688
14689 CallExpr *TheCall;
14690 ArrayRef<const Expr *> ArgsArray(Args, 2);
14691 const Expr *ImplicitThis = nullptr;
14692
14693 // We always create a CXXOperatorCallExpr, even for explicit object
14694 // members; CodeGen should take care not to emit the this pointer.
14696 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14697 CurFPFeatureOverrides(), Best->IsADLCandidate);
14698
14699 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14700 Method && Method->isImplicitObjectMemberFunction()) {
14701 // Cut off the implicit 'this'.
14702 ImplicitThis = ArgsArray[0];
14703 ArgsArray = ArgsArray.slice(1);
14704 }
14705
14706 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14707 FnDecl))
14708 return ExprError();
14709
14710 if (Op == OO_Equal) {
14711 // Check for a self move.
14712 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14713 // lifetime check.
14714 checkExprLifetime(*this, AssignedEntity{Args[0]}, Args[1]);
14715 }
14716 if (ImplicitThis) {
14717 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14718 QualType ThisTypeFromDecl = Context.getPointerType(
14719 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14720
14721 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14722 ThisTypeFromDecl);
14723 }
14724
14725 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14726 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14727 VariadicDoesNotApply);
14728
14729 ExprResult R = MaybeBindToTemporary(TheCall);
14730 if (R.isInvalid())
14731 return ExprError();
14732
14733 R = CheckForImmediateInvocation(R, FnDecl);
14734 if (R.isInvalid())
14735 return ExprError();
14736
14737 // For a rewritten candidate, we've already reversed the arguments
14738 // if needed. Perform the rest of the rewrite now.
14739 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14740 (Op == OO_Spaceship && IsReversed)) {
14741 if (Op == OO_ExclaimEqual) {
14742 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14743 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14744 } else {
14745 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14746 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14747 Expr *ZeroLiteral =
14748 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14749
14752 Ctx.Entity = FnDecl;
14753 pushCodeSynthesisContext(Ctx);
14754
14755 R = CreateOverloadedBinOp(
14756 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14757 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14758 /*AllowRewrittenCandidates=*/false);
14759
14760 popCodeSynthesisContext();
14761 }
14762 if (R.isInvalid())
14763 return ExprError();
14764 } else {
14765 assert(ChosenOp == Op && "unexpected operator name");
14766 }
14767
14768 // Make a note in the AST if we did any rewriting.
14769 if (Best->RewriteKind != CRK_None)
14770 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14771
14772 return R;
14773 } else {
14774 // We matched a built-in operator. Convert the arguments, then
14775 // break out so that we will build the appropriate built-in
14776 // operator node.
14777 ExprResult ArgsRes0 = PerformImplicitConversion(
14778 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14780 if (ArgsRes0.isInvalid())
14781 return ExprError();
14782 Args[0] = ArgsRes0.get();
14783
14784 ExprResult ArgsRes1 = PerformImplicitConversion(
14785 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14787 if (ArgsRes1.isInvalid())
14788 return ExprError();
14789 Args[1] = ArgsRes1.get();
14790 break;
14791 }
14792 }
14793
14794 case OR_No_Viable_Function: {
14795 // C++ [over.match.oper]p9:
14796 // If the operator is the operator , [...] and there are no
14797 // viable functions, then the operator is assumed to be the
14798 // built-in operator and interpreted according to clause 5.
14799 if (Opc == BO_Comma)
14800 break;
14801
14802 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14803 // compare result using '==' and '<'.
14804 if (DefaultedFn && Opc == BO_Cmp) {
14805 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14806 Args[1], DefaultedFn);
14807 if (E.isInvalid() || E.isUsable())
14808 return E;
14809 }
14810
14811 // For class as left operand for assignment or compound assignment
14812 // operator do not fall through to handling in built-in, but report that
14813 // no overloaded assignment operator found
14815 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14816 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14817 Args, OpLoc);
14818 DeferDiagsRAII DDR(*this,
14819 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14820 if (Args[0]->getType()->isRecordType() &&
14821 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14822 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14824 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14825 if (Args[0]->getType()->isIncompleteType()) {
14826 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14827 << Args[0]->getType()
14828 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14829 }
14830 } else {
14831 // This is an erroneous use of an operator which can be overloaded by
14832 // a non-member function. Check for non-member operators which were
14833 // defined too late to be candidates.
14834 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14835 // FIXME: Recover by calling the found function.
14836 return ExprError();
14837
14838 // No viable function; try to create a built-in operation, which will
14839 // produce an error. Then, show the non-viable candidates.
14840 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14841 }
14842 assert(Result.isInvalid() &&
14843 "C++ binary operator overloading is missing candidates!");
14844 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14845 return Result;
14846 }
14847
14848 case OR_Ambiguous:
14849 CandidateSet.NoteCandidates(
14850 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14852 << Args[0]->getType()
14853 << Args[1]->getType()
14854 << Args[0]->getSourceRange()
14855 << Args[1]->getSourceRange()),
14857 OpLoc);
14858 return ExprError();
14859
14860 case OR_Deleted: {
14861 if (isImplicitlyDeleted(Best->Function)) {
14862 FunctionDecl *DeletedFD = Best->Function;
14863 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14864 if (DFK.isSpecialMember()) {
14865 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14866 << Args[0]->getType()
14867 << llvm::to_underlying(DFK.asSpecialMember());
14868 } else {
14869 assert(DFK.isComparison());
14870 Diag(OpLoc, diag::err_ovl_deleted_comparison)
14871 << Args[0]->getType() << DeletedFD;
14872 }
14873
14874 // The user probably meant to call this special member. Just
14875 // explain why it's deleted.
14876 NoteDeletedFunction(DeletedFD);
14877 return ExprError();
14878 }
14879
14880 StringLiteral *Msg = Best->Function->getDeletedMessage();
14881 CandidateSet.NoteCandidates(
14883 OpLoc,
14884 PDiag(diag::err_ovl_deleted_oper)
14885 << getOperatorSpelling(Best->Function->getDeclName()
14886 .getCXXOverloadedOperator())
14887 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
14888 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
14890 OpLoc);
14891 return ExprError();
14892 }
14893 }
14894
14895 // We matched a built-in operator; build it.
14896 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14897}
14898
14900 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14901 FunctionDecl *DefaultedFn) {
14902 const ComparisonCategoryInfo *Info =
14903 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14904 // If we're not producing a known comparison category type, we can't
14905 // synthesize a three-way comparison. Let the caller diagnose this.
14906 if (!Info)
14907 return ExprResult((Expr*)nullptr);
14908
14909 // If we ever want to perform this synthesis more generally, we will need to
14910 // apply the temporary materialization conversion to the operands.
14911 assert(LHS->isGLValue() && RHS->isGLValue() &&
14912 "cannot use prvalue expressions more than once");
14913 Expr *OrigLHS = LHS;
14914 Expr *OrigRHS = RHS;
14915
14916 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14917 // each of them multiple times below.
14918 LHS = new (Context)
14919 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14920 LHS->getObjectKind(), LHS);
14921 RHS = new (Context)
14922 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14923 RHS->getObjectKind(), RHS);
14924
14925 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14926 DefaultedFn);
14927 if (Eq.isInvalid())
14928 return ExprError();
14929
14930 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14931 true, DefaultedFn);
14932 if (Less.isInvalid())
14933 return ExprError();
14934
14936 if (Info->isPartial()) {
14937 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14938 DefaultedFn);
14939 if (Greater.isInvalid())
14940 return ExprError();
14941 }
14942
14943 // Form the list of comparisons we're going to perform.
14944 struct Comparison {
14945 ExprResult Cmp;
14947 } Comparisons[4] =
14953 };
14954
14955 int I = Info->isPartial() ? 3 : 2;
14956
14957 // Combine the comparisons with suitable conditional expressions.
14959 for (; I >= 0; --I) {
14960 // Build a reference to the comparison category constant.
14961 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14962 // FIXME: Missing a constant for a comparison category. Diagnose this?
14963 if (!VI)
14964 return ExprResult((Expr*)nullptr);
14965 ExprResult ThisResult =
14966 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14967 if (ThisResult.isInvalid())
14968 return ExprError();
14969
14970 // Build a conditional unless this is the final case.
14971 if (Result.get()) {
14972 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14973 ThisResult.get(), Result.get());
14974 if (Result.isInvalid())
14975 return ExprError();
14976 } else {
14977 Result = ThisResult;
14978 }
14979 }
14980
14981 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14982 // bind the OpaqueValueExprs before they're (repeatedly) used.
14983 Expr *SyntacticForm = BinaryOperator::Create(
14984 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14985 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14986 CurFPFeatureOverrides());
14987 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14988 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14989}
14990
14992 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14993 MultiExprArg Args, SourceLocation LParenLoc) {
14994
14995 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14996 unsigned NumParams = Proto->getNumParams();
14997 unsigned NumArgsSlots =
14998 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14999 // Build the full argument list for the method call (the implicit object
15000 // parameter is placed at the beginning of the list).
15001 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15002 bool IsError = false;
15003 // Initialize the implicit object parameter.
15004 // Check the argument types.
15005 for (unsigned i = 0; i != NumParams; i++) {
15006 Expr *Arg;
15007 if (i < Args.size()) {
15008 Arg = Args[i];
15009 ExprResult InputInit =
15011 S.Context, Method->getParamDecl(i)),
15012 SourceLocation(), Arg);
15013 IsError |= InputInit.isInvalid();
15014 Arg = InputInit.getAs<Expr>();
15015 } else {
15016 ExprResult DefArg =
15017 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15018 if (DefArg.isInvalid()) {
15019 IsError = true;
15020 break;
15021 }
15022 Arg = DefArg.getAs<Expr>();
15023 }
15024
15025 MethodArgs.push_back(Arg);
15026 }
15027 return IsError;
15028}
15029
15031 SourceLocation RLoc,
15032 Expr *Base,
15033 MultiExprArg ArgExpr) {
15035 Args.push_back(Base);
15036 for (auto *e : ArgExpr) {
15037 Args.push_back(e);
15038 }
15039 DeclarationName OpName =
15040 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15041
15042 SourceRange Range = ArgExpr.empty()
15043 ? SourceRange{}
15044 : SourceRange(ArgExpr.front()->getBeginLoc(),
15045 ArgExpr.back()->getEndLoc());
15046
15047 // If either side is type-dependent, create an appropriate dependent
15048 // expression.
15050
15051 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15052 // CHECKME: no 'operator' keyword?
15053 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15054 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15055 ExprResult Fn = CreateUnresolvedLookupExpr(
15056 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15057 if (Fn.isInvalid())
15058 return ExprError();
15059 // Can't add any actual overloads yet
15060
15061 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15062 Context.DependentTy, VK_PRValue, RLoc,
15063 CurFPFeatureOverrides());
15064 }
15065
15066 // Handle placeholders
15067 UnbridgedCastsSet UnbridgedCasts;
15068 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15069 return ExprError();
15070 }
15071 // Build an empty overload set.
15073
15074 // Subscript can only be overloaded as a member function.
15075
15076 // Add operator candidates that are member functions.
15077 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15078
15079 // Add builtin operator candidates.
15080 if (Args.size() == 2)
15081 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15082
15083 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15084
15085 // Perform overload resolution.
15087 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15088 case OR_Success: {
15089 // We found a built-in operator or an overloaded operator.
15090 FunctionDecl *FnDecl = Best->Function;
15091
15092 if (FnDecl) {
15093 // We matched an overloaded operator. Build a call to that
15094 // operator.
15095
15096 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15097
15098 // Convert the arguments.
15099 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15100 SmallVector<Expr *, 2> MethodArgs;
15101
15102 // Initialize the object parameter.
15103 if (Method->isExplicitObjectMemberFunction()) {
15104 ExprResult Res =
15105 InitializeExplicitObjectArgument(*this, Args[0], Method);
15106 if (Res.isInvalid())
15107 return ExprError();
15108 Args[0] = Res.get();
15109 ArgExpr = Args;
15110 } else {
15111 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15112 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15113 if (Arg0.isInvalid())
15114 return ExprError();
15115
15116 MethodArgs.push_back(Arg0.get());
15117 }
15118
15120 *this, MethodArgs, Method, ArgExpr, LLoc);
15121 if (IsError)
15122 return ExprError();
15123
15124 // Build the actual expression node.
15125 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15126 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15128 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15129 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15130 if (FnExpr.isInvalid())
15131 return ExprError();
15132
15133 // Determine the result type
15134 QualType ResultTy = FnDecl->getReturnType();
15136 ResultTy = ResultTy.getNonLValueExprType(Context);
15137
15139 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15140 CurFPFeatureOverrides());
15141
15142 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15143 return ExprError();
15144
15145 if (CheckFunctionCall(Method, TheCall,
15146 Method->getType()->castAs<FunctionProtoType>()))
15147 return ExprError();
15148
15149 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15150 FnDecl);
15151 } else {
15152 // We matched a built-in operator. Convert the arguments, then
15153 // break out so that we will build the appropriate built-in
15154 // operator node.
15155 ExprResult ArgsRes0 = PerformImplicitConversion(
15156 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15158 if (ArgsRes0.isInvalid())
15159 return ExprError();
15160 Args[0] = ArgsRes0.get();
15161
15162 ExprResult ArgsRes1 = PerformImplicitConversion(
15163 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15165 if (ArgsRes1.isInvalid())
15166 return ExprError();
15167 Args[1] = ArgsRes1.get();
15168
15169 break;
15170 }
15171 }
15172
15173 case OR_No_Viable_Function: {
15175 CandidateSet.empty()
15176 ? (PDiag(diag::err_ovl_no_oper)
15177 << Args[0]->getType() << /*subscript*/ 0
15178 << Args[0]->getSourceRange() << Range)
15179 : (PDiag(diag::err_ovl_no_viable_subscript)
15180 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15181 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15182 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15183 return ExprError();
15184 }
15185
15186 case OR_Ambiguous:
15187 if (Args.size() == 2) {
15188 CandidateSet.NoteCandidates(
15190 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15191 << "[]" << Args[0]->getType() << Args[1]->getType()
15192 << Args[0]->getSourceRange() << Range),
15193 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15194 } else {
15195 CandidateSet.NoteCandidates(
15197 PDiag(diag::err_ovl_ambiguous_subscript_call)
15198 << Args[0]->getType()
15199 << Args[0]->getSourceRange() << Range),
15200 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15201 }
15202 return ExprError();
15203
15204 case OR_Deleted: {
15205 StringLiteral *Msg = Best->Function->getDeletedMessage();
15206 CandidateSet.NoteCandidates(
15208 PDiag(diag::err_ovl_deleted_oper)
15209 << "[]" << (Msg != nullptr)
15210 << (Msg ? Msg->getString() : StringRef())
15211 << Args[0]->getSourceRange() << Range),
15212 *this, OCD_AllCandidates, Args, "[]", LLoc);
15213 return ExprError();
15214 }
15215 }
15216
15217 // We matched a built-in operator; build it.
15218 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15219}
15220
15222 SourceLocation LParenLoc,
15223 MultiExprArg Args,
15224 SourceLocation RParenLoc,
15225 Expr *ExecConfig, bool IsExecConfig,
15226 bool AllowRecovery) {
15227 assert(MemExprE->getType() == Context.BoundMemberTy ||
15228 MemExprE->getType() == Context.OverloadTy);
15229
15230 // Dig out the member expression. This holds both the object
15231 // argument and the member function we're referring to.
15232 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15233
15234 // Determine whether this is a call to a pointer-to-member function.
15235 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15236 assert(op->getType() == Context.BoundMemberTy);
15237 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15238
15239 QualType fnType =
15240 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15241
15242 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15243 QualType resultType = proto->getCallResultType(Context);
15245
15246 // Check that the object type isn't more qualified than the
15247 // member function we're calling.
15248 Qualifiers funcQuals = proto->getMethodQuals();
15249
15250 QualType objectType = op->getLHS()->getType();
15251 if (op->getOpcode() == BO_PtrMemI)
15252 objectType = objectType->castAs<PointerType>()->getPointeeType();
15253 Qualifiers objectQuals = objectType.getQualifiers();
15254
15255 Qualifiers difference = objectQuals - funcQuals;
15256 difference.removeObjCGCAttr();
15257 difference.removeAddressSpace();
15258 if (difference) {
15259 std::string qualsString = difference.getAsString();
15260 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15261 << fnType.getUnqualifiedType()
15262 << qualsString
15263 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15264 }
15265
15267 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15268 CurFPFeatureOverrides(), proto->getNumParams());
15269
15270 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15271 call, nullptr))
15272 return ExprError();
15273
15274 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15275 return ExprError();
15276
15277 if (CheckOtherCall(call, proto))
15278 return ExprError();
15279
15280 return MaybeBindToTemporary(call);
15281 }
15282
15283 // We only try to build a recovery expr at this level if we can preserve
15284 // the return type, otherwise we return ExprError() and let the caller
15285 // recover.
15286 auto BuildRecoveryExpr = [&](QualType Type) {
15287 if (!AllowRecovery)
15288 return ExprError();
15289 std::vector<Expr *> SubExprs = {MemExprE};
15290 llvm::append_range(SubExprs, Args);
15291 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15292 Type);
15293 };
15294 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15295 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15296 RParenLoc, CurFPFeatureOverrides());
15297
15298 UnbridgedCastsSet UnbridgedCasts;
15299 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15300 return ExprError();
15301
15302 MemberExpr *MemExpr;
15303 CXXMethodDecl *Method = nullptr;
15304 bool HadMultipleCandidates = false;
15305 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15306 NestedNameSpecifier *Qualifier = nullptr;
15307 if (isa<MemberExpr>(NakedMemExpr)) {
15308 MemExpr = cast<MemberExpr>(NakedMemExpr);
15309 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15310 FoundDecl = MemExpr->getFoundDecl();
15311 Qualifier = MemExpr->getQualifier();
15312 UnbridgedCasts.restore();
15313 } else {
15314 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15315 Qualifier = UnresExpr->getQualifier();
15316
15317 QualType ObjectType = UnresExpr->getBaseType();
15318 Expr::Classification ObjectClassification
15320 : UnresExpr->getBase()->Classify(Context);
15321
15322 // Add overload candidates
15323 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15325
15326 // FIXME: avoid copy.
15327 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15328 if (UnresExpr->hasExplicitTemplateArgs()) {
15329 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15330 TemplateArgs = &TemplateArgsBuffer;
15331 }
15332
15334 E = UnresExpr->decls_end(); I != E; ++I) {
15335
15336 QualType ExplicitObjectType = ObjectType;
15337
15338 NamedDecl *Func = *I;
15339 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15340 if (isa<UsingShadowDecl>(Func))
15341 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15342
15343 bool HasExplicitParameter = false;
15344 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15345 M && M->hasCXXExplicitFunctionObjectParameter())
15346 HasExplicitParameter = true;
15347 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15348 M &&
15349 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15350 HasExplicitParameter = true;
15351
15352 if (HasExplicitParameter)
15353 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15354
15355 // Microsoft supports direct constructor calls.
15356 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15357 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15358 CandidateSet,
15359 /*SuppressUserConversions*/ false);
15360 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15361 // If explicit template arguments were provided, we can't call a
15362 // non-template member function.
15363 if (TemplateArgs)
15364 continue;
15365
15366 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15367 ObjectClassification, Args, CandidateSet,
15368 /*SuppressUserConversions=*/false);
15369 } else {
15370 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15371 I.getPair(), ActingDC, TemplateArgs,
15372 ExplicitObjectType, ObjectClassification,
15373 Args, CandidateSet,
15374 /*SuppressUserConversions=*/false);
15375 }
15376 }
15377
15378 HadMultipleCandidates = (CandidateSet.size() > 1);
15379
15380 DeclarationName DeclName = UnresExpr->getMemberName();
15381
15382 UnbridgedCasts.restore();
15383
15385 bool Succeeded = false;
15386 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15387 Best)) {
15388 case OR_Success:
15389 Method = cast<CXXMethodDecl>(Best->Function);
15390 FoundDecl = Best->FoundDecl;
15391 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15392 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15393 break;
15394 // If FoundDecl is different from Method (such as if one is a template
15395 // and the other a specialization), make sure DiagnoseUseOfDecl is
15396 // called on both.
15397 // FIXME: This would be more comprehensively addressed by modifying
15398 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15399 // being used.
15400 if (Method != FoundDecl.getDecl() &&
15401 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15402 break;
15403 Succeeded = true;
15404 break;
15405
15407 CandidateSet.NoteCandidates(
15409 UnresExpr->getMemberLoc(),
15410 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15411 << DeclName << MemExprE->getSourceRange()),
15412 *this, OCD_AllCandidates, Args);
15413 break;
15414 case OR_Ambiguous:
15415 CandidateSet.NoteCandidates(
15416 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15417 PDiag(diag::err_ovl_ambiguous_member_call)
15418 << DeclName << MemExprE->getSourceRange()),
15419 *this, OCD_AmbiguousCandidates, Args);
15420 break;
15421 case OR_Deleted:
15422 DiagnoseUseOfDeletedFunction(
15423 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15424 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15425 break;
15426 }
15427 // Overload resolution fails, try to recover.
15428 if (!Succeeded)
15429 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15430
15431 ExprResult Res =
15432 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15433 if (Res.isInvalid())
15434 return ExprError();
15435 MemExprE = Res.get();
15436
15437 // If overload resolution picked a static member
15438 // build a non-member call based on that function.
15439 if (Method->isStatic()) {
15440 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15441 ExecConfig, IsExecConfig);
15442 }
15443
15444 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15445 }
15446
15447 QualType ResultType = Method->getReturnType();
15449 ResultType = ResultType.getNonLValueExprType(Context);
15450
15451 assert(Method && "Member call to something that isn't a method?");
15452 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15453
15454 CallExpr *TheCall = nullptr;
15456 if (Method->isExplicitObjectMemberFunction()) {
15457 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15458 NewArgs))
15459 return ExprError();
15460
15461 // Build the actual expression node.
15462 ExprResult FnExpr =
15463 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15464 HadMultipleCandidates, MemExpr->getExprLoc());
15465 if (FnExpr.isInvalid())
15466 return ExprError();
15467
15468 TheCall =
15469 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15470 CurFPFeatureOverrides(), Proto->getNumParams());
15471 } else {
15472 // Convert the object argument (for a non-static member function call).
15473 // We only need to do this if there was actually an overload; otherwise
15474 // it was done at lookup.
15475 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15476 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15477 if (ObjectArg.isInvalid())
15478 return ExprError();
15479 MemExpr->setBase(ObjectArg.get());
15480 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15481 RParenLoc, CurFPFeatureOverrides(),
15482 Proto->getNumParams());
15483 }
15484
15485 // Check for a valid return type.
15486 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15487 TheCall, Method))
15488 return BuildRecoveryExpr(ResultType);
15489
15490 // Convert the rest of the arguments
15491 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15492 RParenLoc))
15493 return BuildRecoveryExpr(ResultType);
15494
15495 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15496
15497 if (CheckFunctionCall(Method, TheCall, Proto))
15498 return ExprError();
15499
15500 // In the case the method to call was not selected by the overloading
15501 // resolution process, we still need to handle the enable_if attribute. Do
15502 // that here, so it will not hide previous -- and more relevant -- errors.
15503 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15504 if (const EnableIfAttr *Attr =
15505 CheckEnableIf(Method, LParenLoc, Args, true)) {
15506 Diag(MemE->getMemberLoc(),
15507 diag::err_ovl_no_viable_member_function_in_call)
15508 << Method << Method->getSourceRange();
15509 Diag(Method->getLocation(),
15510 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15511 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15512 return ExprError();
15513 }
15514 }
15515
15516 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15517 TheCall->getDirectCallee()->isPureVirtual()) {
15518 const FunctionDecl *MD = TheCall->getDirectCallee();
15519
15520 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15521 MemExpr->performsVirtualDispatch(getLangOpts())) {
15522 Diag(MemExpr->getBeginLoc(),
15523 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15524 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15525 << MD->getParent();
15526
15527 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15528 if (getLangOpts().AppleKext)
15529 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15530 << MD->getParent() << MD->getDeclName();
15531 }
15532 }
15533
15534 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15535 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15536 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15537 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15538 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15539 MemExpr->getMemberLoc());
15540 }
15541
15542 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15543 TheCall->getDirectCallee());
15544}
15545
15548 SourceLocation LParenLoc,
15549 MultiExprArg Args,
15550 SourceLocation RParenLoc) {
15551 if (checkPlaceholderForOverload(*this, Obj))
15552 return ExprError();
15553 ExprResult Object = Obj;
15554
15555 UnbridgedCastsSet UnbridgedCasts;
15556 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15557 return ExprError();
15558
15559 assert(Object.get()->getType()->isRecordType() &&
15560 "Requires object type argument");
15561
15562 // C++ [over.call.object]p1:
15563 // If the primary-expression E in the function call syntax
15564 // evaluates to a class object of type "cv T", then the set of
15565 // candidate functions includes at least the function call
15566 // operators of T. The function call operators of T are obtained by
15567 // ordinary lookup of the name operator() in the context of
15568 // (E).operator().
15569 OverloadCandidateSet CandidateSet(LParenLoc,
15571 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15572
15573 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15574 diag::err_incomplete_object_call, Object.get()))
15575 return true;
15576
15577 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15578 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15579 LookupQualifiedName(R, Record->getDecl());
15580 R.suppressAccessDiagnostics();
15581
15582 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15583 Oper != OperEnd; ++Oper) {
15584 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15585 Object.get()->Classify(Context), Args, CandidateSet,
15586 /*SuppressUserConversion=*/false);
15587 }
15588
15589 // When calling a lambda, both the call operator, and
15590 // the conversion operator to function pointer
15591 // are considered. But when constraint checking
15592 // on the call operator fails, it will also fail on the
15593 // conversion operator as the constraints are always the same.
15594 // As the user probably does not intend to perform a surrogate call,
15595 // we filter them out to produce better error diagnostics, ie to avoid
15596 // showing 2 failed overloads instead of one.
15597 bool IgnoreSurrogateFunctions = false;
15598 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15599 const OverloadCandidate &Candidate = *CandidateSet.begin();
15600 if (!Candidate.Viable &&
15602 IgnoreSurrogateFunctions = true;
15603 }
15604
15605 // C++ [over.call.object]p2:
15606 // In addition, for each (non-explicit in C++0x) conversion function
15607 // declared in T of the form
15608 //
15609 // operator conversion-type-id () cv-qualifier;
15610 //
15611 // where cv-qualifier is the same cv-qualification as, or a
15612 // greater cv-qualification than, cv, and where conversion-type-id
15613 // denotes the type "pointer to function of (P1,...,Pn) returning
15614 // R", or the type "reference to pointer to function of
15615 // (P1,...,Pn) returning R", or the type "reference to function
15616 // of (P1,...,Pn) returning R", a surrogate call function [...]
15617 // is also considered as a candidate function. Similarly,
15618 // surrogate call functions are added to the set of candidate
15619 // functions for each conversion function declared in an
15620 // accessible base class provided the function is not hidden
15621 // within T by another intervening declaration.
15622 const auto &Conversions =
15623 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15624 for (auto I = Conversions.begin(), E = Conversions.end();
15625 !IgnoreSurrogateFunctions && I != E; ++I) {
15626 NamedDecl *D = *I;
15627 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15628 if (isa<UsingShadowDecl>(D))
15629 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15630
15631 // Skip over templated conversion functions; they aren't
15632 // surrogates.
15633 if (isa<FunctionTemplateDecl>(D))
15634 continue;
15635
15636 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15637 if (!Conv->isExplicit()) {
15638 // Strip the reference type (if any) and then the pointer type (if
15639 // any) to get down to what might be a function type.
15640 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15641 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15642 ConvType = ConvPtrType->getPointeeType();
15643
15644 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15645 {
15646 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15647 Object.get(), Args, CandidateSet);
15648 }
15649 }
15650 }
15651
15652 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15653
15654 // Perform overload resolution.
15656 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15657 Best)) {
15658 case OR_Success:
15659 // Overload resolution succeeded; we'll build the appropriate call
15660 // below.
15661 break;
15662
15663 case OR_No_Viable_Function: {
15665 CandidateSet.empty()
15666 ? (PDiag(diag::err_ovl_no_oper)
15667 << Object.get()->getType() << /*call*/ 1
15668 << Object.get()->getSourceRange())
15669 : (PDiag(diag::err_ovl_no_viable_object_call)
15670 << Object.get()->getType() << Object.get()->getSourceRange());
15671 CandidateSet.NoteCandidates(
15672 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15673 OCD_AllCandidates, Args);
15674 break;
15675 }
15676 case OR_Ambiguous:
15677 if (!R.isAmbiguous())
15678 CandidateSet.NoteCandidates(
15679 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15680 PDiag(diag::err_ovl_ambiguous_object_call)
15681 << Object.get()->getType()
15682 << Object.get()->getSourceRange()),
15683 *this, OCD_AmbiguousCandidates, Args);
15684 break;
15685
15686 case OR_Deleted: {
15687 // FIXME: Is this diagnostic here really necessary? It seems that
15688 // 1. we don't have any tests for this diagnostic, and
15689 // 2. we already issue err_deleted_function_use for this later on anyway.
15690 StringLiteral *Msg = Best->Function->getDeletedMessage();
15691 CandidateSet.NoteCandidates(
15692 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15693 PDiag(diag::err_ovl_deleted_object_call)
15694 << Object.get()->getType() << (Msg != nullptr)
15695 << (Msg ? Msg->getString() : StringRef())
15696 << Object.get()->getSourceRange()),
15697 *this, OCD_AllCandidates, Args);
15698 break;
15699 }
15700 }
15701
15702 if (Best == CandidateSet.end())
15703 return true;
15704
15705 UnbridgedCasts.restore();
15706
15707 if (Best->Function == nullptr) {
15708 // Since there is no function declaration, this is one of the
15709 // surrogate candidates. Dig out the conversion function.
15710 CXXConversionDecl *Conv
15711 = cast<CXXConversionDecl>(
15712 Best->Conversions[0].UserDefined.ConversionFunction);
15713
15714 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15715 Best->FoundDecl);
15716 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15717 return ExprError();
15718 assert(Conv == Best->FoundDecl.getDecl() &&
15719 "Found Decl & conversion-to-functionptr should be same, right?!");
15720 // We selected one of the surrogate functions that converts the
15721 // object parameter to a function pointer. Perform the conversion
15722 // on the object argument, then let BuildCallExpr finish the job.
15723
15724 // Create an implicit member expr to refer to the conversion operator.
15725 // and then call it.
15726 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15727 Conv, HadMultipleCandidates);
15728 if (Call.isInvalid())
15729 return ExprError();
15730 // Record usage of conversion in an implicit cast.
15732 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15733 nullptr, VK_PRValue, CurFPFeatureOverrides());
15734
15735 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15736 }
15737
15738 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15739
15740 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15741 // that calls this method, using Object for the implicit object
15742 // parameter and passing along the remaining arguments.
15743 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15744
15745 // An error diagnostic has already been printed when parsing the declaration.
15746 if (Method->isInvalidDecl())
15747 return ExprError();
15748
15749 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15750 unsigned NumParams = Proto->getNumParams();
15751
15752 DeclarationNameInfo OpLocInfo(
15753 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15754 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15755 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15756 Obj, HadMultipleCandidates,
15757 OpLocInfo.getLoc(),
15758 OpLocInfo.getInfo());
15759 if (NewFn.isInvalid())
15760 return true;
15761
15762 SmallVector<Expr *, 8> MethodArgs;
15763 MethodArgs.reserve(NumParams + 1);
15764
15765 bool IsError = false;
15766
15767 // Initialize the object parameter.
15769 if (Method->isExplicitObjectMemberFunction()) {
15770 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15771 } else {
15772 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15773 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15774 if (ObjRes.isInvalid())
15775 IsError = true;
15776 else
15777 Object = ObjRes;
15778 MethodArgs.push_back(Object.get());
15779 }
15780
15782 *this, MethodArgs, Method, Args, LParenLoc);
15783
15784 // If this is a variadic call, handle args passed through "...".
15785 if (Proto->isVariadic()) {
15786 // Promote the arguments (C99 6.5.2.2p7).
15787 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15788 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15789 nullptr);
15790 IsError |= Arg.isInvalid();
15791 MethodArgs.push_back(Arg.get());
15792 }
15793 }
15794
15795 if (IsError)
15796 return true;
15797
15798 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15799
15800 // Once we've built TheCall, all of the expressions are properly owned.
15801 QualType ResultTy = Method->getReturnType();
15803 ResultTy = ResultTy.getNonLValueExprType(Context);
15804
15806 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15807 CurFPFeatureOverrides());
15808
15809 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15810 return true;
15811
15812 if (CheckFunctionCall(Method, TheCall, Proto))
15813 return true;
15814
15815 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15816}
15817
15820 bool *NoArrowOperatorFound) {
15821 assert(Base->getType()->isRecordType() &&
15822 "left-hand side must have class type");
15823
15825 return ExprError();
15826
15827 SourceLocation Loc = Base->getExprLoc();
15828
15829 // C++ [over.ref]p1:
15830 //
15831 // [...] An expression x->m is interpreted as (x.operator->())->m
15832 // for a class object x of type T if T::operator->() exists and if
15833 // the operator is selected as the best match function by the
15834 // overload resolution mechanism (13.3).
15835 DeclarationName OpName =
15836 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15838
15839 if (RequireCompleteType(Loc, Base->getType(),
15840 diag::err_typecheck_incomplete_tag, Base))
15841 return ExprError();
15842
15843 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15844 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15846
15847 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15848 Oper != OperEnd; ++Oper) {
15849 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15850 std::nullopt, CandidateSet,
15851 /*SuppressUserConversion=*/false);
15852 }
15853
15854 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15855
15856 // Perform overload resolution.
15858 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15859 case OR_Success:
15860 // Overload resolution succeeded; we'll build the call below.
15861 break;
15862
15863 case OR_No_Viable_Function: {
15864 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15865 if (CandidateSet.empty()) {
15866 QualType BaseType = Base->getType();
15867 if (NoArrowOperatorFound) {
15868 // Report this specific error to the caller instead of emitting a
15869 // diagnostic, as requested.
15870 *NoArrowOperatorFound = true;
15871 return ExprError();
15872 }
15873 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15874 << BaseType << Base->getSourceRange();
15875 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15876 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15877 << FixItHint::CreateReplacement(OpLoc, ".");
15878 }
15879 } else
15880 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15881 << "operator->" << Base->getSourceRange();
15882 CandidateSet.NoteCandidates(*this, Base, Cands);
15883 return ExprError();
15884 }
15885 case OR_Ambiguous:
15886 if (!R.isAmbiguous())
15887 CandidateSet.NoteCandidates(
15888 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15889 << "->" << Base->getType()
15890 << Base->getSourceRange()),
15892 return ExprError();
15893
15894 case OR_Deleted: {
15895 StringLiteral *Msg = Best->Function->getDeletedMessage();
15896 CandidateSet.NoteCandidates(
15897 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15898 << "->" << (Msg != nullptr)
15899 << (Msg ? Msg->getString() : StringRef())
15900 << Base->getSourceRange()),
15901 *this, OCD_AllCandidates, Base);
15902 return ExprError();
15903 }
15904 }
15905
15906 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15907
15908 // Convert the object parameter.
15909 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15910
15911 if (Method->isExplicitObjectMemberFunction()) {
15912 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
15913 if (R.isInvalid())
15914 return ExprError();
15915 Base = R.get();
15916 } else {
15917 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
15918 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15919 if (BaseResult.isInvalid())
15920 return ExprError();
15921 Base = BaseResult.get();
15922 }
15923
15924 // Build the operator call.
15925 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15926 Base, HadMultipleCandidates, OpLoc);
15927 if (FnExpr.isInvalid())
15928 return ExprError();
15929
15930 QualType ResultTy = Method->getReturnType();
15932 ResultTy = ResultTy.getNonLValueExprType(Context);
15933
15934 CallExpr *TheCall =
15935 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15936 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15937
15938 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15939 return ExprError();
15940
15941 if (CheckFunctionCall(Method, TheCall,
15942 Method->getType()->castAs<FunctionProtoType>()))
15943 return ExprError();
15944
15945 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15946}
15947
15949 DeclarationNameInfo &SuffixInfo,
15950 ArrayRef<Expr*> Args,
15951 SourceLocation LitEndLoc,
15952 TemplateArgumentListInfo *TemplateArgs) {
15953 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15954
15955 OverloadCandidateSet CandidateSet(UDSuffixLoc,
15957 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15958 TemplateArgs);
15959
15960 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15961
15962 // Perform overload resolution. This will usually be trivial, but might need
15963 // to perform substitutions for a literal operator template.
15965 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15966 case OR_Success:
15967 case OR_Deleted:
15968 break;
15969
15971 CandidateSet.NoteCandidates(
15972 PartialDiagnosticAt(UDSuffixLoc,
15973 PDiag(diag::err_ovl_no_viable_function_in_call)
15974 << R.getLookupName()),
15975 *this, OCD_AllCandidates, Args);
15976 return ExprError();
15977
15978 case OR_Ambiguous:
15979 CandidateSet.NoteCandidates(
15980 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15981 << R.getLookupName()),
15982 *this, OCD_AmbiguousCandidates, Args);
15983 return ExprError();
15984 }
15985
15986 FunctionDecl *FD = Best->Function;
15987 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15988 nullptr, HadMultipleCandidates,
15989 SuffixInfo.getLoc(),
15990 SuffixInfo.getInfo());
15991 if (Fn.isInvalid())
15992 return true;
15993
15994 // Check the argument types. This should almost always be a no-op, except
15995 // that array-to-pointer decay is applied to string literals.
15996 Expr *ConvArgs[2];
15997 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15998 ExprResult InputInit = PerformCopyInitialization(
16000 SourceLocation(), Args[ArgIdx]);
16001 if (InputInit.isInvalid())
16002 return true;
16003 ConvArgs[ArgIdx] = InputInit.get();
16004 }
16005
16006 QualType ResultTy = FD->getReturnType();
16008 ResultTy = ResultTy.getNonLValueExprType(Context);
16009
16011 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16012 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16013
16014 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16015 return ExprError();
16016
16017 if (CheckFunctionCall(FD, UDL, nullptr))
16018 return ExprError();
16019
16020 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16021}
16022
16025 SourceLocation RangeLoc,
16026 const DeclarationNameInfo &NameInfo,
16027 LookupResult &MemberLookup,
16028 OverloadCandidateSet *CandidateSet,
16030 Scope *S = nullptr;
16031
16033 if (!MemberLookup.empty()) {
16034 ExprResult MemberRef =
16035 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16036 /*IsPtr=*/false, CXXScopeSpec(),
16037 /*TemplateKWLoc=*/SourceLocation(),
16038 /*FirstQualifierInScope=*/nullptr,
16039 MemberLookup,
16040 /*TemplateArgs=*/nullptr, S);
16041 if (MemberRef.isInvalid()) {
16042 *CallExpr = ExprError();
16043 return FRS_DiagnosticIssued;
16044 }
16045 *CallExpr =
16046 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16047 if (CallExpr->isInvalid()) {
16048 *CallExpr = ExprError();
16049 return FRS_DiagnosticIssued;
16050 }
16051 } else {
16052 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16054 NameInfo, UnresolvedSet<0>());
16055 if (FnR.isInvalid())
16056 return FRS_DiagnosticIssued;
16057 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16058
16059 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16060 CandidateSet, CallExpr);
16061 if (CandidateSet->empty() || CandidateSetError) {
16062 *CallExpr = ExprError();
16063 return FRS_NoViableFunction;
16064 }
16066 OverloadingResult OverloadResult =
16067 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16068
16069 if (OverloadResult == OR_No_Viable_Function) {
16070 *CallExpr = ExprError();
16071 return FRS_NoViableFunction;
16072 }
16073 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16074 Loc, nullptr, CandidateSet, &Best,
16075 OverloadResult,
16076 /*AllowTypoCorrection=*/false);
16077 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16078 *CallExpr = ExprError();
16079 return FRS_DiagnosticIssued;
16080 }
16081 }
16082 return FRS_Success;
16083}
16084
16086 FunctionDecl *Fn) {
16087 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16088 ExprResult SubExpr =
16089 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16090 if (SubExpr.isInvalid())
16091 return ExprError();
16092 if (SubExpr.get() == PE->getSubExpr())
16093 return PE;
16094
16095 return new (Context)
16096 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16097 }
16098
16099 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16100 ExprResult SubExpr =
16101 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16102 if (SubExpr.isInvalid())
16103 return ExprError();
16104 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16105 SubExpr.get()->getType()) &&
16106 "Implicit cast type cannot be determined from overload");
16107 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16108 if (SubExpr.get() == ICE->getSubExpr())
16109 return ICE;
16110
16111 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16112 SubExpr.get(), nullptr, ICE->getValueKind(),
16113 CurFPFeatureOverrides());
16114 }
16115
16116 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16117 if (!GSE->isResultDependent()) {
16118 ExprResult SubExpr =
16119 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16120 if (SubExpr.isInvalid())
16121 return ExprError();
16122 if (SubExpr.get() == GSE->getResultExpr())
16123 return GSE;
16124
16125 // Replace the resulting type information before rebuilding the generic
16126 // selection expression.
16127 ArrayRef<Expr *> A = GSE->getAssocExprs();
16128 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16129 unsigned ResultIdx = GSE->getResultIndex();
16130 AssocExprs[ResultIdx] = SubExpr.get();
16131
16132 if (GSE->isExprPredicate())
16134 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16135 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16136 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16137 ResultIdx);
16139 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16140 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16141 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16142 ResultIdx);
16143 }
16144 // Rather than fall through to the unreachable, return the original generic
16145 // selection expression.
16146 return GSE;
16147 }
16148
16149 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16150 assert(UnOp->getOpcode() == UO_AddrOf &&
16151 "Can only take the address of an overloaded function");
16152 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16153 if (!Method->isImplicitObjectMemberFunction()) {
16154 // Do nothing: the address of static and
16155 // explicit object member functions is a (non-member) function pointer.
16156 } else {
16157 // Fix the subexpression, which really has to be an
16158 // UnresolvedLookupExpr holding an overloaded member function
16159 // or template.
16160 ExprResult SubExpr =
16161 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16162 if (SubExpr.isInvalid())
16163 return ExprError();
16164 if (SubExpr.get() == UnOp->getSubExpr())
16165 return UnOp;
16166
16167 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16168 SubExpr.get(), Method))
16169 return ExprError();
16170
16171 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16172 "fixed to something other than a decl ref");
16173 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16174 "fixed to a member ref with no nested name qualifier");
16175
16176 // We have taken the address of a pointer to member
16177 // function. Perform the computation here so that we get the
16178 // appropriate pointer to member type.
16179 QualType ClassType
16180 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16181 QualType MemPtrType
16182 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16183 // Under the MS ABI, lock down the inheritance model now.
16184 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16185 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16186
16187 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16188 MemPtrType, VK_PRValue, OK_Ordinary,
16189 UnOp->getOperatorLoc(), false,
16190 CurFPFeatureOverrides());
16191 }
16192 }
16193 ExprResult SubExpr =
16194 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16195 if (SubExpr.isInvalid())
16196 return ExprError();
16197 if (SubExpr.get() == UnOp->getSubExpr())
16198 return UnOp;
16199
16200 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16201 SubExpr.get());
16202 }
16203
16204 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16205 // FIXME: avoid copy.
16206 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16207 if (ULE->hasExplicitTemplateArgs()) {
16208 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16209 TemplateArgs = &TemplateArgsBuffer;
16210 }
16211
16212 QualType Type = Fn->getType();
16213 ExprValueKind ValueKind =
16214 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16215 ? VK_LValue
16216 : VK_PRValue;
16217
16218 // FIXME: Duplicated from BuildDeclarationNameExpr.
16219 if (unsigned BID = Fn->getBuiltinID()) {
16220 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16221 Type = Context.BuiltinFnTy;
16222 ValueKind = VK_PRValue;
16223 }
16224 }
16225
16226 DeclRefExpr *DRE = BuildDeclRefExpr(
16227 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16228 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16229 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16230 return DRE;
16231 }
16232
16233 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16234 // FIXME: avoid copy.
16235 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16236 if (MemExpr->hasExplicitTemplateArgs()) {
16237 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16238 TemplateArgs = &TemplateArgsBuffer;
16239 }
16240
16241 Expr *Base;
16242
16243 // If we're filling in a static method where we used to have an
16244 // implicit member access, rewrite to a simple decl ref.
16245 if (MemExpr->isImplicitAccess()) {
16246 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16247 DeclRefExpr *DRE = BuildDeclRefExpr(
16248 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16249 MemExpr->getQualifierLoc(), Found.getDecl(),
16250 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16251 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16252 return DRE;
16253 } else {
16254 SourceLocation Loc = MemExpr->getMemberLoc();
16255 if (MemExpr->getQualifier())
16256 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16257 Base =
16258 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16259 }
16260 } else
16261 Base = MemExpr->getBase();
16262
16263 ExprValueKind valueKind;
16264 QualType type;
16265 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16266 valueKind = VK_LValue;
16267 type = Fn->getType();
16268 } else {
16269 valueKind = VK_PRValue;
16270 type = Context.BoundMemberTy;
16271 }
16272
16273 return BuildMemberExpr(
16274 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16275 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16276 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16277 type, valueKind, OK_Ordinary, TemplateArgs);
16278 }
16279
16280 llvm_unreachable("Invalid reference to overloaded function");
16281}
16282
16285 FunctionDecl *Fn) {
16286 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16287}
16288
16289bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16291 if (!PartialOverloading || !Function)
16292 return true;
16293 if (Function->isVariadic())
16294 return false;
16295 if (const auto *Proto =
16296 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16297 if (Proto->isTemplateVariadic())
16298 return false;
16299 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16300 if (const auto *Proto =
16301 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16302 if (Proto->isTemplateVariadic())
16303 return false;
16304 return true;
16305}
16306
16308 DeclarationName Name,
16309 OverloadCandidateSet &CandidateSet,
16310 FunctionDecl *Fn, MultiExprArg Args,
16311 bool IsMember) {
16312 StringLiteral *Msg = Fn->getDeletedMessage();
16313 CandidateSet.NoteCandidates(
16314 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16315 << IsMember << Name << (Msg != nullptr)
16316 << (Msg ? Msg->getString() : StringRef())
16317 << Range),
16318 *this, OCD_AllCandidates, Args);
16319}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3338
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)
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
LangStandard::Kind Std
#define X(type, name)
Definition: Value.h:143
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static std::string getName(const CallEvent &Call)
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:5814
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
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 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
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 std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static 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 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 shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
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 NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, PackFold PackFold=PackFold::ParameterToArgument)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
__device__ __2f16 b
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:869
iterator end()
Definition: Lookup.h:893
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:885
iterator begin()
Definition: Lookup.h:892
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:890
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:397
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
APFloat & getFloat()
Definition: APValue.h:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
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:1127
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:1127
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:663
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1130
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:2625
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:2641
CanQualType DoubleTy
Definition: ASTContext.h:1130
CanQualType LongDoubleTy
Definition: ASTContext.h:1130
CanQualType Char16Ty
Definition: ASTContext.h:1125
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:1146
CanQualType NullPtrTy
Definition: ASTContext.h:1145
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:1634
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:661
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:796
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:1130
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:2322
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:1119
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:779
CanQualType Float128Ty
Definition: ASTContext.h:1130
CanQualType UnsignedLongTy
Definition: ASTContext.h:1128
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:2921
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1322
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1146
CanQualType CharTy
Definition: ASTContext.h:1120
CanQualType IntTy
Definition: ASTContext.h:1127
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
CanQualType SignedCharTy
Definition: ASTContext.h:1127
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1146
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2114
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
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:2391
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1129
CanQualType BuiltinFnTy
Definition: ASTContext.h:1148
CanQualType VoidTy
Definition: ASTContext.h:1118
CanQualType UnsignedCharTy
Definition: ASTContext.h:1128
CanQualType UnsignedIntTy
Definition: ASTContext.h:1128
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1331
CanQualType UnknownAnyTy
Definition: ASTContext.h:1147
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1129
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1128
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:1612
CanQualType ShortTy
Definition: ASTContext.h:1127
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:1126
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2202
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:778
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:1127
CanQualType WCharTy
Definition: ASTContext.h:1121
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1124
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3540
QualType getElementType() const
Definition: Type.h:3552
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7573
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
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:3925
bool isCompoundAssignmentOp() const
Definition: Expr.h:4003
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:4804
Pointer to a block type.
Definition: Type.h:3371
This class is used for builtin types like 'int'.
Definition: Type.h:3000
Kind getKind() const
Definition: Type.h:3045
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2898
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:673
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2457
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2464
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2578
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2567
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2490
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isStatic() const
Definition: DeclCXX.cpp:2188
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:609
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1836
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:1597
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
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:3000
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3157
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:3108
QualType getElementType() const
Definition: Type.h:3118
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:4826
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
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:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2208
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1982
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
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:1452
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:261
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1205
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1159
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:296
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
bool isInvalidDecl() const
Definition: DeclBase.h:594
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:575
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:570
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
bool hasAttr() const
Definition: DeclBase.h:583
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:789
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
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:3840
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4045
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
EnumDecl * getDecl() const
Definition: Type.h:5969
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1921
const Expr * getExpr() const
Definition: DeclCXX.h:1906
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2146
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1444
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, modifiable 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:3075
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:3066
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:3290
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4102
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
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:806
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:3941
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
ExtVectorType - Extended vector type.
Definition: Type.h:4083
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
Represents a member of a struct/union/class.
Definition: Decl.h:3030
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:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3701
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4030
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3620
param_iterator param_end()
Definition: Decl.h:2659
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3524
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3719
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
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:4101
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4150
param_iterator param_begin()
Definition: Decl.h:2658
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4225
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4166
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3302
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4094
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3723
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3294
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4383
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3967
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4254
bool isConsteval() const
Definition: Decl.h:2407
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3568
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:2734
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:3573
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3680
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2558
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
unsigned getNumParams() const
Definition: Type.h:5226
Qualifiers getMethodQuals() const
Definition: Type.h:5368
QualType getParamType(unsigned i) const
Definition: Type.h:5228
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5350
ArrayRef< QualType > param_types() const
Definition: Type.h:5382
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4389
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4463
bool getNoReturn() const
Definition: Type.h:4437
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4278
ExtInfo getExtInfo() const
Definition: Type.h:4612
CallingConv getCallConv() const
Definition: Type.h:4611
QualType getReturnType() const
Definition: Type.h:4600
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4624
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:4493
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:3675
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:567
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:618
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:715
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:622
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:766
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:626
bool hasInitializerListContainerType() const
Definition: Overload.h:748
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:679
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:755
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:630
QualType getInitializerListContainerType() const
Definition: Overload.h:758
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5029
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:5136
unsigned getNumInits() const
Definition: Expr.h:5059
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2477
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5075
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2495
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:3446
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:629
Represents the results of name lookup.
Definition: Lookup.h:46
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:485
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
bool isAmbiguous() const
Definition: Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition: Lookup.h:641
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3376
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3270
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3284
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3405
Expr * getBase() const
Definition: Expr.h:3264
void setBase(Expr *E)
Definition: Expr.h:3263
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3298
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1798
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3382
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3274
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3482
QualType getPointeeType() const
Definition: Type.h:3498
const Type * getClass() const
Definition: Type.h:3512
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
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:1668
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7336
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:7392
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7481
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7450
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7404
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7444
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1799
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7456
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
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:1169
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1196
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:1210
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1162
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition: Overload.h:1033
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1029
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:1024
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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:1177
SourceLocation getLocation() const
Definition: Overload.h:1160
CandidateSetKind getKind() const
Definition: Overload.h:1161
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:2982
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3098
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3134
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3043
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3095
decls_iterator decls_begin() const
Definition: ExprCXX.h:3075
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3086
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3108
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3104
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3154
decls_iterator decls_end() const
Definition: ExprCXX.h:3078
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3092
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
Represents a parameter to a function.
Definition: Decl.h:1722
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3161
QualType getPointeeType() const
Definition: Type.h:3171
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4898
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7827
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7821
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7832
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3469
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1232
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:7925
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7743
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7869
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
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:7944
QualType getCanonicalType() const
Definition: Type.h:7795
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1093
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7915
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7816
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7864
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7789
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7775
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7683
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7690
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4349
bool hasAtomic() const
Definition: Type.h:845
bool hasRestrict() const
Definition: Type.h:844
QualifiersAndAtomic withVolatile()
Definition: Type.h:857
QualifiersAndAtomic withAtomic()
Definition: Type.h:864
bool hasVolatile() const
Definition: Type.h:842
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
GC getObjCGCAttr() const
Definition: Type.h:506
bool hasOnlyConst() const
Definition: Type.h:445
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
void removeObjCLifetime()
Definition: Type.h:538
bool hasConst() const
Definition: Type.h:444
void addRestrict()
Definition: Type.h:467
bool hasRestrict() const
Definition: Type.h:464
void removeObjCGCAttr()
Definition: Type.h:510
void removeUnaligned()
Definition: Type.h:502
void removeAddressSpace()
Definition: Type.h:583
void addConst()
Definition: Type.h:447
void setAddressSpace(LangAS space)
Definition: Type.h:578
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:695
bool hasVolatile() const
Definition: Type.h:454
bool hasObjCGCAttr() const
Definition: Type.h:505
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
std::string getAsString() const
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:732
LangAS getAddressSpace() const
Definition: Type.h:558
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:755
void addVolatile()
Definition: Type.h:457
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3464
Represents a struct/union/class.
Definition: Decl.h:4141
field_range fields() const
Definition: Decl.h:4347
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
QualType getPointeeType() const
Definition: Type.h:3420
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:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition: SemaCUDA.h:176
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:372
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:314
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition: SemaCUDA.cpp:320
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:227
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Definition: SemaObjC.cpp:1317
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:10040
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:5885
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5914
RAII class to control scope of DeferDiags.
Definition: Sema.h:9767
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:12080
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12110
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
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:2434
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:9783
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:8999
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:9011
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9007
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:169
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:1164
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:10123
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10126
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10132
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10130
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1731
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:1547
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:1002
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:597
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition: Sema.h:1204
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:600
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:694
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:10486
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:9843
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:908
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:11786
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:83
const LangOptions & getLangOpts() const
Definition: Sema.h:593
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:6394
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:1000
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:6645
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9543
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:635
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3163
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14960
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:1137
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7426
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7583
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7622
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7601
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7585
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7618
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19739
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20694
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:13471
AssignmentAction
Definition: Sema.h:6479
@ AA_Converting
Definition: Sema.h:6483
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5441
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:7477
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:7514
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:215
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:14915
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3441
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:10007
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10012
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:10013
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10011
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:10010
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:9785
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...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:1005
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2375
DiagnosticsEngine & Diags
Definition: Sema.h:1004
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9616
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:20889
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:9601
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:392
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8277
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:292
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:381
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:379
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:351
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
QualType getFromType() const
Definition: Overload.h:394
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:356
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:333
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:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:378
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:328
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:361
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:312
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:323
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:383
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:371
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:343
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition: Overload.h:308
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:347
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:338
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:388
QualType getToType(unsigned Idx) const
Definition: Overload.h:398
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:1778
StringRef getString() const
Definition: Expr.h:1855
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:655
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:708
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:693
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:244
Represents a template argument.
Definition: TemplateBase.h:61
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool isTypeAlias() const
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:203
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:220
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:6473
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3387
The base class of the type hierarchy.
Definition: Type.h:1829
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2416
bool isBlockPointerType() const
Definition: Type.h:8006
bool isVoidType() const
Definition: Type.h:8295
bool isBooleanType() const
Definition: Type.h:8423
bool isObjCBuiltinType() const
Definition: Type.h:8185
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
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:1899
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:8072
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isFloat16Type() const
Definition: Type.h:8304
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:677
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool isRValueReferenceType() const
Definition: Type.h:8018
bool isConstantArrayType() const
Definition: Type.h:8068
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8453
bool isArrayType() const
Definition: Type.h:8064
bool isCharType() const
Definition: Type.cpp:2089
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:8360
bool isArithmeticType() const
Definition: Type.cpp:2281
bool isPointerType() const
Definition: Type.h:7996
bool isArrayParameterType() const
Definition: Type.h:8080
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8335
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2480
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
bool isEnumeralType() const
Definition: Type.h:8096
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
bool isObjCQualifiedIdType() const
Definition: Type.h:8155
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8410
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2125
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8142
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2680
bool isLValueReferenceType() const
Definition: Type.h:8014
bool isBitIntType() const
Definition: Type.h:8230
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2338
bool isAnyComplexType() const
Definition: Type.h:8100
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8348
bool isHalfType() const
Definition: Type.h:8299
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8277
bool isQueueT() const
Definition: Type.h:8211
bool isMemberPointerType() const
Definition: Type.h:8046
bool isObjCIdType() const
Definition: Type.h:8167
bool isMatrixType() const
Definition: Type.h:8122
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8429
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2421
bool isEventT() const
Definition: Type.h:8203
bool isBFloat16Type() const
Definition: Type.h:8316
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7992
bool isObjCObjectPointerType() const
Definition: Type.h:8134
bool isVectorType() const
Definition: Type.h:8104
bool isObjCClassType() const
Definition: Type.h:8173
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2494
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:2196
bool isAnyPointerType() const
Definition: Type.h:8000
TypeClass getTypeClass() const
Definition: Type.h:2316
bool isSamplerT() const
Definition: Type.h:8199
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isNullPtrType() const
Definition: Type.h:8328
bool isRecordType() const
Definition: Type.h:8092
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
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:4861
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:3202
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:419
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3270
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3941
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4049
QualType getBaseType() const
Definition: ExprCXX.h:4023
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4033
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4014
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4059
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4053
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
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:947
QualType getType() const
Definition: Decl.h:678
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:33
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:275
void checkExprLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
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:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:58
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:140
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:798
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:826
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:835
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:818
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:822
@ 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:863
@ ovl_fail_too_few_arguments
Definition: Overload.h:800
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:842
@ ovl_fail_too_many_arguments
Definition: Overload.h:799
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:850
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:859
@ ovl_fail_bad_conversion
Definition: Overload.h:801
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:831
@ ovl_fail_bad_deduction
Definition: Overload.h:802
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:846
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:855
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:839
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:807
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1778
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1781
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:215
@ ICR_Conversion
Conversion.
Definition: Overload.h:232
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:244
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition: Overload.h:229
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition: Overload.h:257
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition: Overload.h:220
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:247
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:235
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:241
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition: Overload.h:238
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition: Overload.h:254
@ ICR_Promotion
Promotion.
Definition: Overload.h:223
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:217
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:251
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition: Overload.h:226
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_HLSL_Vector_Splat
Definition: Overload.h:205
@ 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:208
@ 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:445
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:268
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
@ 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:1264
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:387
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1273
@ None
The alignment was not explicit in code.
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:467
ConversionSet::const_iterator const_iterator
Definition: Overload.h:503
ConversionSet & conversions()
Definition: Overload.h:486
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:494
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:469
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:552
QualType getFromType() const
Definition: Overload.h:551
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:5058
FunctionEffectsRef FunctionEffects
Definition: Type.h:5068
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5066
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1038
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:1051
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1087
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1060
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1077
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
CallExpr::ADLCallKind IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:929
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:971
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:959
bool IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:915
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:886
bool IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:924
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:882
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:877
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:901
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:933
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:898
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:950
unsigned getNumParams() const
Definition: Overload.h:984
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:941
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:937
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:895
DeductionFailureInfo DeductionFailure
Definition: Overload.h:944
bool Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:910
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:890
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:955
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12654
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12742
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12774
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10140
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7871
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:422
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:434
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:456
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:447
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:451
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:442
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:461
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.