clang 24.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"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaARM.h"
35#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaObjC.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/DenseSet.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/STLForwardCompat.h"
43#include "llvm/ADT/ScopeExit.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdlib>
50#include <optional>
51
52using namespace clang;
53using namespace sema;
54
56
58 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
59 return P->hasAttr<PassObjectSizeAttr>();
60 });
61}
62
63/// A convenience routine for creating a decayed reference to a function.
65 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
66 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
67 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
68 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
69 return ExprError();
70 // If FoundDecl is different from Fn (such as if one is a template
71 // and the other a specialization), make sure DiagnoseUseOfDecl is
72 // called on both.
73 // FIXME: This would be more comprehensively addressed by modifying
74 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
75 // being used.
76 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
77 return ExprError();
78 DeclRefExpr *DRE = new (S.Context)
79 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
80 if (HadMultipleCandidates)
81 DRE->setHadMultipleCandidates(true);
82
84 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
85 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
86 S.ResolveExceptionSpec(Loc, FPT);
87 DRE->setType(Fn->getType());
88 }
89 }
90 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
91 CK_FunctionToPointerDecay);
92}
93
94static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
95 bool InOverloadResolution,
97 bool CStyle,
98 bool AllowObjCWritebackConversion);
99
101 QualType &ToType,
102 bool InOverloadResolution,
104 bool CStyle);
106IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
108 OverloadCandidateSet& Conversions,
109 AllowedExplicit AllowExplicit,
110 bool AllowObjCConversionOnExplicit);
111
114 const StandardConversionSequence& SCS1,
115 const StandardConversionSequence& SCS2);
116
119 const StandardConversionSequence& SCS1,
120 const StandardConversionSequence& SCS2);
121
124 const StandardConversionSequence &SCS1,
125 const StandardConversionSequence &SCS2);
126
129 const StandardConversionSequence& SCS1,
130 const StandardConversionSequence& SCS2);
131
132/// GetConversionRank - Retrieve the implicit conversion rank
133/// corresponding to the given implicit conversion kind.
135 static const ImplicitConversionRank Rank[] = {
162 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
163 // it was omitted by the patch that added
164 // ICK_Zero_Event_Conversion
165 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
166 // it was omitted by the patch that added
167 // ICK_Zero_Queue_Conversion
176 };
177 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
178 return Rank[(int)Kind];
179}
180
199
200/// GetImplicitConversionName - Return the name of this kind of
201/// implicit conversion.
203 static const char *const Name[] = {
204 "No conversion",
205 "Lvalue-to-rvalue",
206 "Array-to-pointer",
207 "Function-to-pointer",
208 "Function pointer conversion",
209 "Qualification",
210 "Integral promotion",
211 "Floating point promotion",
212 "Complex promotion",
213 "Integral conversion",
214 "Floating conversion",
215 "Complex conversion",
216 "Floating-integral conversion",
217 "Pointer conversion",
218 "Pointer-to-member conversion",
219 "Boolean conversion",
220 "Compatible-types conversion",
221 "Derived-to-base conversion",
222 "Vector conversion",
223 "SVE Vector conversion",
224 "RVV Vector conversion",
225 "Vector splat",
226 "Complex-real conversion",
227 "Block Pointer conversion",
228 "Transparent Union Conversion",
229 "Writeback conversion",
230 "OpenCL Zero Event Conversion",
231 "OpenCL Zero Queue Conversion",
232 "C specific type conversion",
233 "Incompatible pointer conversion",
234 "Fixed point conversion",
235 "HLSL vector truncation",
236 "HLSL matrix truncation",
237 "Non-decaying array conversion",
238 "HLSL vector splat",
239 "HLSL matrix splat",
240 };
241 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
242 return Name[Kind];
243}
244
245/// StandardConversionSequence - Set the standard conversion
246/// sequence to the identity conversion.
264
265/// getRank - Retrieve the rank of this standard conversion sequence
266/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
267/// implicit conversions.
280
281/// isPointerConversionToBool - Determines whether this conversion is
282/// a conversion of a pointer or pointer-to-member to bool. This is
283/// used as part of the ranking of standard conversion sequences
284/// (C++ 13.3.3.2p4).
286 // Note that FromType has not necessarily been transformed by the
287 // array-to-pointer or function-to-pointer implicit conversions, so
288 // check for their presence as well as checking whether FromType is
289 // a pointer.
290 if (getToType(1)->isBooleanType() &&
291 (getFromType()->isPointerType() ||
292 getFromType()->isMemberPointerType() ||
293 getFromType()->isObjCObjectPointerType() ||
294 getFromType()->isBlockPointerType() ||
296 return true;
297
298 return false;
299}
300
301/// isPointerConversionToVoidPointer - Determines whether this
302/// conversion is a conversion of a pointer to a void pointer. This is
303/// used as part of the ranking of standard conversion sequences (C++
304/// 13.3.3.2p4).
305bool
308 QualType FromType = getFromType();
309 QualType ToType = getToType(1);
310
311 // Note that FromType has not necessarily been transformed by the
312 // array-to-pointer implicit conversion, so check for its presence
313 // and redo the conversion to get a pointer.
315 FromType = Context.getArrayDecayedType(FromType);
316
317 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
318 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
319 return ToPtrType->getPointeeType()->isVoidType();
320
321 return false;
322}
323
324/// Skip any implicit casts which could be either part of a narrowing conversion
325/// or after one in an implicit conversion.
327 const Expr *Converted) {
328 // We can have cleanups wrapping the converted expression; these need to be
329 // preserved so that destructors run if necessary.
330 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
331 Expr *Inner =
332 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
333 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
334 EWC->getObjects());
335 }
336
337 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
338 switch (ICE->getCastKind()) {
339 case CK_NoOp:
340 case CK_IntegralCast:
341 case CK_IntegralToBoolean:
342 case CK_IntegralToFloating:
343 case CK_BooleanToSignedIntegral:
344 case CK_FloatingToIntegral:
345 case CK_FloatingToBoolean:
346 case CK_FloatingCast:
347 Converted = ICE->getSubExpr();
348 continue;
349
350 default:
351 return Converted;
352 }
353 }
354
355 return Converted;
356}
357
358/// Check if this standard conversion sequence represents a narrowing
359/// conversion, according to C++11 [dcl.init.list]p7.
360///
361/// \param Ctx The AST context.
362/// \param Converted The result of applying this standard conversion sequence.
363/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
364/// value of the expression prior to the narrowing conversion.
365/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
366/// type of the expression prior to the narrowing conversion.
367/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
368/// from floating point types to integral types should be ignored.
370 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
371 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
372 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
373 "narrowing check outside C++");
374
375 // C++11 [dcl.init.list]p7:
376 // A narrowing conversion is an implicit conversion ...
377 QualType FromType = getToType(0);
378 QualType ToType = getToType(1);
379
380 // A conversion to an enumeration type is narrowing if the conversion to
381 // the underlying type is narrowing. This only arises for expressions of
382 // the form 'Enum{init}'.
383 if (const auto *ED = ToType->getAsEnumDecl())
384 ToType = ED->getIntegerType();
385
386 switch (Second) {
387 // 'bool' is an integral type; dispatch to the right place to handle it.
389 if (FromType->isRealFloatingType())
390 goto FloatingIntegralConversion;
392 goto IntegralConversion;
393 // -- from a pointer type or pointer-to-member type to bool, or
394 return NK_Type_Narrowing;
395
396 // -- from a floating-point type to an integer type, or
397 //
398 // -- from an integer type or unscoped enumeration type to a floating-point
399 // type, except where the source is a constant expression and the actual
400 // value after conversion will fit into the target type and will produce
401 // the original value when converted back to the original type, or
403 FloatingIntegralConversion:
404 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
405 return NK_Type_Narrowing;
406 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
407 ToType->isRealFloatingType()) {
408 if (IgnoreFloatToIntegralConversion)
409 return NK_Not_Narrowing;
410 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
411 assert(Initializer && "Unknown conversion expression");
412
413 // If it's value-dependent, we can't tell whether it's narrowing.
414 if (Initializer->isValueDependent())
416
417 if (std::optional<llvm::APSInt> IntConstantValue =
418 Initializer->getIntegerConstantExpr(Ctx)) {
419 // Convert the integer to the floating type.
420 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
421 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
422 llvm::APFloat::rmNearestTiesToEven);
423 // And back.
424 llvm::APSInt ConvertedValue = *IntConstantValue;
425 bool ignored;
426 llvm::APFloat::opStatus Status = Result.convertToInteger(
427 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
428 // If the converted-back integer has unspecified value, or if the
429 // resulting value is different, this was a narrowing conversion.
430 if (Status == llvm::APFloat::opInvalidOp ||
431 *IntConstantValue != ConvertedValue) {
432 ConstantValue = APValue(*IntConstantValue);
433 ConstantType = Initializer->getType();
435 }
436 } else {
437 // Variables are always narrowings.
439 }
440 }
441 return NK_Not_Narrowing;
442
443 // -- from long double to double or float, or from double to float, except
444 // where the source is a constant expression and the actual value after
445 // conversion is within the range of values that can be represented (even
446 // if it cannot be represented exactly), or
448 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
449 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
450 // FromType is larger than ToType.
451 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
452
453 // If it's value-dependent, we can't tell whether it's narrowing.
454 if (Initializer->isValueDependent())
456
458 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
459 ((Ctx.getLangOpts().CPlusPlus &&
460 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
461 // Constant!
462 if (Ctx.getLangOpts().C23)
463 ConstantValue = R.Val;
464 assert(ConstantValue.isFloat());
465 llvm::APFloat FloatVal = ConstantValue.getFloat();
466 // Convert the source value into the target type.
467 bool ignored;
468 llvm::APFloat Converted = FloatVal;
469 llvm::APFloat::opStatus ConvertStatus =
470 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
471 llvm::APFloat::rmNearestTiesToEven, &ignored);
472 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
473 llvm::APFloat::rmNearestTiesToEven, &ignored);
474 if (Ctx.getLangOpts().C23) {
475 if (FloatVal.isNaN() && Converted.isNaN() &&
476 !FloatVal.isSignaling() && !Converted.isSignaling()) {
477 // Quiet NaNs are considered the same value, regardless of
478 // payloads.
479 return NK_Not_Narrowing;
480 }
481 // For normal values, check exact equality.
482 if (!Converted.bitwiseIsEqual(FloatVal)) {
483 ConstantType = Initializer->getType();
485 }
486 } else {
487 // If there was no overflow, the source value is within the range of
488 // values that can be represented.
489 if (ConvertStatus & llvm::APFloat::opOverflow) {
490 ConstantType = Initializer->getType();
492 }
493 }
494 } else {
496 }
497 }
498 return NK_Not_Narrowing;
499
500 // -- from an integer type or unscoped enumeration type to an integer type
501 // that cannot represent all the values of the original type, except where
502 // (CWG2627) -- the source is a bit-field whose width w is less than that
503 // of its type (or, for an enumeration type, its underlying type) and the
504 // target type can represent all the values of a hypothetical extended
505 // integer type with width w and with the same signedness as the original
506 // type or
507 // -- the source is a constant expression and the actual value after
508 // conversion will fit into the target type and will produce the original
509 // value when converted back to the original type.
511 IntegralConversion: {
512 assert(FromType->isIntegralOrUnscopedEnumerationType());
513 assert(ToType->isIntegralOrUnscopedEnumerationType());
514 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
515 unsigned FromWidth = Ctx.getIntWidth(FromType);
516 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
517 const unsigned ToWidth = Ctx.getIntWidth(ToType);
518
519 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
520 bool ToSigned, unsigned ToWidth) {
521 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
522 !(FromSigned && !ToSigned);
523 };
524
525 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // Not all values of FromType can be represented in ToType.
529 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
530
531 bool DependentBitField = false;
532 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
533 if (BitField->getBitWidth()->isValueDependent())
534 DependentBitField = true;
535 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
536 BitFieldWidth < FromWidth) {
537 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
538 return NK_Not_Narrowing;
539
540 // The initializer will be truncated to the bit-field width
541 FromWidth = BitFieldWidth;
542 }
543 }
544
545 // If it's value-dependent, we can't tell whether it's narrowing.
546 if (Initializer->isValueDependent())
548
549 std::optional<llvm::APSInt> OptInitializerValue =
550 Initializer->getIntegerConstantExpr(Ctx);
551 if (!OptInitializerValue) {
552 // If the bit-field width was dependent, it might end up being small
553 // enough to fit in the target type (unless the target type is unsigned
554 // and the source type is signed, in which case it will never fit)
555 if (DependentBitField && !(FromSigned && !ToSigned))
557
558 // Otherwise, such a conversion is always narrowing
560 }
561 llvm::APSInt &InitializerValue = *OptInitializerValue;
562 bool Narrowing = false;
563 if (FromWidth < ToWidth) {
564 // Negative -> unsigned is narrowing. Otherwise, more bits is never
565 // narrowing.
566 if (InitializerValue.isSigned() && InitializerValue.isNegative())
567 Narrowing = true;
568 } else {
569 // Add a bit to the InitializerValue so we don't have to worry about
570 // signed vs. unsigned comparisons.
571 InitializerValue =
572 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
573 // Convert the initializer to and from the target width and signed-ness.
574 llvm::APSInt ConvertedValue = InitializerValue;
575 ConvertedValue = ConvertedValue.trunc(ToWidth);
576 ConvertedValue.setIsSigned(ToSigned);
577 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
578 ConvertedValue.setIsSigned(InitializerValue.isSigned());
579 // If the result is different, this was a narrowing conversion.
580 if (ConvertedValue != InitializerValue)
581 Narrowing = true;
582 }
583 if (Narrowing) {
584 ConstantType = Initializer->getType();
585 ConstantValue = APValue(InitializerValue);
587 }
588
589 return NK_Not_Narrowing;
590 }
591 case ICK_Complex_Real:
592 if (FromType->isComplexType() && !ToType->isComplexType())
593 return NK_Type_Narrowing;
594 return NK_Not_Narrowing;
595
597 if (Ctx.getLangOpts().C23) {
598 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
600 if (Initializer->EvaluateAsRValue(R, Ctx)) {
601 ConstantValue = R.Val;
602 assert(ConstantValue.isFloat());
603 llvm::APFloat FloatVal = ConstantValue.getFloat();
604 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
605 // value, the unqualified versions of the type of the initializer and
606 // the corresponding real type of the object declared shall be
607 // compatible.
608 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
609 ConstantType = Initializer->getType();
611 }
612 }
613 }
614 return NK_Not_Narrowing;
615 default:
616 // Other kinds of conversions are not narrowings.
617 return NK_Not_Narrowing;
618 }
619}
620
621/// dump - Print this standard conversion sequence to standard
622/// error. Useful for debugging overloading issues.
623LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
624 raw_ostream &OS = llvm::errs();
625 bool PrintedSomething = false;
626 if (First != ICK_Identity) {
628 PrintedSomething = true;
629 }
630
631 if (Second != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
636
637 if (CopyConstructor) {
638 OS << " (by copy constructor)";
639 } else if (DirectBinding) {
640 OS << " (direct reference binding)";
641 } else if (ReferenceBinding) {
642 OS << " (reference binding)";
643 }
644 PrintedSomething = true;
645 }
646
647 if (Third != ICK_Identity) {
648 if (PrintedSomething) {
649 OS << " -> ";
650 }
652 PrintedSomething = true;
653 }
654
655 if (!PrintedSomething) {
656 OS << "No conversions required";
657 }
658}
659
660/// dump - Print this user-defined conversion sequence to standard
661/// error. Useful for debugging overloading issues.
663 raw_ostream &OS = llvm::errs();
664 if (Before.First || Before.Second || Before.Third) {
665 Before.dump();
666 OS << " -> ";
667 }
669 OS << '\'' << *ConversionFunction << '\'';
670 else
671 OS << "aggregate initialization";
672 if (After.First || After.Second || After.Third) {
673 OS << " -> ";
674 After.dump();
675 }
676}
677
678/// dump - Print this implicit conversion sequence to standard
679/// error. Useful for debugging overloading issues.
681 raw_ostream &OS = llvm::errs();
683 OS << "Worst list element conversion: ";
684 switch (ConversionKind) {
686 OS << "Standard conversion: ";
687 Standard.dump();
688 break;
690 OS << "User-defined conversion: ";
691 UserDefined.dump();
692 break;
694 OS << "Ellipsis conversion";
695 break;
697 OS << "Ambiguous conversion";
698 break;
699 case BadConversion:
700 OS << "Bad conversion";
701 break;
702 }
703
704 OS << "\n";
705}
706
710
712 conversions().~ConversionSet();
713}
714
715void
721
722namespace {
723 // Structure used by DeductionFailureInfo to store
724 // template argument information.
725 struct DFIArguments {
726 TemplateArgument FirstArg;
727 TemplateArgument SecondArg;
728 };
729 // Structure used by DeductionFailureInfo to store
730 // template parameter and template argument information.
731 struct DFIParamWithArguments : DFIArguments {
732 TemplateParameter Param;
733 };
734 // Structure used by DeductionFailureInfo to store template argument
735 // information and the index of the problematic call argument.
736 struct DFIDeducedMismatchArgs : DFIArguments {
737 TemplateArgumentList *TemplateArgs;
738 unsigned CallArgIndex;
739 };
740 // Structure used by DeductionFailureInfo to store information about
741 // unsatisfied constraints.
742 struct CNSInfo {
743 TemplateArgumentList *TemplateArgs;
744 ConstraintSatisfaction Satisfaction;
745 };
746}
747
748/// Convert from Sema's representation of template deduction information
749/// to the form used in overload-candidate information.
753 TemplateDeductionInfo &Info) {
755 Result.Result = static_cast<unsigned>(TDK);
756 Result.HasDiagnostic = false;
757 switch (TDK) {
764 Result.Data = nullptr;
765 break;
766
768 Result.Data = Info.Param.getOpaqueValue();
769 break;
771 Result.Data = Info.Param.getOpaqueValue();
772 if (Info.hasSFINAEDiagnostic()) {
776 Result.HasDiagnostic = true;
777 }
778 break;
779
782 // FIXME: Should allocate from normal heap so that we can free this later.
783 auto *Saved = new (Context) DFIDeducedMismatchArgs;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Saved->TemplateArgs = Info.takeSugared();
787 Saved->CallArgIndex = Info.CallArgIndex;
788 Result.Data = Saved;
789 break;
790 }
791
793 // FIXME: Should allocate from normal heap so that we can free this later.
794 DFIArguments *Saved = new (Context) DFIArguments;
795 Saved->FirstArg = Info.FirstArg;
796 Saved->SecondArg = Info.SecondArg;
797 Result.Data = Saved;
798 break;
799 }
800
802 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
805 // FIXME: Should allocate from normal heap so that we can free this later.
806 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
807 Saved->Param = Info.Param;
808 Saved->FirstArg = Info.FirstArg;
809 Saved->SecondArg = Info.SecondArg;
810 Result.Data = Saved;
811 break;
812 }
813
815 Result.Data = Info.takeSugared();
816 if (Info.hasSFINAEDiagnostic()) {
820 Result.HasDiagnostic = true;
821 }
822 break;
823
825 CNSInfo *Saved = new (Context) CNSInfo;
826 Saved->TemplateArgs = Info.takeSugared();
827 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
828 Result.Data = Saved;
829 break;
830 }
831
835 llvm_unreachable("not a deduction failure");
836 }
837
838 return Result;
839}
840
842 switch (static_cast<TemplateDeductionResult>(Result)) {
851 break;
852
859 // FIXME: Destroy the data?
860 Data = nullptr;
861 break;
862
865 // FIXME: Destroy the template argument list?
866 Data = nullptr;
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
874 // FIXME: Destroy the template argument list?
875 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
876 Data = nullptr;
878 Diag->~PartialDiagnosticAt();
879 HasDiagnostic = false;
880 }
881 break;
882
883 // Unhandled
886 break;
887 }
888}
889
891 if (HasDiagnostic)
892 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
893 return nullptr;
894}
895
929
965
997
1029
1031 switch (static_cast<TemplateDeductionResult>(Result)) {
1034 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1035
1036 default:
1037 return std::nullopt;
1038 }
1039}
1040
1042 const FunctionDecl *Y) {
1043 if (!X || !Y)
1044 return false;
1045 if (X->getNumParams() != Y->getNumParams())
1046 return false;
1047 // FIXME: when do rewritten comparison operators
1048 // with explicit object parameters correspond?
1049 // https://cplusplus.github.io/CWG/issues/2797.html
1050 for (unsigned I = 0; I < X->getNumParams(); ++I)
1051 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1052 Y->getParamDecl(I)->getType()))
1053 return false;
1054 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1055 auto *FTY = Y->getDescribedFunctionTemplate();
1056 if (!FTY)
1057 return false;
1058 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1059 FTY->getTemplateParameters()))
1060 return false;
1061 }
1062 return true;
1063}
1064
1066 Expr *FirstOperand, FunctionDecl *EqFD) {
1067 assert(EqFD->getOverloadedOperator() ==
1068 OverloadedOperatorKind::OO_EqualEqual);
1069 // C++2a [over.match.oper]p4:
1070 // A non-template function or function template F named operator== is a
1071 // rewrite target with first operand o unless a search for the name operator!=
1072 // in the scope S from the instantiation context of the operator expression
1073 // finds a function or function template that would correspond
1074 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1075 // scope of the class type of o if F is a class member, and the namespace
1076 // scope of which F is a member otherwise. A function template specialization
1077 // named operator== is a rewrite target if its function template is a rewrite
1078 // target.
1080 OverloadedOperatorKind::OO_ExclaimEqual);
1081 if (isa<CXXMethodDecl>(EqFD)) {
1082 // If F is a class member, search scope is class type of first operand.
1083 QualType RHS = FirstOperand->getType();
1084 auto *RHSRec = RHS->getAsCXXRecordDecl();
1085 if (!RHSRec)
1086 return true;
1087 LookupResult Members(S, NotEqOp, OpLoc,
1089 S.LookupQualifiedName(Members, RHSRec);
1090 Members.suppressAccessDiagnostics();
1091 for (NamedDecl *Op : Members)
1092 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1093 return false;
1094 return true;
1095 }
1096 // Otherwise the search scope is the namespace scope of which F is a member.
1097 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1098 auto *NotEqFD = Op->getAsFunction();
1099 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1100 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1101 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1103 cast<Decl>(Op->getLexicalDeclContext())))
1104 return false;
1105 }
1106 return true;
1107}
1108
1110 OverloadedOperatorKind Op) const {
1112 return false;
1113 return Op == OO_EqualEqual || Op == OO_Spaceship;
1114}
1115
1117 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1118 auto Op = FD->getOverloadedOperator();
1119 if (!allowsReversed(Op))
1120 return false;
1121 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1122 assert(OriginalArgs.size() == 2);
1124 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1125 return false;
1126 }
1127 // Don't bother adding a reversed candidate that can never be a better
1128 // match than the non-reversed version.
1129 return FD->getNumNonObjectParams() != 2 ||
1131 FD->getParamDecl(1)->getType()) ||
1132 FD->hasAttr<EnableIfAttr>();
1133}
1134
1135void OverloadCandidateSet::destroyCandidates() {
1136 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1137 for (auto &C : i->Conversions)
1138 C.~ImplicitConversionSequence();
1139 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1140 i->DeductionFailure.Destroy();
1141 }
1142}
1143
1145 destroyCandidates();
1146 SlabAllocator.Reset();
1147 NumInlineBytesUsed = 0;
1148 Candidates.clear();
1149 Functions.clear();
1150 Kind = CSK;
1151 FirstDeferredCandidate = nullptr;
1152 DeferredCandidatesCount = 0;
1153 HasDeferredTemplateConstructors = false;
1154 ResolutionByPerfectCandidateIsDisabled = false;
1155}
1156
1157namespace {
1158 class UnbridgedCastsSet {
1159 struct Entry {
1160 Expr **Addr;
1161 Expr *Saved;
1162 };
1163 SmallVector<Entry, 2> Entries;
1164
1165 public:
1166 void save(Sema &S, Expr *&E) {
1167 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1168 Entry entry = { &E, E };
1169 Entries.push_back(entry);
1170 E = S.ObjC().stripARCUnbridgedCast(E);
1171 }
1172
1173 void restore() {
1174 for (SmallVectorImpl<Entry>::iterator
1175 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1176 *i->Addr = i->Saved;
1177 }
1178 };
1179}
1180
1181/// checkPlaceholderForOverload - Do any interesting placeholder-like
1182/// preprocessing on the given expression.
1183///
1184/// \param unbridgedCasts a collection to which to add unbridged casts;
1185/// without this, they will be immediately diagnosed as errors
1186///
1187/// Return true on unrecoverable error.
1188static bool
1190 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1191 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1192 // We can't handle overloaded expressions here because overload
1193 // resolution might reasonably tweak them.
1194 if (placeholder->getKind() == BuiltinType::Overload) return false;
1195
1196 // If the context potentially accepts unbridged ARC casts, strip
1197 // the unbridged cast and add it to the collection for later restoration.
1198 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1199 unbridgedCasts) {
1200 unbridgedCasts->save(S, E);
1201 return false;
1202 }
1203
1204 // Go ahead and check everything else.
1205 ExprResult result = S.CheckPlaceholderExpr(E);
1206 if (result.isInvalid())
1207 return true;
1208
1209 E = result.get();
1210 return false;
1211 }
1212
1213 // Nothing to do.
1214 return false;
1215}
1216
1217/// checkArgPlaceholdersForOverload - Check a set of call operands for
1218/// placeholders.
1220 UnbridgedCastsSet &unbridged) {
1221 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1222 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1223 return true;
1224
1225 return false;
1226}
1227
1229 const LookupResult &Old, NamedDecl *&Match,
1230 bool NewIsUsingDecl) {
1231 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1232 I != E; ++I) {
1233 NamedDecl *OldD = *I;
1234
1235 bool OldIsUsingDecl = false;
1236 if (isa<UsingShadowDecl>(OldD)) {
1237 OldIsUsingDecl = true;
1238
1239 // We can always introduce two using declarations into the same
1240 // context, even if they have identical signatures.
1241 if (NewIsUsingDecl) continue;
1242
1243 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1244 }
1245
1246 // A using-declaration does not conflict with another declaration
1247 // if one of them is hidden.
1248 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1249 continue;
1250
1251 // If either declaration was introduced by a using declaration,
1252 // we'll need to use slightly different rules for matching.
1253 // Essentially, these rules are the normal rules, except that
1254 // function templates hide function templates with different
1255 // return types or template parameter lists.
1256 bool UseMemberUsingDeclRules =
1257 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1258 !New->getFriendObjectKind();
1259
1260 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1261 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1262 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1264 continue;
1265 }
1266
1267 if (!isa<FunctionTemplateDecl>(OldD) &&
1268 !shouldLinkPossiblyHiddenDecl(*I, New))
1269 continue;
1270
1271 Match = *I;
1272 return OverloadKind::Match;
1273 }
1274
1275 // Builtins that have custom typechecking or have a reference should
1276 // not be overloadable or redeclarable.
1277 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1278 Match = *I;
1280 }
1281 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1282 // We can overload with these, which can show up when doing
1283 // redeclaration checks for UsingDecls.
1284 assert(Old.getLookupKind() == LookupUsingDeclName);
1285 } else if (isa<TagDecl>(OldD)) {
1286 // We can always overload with tags by hiding them.
1287 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1288 // Optimistically assume that an unresolved using decl will
1289 // overload; if it doesn't, we'll have to diagnose during
1290 // template instantiation.
1291 //
1292 // Exception: if the scope is dependent and this is not a class
1293 // member, the using declaration can only introduce an enumerator.
1294 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1295 Match = *I;
1297 }
1298 } else {
1299 // (C++ 13p1):
1300 // Only function declarations can be overloaded; object and type
1301 // declarations cannot be overloaded.
1302 Match = *I;
1304 }
1305 }
1306
1307 // C++ [temp.friend]p1:
1308 // For a friend function declaration that is not a template declaration:
1309 // -- if the name of the friend is a qualified or unqualified template-id,
1310 // [...], otherwise
1311 // -- if the name of the friend is a qualified-id and a matching
1312 // non-template function is found in the specified class or namespace,
1313 // the friend declaration refers to that function, otherwise,
1314 // -- if the name of the friend is a qualified-id and a matching function
1315 // template is found in the specified class or namespace, the friend
1316 // declaration refers to the deduced specialization of that function
1317 // template, otherwise
1318 // -- the name shall be an unqualified-id [...]
1319 // If we get here for a qualified friend declaration, we've just reached the
1320 // third bullet. If the type of the friend is dependent, skip this lookup
1321 // until instantiation.
1322 if (New->getFriendObjectKind() && New->getQualifier() &&
1323 !New->getDescribedFunctionTemplate() &&
1324 !New->getDependentSpecializationInfo() &&
1325 !New->getType()->isDependentType()) {
1326 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1327 TemplateSpecResult.addAllDecls(Old);
1328 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1329 /*QualifiedFriend*/true)) {
1330 New->setInvalidDecl();
1332 }
1333
1334 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1335 return OverloadKind::Match;
1336 }
1337
1339}
1340
1341template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1342 assert(D && "function decl should not be null");
1343 if (auto *A = D->getAttr<AttrT>())
1344 return !A->isImplicit();
1345 return false;
1346}
1347
1349 FunctionDecl *Old,
1350 bool UseMemberUsingDeclRules,
1351 bool ConsiderCudaAttrs,
1352 bool UseOverrideRules = false) {
1353 // C++ [basic.start.main]p2: This function shall not be overloaded.
1354 if (New->isMain())
1355 return false;
1356
1357 // MSVCRT user defined entry points cannot be overloaded.
1358 if (New->isMSVCRTEntryPoint())
1359 return false;
1360
1361 NamedDecl *OldDecl = Old;
1362 NamedDecl *NewDecl = New;
1364 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1365
1366 // C++ [temp.fct]p2:
1367 // A function template can be overloaded with other function templates
1368 // and with normal (non-template) functions.
1369 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1370 return true;
1371
1372 // Is the function New an overload of the function Old?
1373 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1374 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1375
1376 // Compare the signatures (C++ 1.3.10) of the two functions to
1377 // determine whether they are overloads. If we find any mismatch
1378 // in the signature, they are overloads.
1379
1380 // If either of these functions is a K&R-style function (no
1381 // prototype), then we consider them to have matching signatures.
1382 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1384 return false;
1385
1386 const auto *OldType = cast<FunctionProtoType>(OldQType);
1387 const auto *NewType = cast<FunctionProtoType>(NewQType);
1388
1389 // The signature of a function includes the types of its
1390 // parameters (C++ 1.3.10), which includes the presence or absence
1391 // of the ellipsis; see C++ DR 357).
1392 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1393 return true;
1394
1395 // For member-like friends, the enclosing class is part of the signature.
1396 if ((New->isMemberLikeConstrainedFriend() ||
1398 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1399 return true;
1400
1401 // Compare the parameter lists.
1402 // This can only be done once we have establish that friend functions
1403 // inhabit the same context, otherwise we might tried to instantiate
1404 // references to non-instantiated entities during constraint substitution.
1405 // GH78101.
1406 if (NewTemplate) {
1407 OldDecl = OldTemplate;
1408 NewDecl = NewTemplate;
1409 // C++ [temp.over.link]p4:
1410 // The signature of a function template consists of its function
1411 // signature, its return type and its template parameter list. The names
1412 // of the template parameters are significant only for establishing the
1413 // relationship between the template parameters and the rest of the
1414 // signature.
1415 //
1416 // We check the return type and template parameter lists for function
1417 // templates first; the remaining checks follow.
1418 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1419 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1420 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1421 bool SameReturnType = SemaRef.Context.hasSameType(
1422 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1423 // FIXME(GH58571): Match template parameter list even for non-constrained
1424 // template heads. This currently ensures that the code prior to C++20 is
1425 // not newly broken.
1426 bool ConstraintsInTemplateHead =
1429 // C++ [namespace.udecl]p11:
1430 // The set of declarations named by a using-declarator that inhabits a
1431 // class C does not include member functions and member function
1432 // templates of a base class that "correspond" to (and thus would
1433 // conflict with) a declaration of a function or function template in
1434 // C.
1435 // Comparing return types is not required for the "correspond" check to
1436 // decide whether a member introduced by a shadow declaration is hidden.
1437 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1438 !SameTemplateParameterList)
1439 return true;
1440 if (!UseMemberUsingDeclRules &&
1441 (!SameTemplateParameterList || !SameReturnType))
1442 return true;
1443 }
1444
1445 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1446 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1447
1448 int OldParamsOffset = 0;
1449 int NewParamsOffset = 0;
1450
1451 // When determining if a method is an overload from a base class, act as if
1452 // the implicit object parameter are of the same type.
1453
1454 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1456 auto ThisType = M->getFunctionObjectParameterReferenceType();
1457 if (ThisType.isConstQualified())
1458 Q.removeConst();
1459 return Q;
1460 }
1461
1462 // We do not allow overloading based off of '__restrict'.
1463 Q.removeRestrict();
1464
1465 // We may not have applied the implicit const for a constexpr member
1466 // function yet (because we haven't yet resolved whether this is a static
1467 // or non-static member function). Add it now, on the assumption that this
1468 // is a redeclaration of OldMethod.
1469 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1470 (M->isConstexpr() || M->isConsteval()) &&
1471 !isa<CXXConstructorDecl>(NewMethod))
1472 Q.addConst();
1473 return Q;
1474 };
1475
1476 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1477 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1478 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1479
1480 if (OldMethod->isExplicitObjectMemberFunction()) {
1481 BS.Quals.removeVolatile();
1482 DS.Quals.removeVolatile();
1483 }
1484
1485 return BS.Quals == DS.Quals;
1486 };
1487
1488 auto CompareType = [&](QualType Base, QualType D) {
1489 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1490 auto DS = D.getNonReferenceType().getCanonicalType().split();
1491
1492 if (!AreQualifiersEqual(BS, DS))
1493 return false;
1494
1495 if (OldMethod->isImplicitObjectMemberFunction() &&
1496 OldMethod->getParent() != NewMethod->getParent()) {
1497 CanQualType ParentType =
1498 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1499 if (ParentType.getTypePtr() != BS.Ty)
1500 return false;
1501 BS.Ty = DS.Ty;
1502 }
1503
1504 // FIXME: should we ignore some type attributes here?
1505 if (BS.Ty != DS.Ty)
1506 return false;
1507
1508 if (Base->isLValueReferenceType())
1509 return D->isLValueReferenceType();
1510 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1511 };
1512
1513 // If the function is a class member, its signature includes the
1514 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1515 auto DiagnoseInconsistentRefQualifiers = [&]() {
1516 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1517 return false;
1518 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1519 return false;
1520 if (OldMethod->isExplicitObjectMemberFunction() ||
1521 NewMethod->isExplicitObjectMemberFunction())
1522 return false;
1523 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1524 NewMethod->getRefQualifier() == RQ_None)) {
1525 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1526 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1527 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1528 return true;
1529 }
1530 return false;
1531 };
1532
1533 // We look at the parameters first, as it is the common case.
1534 // However we should not emit diagnostic before checking
1535 // the overloads do not differ by constraints or other discriminant.
1536 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1537 bool HaveInconsistentQualifiers = false;
1538
1539 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1540 OldParamsOffset++;
1541 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1542 NewParamsOffset++;
1543
1544 if (OldType->getNumParams() - OldParamsOffset !=
1545 NewType->getNumParams() - NewParamsOffset ||
1547 {OldType->param_type_begin() + OldParamsOffset,
1548 OldType->param_type_end()},
1549 {NewType->param_type_begin() + NewParamsOffset,
1550 NewType->param_type_end()},
1551 nullptr)) {
1552 return true;
1553 }
1554
1555 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1556 !NewMethod->isStatic()) {
1557 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1558 const CXXMethodDecl *New) {
1559 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1560 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1561
1562 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1563 return F->getRefQualifier() == RQ_None &&
1564 !F->isExplicitObjectMemberFunction();
1565 };
1566
1567 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1568 CompareType(OldObjectType.getNonReferenceType(),
1569 NewObjectType.getNonReferenceType()))
1570 return true;
1571 return CompareType(OldObjectType, NewObjectType);
1572 }(OldMethod, NewMethod);
1573
1574 if (!HaveCorrespondingObjectParameters) {
1575 ShouldDiagnoseInconsistentRefQualifiers = true;
1576 // CWG2554
1577 // and, if at least one is an explicit object member function, ignoring
1578 // object parameters
1579 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1580 !OldMethod->isExplicitObjectMemberFunction()))
1581 HaveInconsistentQualifiers = true;
1582 }
1583 }
1584
1585 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1586 NewMethod->isImplicitObjectMemberFunction())
1587 ShouldDiagnoseInconsistentRefQualifiers = true;
1588
1589 if (!UseOverrideRules &&
1590 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1591 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1592 OldRC = Old->getTrailingRequiresClause();
1593 if (!NewRC != !OldRC)
1594 return true;
1595 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1596 return true;
1597 if (NewRC &&
1598 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1599 NewDecl, NewRC.ConstraintExpr))
1600 return true;
1601 }
1602
1603 // Though pass_object_size is placed on parameters and takes an argument, we
1604 // consider it to be a function-level modifier for the sake of function
1605 // identity. Either the function has one or more parameters with
1606 // pass_object_size or it doesn't.
1609 return true;
1610
1611 // enable_if attributes are an order-sensitive part of the signature.
1613 NewI = New->specific_attr_begin<EnableIfAttr>(),
1614 NewE = New->specific_attr_end<EnableIfAttr>(),
1615 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1616 OldE = Old->specific_attr_end<EnableIfAttr>();
1617 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1618 if (NewI == NewE || OldI == OldE)
1619 return true;
1620 llvm::FoldingSetNodeID NewID, OldID;
1621 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1622 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1623 if (NewID != OldID)
1624 return true;
1625 }
1626
1627 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1628 DiagnoseInconsistentRefQualifiers()) ||
1629 HaveInconsistentQualifiers)
1630 return true;
1631
1632 // At this point, it is known that the two functions have the same signature.
1633 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1634 // Don't allow overloading of destructors. (In theory we could, but it
1635 // would be a giant change to clang.)
1637 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1638 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1639 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1640 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1641 "Unexpected invalid target.");
1642
1643 // Allow overloading of functions with same signature and different CUDA
1644 // target attributes.
1645 if (NewTarget != OldTarget) {
1646 // Special case: non-constexpr function is allowed to override
1647 // constexpr virtual function
1648 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1649 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1654 return false;
1655 }
1656 return true;
1657 }
1658 }
1659 }
1660 }
1661
1662 // The signatures match; this is not an overload.
1663 return false;
1664}
1665
1667 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1668 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1669 ConsiderCudaAttrs);
1670}
1671
1673 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1674 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1675 /*UseMemberUsingDeclRules=*/false,
1676 /*ConsiderCudaAttrs=*/true,
1677 /*UseOverrideRules=*/true);
1678}
1679
1680/// Tries a user-defined conversion from From to ToType.
1681///
1682/// Produces an implicit conversion sequence for when a standard conversion
1683/// is not an option. See TryImplicitConversion for more information.
1686 bool SuppressUserConversions,
1687 AllowedExplicit AllowExplicit,
1688 bool InOverloadResolution,
1689 bool CStyle,
1690 bool AllowObjCWritebackConversion,
1691 bool AllowObjCConversionOnExplicit) {
1693
1694 if (SuppressUserConversions) {
1695 // We're not in the case above, so there is no conversion that
1696 // we can perform.
1698 return ICS;
1699 }
1700
1701 // Attempt user-defined conversion.
1702 OverloadCandidateSet Conversions(From->getExprLoc(),
1704 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1705 Conversions, AllowExplicit,
1706 AllowObjCConversionOnExplicit)) {
1707 case OR_Success:
1708 case OR_Deleted:
1709 ICS.setUserDefined();
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
1715 // constructor (i.e., a user-defined conversion function) is
1716 // called for those cases.
1718 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1719 QualType FromType;
1720 SourceLocation FromLoc;
1721 // C++11 [over.ics.list]p6, per DR2137:
1722 // C++17 [over.ics.list]p6:
1723 // If C is not an initializer-list constructor and the initializer list
1724 // has a single element of type cv U, where U is X or a class derived
1725 // from X, the implicit conversion sequence has Exact Match rank if U is
1726 // X, or Conversion rank if U is derived from X.
1727 bool FromListInit = false;
1728 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1729 InitList && InitList->getNumInits() == 1 &&
1731 const Expr *SingleInit = InitList->getInit(0);
1732 FromType = SingleInit->getType();
1733 FromLoc = SingleInit->getBeginLoc();
1734 FromListInit = true;
1735 } else {
1736 FromType = From->getType();
1737 FromLoc = From->getBeginLoc();
1738 }
1739 QualType FromCanon =
1741 QualType ToCanon
1743 if ((FromCanon == ToCanon ||
1744 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1745 // Turn this into a "standard" conversion sequence, so that it
1746 // gets ranked with standard conversion sequences.
1748 ICS.setStandard();
1750 ICS.Standard.setFromType(FromType);
1751 ICS.Standard.setAllToTypes(ToType);
1752 ICS.Standard.FromBracedInitList = FromListInit;
1755 if (ToCanon != FromCanon)
1757 }
1758 }
1759 break;
1760
1761 case OR_Ambiguous:
1762 ICS.setAmbiguous();
1763 ICS.Ambiguous.setFromType(From->getType());
1764 ICS.Ambiguous.setToType(ToType);
1765 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1766 Cand != Conversions.end(); ++Cand)
1767 if (Cand->Best)
1768 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1769 break;
1770
1771 // Fall through.
1774 break;
1775 }
1776
1777 return ICS;
1778}
1779
1780/// TryImplicitConversion - Attempt to perform an implicit conversion
1781/// from the given expression (Expr) to the given type (ToType). This
1782/// function returns an implicit conversion sequence that can be used
1783/// to perform the initialization. Given
1784///
1785/// void f(float f);
1786/// void g(int i) { f(i); }
1787///
1788/// this routine would produce an implicit conversion sequence to
1789/// describe the initialization of f from i, which will be a standard
1790/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1791/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1792//
1793/// Note that this routine only determines how the conversion can be
1794/// performed; it does not actually perform the conversion. As such,
1795/// it will not produce any diagnostics if no conversion is available,
1796/// but will instead return an implicit conversion sequence of kind
1797/// "BadConversion".
1798///
1799/// If @p SuppressUserConversions, then user-defined conversions are
1800/// not permitted.
1801/// If @p AllowExplicit, then explicit user-defined conversions are
1802/// permitted.
1803///
1804/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1805/// writeback conversion, which allows __autoreleasing id* parameters to
1806/// be initialized with __strong id* or __weak id* arguments.
1807static ImplicitConversionSequence
1809 bool SuppressUserConversions,
1810 AllowedExplicit AllowExplicit,
1811 bool InOverloadResolution,
1812 bool CStyle,
1813 bool AllowObjCWritebackConversion,
1814 bool AllowObjCConversionOnExplicit) {
1816 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1817 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1818 ICS.setStandard();
1819 return ICS;
1820 }
1821
1822 if (!S.getLangOpts().CPlusPlus) {
1824 return ICS;
1825 }
1826
1827 // C++ [over.ics.user]p4:
1828 // A conversion of an expression of class type to the same class
1829 // type is given Exact Match rank, and a conversion of an
1830 // expression of class type to a base class of that type is
1831 // given Conversion rank, in spite of the fact that a copy/move
1832 // constructor (i.e., a user-defined conversion function) is
1833 // called for those cases.
1834 QualType FromType = From->getType();
1835 if (ToType->isRecordType() &&
1836 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1837 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1838 ICS.setStandard();
1840 ICS.Standard.setFromType(FromType);
1841 ICS.Standard.setAllToTypes(ToType);
1842
1843 // We don't actually check at this point whether there is a valid
1844 // copy/move constructor, since overloading just assumes that it
1845 // exists. When we actually perform initialization, we'll find the
1846 // appropriate constructor to copy the returned object, if needed.
1847 ICS.Standard.CopyConstructor = nullptr;
1848
1849 // In HLSL, a conversion of an expression of class type to the same class
1850 // type needs implicit LvaluetoRvalue conversion.
1851 if (S.getLangOpts().HLSL)
1853
1854 // Determine whether this is considered a derived-to-base conversion.
1855 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1857
1858 return ICS;
1859 }
1860
1861 if (S.getLangOpts().HLSL) {
1862 // Handle conversion of the HLSL resource types.
1863 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1864 if (FromTy->isHLSLAttributedResourceType()) {
1865 // Attributed resource types can convert to other attributed
1866 // resource types with the same attributes and contained types,
1867 // or to __hlsl_resource_t without any attributes.
1868 bool CanConvert = false;
1869 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1870 if (ToTy->isHLSLAttributedResourceType()) {
1871 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1872 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1873 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1874 FromResType->getWrappedType()) &&
1875 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1876 FromResType->getContainedType()) &&
1877 ToResType->getAttrs() == FromResType->getAttrs())
1878 CanConvert = true;
1879 } else if (ToTy->isHLSLResourceType()) {
1880 CanConvert = true;
1881 }
1882 if (CanConvert) {
1883 ICS.setStandard();
1885 ICS.Standard.setFromType(FromType);
1886 ICS.Standard.setAllToTypes(ToType);
1887 return ICS;
1888 }
1889 }
1890 }
1891
1892 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1893 AllowExplicit, InOverloadResolution, CStyle,
1894 AllowObjCWritebackConversion,
1895 AllowObjCConversionOnExplicit);
1896}
1897
1898ImplicitConversionSequence
1900 bool SuppressUserConversions,
1901 AllowedExplicit AllowExplicit,
1902 bool InOverloadResolution,
1903 bool CStyle,
1904 bool AllowObjCWritebackConversion) {
1905 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1906 AllowExplicit, InOverloadResolution, CStyle,
1907 AllowObjCWritebackConversion,
1908 /*AllowObjCConversionOnExplicit=*/false);
1909}
1910
1912 AssignmentAction Action,
1913 bool AllowExplicit) {
1914 if (checkPlaceholderForOverload(*this, From))
1915 return ExprError();
1916
1917 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1918 bool AllowObjCWritebackConversion =
1919 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1920 Action == AssignmentAction::Sending);
1921 if (getLangOpts().ObjC)
1922 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1923 From->getType(), From);
1925 *this, From, ToType,
1926 /*SuppressUserConversions=*/false,
1927 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1928 /*InOverloadResolution=*/false,
1929 /*CStyle=*/false, AllowObjCWritebackConversion,
1930 /*AllowObjCConversionOnExplicit=*/false);
1931 return PerformImplicitConversion(From, ToType, ICS, Action);
1932}
1933
1935 QualType &ResultTy) const {
1936 bool Changed = IsFunctionConversion(FromType, ToType);
1937 if (Changed)
1938 ResultTy = ToType;
1939 return Changed;
1940}
1941
1942bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1943 if (Context.hasSameUnqualifiedType(FromType, ToType))
1944 return false;
1945
1946 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1947 // or F(t noexcept) -> F(t)
1948 // where F adds one of the following at most once:
1949 // - a pointer
1950 // - a member pointer
1951 // - a block pointer
1952 // Changes here need matching changes in FindCompositePointerType.
1953 CanQualType CanTo = Context.getCanonicalType(ToType);
1954 CanQualType CanFrom = Context.getCanonicalType(FromType);
1955 Type::TypeClass TyClass = CanTo->getTypeClass();
1956 if (TyClass != CanFrom->getTypeClass()) return false;
1957 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1958 if (TyClass == Type::Pointer) {
1959 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1960 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1961 } else if (TyClass == Type::BlockPointer) {
1962 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1963 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1964 } else if (TyClass == Type::MemberPointer) {
1965 auto ToMPT = CanTo.castAs<MemberPointerType>();
1966 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1967 // A function pointer conversion cannot change the class of the function.
1968 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1969 FromMPT->getMostRecentCXXRecordDecl()))
1970 return false;
1971 CanTo = ToMPT->getPointeeType();
1972 CanFrom = FromMPT->getPointeeType();
1973 } else {
1974 return false;
1975 }
1976
1977 TyClass = CanTo->getTypeClass();
1978 if (TyClass != CanFrom->getTypeClass()) return false;
1979 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1980 return false;
1981 }
1982
1983 const auto *FromFn = cast<FunctionType>(CanFrom);
1984 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1985
1986 const auto *ToFn = cast<FunctionType>(CanTo);
1987 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1988
1989 bool Changed = false;
1990
1991 // Drop 'noreturn' if not present in target type.
1992 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1993 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1994 Changed = true;
1995 }
1996
1997 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1998 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1999
2000 if (FromFPT && ToFPT) {
2001 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2002 QualType NewTy = Context.getFunctionType(
2003 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2004 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2005 ToFPT->hasCFIUncheckedCallee()));
2006 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2007 FromFn = FromFPT;
2008 Changed = true;
2009 }
2010 }
2011
2012 // Drop 'noexcept' if not present in target type.
2013 if (FromFPT && ToFPT) {
2014 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2015 FromFn = cast<FunctionType>(
2016 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2017 EST_None)
2018 .getTypePtr());
2019 Changed = true;
2020 }
2021
2022 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2023 // only if the ExtParameterInfo lists of the two function prototypes can be
2024 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2026 bool CanUseToFPT, CanUseFromFPT;
2027 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2028 CanUseFromFPT, NewParamInfos) &&
2029 CanUseToFPT && !CanUseFromFPT) {
2030 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2031 ExtInfo.ExtParameterInfos =
2032 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2033 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2034 FromFPT->getParamTypes(), ExtInfo);
2035 FromFn = QT->getAs<FunctionType>();
2036 Changed = true;
2037 }
2038
2039 if (Context.hasAnyFunctionEffects()) {
2040 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2041
2042 // Transparently add/drop effects; here we are concerned with
2043 // language rules/canonicalization. Adding/dropping effects is a warning.
2044 const auto FromFX = FromFPT->getFunctionEffects();
2045 const auto ToFX = ToFPT->getFunctionEffects();
2046 if (FromFX != ToFX) {
2047 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2048 ExtInfo.FunctionEffects = ToFX;
2049 QualType QT = Context.getFunctionType(
2050 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2051 FromFn = QT->getAs<FunctionType>();
2052 Changed = true;
2053 }
2054 }
2055 }
2056
2057 if (!Changed)
2058 return false;
2059
2060 assert(QualType(FromFn, 0).isCanonical());
2061 if (QualType(FromFn, 0) != CanTo) return false;
2062
2063 return true;
2064}
2065
2066/// Determine whether the conversion from FromType to ToType is a valid
2067/// floating point conversion.
2068///
2069static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2070 QualType ToType) {
2071 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2072 return false;
2073 // FIXME: disable conversions between long double, __ibm128 and __float128
2074 // if their representation is different until there is back end support
2075 // We of course allow this conversion if long double is really double.
2076
2077 // Conversions between bfloat16 and float16 are currently not supported.
2078 if ((FromType->isBFloat16Type() &&
2079 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2080 (ToType->isBFloat16Type() &&
2081 (FromType->isFloat16Type() || FromType->isHalfType())))
2082 return false;
2083
2084 // Conversions between IEEE-quad and IBM-extended semantics are not
2085 // permitted.
2086 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2087 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2088 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2089 &ToSem == &llvm::APFloat::IEEEquad()) ||
2090 (&FromSem == &llvm::APFloat::IEEEquad() &&
2091 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2092 return false;
2093 return true;
2094}
2095
2097 QualType ToType,
2099 Expr *From) {
2100 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2101 return true;
2102
2103 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2105 return true;
2106 }
2107
2108 if (IsFloatingPointConversion(S, FromType, ToType)) {
2110 return true;
2111 }
2112
2113 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2115 return true;
2116 }
2117
2118 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2120 ToType->isRealFloatingType())) {
2122 return true;
2123 }
2124
2125 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2127 return true;
2128 }
2129
2130 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2131 ToType->isIntegralType(S.Context)) {
2133 return true;
2134 }
2135
2136 return false;
2137}
2138
2139/// Determine whether the conversion from FromType to ToType is a valid
2140/// matrix conversion.
2141///
2142/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2143/// conversion.
2144static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2146 ImplicitConversionKind &ElConv, Expr *From,
2147 bool InOverloadResolution, bool CStyle) {
2148 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2149 if (!S.getLangOpts().HLSL)
2150 return false;
2151
2152 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2153 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2154
2155 // If both arguments are matrix, handle possible matrix truncation and
2156 // element conversion.
2157 if (ToMatrixType && FromMatrixType) {
2158 unsigned FromCols = FromMatrixType->getNumColumns();
2159 unsigned ToCols = ToMatrixType->getNumColumns();
2160 if (FromCols < ToCols)
2161 return false;
2162
2163 unsigned FromRows = FromMatrixType->getNumRows();
2164 unsigned ToRows = ToMatrixType->getNumRows();
2165 if (FromRows < ToRows)
2166 return false;
2167
2168 if (FromRows == ToRows && FromCols == ToCols)
2169 ElConv = ICK_Identity;
2170 else
2172
2173 QualType FromElTy = FromMatrixType->getElementType();
2174 QualType ToElTy = ToMatrixType->getElementType();
2175 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2176 return true;
2177 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2178 }
2179
2180 // Matrix splat from any arithmetic type to a matrix.
2181 if (ToMatrixType && FromType->isArithmeticType()) {
2182 ElConv = ICK_HLSL_Matrix_Splat;
2183 QualType ToElTy = ToMatrixType->getElementType();
2184 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2185 }
2186 if (FromMatrixType && !ToMatrixType) {
2188 QualType FromElTy = FromMatrixType->getElementType();
2189 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2190 return true;
2191 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2192 }
2193
2194 return false;
2195}
2196
2197/// Determine whether the conversion from FromType to ToType is a valid
2198/// vector conversion.
2199///
2200/// \param ICK Will be set to the vector conversion kind, if this is a vector
2201/// conversion.
2202static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2204 ImplicitConversionKind &ElConv, Expr *From,
2205 bool InOverloadResolution, bool CStyle) {
2206 // We need at least one of these types to be a vector type to have a vector
2207 // conversion.
2208 if (!ToType->isVectorType() && !FromType->isVectorType())
2209 return false;
2210
2211 // Identical types require no conversions.
2212 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2213 return false;
2214
2215 // HLSL allows implicit truncation of vector types.
2216 if (S.getLangOpts().HLSL) {
2217 auto *ToExtType = ToType->getAs<ExtVectorType>();
2218 auto *FromExtType = FromType->getAs<ExtVectorType>();
2219
2220 // If both arguments are vectors, handle possible vector truncation and
2221 // element conversion.
2222 if (ToExtType && FromExtType) {
2223 unsigned FromElts = FromExtType->getNumElements();
2224 unsigned ToElts = ToExtType->getNumElements();
2225 if (FromElts < ToElts)
2226 return false;
2227 if (FromElts == ToElts)
2228 ElConv = ICK_Identity;
2229 else
2231
2232 QualType FromElTy = FromExtType->getElementType();
2233 QualType ToElTy = ToExtType->getElementType();
2234 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2235 return true;
2236 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2237 }
2238 if (FromExtType && !ToExtType) {
2240 QualType FromElTy = FromExtType->getElementType();
2241 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2242 return true;
2243 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2244 }
2245 // Fallthrough for the case where ToType is a vector and FromType is not.
2246 }
2247
2248 // There are no conversions between extended vector types, only identity.
2249 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2250 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2251 // Implicit conversions require the same number of elements.
2252 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2253 return false;
2254
2255 // Permit implicit conversions from integral values to boolean vectors.
2256 if (ToType->isExtVectorBoolType() &&
2257 FromExtType->getElementType()->isIntegerType()) {
2259 return true;
2260 }
2261 // There are no other conversions between extended vector types.
2262 return false;
2263 }
2264
2265 // Vector splat from any arithmetic type to a vector.
2266 if (FromType->isArithmeticType()) {
2267 if (S.getLangOpts().HLSL) {
2268 ElConv = ICK_HLSL_Vector_Splat;
2269 QualType ToElTy = ToExtType->getElementType();
2270 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2271 From);
2272 }
2273 ICK = ICK_Vector_Splat;
2274 return true;
2275 }
2276 }
2277
2278 if (ToType->isSVESizelessBuiltinType() ||
2279 FromType->isSVESizelessBuiltinType())
2280 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2281 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2283 return true;
2284 }
2285
2286 if (ToType->isRVVSizelessBuiltinType() ||
2287 FromType->isRVVSizelessBuiltinType())
2288 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2289 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2291 return true;
2292 }
2293
2294 // We can perform the conversion between vector types in the following cases:
2295 // 1)vector types are equivalent AltiVec and GCC vector types
2296 // 2)lax vector conversions are permitted and the vector types are of the
2297 // same size
2298 // 3)the destination type does not have the ARM MVE strict-polymorphism
2299 // attribute, which inhibits lax vector conversion for overload resolution
2300 // only
2301 if (ToType->isVectorType() && FromType->isVectorType()) {
2302 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2303 (S.isLaxVectorConversion(FromType, ToType) &&
2304 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2305 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2306 S.isLaxVectorConversion(FromType, ToType) &&
2307 S.anyAltivecTypes(FromType, ToType) &&
2308 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2309 !InOverloadResolution && !CStyle) {
2310 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2311 << FromType << ToType;
2312 }
2314 return true;
2315 }
2316 }
2317
2318 return false;
2319}
2320
2321static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2322 bool InOverloadResolution,
2323 StandardConversionSequence &SCS,
2324 bool CStyle);
2325
2326static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2327 QualType ToType,
2328 bool InOverloadResolution,
2329 StandardConversionSequence &SCS,
2330 bool CStyle);
2331
2332/// IsStandardConversion - Determines whether there is a standard
2333/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2334/// expression From to the type ToType. Standard conversion sequences
2335/// only consider non-class types; for conversions that involve class
2336/// types, use TryImplicitConversion. If a conversion exists, SCS will
2337/// contain the standard conversion sequence required to perform this
2338/// conversion and this routine will return true. Otherwise, this
2339/// routine will return false and the value of SCS is unspecified.
2340static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2341 bool InOverloadResolution,
2343 bool CStyle,
2344 bool AllowObjCWritebackConversion) {
2345 QualType FromType = From->getType();
2346
2347 // Standard conversions (C++ [conv])
2349 SCS.IncompatibleObjC = false;
2350 SCS.setFromType(FromType);
2351 SCS.CopyConstructor = nullptr;
2352
2353 // There are no standard conversions for class types in C++, so
2354 // abort early. When overloading in C, however, we do permit them.
2355 if (S.getLangOpts().CPlusPlus &&
2356 (FromType->isRecordType() || ToType->isRecordType()))
2357 return false;
2358
2359 // The first conversion can be an lvalue-to-rvalue conversion,
2360 // array-to-pointer conversion, or function-to-pointer conversion
2361 // (C++ 4p1).
2362
2363 if (FromType == S.Context.OverloadTy) {
2364 DeclAccessPair AccessPair;
2365 if (FunctionDecl *Fn
2366 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2367 AccessPair)) {
2368 // We were able to resolve the address of the overloaded function,
2369 // so we can convert to the type of that function.
2370 FromType = Fn->getType();
2371 SCS.setFromType(FromType);
2372
2373 // we can sometimes resolve &foo<int> regardless of ToType, so check
2374 // if the type matches (identity) or we are converting to bool
2376 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2377 // if the function type matches except for [[noreturn]], it's ok
2378 if (!S.IsFunctionConversion(FromType,
2380 // otherwise, only a boolean conversion is standard
2381 if (!ToType->isBooleanType())
2382 return false;
2383 }
2384
2385 // Check if the "from" expression is taking the address of an overloaded
2386 // function and recompute the FromType accordingly. Take advantage of the
2387 // fact that non-static member functions *must* have such an address-of
2388 // expression.
2389 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2390 if (Method && !Method->isStatic() &&
2391 !Method->isExplicitObjectMemberFunction()) {
2392 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2393 "Non-unary operator on non-static member address");
2394 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2395 == UO_AddrOf &&
2396 "Non-address-of operator on non-static member address");
2397 FromType = S.Context.getMemberPointerType(
2398 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2399 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2400 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2401 UO_AddrOf &&
2402 "Non-address-of operator for overloaded function expression");
2403 FromType = S.Context.getPointerType(FromType);
2404 }
2405 } else {
2406 return false;
2407 }
2408 }
2409
2410 bool argIsLValue = From->isGLValue();
2411 // To handle conversion from ArrayParameterType to ConstantArrayType
2412 // this block must be above the one below because Array parameters
2413 // do not decay and when handling HLSLOutArgExprs and
2414 // the From expression is an LValue.
2415 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2416 ToType->isConstantArrayType()) {
2417 // HLSL constant array parameters do not decay, so if the argument is a
2418 // constant array and the parameter is an ArrayParameterType we have special
2419 // handling here.
2420 if (ToType->isArrayParameterType()) {
2421 FromType = S.Context.getArrayParameterType(FromType);
2422 } else if (FromType->isArrayParameterType()) {
2423 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2424 FromType = APT->getConstantArrayType(S.Context);
2425 }
2426
2428
2429 // Don't consider qualifiers, which include things like address spaces
2430 if (FromType.getCanonicalType().getUnqualifiedType() !=
2432 return false;
2433
2434 SCS.setAllToTypes(ToType);
2435 return true;
2436 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2437 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2438 // Lvalue-to-rvalue conversion (C++11 4.1):
2439 // A glvalue (3.10) of a non-function, non-array type T can
2440 // be converted to a prvalue.
2441
2443
2444 // C11 6.3.2.1p2:
2445 // ... if the lvalue has atomic type, the value has the non-atomic version
2446 // of the type of the lvalue ...
2447 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2448 FromType = Atomic->getValueType();
2449
2450 // If T is a non-class type, the type of the rvalue is the
2451 // cv-unqualified version of T. Otherwise, the type of the rvalue
2452 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2453 // just strip the qualifiers because they don't matter.
2454 FromType = FromType.getUnqualifiedType();
2455 } else if (FromType->isArrayType()) {
2456 // Array-to-pointer conversion (C++ 4.2)
2458
2459 // An lvalue or rvalue of type "array of N T" or "array of unknown
2460 // bound of T" can be converted to an rvalue of type "pointer to
2461 // T" (C++ 4.2p1).
2462 FromType = S.Context.getArrayDecayedType(FromType);
2463
2464 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2465 // This conversion is deprecated in C++03 (D.4)
2467
2468 // For the purpose of ranking in overload resolution
2469 // (13.3.3.1.1), this conversion is considered an
2470 // array-to-pointer conversion followed by a qualification
2471 // conversion (4.4). (C++ 4.2p2)
2472 SCS.Second = ICK_Identity;
2475 SCS.setAllToTypes(FromType);
2476 return true;
2477 }
2478 } else if (FromType->isFunctionType() && argIsLValue) {
2479 // Function-to-pointer conversion (C++ 4.3).
2481
2482 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2483 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2485 return false;
2486
2487 // An lvalue of function type T can be converted to an rvalue of
2488 // type "pointer to T." The result is a pointer to the
2489 // function. (C++ 4.3p1).
2490 FromType = S.Context.getPointerType(FromType);
2491 } else {
2492 // We don't require any conversions for the first step.
2493 SCS.First = ICK_Identity;
2494 }
2495 SCS.setToType(0, FromType);
2496
2497 // The second conversion can be an integral promotion, floating
2498 // point promotion, integral conversion, floating point conversion,
2499 // floating-integral conversion, pointer conversion,
2500 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2501 // For overloading in C, this can also be a "compatible-type"
2502 // conversion.
2503 bool IncompatibleObjC = false;
2505 ImplicitConversionKind DimensionICK = ICK_Identity;
2506 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2507 // The unqualified versions of the types are the same: there's no
2508 // conversion to do.
2509 SCS.Second = ICK_Identity;
2510 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2511 // Integral promotion (C++ 4.5).
2513 FromType = ToType.getUnqualifiedType();
2514 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2515 // Floating point promotion (C++ 4.6).
2517 FromType = ToType.getUnqualifiedType();
2518 } else if (S.IsComplexPromotion(FromType, ToType)) {
2519 // Complex promotion (Clang extension)
2521 FromType = ToType.getUnqualifiedType();
2522 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2523 // OverflowBehaviorType promotions
2525 FromType = ToType.getUnqualifiedType();
2526 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2527 // OverflowBehaviorType conversions
2529 FromType = ToType.getUnqualifiedType();
2530 } else if (ToType->isBooleanType() &&
2531 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2532 FromType->isBlockPointerType() ||
2533 FromType->isMemberPointerType())) {
2534 // Boolean conversions (C++ 4.12).
2536 FromType = S.Context.BoolTy;
2537 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2538 ToType->isIntegralType(S.Context)) {
2539 // Integral conversions (C++ 4.7).
2541 FromType = ToType.getUnqualifiedType();
2542 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2543 // Complex conversions (C99 6.3.1.6)
2545 FromType = ToType.getUnqualifiedType();
2546 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2547 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2548 // Complex-real conversions (C99 6.3.1.7)
2550 FromType = ToType.getUnqualifiedType();
2551 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2552 // Floating point conversions (C++ 4.8).
2554 FromType = ToType.getUnqualifiedType();
2555 } else if ((FromType->isRealFloatingType() &&
2556 ToType->isIntegralType(S.Context)) ||
2558 ToType->isRealFloatingType())) {
2559
2560 // Floating-integral conversions (C++ 4.9).
2562 FromType = ToType.getUnqualifiedType();
2563 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2565 } else if (AllowObjCWritebackConversion &&
2566 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2568 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2569 FromType, IncompatibleObjC)) {
2570 // Pointer conversions (C++ 4.10).
2572 SCS.IncompatibleObjC = IncompatibleObjC;
2573 FromType = FromType.getUnqualifiedType();
2574 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2575 InOverloadResolution, FromType)) {
2576 // Pointer to member conversions (4.11).
2578 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2579 From, InOverloadResolution, CStyle)) {
2580 SCS.Second = SecondICK;
2581 SCS.Dimension = DimensionICK;
2582 FromType = ToType.getUnqualifiedType();
2583 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2584 From, InOverloadResolution, CStyle)) {
2585 SCS.Second = SecondICK;
2586 SCS.Dimension = DimensionICK;
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (!S.getLangOpts().CPlusPlus &&
2589 S.Context.typesAreCompatible(ToType, FromType)) {
2590 // Compatible conversions (Clang extension for C function overloading)
2592 FromType = ToType.getUnqualifiedType();
2594 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2596 FromType = ToType;
2597 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2598 CStyle)) {
2599 // tryAtomicConversion has updated the standard conversion sequence
2600 // appropriately.
2601 return true;
2603 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2604 return true;
2605 } else if (ToType->isEventT() &&
2607 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2609 FromType = ToType;
2610 } else if (ToType->isQueueT() &&
2612 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2614 FromType = ToType;
2615 } else if (ToType->isSamplerT() &&
2618 FromType = ToType;
2619 } else if ((ToType->isFixedPointType() &&
2620 FromType->isConvertibleToFixedPointType()) ||
2621 (FromType->isFixedPointType() &&
2622 ToType->isConvertibleToFixedPointType())) {
2624 FromType = ToType;
2625 } else {
2626 // No second conversion required.
2627 SCS.Second = ICK_Identity;
2628 }
2629 SCS.setToType(1, FromType);
2630
2631 // The third conversion can be a function pointer conversion or a
2632 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2633 bool ObjCLifetimeConversion;
2634 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2635 // Function pointer conversions (removing 'noexcept') including removal of
2636 // 'noreturn' (Clang extension).
2638 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2639 ObjCLifetimeConversion)) {
2641 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2642 FromType = ToType;
2643 } else {
2644 // No conversion required
2645 SCS.Third = ICK_Identity;
2646 }
2647
2648 // C++ [over.best.ics]p6:
2649 // [...] Any difference in top-level cv-qualification is
2650 // subsumed by the initialization itself and does not constitute
2651 // a conversion. [...]
2652 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2653 QualType CanonTo = S.Context.getCanonicalType(ToType);
2654 if (CanonFrom.getLocalUnqualifiedType()
2655 == CanonTo.getLocalUnqualifiedType() &&
2656 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2657 FromType = ToType;
2658 CanonFrom = CanonTo;
2659 }
2660
2661 SCS.setToType(2, FromType);
2662
2663 if (CanonFrom == CanonTo)
2664 return true;
2665
2666 // If we have not converted the argument type to the parameter type,
2667 // this is a bad conversion sequence, unless we're resolving an overload in C.
2668 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2669 return false;
2670
2671 ExprResult ER = ExprResult{From};
2672 AssignConvertType Conv =
2674 /*Diagnose=*/false,
2675 /*DiagnoseCFAudited=*/false,
2676 /*ConvertRHS=*/false);
2677 ImplicitConversionKind SecondConv;
2678 switch (Conv) {
2680 case AssignConvertType::
2681 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2682 SecondConv = ICK_C_Only_Conversion;
2683 break;
2684 // For our purposes, discarding qualifiers is just as bad as using an
2685 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2686 // qualifiers, as well.
2691 break;
2692 default:
2693 return false;
2694 }
2695
2696 // First can only be an lvalue conversion, so we pretend that this was the
2697 // second conversion. First should already be valid from earlier in the
2698 // function.
2699 SCS.Second = SecondConv;
2700 SCS.setToType(1, ToType);
2701
2702 // Third is Identity, because Second should rank us worse than any other
2703 // conversion. This could also be ICK_Qualification, but it's simpler to just
2704 // lump everything in with the second conversion, and we don't gain anything
2705 // from making this ICK_Qualification.
2706 SCS.Third = ICK_Identity;
2707 SCS.setToType(2, ToType);
2708 return true;
2709}
2710
2711static bool
2713 QualType &ToType,
2714 bool InOverloadResolution,
2716 bool CStyle) {
2717
2718 const RecordType *UT = ToType->getAsUnionType();
2719 if (!UT)
2720 return false;
2721 // The field to initialize within the transparent union.
2722 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2723 if (!UD->hasAttr<TransparentUnionAttr>())
2724 return false;
2725 // It's compatible if the expression matches any of the fields.
2726 for (const auto *it : UD->fields()) {
2727 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2728 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2729 ToType = it->getType();
2730 return true;
2731 }
2732 }
2733 return false;
2734}
2735
2736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2737 const BuiltinType *To = ToType->getAs<BuiltinType>();
2738 // All integers are built-in.
2739 if (!To) {
2740 return false;
2741 }
2742
2743 // An rvalue of type char, signed char, unsigned char, short int, or
2744 // unsigned short int can be converted to an rvalue of type int if
2745 // int can represent all the values of the source type; otherwise,
2746 // the source rvalue can be converted to an rvalue of type unsigned
2747 // int (C++ 4.5p1).
2748 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2749 !FromType->isEnumeralType()) {
2750 if ( // We can promote any signed, promotable integer type to an int
2751 (FromType->isSignedIntegerType() ||
2752 // We can promote any unsigned integer type whose size is
2753 // less than int to an int.
2754 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2755 return To->getKind() == BuiltinType::Int;
2756 }
2757
2758 return To->getKind() == BuiltinType::UInt;
2759 }
2760
2761 // C++11 [conv.prom]p3:
2762 // A prvalue of an unscoped enumeration type whose underlying type is not
2763 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2764 // following types that can represent all the values of the enumeration
2765 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2766 // unsigned int, long int, unsigned long int, long long int, or unsigned
2767 // long long int. If none of the types in that list can represent all the
2768 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2769 // type can be converted to an rvalue a prvalue of the extended integer type
2770 // with lowest integer conversion rank (4.13) greater than the rank of long
2771 // long in which all the values of the enumeration can be represented. If
2772 // there are two such extended types, the signed one is chosen.
2773 // C++11 [conv.prom]p4:
2774 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2775 // can be converted to a prvalue of its underlying type. Moreover, if
2776 // integral promotion can be applied to its underlying type, a prvalue of an
2777 // unscoped enumeration type whose underlying type is fixed can also be
2778 // converted to a prvalue of the promoted underlying type.
2779 if (const auto *FromED = FromType->getAsEnumDecl()) {
2780 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2781 // provided for a scoped enumeration.
2782 if (FromED->isScoped())
2783 return false;
2784
2785 // We can perform an integral promotion to the underlying type of the enum,
2786 // even if that's not the promoted type. Note that the check for promoting
2787 // the underlying type is based on the type alone, and does not consider
2788 // the bitfield-ness of the actual source expression.
2789 if (FromED->isFixed()) {
2790 QualType Underlying = FromED->getIntegerType();
2791 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2792 IsIntegralPromotion(nullptr, Underlying, ToType);
2793 }
2794
2795 // We have already pre-calculated the promotion type, so this is trivial.
2796 if (ToType->isIntegerType() &&
2797 isCompleteType(From->getBeginLoc(), FromType))
2798 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2799
2800 // C++ [conv.prom]p5:
2801 // If the bit-field has an enumerated type, it is treated as any other
2802 // value of that type for promotion purposes.
2803 //
2804 // ... so do not fall through into the bit-field checks below in C++.
2805 if (getLangOpts().CPlusPlus)
2806 return false;
2807 }
2808
2809 // C++0x [conv.prom]p2:
2810 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2811 // to an rvalue a prvalue of the first of the following types that can
2812 // represent all the values of its underlying type: int, unsigned int,
2813 // long int, unsigned long int, long long int, or unsigned long long int.
2814 // If none of the types in that list can represent all the values of its
2815 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2816 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2817 // type.
2818 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2819 ToType->isIntegerType()) {
2820 // Determine whether the type we're converting from is signed or
2821 // unsigned.
2822 bool FromIsSigned = FromType->isSignedIntegerType();
2823 uint64_t FromSize = Context.getTypeSize(FromType);
2824
2825 // The types we'll try to promote to, in the appropriate
2826 // order. Try each of these types.
2827 QualType PromoteTypes[6] = {
2828 Context.IntTy, Context.UnsignedIntTy,
2829 Context.LongTy, Context.UnsignedLongTy ,
2830 Context.LongLongTy, Context.UnsignedLongLongTy
2831 };
2832 for (int Idx = 0; Idx < 6; ++Idx) {
2833 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2834 if (FromSize < ToSize ||
2835 (FromSize == ToSize &&
2836 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2837 // We found the type that we can promote to. If this is the
2838 // type we wanted, we have a promotion. Otherwise, no
2839 // promotion.
2840 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2841 }
2842 }
2843 }
2844
2845 // An rvalue for an integral bit-field (9.6) can be converted to an
2846 // rvalue of type int if int can represent all the values of the
2847 // bit-field; otherwise, it can be converted to unsigned int if
2848 // unsigned int can represent all the values of the bit-field. If
2849 // the bit-field is larger yet, no integral promotion applies to
2850 // it. If the bit-field has an enumerated type, it is treated as any
2851 // other value of that type for promotion purposes (C++ 4.5p3).
2852 // FIXME: We should delay checking of bit-fields until we actually perform the
2853 // conversion.
2854 //
2855 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2856 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2857 // bit-fields and those whose underlying type is larger than int) for GCC
2858 // compatibility.
2859 if (From) {
2860 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2861 std::optional<llvm::APSInt> BitWidth;
2862 if (FromType->isIntegralType(Context) &&
2863 (BitWidth =
2864 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2865 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2866 ToSize = Context.getTypeSize(ToType);
2867
2868 // Are we promoting to an int from a bitfield that fits in an int?
2869 if (*BitWidth < ToSize ||
2870 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2871 return To->getKind() == BuiltinType::Int;
2872 }
2873
2874 // Are we promoting to an unsigned int from an unsigned bitfield
2875 // that fits into an unsigned int?
2876 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2877 return To->getKind() == BuiltinType::UInt;
2878 }
2879
2880 return false;
2881 }
2882 }
2883 }
2884
2885 // An rvalue of type bool can be converted to an rvalue of type int,
2886 // with false becoming zero and true becoming one (C++ 4.5p4).
2887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2888 return true;
2889 }
2890
2891 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2892 // integral type.
2893 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2894 ToType->isIntegerType())
2895 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2896
2897 return false;
2898}
2899
2901 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2902 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2903 /// An rvalue of type float can be converted to an rvalue of type
2904 /// double. (C++ 4.6p1).
2905 if (FromBuiltin->getKind() == BuiltinType::Float &&
2906 ToBuiltin->getKind() == BuiltinType::Double)
2907 return true;
2908
2909 // C99 6.3.1.5p1:
2910 // When a float is promoted to double or long double, or a
2911 // double is promoted to long double [...].
2912 if (!getLangOpts().CPlusPlus &&
2913 (FromBuiltin->getKind() == BuiltinType::Float ||
2914 FromBuiltin->getKind() == BuiltinType::Double) &&
2915 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2916 ToBuiltin->getKind() == BuiltinType::Float128 ||
2917 ToBuiltin->getKind() == BuiltinType::Ibm128))
2918 return true;
2919
2920 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2921 // or not native half types are enabled.
2922 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2923 (ToBuiltin->getKind() == BuiltinType::Float ||
2924 ToBuiltin->getKind() == BuiltinType::Double))
2925 return true;
2926
2927 // Half can be promoted to float.
2928 if (!getLangOpts().NativeHalfType &&
2929 FromBuiltin->getKind() == BuiltinType::Half &&
2930 ToBuiltin->getKind() == BuiltinType::Float)
2931 return true;
2932 }
2933
2934 return false;
2935}
2936
2938 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2939 if (!FromComplex)
2940 return false;
2941
2942 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2943 if (!ToComplex)
2944 return false;
2945
2946 return IsFloatingPointPromotion(FromComplex->getElementType(),
2947 ToComplex->getElementType()) ||
2948 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2949 ToComplex->getElementType());
2950}
2951
2953 if (!getLangOpts().OverflowBehaviorTypes)
2954 return false;
2955
2956 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2957 return false;
2958
2959 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2960}
2961
2963 QualType ToType) {
2964 if (!getLangOpts().OverflowBehaviorTypes)
2965 return false;
2966
2967 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2968 if (ToType->isBooleanType())
2969 return false;
2970 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2971 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2972 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2973 if (ToED->isScoped())
2974 return false;
2975 }
2976 return true;
2977 }
2978
2979 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2980 return true;
2981
2982 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2983 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2984
2985 return false;
2986}
2987
2988/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2989/// the pointer type FromPtr to a pointer to type ToPointee, with the
2990/// same type qualifiers as FromPtr has on its pointee type. ToType,
2991/// if non-empty, will be a pointer to ToType that may or may not have
2992/// the right set of qualifiers on its pointee.
2993///
2994static QualType
2996 QualType ToPointee, QualType ToType,
2997 ASTContext &Context,
2998 bool StripObjCLifetime = false) {
2999 assert((FromPtr->getTypeClass() == Type::Pointer ||
3000 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3001 "Invalid similarly-qualified pointer type");
3002
3003 /// Conversions to 'id' subsume cv-qualifier conversions.
3004 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3005 return ToType.getUnqualifiedType();
3006
3007 QualType CanonFromPointee
3008 = Context.getCanonicalType(FromPtr->getPointeeType());
3009 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3010 Qualifiers Quals = CanonFromPointee.getQualifiers();
3011
3012 if (StripObjCLifetime)
3013 Quals.removeObjCLifetime();
3014
3015 // Exact qualifier match -> return the pointer type we're converting to.
3016 if (CanonToPointee.getLocalQualifiers() == Quals) {
3017 // ToType is exactly what we need. Return it.
3018 if (!ToType.isNull())
3019 return ToType.getUnqualifiedType();
3020
3021 // Build a pointer to ToPointee. It has the right qualifiers
3022 // already.
3023 if (isa<ObjCObjectPointerType>(ToType))
3024 return Context.getObjCObjectPointerType(ToPointee);
3025 return Context.getPointerType(ToPointee);
3026 }
3027
3028 // Just build a canonical type that has the right qualifiers.
3029 QualType QualifiedCanonToPointee
3030 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3031
3032 if (isa<ObjCObjectPointerType>(ToType))
3033 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3034 return Context.getPointerType(QualifiedCanonToPointee);
3035}
3036
3038 bool InOverloadResolution,
3039 ASTContext &Context) {
3040 // Handle value-dependent integral null pointer constants correctly.
3041 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3042 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3044 return !InOverloadResolution;
3045
3046 return Expr->isNullPointerConstant(Context,
3047 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3049}
3050
3052 bool InOverloadResolution,
3053 QualType& ConvertedType,
3054 bool &IncompatibleObjC) {
3055 IncompatibleObjC = false;
3056 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3057 IncompatibleObjC))
3058 return true;
3059
3060 // Conversion from a null pointer constant to any Objective-C pointer type.
3061 if (ToType->isObjCObjectPointerType() &&
3062 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3063 ConvertedType = ToType;
3064 return true;
3065 }
3066
3067 // Blocks: Block pointers can be converted to void*.
3068 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3069 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073 // Blocks: A null pointer constant can be converted to a block
3074 // pointer type.
3075 if (ToType->isBlockPointerType() &&
3076 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3077 ConvertedType = ToType;
3078 return true;
3079 }
3080
3081 // If the left-hand-side is nullptr_t, the right side can be a null
3082 // pointer constant.
3083 if (ToType->isNullPtrType() &&
3084 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3085 ConvertedType = ToType;
3086 return true;
3087 }
3088
3089 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3090 if (!ToTypePtr)
3091 return false;
3092
3093 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3094 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3095 ConvertedType = ToType;
3096 return true;
3097 }
3098
3099 // Beyond this point, both types need to be pointers
3100 // , including objective-c pointers.
3101 QualType ToPointeeType = ToTypePtr->getPointeeType();
3102 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3103 !getLangOpts().ObjCAutoRefCount) {
3104 ConvertedType = BuildSimilarlyQualifiedPointerType(
3105 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3106 Context);
3107 return true;
3108 }
3109 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3110 if (!FromTypePtr)
3111 return false;
3112
3113 QualType FromPointeeType = FromTypePtr->getPointeeType();
3114
3115 // If the unqualified pointee types are the same, this can't be a
3116 // pointer conversion, so don't do all of the work below.
3117 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3118 return false;
3119
3120 // An rvalue of type "pointer to cv T," where T is an object type,
3121 // can be converted to an rvalue of type "pointer to cv void" (C++
3122 // 4.10p2).
3123 if (FromPointeeType->isIncompleteOrObjectType() &&
3124 ToPointeeType->isVoidType()) {
3125 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3126 ToPointeeType,
3127 ToType, Context,
3128 /*StripObjCLifetime=*/true);
3129 return true;
3130 }
3131
3132 // MSVC allows implicit function to void* type conversion.
3133 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3134 ToPointeeType->isVoidType()) {
3135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3136 ToPointeeType,
3137 ToType, Context);
3138 return true;
3139 }
3140
3141 // When we're overloading in C, we allow a special kind of pointer
3142 // conversion for compatible-but-not-identical pointee types.
3143 if (!getLangOpts().CPlusPlus &&
3144 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3146 ToPointeeType,
3147 ToType, Context);
3148 return true;
3149 }
3150
3151 // C++ [conv.ptr]p3:
3152 //
3153 // An rvalue of type "pointer to cv D," where D is a class type,
3154 // can be converted to an rvalue of type "pointer to cv B," where
3155 // B is a base class (clause 10) of D. If B is an inaccessible
3156 // (clause 11) or ambiguous (10.2) base class of D, a program that
3157 // necessitates this conversion is ill-formed. The result of the
3158 // conversion is a pointer to the base class sub-object of the
3159 // derived class object. The null pointer value is converted to
3160 // the null pointer value of the destination type.
3161 //
3162 // Note that we do not check for ambiguity or inaccessibility
3163 // here. That is handled by CheckPointerConversion.
3164 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3165 ToPointeeType->isRecordType() &&
3166 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3167 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3168 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3169 ToPointeeType,
3170 ToType, Context);
3171 return true;
3172 }
3173
3174 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3175 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3176 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3177 ToPointeeType,
3178 ToType, Context);
3179 return true;
3180 }
3181
3182 return false;
3183}
3184
3185/// Adopt the given qualifiers for the given type.
3187 Qualifiers TQs = T.getQualifiers();
3188
3189 // Check whether qualifiers already match.
3190 if (TQs == Qs)
3191 return T;
3192
3193 if (Qs.compatiblyIncludes(TQs, Context))
3194 return Context.getQualifiedType(T, Qs);
3195
3196 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3197}
3198
3200 QualType& ConvertedType,
3201 bool &IncompatibleObjC) {
3202 if (!getLangOpts().ObjC)
3203 return false;
3204
3205 // The set of qualifiers on the type we're converting from.
3206 Qualifiers FromQualifiers = FromType.getQualifiers();
3207
3208 // First, we handle all conversions on ObjC object pointer types.
3209 const ObjCObjectPointerType* ToObjCPtr =
3210 ToType->getAs<ObjCObjectPointerType>();
3211 const ObjCObjectPointerType *FromObjCPtr =
3212 FromType->getAs<ObjCObjectPointerType>();
3213
3214 if (ToObjCPtr && FromObjCPtr) {
3215 // If the pointee types are the same (ignoring qualifications),
3216 // then this is not a pointer conversion.
3217 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3218 FromObjCPtr->getPointeeType()))
3219 return false;
3220
3221 // Conversion between Objective-C pointers.
3222 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3223 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3224 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3225 if (getLangOpts().CPlusPlus && LHS && RHS &&
3227 FromObjCPtr->getPointeeType(), getASTContext()))
3228 return false;
3229 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3230 ToObjCPtr->getPointeeType(),
3231 ToType, Context);
3232 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3233 return true;
3234 }
3235
3236 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3237 // Okay: this is some kind of implicit downcast of Objective-C
3238 // interfaces, which is permitted. However, we're going to
3239 // complain about it.
3240 IncompatibleObjC = true;
3241 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3242 ToObjCPtr->getPointeeType(),
3243 ToType, Context);
3244 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3245 return true;
3246 }
3247 }
3248 // Beyond this point, both types need to be C pointers or block pointers.
3249 QualType ToPointeeType;
3250 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3251 ToPointeeType = ToCPtr->getPointeeType();
3252 else if (const BlockPointerType *ToBlockPtr =
3253 ToType->getAs<BlockPointerType>()) {
3254 // Objective C++: We're able to convert from a pointer to any object
3255 // to a block pointer type.
3256 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3257 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3258 return true;
3259 }
3260 ToPointeeType = ToBlockPtr->getPointeeType();
3261 }
3262 else if (FromType->getAs<BlockPointerType>() &&
3263 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3264 // Objective C++: We're able to convert from a block pointer type to a
3265 // pointer to any object.
3266 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3267 return true;
3268 }
3269 else
3270 return false;
3271
3272 QualType FromPointeeType;
3273 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3274 FromPointeeType = FromCPtr->getPointeeType();
3275 else if (const BlockPointerType *FromBlockPtr =
3276 FromType->getAs<BlockPointerType>())
3277 FromPointeeType = FromBlockPtr->getPointeeType();
3278 else
3279 return false;
3280
3281 // If we have pointers to pointers, recursively check whether this
3282 // is an Objective-C conversion.
3283 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3284 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3285 IncompatibleObjC)) {
3286 // We always complain about this conversion.
3287 IncompatibleObjC = true;
3288 ConvertedType = Context.getPointerType(ConvertedType);
3289 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3290 return true;
3291 }
3292 // Allow conversion of pointee being objective-c pointer to another one;
3293 // as in I* to id.
3294 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3295 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3296 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3297 IncompatibleObjC)) {
3298
3299 ConvertedType = Context.getPointerType(ConvertedType);
3300 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3301 return true;
3302 }
3303
3304 // If we have pointers to functions or blocks, check whether the only
3305 // differences in the argument and result types are in Objective-C
3306 // pointer conversions. If so, we permit the conversion (but
3307 // complain about it).
3308 const FunctionProtoType *FromFunctionType
3309 = FromPointeeType->getAs<FunctionProtoType>();
3310 const FunctionProtoType *ToFunctionType
3311 = ToPointeeType->getAs<FunctionProtoType>();
3312 if (FromFunctionType && ToFunctionType) {
3313 // If the function types are exactly the same, this isn't an
3314 // Objective-C pointer conversion.
3315 if (Context.getCanonicalType(FromPointeeType)
3316 == Context.getCanonicalType(ToPointeeType))
3317 return false;
3318
3319 // Perform the quick checks that will tell us whether these
3320 // function types are obviously different.
3321 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3322 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3323 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3324 return false;
3325
3326 bool HasObjCConversion = false;
3327 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3328 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3329 // Okay, the types match exactly. Nothing to do.
3330 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3331 ToFunctionType->getReturnType(),
3332 ConvertedType, IncompatibleObjC)) {
3333 // Okay, we have an Objective-C pointer conversion.
3334 HasObjCConversion = true;
3335 } else {
3336 // Function types are too different. Abort.
3337 return false;
3338 }
3339
3340 // Check argument types.
3341 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3342 ArgIdx != NumArgs; ++ArgIdx) {
3343 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3344 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3345 if (Context.getCanonicalType(FromArgType)
3346 == Context.getCanonicalType(ToArgType)) {
3347 // Okay, the types match exactly. Nothing to do.
3348 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3349 ConvertedType, IncompatibleObjC)) {
3350 // Okay, we have an Objective-C pointer conversion.
3351 HasObjCConversion = true;
3352 } else {
3353 // Argument types are too different. Abort.
3354 return false;
3355 }
3356 }
3357
3358 if (HasObjCConversion) {
3359 // We had an Objective-C conversion. Allow this pointer
3360 // conversion, but complain about it.
3361 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3362 IncompatibleObjC = true;
3363 return true;
3364 }
3365 }
3366
3367 return false;
3368}
3369
3371 QualType& ConvertedType) {
3372 QualType ToPointeeType;
3373 if (const BlockPointerType *ToBlockPtr =
3374 ToType->getAs<BlockPointerType>())
3375 ToPointeeType = ToBlockPtr->getPointeeType();
3376 else
3377 return false;
3378
3379 QualType FromPointeeType;
3380 if (const BlockPointerType *FromBlockPtr =
3381 FromType->getAs<BlockPointerType>())
3382 FromPointeeType = FromBlockPtr->getPointeeType();
3383 else
3384 return false;
3385 // We have pointer to blocks, check whether the only
3386 // differences in the argument and result types are in Objective-C
3387 // pointer conversions. If so, we permit the conversion.
3388
3389 const FunctionProtoType *FromFunctionType
3390 = FromPointeeType->getAs<FunctionProtoType>();
3391 const FunctionProtoType *ToFunctionType
3392 = ToPointeeType->getAs<FunctionProtoType>();
3393
3394 if (!FromFunctionType || !ToFunctionType)
3395 return false;
3396
3397 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3398 return true;
3399
3400 // Perform the quick checks that will tell us whether these
3401 // function types are obviously different.
3402 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3403 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3404 return false;
3405
3406 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3407 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3408 if (FromEInfo != ToEInfo)
3409 return false;
3410
3411 bool IncompatibleObjC = false;
3412 if (Context.hasSameType(FromFunctionType->getReturnType(),
3413 ToFunctionType->getReturnType())) {
3414 // Okay, the types match exactly. Nothing to do.
3415 } else {
3416 QualType RHS = FromFunctionType->getReturnType();
3417 QualType LHS = ToFunctionType->getReturnType();
3418 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3419 !RHS.hasQualifiers() && LHS.hasQualifiers())
3420 LHS = LHS.getUnqualifiedType();
3421
3422 if (Context.hasSameType(RHS,LHS)) {
3423 // OK exact match.
3424 } else if (isObjCPointerConversion(RHS, LHS,
3425 ConvertedType, IncompatibleObjC)) {
3426 if (IncompatibleObjC)
3427 return false;
3428 // Okay, we have an Objective-C pointer conversion.
3429 }
3430 else
3431 return false;
3432 }
3433
3434 // Check argument types.
3435 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3436 ArgIdx != NumArgs; ++ArgIdx) {
3437 IncompatibleObjC = false;
3438 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3439 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3440 if (Context.hasSameType(FromArgType, ToArgType)) {
3441 // Okay, the types match exactly. Nothing to do.
3442 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3443 ConvertedType, IncompatibleObjC)) {
3444 if (IncompatibleObjC)
3445 return false;
3446 // Okay, we have an Objective-C pointer conversion.
3447 } else
3448 // Argument types are too different. Abort.
3449 return false;
3450 }
3451
3453 bool CanUseToFPT, CanUseFromFPT;
3454 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3455 CanUseToFPT, CanUseFromFPT,
3456 NewParamInfos))
3457 return false;
3458
3459 ConvertedType = ToType;
3460 return true;
3461}
3462
3463enum {
3471};
3472
3473/// Attempts to get the FunctionProtoType from a Type. Handles
3474/// MemberFunctionPointers properly.
3476 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3477 return FPT;
3478
3479 if (auto *MPT = FromType->getAs<MemberPointerType>())
3480 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3481
3482 return nullptr;
3483}
3484
3486 QualType FromType, QualType ToType) {
3487 // If either type is not valid, include no extra info.
3488 if (FromType.isNull() || ToType.isNull()) {
3489 PDiag << ft_default;
3490 return;
3491 }
3492
3493 // Get the function type from the pointers.
3494 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3495 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3496 *ToMember = ToType->castAs<MemberPointerType>();
3497 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3498 ToMember->getMostRecentCXXRecordDecl())) {
3500 if (ToMember->isSugared())
3501 PDiag << Context.getCanonicalTagType(
3502 ToMember->getMostRecentCXXRecordDecl());
3503 else
3504 PDiag << ToMember->getQualifier();
3505 if (FromMember->isSugared())
3506 PDiag << Context.getCanonicalTagType(
3507 FromMember->getMostRecentCXXRecordDecl());
3508 else
3509 PDiag << FromMember->getQualifier();
3510 return;
3511 }
3512 FromType = FromMember->getPointeeType();
3513 ToType = ToMember->getPointeeType();
3514 }
3515
3516 if (FromType->isPointerType())
3517 FromType = FromType->getPointeeType();
3518 if (ToType->isPointerType())
3519 ToType = ToType->getPointeeType();
3520
3521 // Remove references.
3522 FromType = FromType.getNonReferenceType();
3523 ToType = ToType.getNonReferenceType();
3524
3525 // Don't print extra info for non-specialized template functions.
3526 if (FromType->isInstantiationDependentType() &&
3527 !FromType->getAs<TemplateSpecializationType>()) {
3528 PDiag << ft_default;
3529 return;
3530 }
3531
3532 // No extra info for same types.
3533 if (Context.hasSameType(FromType, ToType)) {
3534 PDiag << ft_default;
3535 return;
3536 }
3537
3538 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3539 *ToFunction = tryGetFunctionProtoType(ToType);
3540
3541 // Both types need to be function types.
3542 if (!FromFunction || !ToFunction) {
3543 PDiag << ft_default;
3544 return;
3545 }
3546
3547 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3548 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3549 << FromFunction->getNumParams();
3550 return;
3551 }
3552
3553 // Handle different parameter types.
3554 unsigned ArgPos;
3555 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3556 PDiag << ft_parameter_mismatch << ArgPos + 1
3557 << ToFunction->getParamType(ArgPos)
3558 << FromFunction->getParamType(ArgPos);
3559 return;
3560 }
3561
3562 // Handle different return type.
3563 if (!Context.hasSameType(FromFunction->getReturnType(),
3564 ToFunction->getReturnType())) {
3565 PDiag << ft_return_type << ToFunction->getReturnType()
3566 << FromFunction->getReturnType();
3567 return;
3568 }
3569
3570 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3571 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3572 << FromFunction->getMethodQuals();
3573 return;
3574 }
3575
3576 // Handle exception specification differences on canonical type (in C++17
3577 // onwards).
3579 ->isNothrow() !=
3580 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3581 ->isNothrow()) {
3582 PDiag << ft_noexcept;
3583 return;
3584 }
3585
3586 // Unable to find a difference, so add no extra info.
3587 PDiag << ft_default;
3588}
3589
3591 ArrayRef<QualType> New, unsigned *ArgPos,
3592 bool Reversed) {
3593 assert(llvm::size(Old) == llvm::size(New) &&
3594 "Can't compare parameters of functions with different number of "
3595 "parameters!");
3596
3597 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3598 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3599 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3600
3601 // Ignore address spaces in pointee type. This is to disallow overloading
3602 // on __ptr32/__ptr64 address spaces.
3603 QualType OldType =
3604 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3605 QualType NewType =
3606 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3607
3608 if (!Context.hasSameType(OldType, NewType)) {
3609 if (ArgPos)
3610 *ArgPos = Idx;
3611 return false;
3612 }
3613 }
3614 return true;
3615}
3616
3618 const FunctionProtoType *NewType,
3619 unsigned *ArgPos, bool Reversed) {
3620 return FunctionParamTypesAreEqual(OldType->param_types(),
3621 NewType->param_types(), ArgPos, Reversed);
3622}
3623
3625 const FunctionDecl *NewFunction,
3626 unsigned *ArgPos,
3627 bool Reversed) {
3628
3629 if (OldFunction->getNumNonObjectParams() !=
3630 NewFunction->getNumNonObjectParams())
3631 return false;
3632
3633 unsigned OldIgnore =
3635 unsigned NewIgnore =
3637
3638 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3639 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3640
3641 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3642 NewPT->param_types().slice(NewIgnore),
3643 ArgPos, Reversed);
3644}
3645
3647 CastKind &Kind,
3648 CXXCastPath& BasePath,
3649 bool IgnoreBaseAccess,
3650 bool Diagnose) {
3651 QualType FromType = From->getType();
3652 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3653
3654 Kind = CK_BitCast;
3655
3656 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3659 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3660 DiagRuntimeBehavior(From->getExprLoc(), From,
3661 PDiag(diag::warn_impcast_bool_to_null_pointer)
3662 << ToType << From->getSourceRange());
3663 else if (!isUnevaluatedContext())
3664 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3665 << ToType << From->getSourceRange();
3666 }
3667 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3668 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3669 QualType FromPointeeType = FromPtrType->getPointeeType(),
3670 ToPointeeType = ToPtrType->getPointeeType();
3671
3672 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3673 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3674 // We must have a derived-to-base conversion. Check an
3675 // ambiguous or inaccessible conversion.
3676 unsigned InaccessibleID = 0;
3677 unsigned AmbiguousID = 0;
3678 if (Diagnose) {
3679 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3680 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3681 }
3683 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3684 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3685 &BasePath, IgnoreBaseAccess))
3686 return true;
3687
3688 // The conversion was successful.
3689 Kind = CK_DerivedToBase;
3690 }
3691
3692 if (Diagnose && !IsCStyleOrFunctionalCast &&
3693 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3694 assert(getLangOpts().MSVCCompat &&
3695 "this should only be possible with MSVCCompat!");
3696 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3697 << From->getSourceRange();
3698 }
3699 }
3700 } else if (const ObjCObjectPointerType *ToPtrType =
3701 ToType->getAs<ObjCObjectPointerType>()) {
3702 if (const ObjCObjectPointerType *FromPtrType =
3703 FromType->getAs<ObjCObjectPointerType>()) {
3704 // Objective-C++ conversions are always okay.
3705 // FIXME: We should have a different class of conversions for the
3706 // Objective-C++ implicit conversions.
3707 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3708 return false;
3709 } else if (FromType->isBlockPointerType()) {
3710 Kind = CK_BlockPointerToObjCPointerCast;
3711 } else {
3712 Kind = CK_CPointerToObjCPointerCast;
3713 }
3714 } else if (ToType->isBlockPointerType()) {
3715 if (!FromType->isBlockPointerType())
3716 Kind = CK_AnyPointerToBlockPointerCast;
3717 }
3718
3719 // We shouldn't fall into this case unless it's valid for other
3720 // reasons.
3722 Kind = CK_NullToPointer;
3723
3724 return false;
3725}
3726
3728 QualType ToType,
3729 bool InOverloadResolution,
3730 QualType &ConvertedType) {
3731 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3732 if (!ToTypePtr)
3733 return false;
3734
3735 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3737 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3739 ConvertedType = ToType;
3740 return true;
3741 }
3742
3743 // Otherwise, both types have to be member pointers.
3744 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3745 if (!FromTypePtr)
3746 return false;
3747
3748 // A pointer to member of B can be converted to a pointer to member of D,
3749 // where D is derived from B (C++ 4.11p2).
3750 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3751 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3752
3753 if (!declaresSameEntity(FromClass, ToClass) &&
3754 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3755 ConvertedType = Context.getMemberPointerType(
3756 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3757 return true;
3758 }
3759
3760 return false;
3761}
3762
3764 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3765 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3766 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3767 // Lock down the inheritance model right now in MS ABI, whether or not the
3768 // pointee types are the same.
3769 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3770 (void)isCompleteType(CheckLoc, FromType);
3771 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3772 }
3773
3774 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3775 if (!FromPtrType) {
3776 // This must be a null pointer to member pointer conversion
3777 Kind = CK_NullToMemberPointer;
3779 }
3780
3781 // T == T, modulo cv
3783 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3784 ToPtrType->getPointeeType()))
3786
3787 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3788 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3789
3790 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3791 const CXXRecordDecl *Cls) {
3792 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3793 PD << Qual;
3794 else
3795 PD << Context.getCanonicalTagType(Cls);
3796 };
3797 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3798 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3799 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3800 return PD;
3801 };
3802
3803 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3805 std::swap(Base, Derived);
3806
3807 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3808 /*DetectVirtual=*/true);
3809 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3811
3812 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3813 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3814 PD << int(Direction);
3815 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3816 Diag(CheckLoc, PD);
3818 }
3819
3820 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3821 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3822 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3823 Diag(CheckLoc, PD);
3825 }
3826
3827 // Must be a base to derived member conversion.
3828 BuildBasePathArray(Paths, BasePath);
3830 ? CK_DerivedToBaseMemberPointer
3831 : CK_BaseToDerivedMemberPointer;
3832
3833 if (!IgnoreBaseAccess)
3834 switch (CheckBaseClassAccess(
3835 CheckLoc, Base, Derived, Paths.front(),
3837 ? diag::err_upcast_to_inaccessible_base
3838 : diag::err_downcast_from_inaccessible_base,
3839 [&](PartialDiagnostic &PD) {
3840 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3841 DerivedQual = ToPtrType->getQualifier();
3842 if (Direction == MemberPointerConversionDirection::Upcast)
3843 std::swap(BaseQual, DerivedQual);
3844 DiagCls(PD, DerivedQual, Derived);
3845 DiagCls(PD, BaseQual, Base);
3846 })) {
3848 case Sema::AR_delayed:
3849 case Sema::AR_dependent:
3850 // Optimistically assume that the delayed and dependent cases
3851 // will work out.
3852 break;
3853
3856 }
3857
3859}
3860
3861/// Determine whether the lifetime conversion between the two given
3862/// qualifiers sets is nontrivial.
3864 Qualifiers ToQuals) {
3865 // Converting anything to const __unsafe_unretained is trivial.
3866 if (ToQuals.hasConst() &&
3868 return false;
3869
3870 return true;
3871}
3872
3873/// Perform a single iteration of the loop for checking if a qualification
3874/// conversion is valid.
3875///
3876/// Specifically, check whether any change between the qualifiers of \p
3877/// FromType and \p ToType is permissible, given knowledge about whether every
3878/// outer layer is const-qualified.
3880 bool CStyle, bool IsTopLevel,
3881 bool &PreviousToQualsIncludeConst,
3882 bool &ObjCLifetimeConversion,
3883 const ASTContext &Ctx) {
3884 Qualifiers FromQuals = FromType.getQualifiers();
3885 Qualifiers ToQuals = ToType.getQualifiers();
3886
3887 // Ignore __unaligned qualifier.
3888 FromQuals.removeUnaligned();
3889
3890 // Objective-C ARC:
3891 // Check Objective-C lifetime conversions.
3892 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3893 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3894 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3895 ObjCLifetimeConversion = true;
3896 FromQuals.removeObjCLifetime();
3897 ToQuals.removeObjCLifetime();
3898 } else {
3899 // Qualification conversions cannot cast between different
3900 // Objective-C lifetime qualifiers.
3901 return false;
3902 }
3903 }
3904
3905 // Allow addition/removal of GC attributes but not changing GC attributes.
3906 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3907 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3908 FromQuals.removeObjCGCAttr();
3909 ToQuals.removeObjCGCAttr();
3910 }
3911
3912 // __ptrauth qualifiers must match exactly.
3913 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3914 return false;
3915
3916 // -- for every j > 0, if const is in cv 1,j then const is in cv
3917 // 2,j, and similarly for volatile.
3918 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3919 return false;
3920
3921 // If address spaces mismatch:
3922 // - in top level it is only valid to convert to addr space that is a
3923 // superset in all cases apart from C-style casts where we allow
3924 // conversions between overlapping address spaces.
3925 // - in non-top levels it is not a valid conversion.
3926 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3927 (!IsTopLevel ||
3928 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3929 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3930 return false;
3931
3932 // -- if the cv 1,j and cv 2,j are different, then const is in
3933 // every cv for 0 < k < j.
3934 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3935 !PreviousToQualsIncludeConst)
3936 return false;
3937
3938 // The following wording is from C++20, where the result of the conversion
3939 // is T3, not T2.
3940 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3941 // "array of unknown bound of"
3942 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3943 return false;
3944
3945 // -- if the resulting P3,i is different from P1,i [...], then const is
3946 // added to every cv 3_k for 0 < k < i.
3947 if (!CStyle && FromType->isConstantArrayType() &&
3948 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3949 return false;
3950
3951 // Keep track of whether all prior cv-qualifiers in the "to" type
3952 // include const.
3953 PreviousToQualsIncludeConst =
3954 PreviousToQualsIncludeConst && ToQuals.hasConst();
3955 return true;
3956}
3957
3958bool
3960 bool CStyle, bool &ObjCLifetimeConversion) {
3961 FromType = Context.getCanonicalType(FromType);
3962 ToType = Context.getCanonicalType(ToType);
3963 ObjCLifetimeConversion = false;
3964
3965 // If FromType and ToType are the same type, this is not a
3966 // qualification conversion.
3967 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3968 return false;
3969
3970 // (C++ 4.4p4):
3971 // A conversion can add cv-qualifiers at levels other than the first
3972 // in multi-level pointers, subject to the following rules: [...]
3973 bool PreviousToQualsIncludeConst = true;
3974 bool UnwrappedAnyPointer = false;
3975 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3976 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3977 !UnwrappedAnyPointer,
3978 PreviousToQualsIncludeConst,
3979 ObjCLifetimeConversion, getASTContext()))
3980 return false;
3981 UnwrappedAnyPointer = true;
3982 }
3983
3984 // We are left with FromType and ToType being the pointee types
3985 // after unwrapping the original FromType and ToType the same number
3986 // of times. If we unwrapped any pointers, and if FromType and
3987 // ToType have the same unqualified type (since we checked
3988 // qualifiers above), then this is a qualification conversion.
3989 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3990}
3991
3992/// - Determine whether this is a conversion from a scalar type to an
3993/// atomic type.
3994///
3995/// If successful, updates \c SCS's second and third steps in the conversion
3996/// sequence to finish the conversion.
3997static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3998 bool InOverloadResolution,
4000 bool CStyle) {
4001 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4002 if (!ToAtomic)
4003 return false;
4004
4006 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4007 InOverloadResolution, InnerSCS,
4008 CStyle, /*AllowObjCWritebackConversion=*/false))
4009 return false;
4010
4011 SCS.Second = InnerSCS.Second;
4012 SCS.setToType(1, InnerSCS.getToType(1));
4013 SCS.Third = InnerSCS.Third;
4016 SCS.setToType(2, InnerSCS.getToType(2));
4017 return true;
4018}
4019
4021 QualType ToType,
4022 bool InOverloadResolution,
4024 bool CStyle) {
4025 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4026 if (!ToOBT)
4027 return false;
4028
4029 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4030 QualType FromType = From->getType();
4031 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4032 return false;
4033
4035 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4036 InOverloadResolution, InnerSCS, CStyle,
4037 /*AllowObjCWritebackConversion=*/false))
4038 return false;
4039
4040 SCS.Second = InnerSCS.Second;
4041 SCS.setToType(1, InnerSCS.getToType(1));
4042 SCS.Third = InnerSCS.Third;
4045 SCS.setToType(2, InnerSCS.getToType(2));
4046 return true;
4047}
4048
4051 QualType Type) {
4052 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4053 if (CtorType->getNumParams() > 0) {
4054 QualType FirstArg = CtorType->getParamType(0);
4055 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4056 return true;
4057 }
4058 return false;
4059}
4060
4061static OverloadingResult
4063 CXXRecordDecl *To,
4065 OverloadCandidateSet &CandidateSet,
4066 bool AllowExplicit) {
4068 for (auto *D : S.LookupConstructors(To)) {
4069 auto Info = getConstructorInfo(D);
4070 if (!Info)
4071 continue;
4072
4073 bool Usable = !Info.Constructor->isInvalidDecl() &&
4074 S.isInitListConstructor(Info.Constructor);
4075 if (Usable) {
4076 bool SuppressUserConversions = false;
4077 if (Info.ConstructorTmpl)
4078 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4079 /*ExplicitArgs*/ nullptr, From,
4080 CandidateSet, SuppressUserConversions,
4081 /*PartialOverloading*/ false,
4082 AllowExplicit);
4083 else
4084 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4085 CandidateSet, SuppressUserConversions,
4086 /*PartialOverloading*/ false, AllowExplicit);
4087 }
4088 }
4089
4090 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4091
4093 switch (auto Result =
4094 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4095 case OR_Deleted:
4096 case OR_Success: {
4097 // Record the standard conversion we used and the conversion function.
4099 QualType ThisType = Constructor->getFunctionObjectParameterType();
4100 // Initializer lists don't have conversions as such.
4102 User.HadMultipleCandidates = HadMultipleCandidates;
4104 User.FoundConversionFunction = Best->FoundDecl;
4106 User.After.setFromType(ThisType);
4107 User.After.setAllToTypes(ToType);
4108 return Result;
4109 }
4110
4112 return OR_No_Viable_Function;
4113 case OR_Ambiguous:
4114 return OR_Ambiguous;
4115 }
4116
4117 llvm_unreachable("Invalid OverloadResult!");
4118}
4119
4120/// Determines whether there is a user-defined conversion sequence
4121/// (C++ [over.ics.user]) that converts expression From to the type
4122/// ToType. If such a conversion exists, User will contain the
4123/// user-defined conversion sequence that performs such a conversion
4124/// and this routine will return true. Otherwise, this routine returns
4125/// false and User is unspecified.
4126///
4127/// \param AllowExplicit true if the conversion should consider C++0x
4128/// "explicit" conversion functions as well as non-explicit conversion
4129/// functions (C++0x [class.conv.fct]p2).
4130///
4131/// \param AllowObjCConversionOnExplicit true if the conversion should
4132/// allow an extra Objective-C pointer conversion on uses of explicit
4133/// constructors. Requires \c AllowExplicit to also be set.
4134static OverloadingResult
4137 OverloadCandidateSet &CandidateSet,
4138 AllowedExplicit AllowExplicit,
4139 bool AllowObjCConversionOnExplicit) {
4140 assert(AllowExplicit != AllowedExplicit::None ||
4141 !AllowObjCConversionOnExplicit);
4143
4144 // Whether we will only visit constructors.
4145 bool ConstructorsOnly = false;
4146
4147 // If the type we are conversion to is a class type, enumerate its
4148 // constructors.
4149 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4150 // C++ [over.match.ctor]p1:
4151 // When objects of class type are direct-initialized (8.5), or
4152 // copy-initialized from an expression of the same or a
4153 // derived class type (8.5), overload resolution selects the
4154 // constructor. [...] For copy-initialization, the candidate
4155 // functions are all the converting constructors (12.3.1) of
4156 // that class. The argument list is the expression-list within
4157 // the parentheses of the initializer.
4158 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4159 (From->getType()->isRecordType() &&
4160 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4161 ConstructorsOnly = true;
4162
4163 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4164 // We're not going to find any constructors.
4165 } else if (auto *ToRecordDecl =
4166 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4167 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4168
4169 Expr **Args = &From;
4170 unsigned NumArgs = 1;
4171 bool ListInitializing = false;
4172 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4173 // But first, see if there is an init-list-constructor that will work.
4175 S, From, ToType, ToRecordDecl, User, CandidateSet,
4176 AllowExplicit == AllowedExplicit::All);
4178 return Result;
4179 // Never mind.
4180 CandidateSet.clear(
4182
4183 // If we're list-initializing, we pass the individual elements as
4184 // arguments, not the entire list.
4185 Args = InitList->getInits();
4186 NumArgs = InitList->getNumInits();
4187 ListInitializing = true;
4188 }
4189
4190 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4191 auto Info = getConstructorInfo(D);
4192 if (!Info)
4193 continue;
4194
4195 bool Usable = !Info.Constructor->isInvalidDecl();
4196 if (!ListInitializing)
4197 Usable = Usable && Info.Constructor->isConvertingConstructor(
4198 /*AllowExplicit*/ true);
4199 if (Usable) {
4200 bool SuppressUserConversions = !ConstructorsOnly;
4201 // C++20 [over.best.ics.general]/4.5:
4202 // if the target is the first parameter of a constructor [of class
4203 // X] and the constructor [...] is a candidate by [...] the second
4204 // phase of [over.match.list] when the initializer list has exactly
4205 // one element that is itself an initializer list, [...] and the
4206 // conversion is to X or reference to cv X, user-defined conversion
4207 // sequences are not considered.
4208 if (SuppressUserConversions && ListInitializing) {
4209 SuppressUserConversions =
4210 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4211 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4212 ToType);
4213 }
4214 if (Info.ConstructorTmpl)
4216 Info.ConstructorTmpl, Info.FoundDecl,
4217 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4218 CandidateSet, SuppressUserConversions,
4219 /*PartialOverloading*/ false,
4220 AllowExplicit == AllowedExplicit::All);
4221 else
4222 // Allow one user-defined conversion when user specifies a
4223 // From->ToType conversion via an static cast (c-style, etc).
4224 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4225 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4226 SuppressUserConversions,
4227 /*PartialOverloading*/ false,
4228 AllowExplicit == AllowedExplicit::All);
4229 }
4230 }
4231 }
4232 }
4233
4234 // Enumerate conversion functions, if we're allowed to.
4235 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4236 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4237 // No conversion functions from incomplete types.
4238 } else if (const RecordType *FromRecordType =
4239 From->getType()->getAsCanonical<RecordType>()) {
4240 if (auto *FromRecordDecl =
4241 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4242 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4243 // Add all of the conversion functions as candidates.
4244 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4245 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4246 DeclAccessPair FoundDecl = I.getPair();
4247 NamedDecl *D = FoundDecl.getDecl();
4248 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4249 if (isa<UsingShadowDecl>(D))
4250 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4251
4252 CXXConversionDecl *Conv;
4253 FunctionTemplateDecl *ConvTemplate;
4254 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4255 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4256 else
4257 Conv = cast<CXXConversionDecl>(D);
4258
4259 if (ConvTemplate)
4261 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4262 CandidateSet, AllowObjCConversionOnExplicit,
4263 AllowExplicit != AllowedExplicit::None);
4264 else
4265 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4266 CandidateSet, AllowObjCConversionOnExplicit,
4267 AllowExplicit != AllowedExplicit::None);
4268 }
4269 }
4270 }
4271
4272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4273
4275 switch (auto Result =
4276 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4277 case OR_Success:
4278 case OR_Deleted:
4279 // Record the standard conversion we used and the conversion function.
4281 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4282 // C++ [over.ics.user]p1:
4283 // If the user-defined conversion is specified by a
4284 // constructor (12.3.1), the initial standard conversion
4285 // sequence converts the source type to the type required by
4286 // the argument of the constructor.
4287 //
4288 if (isa<InitListExpr>(From)) {
4289 // Initializer lists don't have conversions as such.
4291 User.Before.FromBracedInitList = true;
4292 } else {
4293 if (Best->Conversions[0].isEllipsis())
4294 User.EllipsisConversion = true;
4295 else {
4296 User.Before = Best->Conversions[0].Standard;
4297 User.EllipsisConversion = false;
4298 }
4299 }
4300 User.HadMultipleCandidates = HadMultipleCandidates;
4302 User.FoundConversionFunction = Best->FoundDecl;
4304 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4305 User.After.setAllToTypes(ToType);
4306 return Result;
4307 }
4308 if (CXXConversionDecl *Conversion
4309 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4310
4311 assert(Best->HasFinalConversion);
4312
4313 // C++ [over.ics.user]p1:
4314 //
4315 // [...] If the user-defined conversion is specified by a
4316 // conversion function (12.3.2), the initial standard
4317 // conversion sequence converts the source type to the
4318 // implicit object parameter of the conversion function.
4319 User.Before = Best->Conversions[0].Standard;
4320 User.HadMultipleCandidates = HadMultipleCandidates;
4321 User.ConversionFunction = Conversion;
4322 User.FoundConversionFunction = Best->FoundDecl;
4323 User.EllipsisConversion = false;
4324
4325 // C++ [over.ics.user]p2:
4326 // The second standard conversion sequence converts the
4327 // result of the user-defined conversion to the target type
4328 // for the sequence. Since an implicit conversion sequence
4329 // is an initialization, the special rules for
4330 // initialization by user-defined conversion apply when
4331 // selecting the best user-defined conversion for a
4332 // user-defined conversion sequence (see 13.3.3 and
4333 // 13.3.3.1).
4334 User.After = Best->FinalConversion;
4335 return Result;
4336 }
4337 llvm_unreachable("Not a constructor or conversion function?");
4338
4340 return OR_No_Viable_Function;
4341
4342 case OR_Ambiguous:
4343 return OR_Ambiguous;
4344 }
4345
4346 llvm_unreachable("Invalid OverloadResult!");
4347}
4348
4349bool
4352 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4354 OverloadingResult OvResult =
4355 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4356 CandidateSet, AllowedExplicit::None, false);
4357
4358 if (!(OvResult == OR_Ambiguous ||
4359 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4360 return false;
4361
4362 auto Cands = CandidateSet.CompleteCandidates(
4363 *this,
4365 From);
4366 if (OvResult == OR_Ambiguous)
4367 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4368 << From->getType() << ToType << From->getSourceRange();
4369 else { // OR_No_Viable_Function && !CandidateSet.empty()
4370 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4371 diag::err_typecheck_nonviable_condition_incomplete,
4372 From->getType(), From->getSourceRange()))
4373 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4374 << false << From->getType() << From->getSourceRange() << ToType;
4375 }
4376
4377 CandidateSet.NoteCandidates(
4378 *this, From, Cands);
4379 return true;
4380}
4381
4382// Helper for compareConversionFunctions that gets the FunctionType that the
4383// conversion-operator return value 'points' to, or nullptr.
4384static const FunctionType *
4386 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4387 const PointerType *RetPtrTy =
4388 ConvFuncTy->getReturnType()->getAs<PointerType>();
4389
4390 if (!RetPtrTy)
4391 return nullptr;
4392
4393 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4394}
4395
4396/// Compare the user-defined conversion functions or constructors
4397/// of two user-defined conversion sequences to determine whether any ordering
4398/// is possible.
4401 FunctionDecl *Function2) {
4402 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4403 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4404 if (!Conv1 || !Conv2)
4406
4407 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4409
4410 // Objective-C++:
4411 // If both conversion functions are implicitly-declared conversions from
4412 // a lambda closure type to a function pointer and a block pointer,
4413 // respectively, always prefer the conversion to a function pointer,
4414 // because the function pointer is more lightweight and is more likely
4415 // to keep code working.
4416 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4417 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4418 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4419 if (Block1 != Block2)
4420 return Block1 ? ImplicitConversionSequence::Worse
4422 }
4423
4424 // In order to support multiple calling conventions for the lambda conversion
4425 // operator (such as when the free and member function calling convention is
4426 // different), prefer the 'free' mechanism, followed by the calling-convention
4427 // of operator(). The latter is in place to support the MSVC-like solution of
4428 // defining ALL of the possible conversions in regards to calling-convention.
4429 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4430 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4431
4432 if (Conv1FuncRet && Conv2FuncRet &&
4433 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4434 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4435 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4436
4437 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4438 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4439
4440 CallingConv CallOpCC =
4441 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4443 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4445 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4446
4447 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4448 for (CallingConv CC : PrefOrder) {
4449 if (Conv1CC == CC)
4451 if (Conv2CC == CC)
4453 }
4454 }
4455
4457}
4458
4465
4466/// CompareImplicitConversionSequences - Compare two implicit
4467/// conversion sequences to determine whether one is better than the
4468/// other or if they are indistinguishable (C++ 13.3.3.2).
4471 const ImplicitConversionSequence& ICS1,
4472 const ImplicitConversionSequence& ICS2)
4473{
4474 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4475 // conversion sequences (as defined in 13.3.3.1)
4476 // -- a standard conversion sequence (13.3.3.1.1) is a better
4477 // conversion sequence than a user-defined conversion sequence or
4478 // an ellipsis conversion sequence, and
4479 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4480 // conversion sequence than an ellipsis conversion sequence
4481 // (13.3.3.1.3).
4482 //
4483 // C++0x [over.best.ics]p10:
4484 // For the purpose of ranking implicit conversion sequences as
4485 // described in 13.3.3.2, the ambiguous conversion sequence is
4486 // treated as a user-defined sequence that is indistinguishable
4487 // from any other user-defined conversion sequence.
4488
4489 // String literal to 'char *' conversion has been deprecated in C++03. It has
4490 // been removed from C++11. We still accept this conversion, if it happens at
4491 // the best viable function. Otherwise, this conversion is considered worse
4492 // than ellipsis conversion. Consider this as an extension; this is not in the
4493 // standard. For example:
4494 //
4495 // int &f(...); // #1
4496 // void f(char*); // #2
4497 // void g() { int &r = f("foo"); }
4498 //
4499 // In C++03, we pick #2 as the best viable function.
4500 // In C++11, we pick #1 as the best viable function, because ellipsis
4501 // conversion is better than string-literal to char* conversion (since there
4502 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4503 // convert arguments, #2 would be the best viable function in C++11.
4504 // If the best viable function has this conversion, a warning will be issued
4505 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4506
4507 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4510 // Ill-formedness must not differ
4511 ICS1.isBad() == ICS2.isBad())
4515
4516 if (ICS1.getKindRank() < ICS2.getKindRank())
4518 if (ICS2.getKindRank() < ICS1.getKindRank())
4520
4521 // The following checks require both conversion sequences to be of
4522 // the same kind.
4523 if (ICS1.getKind() != ICS2.getKind())
4525
4528
4529 // Two implicit conversion sequences of the same form are
4530 // indistinguishable conversion sequences unless one of the
4531 // following rules apply: (C++ 13.3.3.2p3):
4532
4533 // List-initialization sequence L1 is a better conversion sequence than
4534 // list-initialization sequence L2 if:
4535 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4536 // if not that,
4537 // — L1 and L2 convert to arrays of the same element type, and either the
4538 // number of elements n_1 initialized by L1 is less than the number of
4539 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4540 // an array of unknown bound and L1 does not,
4541 // even if one of the other rules in this paragraph would otherwise apply.
4542 if (!ICS1.isBad()) {
4543 bool StdInit1 = false, StdInit2 = false;
4546 nullptr);
4549 nullptr);
4550 if (StdInit1 != StdInit2)
4551 return StdInit1 ? ImplicitConversionSequence::Better
4553
4556 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4558 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4560 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4561 CAT2->getElementType())) {
4562 // Both to arrays of the same element type
4563 if (CAT1->getSize() != CAT2->getSize())
4564 // Different sized, the smaller wins
4565 return CAT1->getSize().ult(CAT2->getSize())
4570 // One is incomplete, it loses
4574 }
4575 }
4576 }
4577
4578 if (ICS1.isStandard())
4579 // Standard conversion sequence S1 is a better conversion sequence than
4580 // standard conversion sequence S2 if [...]
4582 ICS1.Standard, ICS2.Standard);
4583 else if (ICS1.isUserDefined()) {
4584 // With lazy template loading, it is possible to find non-canonical
4585 // FunctionDecls, depending on when redecl chains are completed. Make sure
4586 // to compare the canonical decls of conversion functions. This avoids
4587 // ambiguity problems for templated conversion operators.
4588 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4589 if (ConvFunc1)
4590 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4591 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4592 if (ConvFunc2)
4593 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4594 // User-defined conversion sequence U1 is a better conversion
4595 // sequence than another user-defined conversion sequence U2 if
4596 // they contain the same user-defined conversion function or
4597 // constructor and if the second standard conversion sequence of
4598 // U1 is better than the second standard conversion sequence of
4599 // U2 (C++ 13.3.3.2p3).
4600 if (ConvFunc1 == ConvFunc2)
4602 ICS1.UserDefined.After,
4603 ICS2.UserDefined.After);
4604 else
4608 }
4609
4610 return Result;
4611}
4612
4613// Per 13.3.3.2p3, compare the given standard conversion sequences to
4614// determine if one is a proper subset of the other.
4617 const StandardConversionSequence& SCS1,
4618 const StandardConversionSequence& SCS2) {
4621
4622 // the identity conversion sequence is considered to be a subsequence of
4623 // any non-identity conversion sequence
4624 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4626 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4628
4629 if (SCS1.Second != SCS2.Second) {
4630 if (SCS1.Second == ICK_Identity)
4632 else if (SCS2.Second == ICK_Identity)
4634 else
4636 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4638
4639 if (SCS1.Third == SCS2.Third) {
4640 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4642 }
4643
4644 if (SCS1.Third == ICK_Identity)
4648
4649 if (SCS2.Third == ICK_Identity)
4653
4655}
4656
4657/// Determine whether one of the given reference bindings is better
4658/// than the other based on what kind of bindings they are.
4659static bool
4661 const StandardConversionSequence &SCS2) {
4662 // C++0x [over.ics.rank]p3b4:
4663 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4664 // implicit object parameter of a non-static member function declared
4665 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4666 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4667 // lvalue reference to a function lvalue and S2 binds an rvalue
4668 // reference*.
4669 //
4670 // FIXME: Rvalue references. We're going rogue with the above edits,
4671 // because the semantics in the current C++0x working paper (N3225 at the
4672 // time of this writing) break the standard definition of std::forward
4673 // and std::reference_wrapper when dealing with references to functions.
4674 // Proposed wording changes submitted to CWG for consideration.
4677 return false;
4678
4679 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4680 SCS2.IsLvalueReference) ||
4683}
4684
4690
4691/// Returns kind of fixed enum promotion the \a SCS uses.
4692static FixedEnumPromotion
4694
4695 if (SCS.Second != ICK_Integral_Promotion)
4697
4698 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4699 if (!Enum)
4701
4702 if (!Enum->isFixed())
4704
4705 QualType UnderlyingType = Enum->getIntegerType();
4706 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4708
4710}
4711
4712/// CompareStandardConversionSequences - Compare two standard
4713/// conversion sequences to determine whether one is better than the
4714/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4717 const StandardConversionSequence& SCS1,
4718 const StandardConversionSequence& SCS2)
4719{
4720 // Standard conversion sequence S1 is a better conversion sequence
4721 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4722
4723 // -- S1 is a proper subsequence of S2 (comparing the conversion
4724 // sequences in the canonical form defined by 13.3.3.1.1,
4725 // excluding any Lvalue Transformation; the identity conversion
4726 // sequence is considered to be a subsequence of any
4727 // non-identity conversion sequence) or, if not that,
4730 return CK;
4731
4732 // -- the rank of S1 is better than the rank of S2 (by the rules
4733 // defined below), or, if not that,
4734 ImplicitConversionRank Rank1 = SCS1.getRank();
4735 ImplicitConversionRank Rank2 = SCS2.getRank();
4736 if (Rank1 < Rank2)
4738 else if (Rank2 < Rank1)
4740
4741 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4742 // are indistinguishable unless one of the following rules
4743 // applies:
4744
4745 // A conversion that is not a conversion of a pointer, or
4746 // pointer to member, to bool is better than another conversion
4747 // that is such a conversion.
4749 return SCS2.isPointerConversionToBool()
4752
4753 // C++14 [over.ics.rank]p4b2:
4754 // This is retroactively applied to C++11 by CWG 1601.
4755 //
4756 // A conversion that promotes an enumeration whose underlying type is fixed
4757 // to its underlying type is better than one that promotes to the promoted
4758 // underlying type, if the two are different.
4761 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4762 FEP1 != FEP2)
4766
4767 // C++ [over.ics.rank]p4b2:
4768 //
4769 // If class B is derived directly or indirectly from class A,
4770 // conversion of B* to A* is better than conversion of B* to
4771 // void*, and conversion of A* to void* is better than conversion
4772 // of B* to void*.
4773 bool SCS1ConvertsToVoid
4775 bool SCS2ConvertsToVoid
4777 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4778 // Exactly one of the conversion sequences is a conversion to
4779 // a void pointer; it's the worse conversion.
4780 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4782 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4783 // Neither conversion sequence converts to a void pointer; compare
4784 // their derived-to-base conversions.
4786 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4787 return DerivedCK;
4788 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4789 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4790 // Both conversion sequences are conversions to void
4791 // pointers. Compare the source types to determine if there's an
4792 // inheritance relationship in their sources.
4793 QualType FromType1 = SCS1.getFromType();
4794 QualType FromType2 = SCS2.getFromType();
4795
4796 // Adjust the types we're converting from via the array-to-pointer
4797 // conversion, if we need to.
4798 if (SCS1.First == ICK_Array_To_Pointer)
4799 FromType1 = S.Context.getArrayDecayedType(FromType1);
4800 if (SCS2.First == ICK_Array_To_Pointer)
4801 FromType2 = S.Context.getArrayDecayedType(FromType2);
4802
4803 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4804 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4805
4806 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4808 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4810
4811 // Objective-C++: If one interface is more specific than the
4812 // other, it is the better one.
4813 const ObjCObjectPointerType* FromObjCPtr1
4814 = FromType1->getAs<ObjCObjectPointerType>();
4815 const ObjCObjectPointerType* FromObjCPtr2
4816 = FromType2->getAs<ObjCObjectPointerType>();
4817 if (FromObjCPtr1 && FromObjCPtr2) {
4818 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4819 FromObjCPtr2);
4820 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4821 FromObjCPtr1);
4822 if (AssignLeft != AssignRight) {
4823 return AssignLeft? ImplicitConversionSequence::Better
4825 }
4826 }
4827 }
4828
4829 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4830 // Check for a better reference binding based on the kind of bindings.
4831 if (isBetterReferenceBindingKind(SCS1, SCS2))
4833 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4835 }
4836
4837 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4838 // bullet 3).
4840 = CompareQualificationConversions(S, SCS1, SCS2))
4841 return QualCK;
4842
4845 return ObtCK;
4846
4847 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4848 // C++ [over.ics.rank]p3b4:
4849 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4850 // which the references refer are the same type except for
4851 // top-level cv-qualifiers, and the type to which the reference
4852 // initialized by S2 refers is more cv-qualified than the type
4853 // to which the reference initialized by S1 refers.
4854 QualType T1 = SCS1.getToType(2);
4855 QualType T2 = SCS2.getToType(2);
4856 T1 = S.Context.getCanonicalType(T1);
4857 T2 = S.Context.getCanonicalType(T2);
4858 Qualifiers T1Quals, T2Quals;
4859 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4860 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4861 if (UnqualT1 == UnqualT2) {
4862 // Objective-C++ ARC: If the references refer to objects with different
4863 // lifetimes, prefer bindings that don't change lifetime.
4869 }
4870
4871 // If the type is an array type, promote the element qualifiers to the
4872 // type for comparison.
4873 if (isa<ArrayType>(T1) && T1Quals)
4874 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4875 if (isa<ArrayType>(T2) && T2Quals)
4876 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4877 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4879 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4881 }
4882 }
4883
4884 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4885 // floating-to-integral conversion if the integral conversion
4886 // is between types of the same size.
4887 // For example:
4888 // void f(float);
4889 // void f(int);
4890 // int main {
4891 // long a;
4892 // f(a);
4893 // }
4894 // Here, MSVC will call f(int) instead of generating a compile error
4895 // as clang will do in standard mode.
4896 if (S.getLangOpts().MSVCCompat &&
4899 SCS2.Second == ICK_Floating_Integral &&
4900 S.Context.getTypeSize(SCS1.getFromType()) ==
4901 S.Context.getTypeSize(SCS1.getToType(2)))
4903
4904 // Prefer a compatible vector conversion over a lax vector conversion
4905 // For example:
4906 //
4907 // typedef float __v4sf __attribute__((__vector_size__(16)));
4908 // void f(vector float);
4909 // void f(vector signed int);
4910 // int main() {
4911 // __v4sf a;
4912 // f(a);
4913 // }
4914 // Here, we'd like to choose f(vector float) and not
4915 // report an ambiguous call error
4916 if (SCS1.Second == ICK_Vector_Conversion &&
4917 SCS2.Second == ICK_Vector_Conversion) {
4918 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4919 SCS1.getFromType(), SCS1.getToType(2));
4920 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4921 SCS2.getFromType(), SCS2.getToType(2));
4922
4923 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4924 return SCS1IsCompatibleVectorConversion
4927 }
4928
4929 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4931 bool SCS1IsCompatibleSVEVectorConversion =
4932 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4933 bool SCS2IsCompatibleSVEVectorConversion =
4934 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4935
4936 if (SCS1IsCompatibleSVEVectorConversion !=
4937 SCS2IsCompatibleSVEVectorConversion)
4938 return SCS1IsCompatibleSVEVectorConversion
4941 }
4942
4943 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4945 bool SCS1IsCompatibleRVVVectorConversion =
4947 bool SCS2IsCompatibleRVVVectorConversion =
4949
4950 if (SCS1IsCompatibleRVVVectorConversion !=
4951 SCS2IsCompatibleRVVVectorConversion)
4952 return SCS1IsCompatibleRVVVectorConversion
4955 }
4957}
4958
4959/// CompareOverflowBehaviorConversions - Compares two standard conversion
4960/// sequences to determine whether they can be ranked based on their
4961/// OverflowBehaviorType's underlying type.
4977
4978/// CompareQualificationConversions - Compares two standard conversion
4979/// sequences to determine whether they can be ranked based on their
4980/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4983 const StandardConversionSequence& SCS1,
4984 const StandardConversionSequence& SCS2) {
4985 // C++ [over.ics.rank]p3:
4986 // -- S1 and S2 differ only in their qualification conversion and
4987 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4988 // [C++98]
4989 // [...] and the cv-qualification signature of type T1 is a proper subset
4990 // of the cv-qualification signature of type T2, and S1 is not the
4991 // deprecated string literal array-to-pointer conversion (4.2).
4992 // [C++2a]
4993 // [...] where T1 can be converted to T2 by a qualification conversion.
4994 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4995 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4997
4998 // FIXME: the example in the standard doesn't use a qualification
4999 // conversion (!)
5000 QualType T1 = SCS1.getToType(2);
5001 QualType T2 = SCS2.getToType(2);
5002 T1 = S.Context.getCanonicalType(T1);
5003 T2 = S.Context.getCanonicalType(T2);
5004 assert(!T1->isReferenceType() && !T2->isReferenceType());
5005 Qualifiers T1Quals, T2Quals;
5006 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5007 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5008
5009 // If the types are the same, we won't learn anything by unwrapping
5010 // them.
5011 if (UnqualT1 == UnqualT2)
5013
5014 // Don't ever prefer a standard conversion sequence that uses the deprecated
5015 // string literal array to pointer conversion.
5016 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5017 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5018
5019 // Objective-C++ ARC:
5020 // Prefer qualification conversions not involving a change in lifetime
5021 // to qualification conversions that do change lifetime.
5024 CanPick1 = false;
5027 CanPick2 = false;
5028
5029 bool ObjCLifetimeConversion;
5030 if (CanPick1 &&
5031 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5032 CanPick1 = false;
5033 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5034 // directions, so we can't short-cut this second check in general.
5035 if (CanPick2 &&
5036 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5037 CanPick2 = false;
5038
5039 if (CanPick1 != CanPick2)
5040 return CanPick1 ? ImplicitConversionSequence::Better
5043}
5044
5045/// CompareDerivedToBaseConversions - Compares two standard conversion
5046/// sequences to determine whether they can be ranked based on their
5047/// various kinds of derived-to-base conversions (C++
5048/// [over.ics.rank]p4b3). As part of these checks, we also look at
5049/// conversions between Objective-C interface types.
5052 const StandardConversionSequence& SCS1,
5053 const StandardConversionSequence& SCS2) {
5054 QualType FromType1 = SCS1.getFromType();
5055 QualType ToType1 = SCS1.getToType(1);
5056 QualType FromType2 = SCS2.getFromType();
5057 QualType ToType2 = SCS2.getToType(1);
5058
5059 // Adjust the types we're converting from via the array-to-pointer
5060 // conversion, if we need to.
5061 if (SCS1.First == ICK_Array_To_Pointer)
5062 FromType1 = S.Context.getArrayDecayedType(FromType1);
5063 if (SCS2.First == ICK_Array_To_Pointer)
5064 FromType2 = S.Context.getArrayDecayedType(FromType2);
5065
5066 // Canonicalize all of the types.
5067 FromType1 = S.Context.getCanonicalType(FromType1);
5068 ToType1 = S.Context.getCanonicalType(ToType1);
5069 FromType2 = S.Context.getCanonicalType(FromType2);
5070 ToType2 = S.Context.getCanonicalType(ToType2);
5071
5072 // C++ [over.ics.rank]p4b3:
5073 //
5074 // If class B is derived directly or indirectly from class A and
5075 // class C is derived directly or indirectly from B,
5076 //
5077 // Compare based on pointer conversions.
5078 if (SCS1.Second == ICK_Pointer_Conversion &&
5080 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5081 FromType1->isPointerType() && FromType2->isPointerType() &&
5082 ToType1->isPointerType() && ToType2->isPointerType()) {
5083 QualType FromPointee1 =
5085 QualType ToPointee1 =
5087 QualType FromPointee2 =
5089 QualType ToPointee2 =
5091
5092 // -- conversion of C* to B* is better than conversion of C* to A*,
5093 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5094 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5096 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5098 }
5099
5100 // -- conversion of B* to A* is better than conversion of C* to A*,
5101 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5102 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5104 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5106 }
5107 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5109 const ObjCObjectPointerType *FromPtr1
5110 = FromType1->getAs<ObjCObjectPointerType>();
5111 const ObjCObjectPointerType *FromPtr2
5112 = FromType2->getAs<ObjCObjectPointerType>();
5113 const ObjCObjectPointerType *ToPtr1
5114 = ToType1->getAs<ObjCObjectPointerType>();
5115 const ObjCObjectPointerType *ToPtr2
5116 = ToType2->getAs<ObjCObjectPointerType>();
5117
5118 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5119 // Apply the same conversion ranking rules for Objective-C pointer types
5120 // that we do for C++ pointers to class types. However, we employ the
5121 // Objective-C pseudo-subtyping relationship used for assignment of
5122 // Objective-C pointer types.
5123 bool FromAssignLeft
5124 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5125 bool FromAssignRight
5126 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5127 bool ToAssignLeft
5128 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5129 bool ToAssignRight
5130 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5131
5132 // A conversion to an a non-id object pointer type or qualified 'id'
5133 // type is better than a conversion to 'id'.
5134 if (ToPtr1->isObjCIdType() &&
5135 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5137 if (ToPtr2->isObjCIdType() &&
5138 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5140
5141 // A conversion to a non-id object pointer type is better than a
5142 // conversion to a qualified 'id' type
5143 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5145 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5147
5148 // A conversion to an a non-Class object pointer type or qualified 'Class'
5149 // type is better than a conversion to 'Class'.
5150 if (ToPtr1->isObjCClassType() &&
5151 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5153 if (ToPtr2->isObjCClassType() &&
5154 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5156
5157 // A conversion to a non-Class object pointer type is better than a
5158 // conversion to a qualified 'Class' type.
5159 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5161 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5163
5164 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5165 if (S.Context.hasSameType(FromType1, FromType2) &&
5166 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5167 (ToAssignLeft != ToAssignRight)) {
5168 if (FromPtr1->isSpecialized()) {
5169 // "conversion of B<A> * to B * is better than conversion of B * to
5170 // C *.
5171 bool IsFirstSame =
5172 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5173 bool IsSecondSame =
5174 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5175 if (IsFirstSame) {
5176 if (!IsSecondSame)
5178 } else if (IsSecondSame)
5180 }
5181 return ToAssignLeft? ImplicitConversionSequence::Worse
5183 }
5184
5185 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5186 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5187 (FromAssignLeft != FromAssignRight))
5188 return FromAssignLeft? ImplicitConversionSequence::Better
5190 }
5191 }
5192
5193 // Ranking of member-pointer types.
5194 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5195 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5196 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5197 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5198 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5199 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5200 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5201 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5202 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5203 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5204 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5205 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5206 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5207 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5209 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5211 }
5212 // conversion of B::* to C::* is better than conversion of A::* to C::*
5213 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5214 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5216 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5218 }
5219 }
5220
5221 if (SCS1.Second == ICK_Derived_To_Base) {
5222 // -- conversion of C to B is better than conversion of C to A,
5223 // -- binding of an expression of type C to a reference of type
5224 // B& is better than binding an expression of type C to a
5225 // reference of type A&,
5226 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5227 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5228 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5230 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5232 }
5233
5234 // -- conversion of B to A is better than conversion of C to A.
5235 // -- binding of an expression of type B to a reference of type
5236 // A& is better than binding an expression of type C to a
5237 // reference of type A&,
5238 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5239 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5240 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5242 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5244 }
5245 }
5246
5248}
5249
5251 if (!T.getQualifiers().hasUnaligned())
5252 return T;
5253
5254 Qualifiers Q;
5255 T = Ctx.getUnqualifiedArrayType(T, Q);
5256 Q.removeUnaligned();
5257 return Ctx.getQualifiedType(T, Q);
5258}
5259
5262 QualType OrigT1, QualType OrigT2,
5263 ReferenceConversions *ConvOut) {
5264 assert(!OrigT1->isReferenceType() &&
5265 "T1 must be the pointee type of the reference type");
5266 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5267
5268 QualType T1 = Context.getCanonicalType(OrigT1);
5269 QualType T2 = Context.getCanonicalType(OrigT2);
5270 Qualifiers T1Quals, T2Quals;
5271 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5272 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5273
5274 ReferenceConversions ConvTmp;
5275 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5276 Conv = ReferenceConversions();
5277
5278 // C++2a [dcl.init.ref]p4:
5279 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5280 // reference-related to "cv2 T2" if T1 is similar to T2, or
5281 // T1 is a base class of T2.
5282 // "cv1 T1" is reference-compatible with "cv2 T2" if
5283 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5284 // "pointer to cv1 T1" via a standard conversion sequence.
5285
5286 // Check for standard conversions we can apply to pointers: derived-to-base
5287 // conversions, ObjC pointer conversions, and function pointer conversions.
5288 // (Qualification conversions are checked last.)
5289 if (UnqualT1 == UnqualT2) {
5290 // Nothing to do.
5291 } else if (isCompleteType(Loc, OrigT2) &&
5292 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5293 Conv |= ReferenceConversions::DerivedToBase;
5294 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5295 UnqualT2->isObjCObjectOrInterfaceType() &&
5296 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5297 Conv |= ReferenceConversions::ObjC;
5298 else if (UnqualT2->isFunctionType() &&
5299 IsFunctionConversion(UnqualT2, UnqualT1)) {
5300 Conv |= ReferenceConversions::Function;
5301 // No need to check qualifiers; function types don't have them.
5302 return Ref_Compatible;
5303 }
5304 bool ConvertedReferent = Conv != 0;
5305
5306 // We can have a qualification conversion. Compute whether the types are
5307 // similar at the same time.
5308 bool PreviousToQualsIncludeConst = true;
5309 bool TopLevel = true;
5310 do {
5311 if (T1 == T2)
5312 break;
5313
5314 // We will need a qualification conversion.
5315 Conv |= ReferenceConversions::Qualification;
5316
5317 // Track whether we performed a qualification conversion anywhere other
5318 // than the top level. This matters for ranking reference bindings in
5319 // overload resolution.
5320 if (!TopLevel)
5321 Conv |= ReferenceConversions::NestedQualification;
5322
5323 // MS compiler ignores __unaligned qualifier for references; do the same.
5324 T1 = withoutUnaligned(Context, T1);
5325 T2 = withoutUnaligned(Context, T2);
5326
5327 // If we find a qualifier mismatch, the types are not reference-compatible,
5328 // but are still be reference-related if they're similar.
5329 bool ObjCLifetimeConversion = false;
5330 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5331 PreviousToQualsIncludeConst,
5332 ObjCLifetimeConversion, getASTContext()))
5333 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5334 ? Ref_Related
5336
5337 // FIXME: Should we track this for any level other than the first?
5338 if (ObjCLifetimeConversion)
5339 Conv |= ReferenceConversions::ObjCLifetime;
5340
5341 TopLevel = false;
5342 } while (Context.UnwrapSimilarTypes(T1, T2));
5343
5344 // At this point, if the types are reference-related, we must either have the
5345 // same inner type (ignoring qualifiers), or must have already worked out how
5346 // to convert the referent.
5347 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5350}
5351
5352/// Look for a user-defined conversion to a value reference-compatible
5353/// with DeclType. Return true if something definite is found.
5354static bool
5356 QualType DeclType, SourceLocation DeclLoc,
5357 Expr *Init, QualType T2, bool AllowRvalues,
5358 bool AllowExplicit) {
5359 assert(T2->isRecordType() && "Can only find conversions of record types.");
5360 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5361 OverloadCandidateSet CandidateSet(
5363 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5364 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5365 NamedDecl *D = *I;
5367 if (isa<UsingShadowDecl>(D))
5368 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5369
5370 FunctionTemplateDecl *ConvTemplate
5371 = dyn_cast<FunctionTemplateDecl>(D);
5372 CXXConversionDecl *Conv;
5373 if (ConvTemplate)
5374 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5375 else
5376 Conv = cast<CXXConversionDecl>(D);
5377
5378 if (AllowRvalues) {
5379 // If we are initializing an rvalue reference, don't permit conversion
5380 // functions that return lvalues.
5381 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5382 const ReferenceType *RefType
5384 if (RefType && !RefType->getPointeeType()->isFunctionType())
5385 continue;
5386 }
5387
5388 if (!ConvTemplate &&
5390 DeclLoc,
5391 Conv->getConversionType()
5396 continue;
5397 } else {
5398 // If the conversion function doesn't return a reference type,
5399 // it can't be considered for this conversion. An rvalue reference
5400 // is only acceptable if its referencee is a function type.
5401
5402 const ReferenceType *RefType =
5404 if (!RefType ||
5405 (!RefType->isLValueReferenceType() &&
5406 !RefType->getPointeeType()->isFunctionType()))
5407 continue;
5408 }
5409
5410 if (ConvTemplate)
5412 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5413 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5414 else
5416 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5417 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5418 }
5419
5420 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5421
5423 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5424 case OR_Success:
5425
5426 assert(Best->HasFinalConversion);
5427
5428 // C++ [over.ics.ref]p1:
5429 //
5430 // [...] If the parameter binds directly to the result of
5431 // applying a conversion function to the argument
5432 // expression, the implicit conversion sequence is a
5433 // user-defined conversion sequence (13.3.3.1.2), with the
5434 // second standard conversion sequence either an identity
5435 // conversion or, if the conversion function returns an
5436 // entity of a type that is a derived class of the parameter
5437 // type, a derived-to-base Conversion.
5438 if (!Best->FinalConversion.DirectBinding)
5439 return false;
5440
5441 ICS.setUserDefined();
5442 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5443 ICS.UserDefined.After = Best->FinalConversion;
5444 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5445 ICS.UserDefined.ConversionFunction = Best->Function;
5446 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5447 ICS.UserDefined.EllipsisConversion = false;
5448 assert(ICS.UserDefined.After.ReferenceBinding &&
5450 "Expected a direct reference binding!");
5451 return true;
5452
5453 case OR_Ambiguous:
5454 ICS.setAmbiguous();
5455 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5456 Cand != CandidateSet.end(); ++Cand)
5457 if (Cand->Best)
5458 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5459 return true;
5460
5462 case OR_Deleted:
5463 // There was no suitable conversion, or we found a deleted
5464 // conversion; continue with other checks.
5465 return false;
5466 }
5467
5468 llvm_unreachable("Invalid OverloadResult!");
5469}
5470
5471/// Compute an implicit conversion sequence for reference
5472/// initialization.
5473static ImplicitConversionSequence
5475 SourceLocation DeclLoc,
5476 bool SuppressUserConversions,
5477 bool AllowExplicit) {
5478 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5479
5480 // Most paths end in a failed conversion.
5483
5484 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5485 QualType T2 = Init->getType();
5486
5487 // If the initializer is the address of an overloaded function, try
5488 // to resolve the overloaded function. If all goes well, T2 is the
5489 // type of the resulting function.
5490 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5493 false, Found))
5494 T2 = Fn->getType();
5495 }
5496
5497 // Compute some basic properties of the types and the initializer.
5498 bool isRValRef = DeclType->isRValueReferenceType();
5499 Expr::Classification InitCategory = Init->Classify(S.Context);
5500
5502 Sema::ReferenceCompareResult RefRelationship =
5503 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5504
5505 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5506 ICS.setStandard();
5508 // FIXME: A reference binding can be a function conversion too. We should
5509 // consider that when ordering reference-to-function bindings.
5510 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5512 : (RefConv & Sema::ReferenceConversions::ObjC)
5514 : ICK_Identity;
5516 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5517 // a reference binding that performs a non-top-level qualification
5518 // conversion as a qualification conversion, not as an identity conversion.
5519 ICS.Standard.Third = (RefConv &
5520 Sema::ReferenceConversions::NestedQualification)
5522 : ICK_Identity;
5523 ICS.Standard.setFromType(T2);
5524 ICS.Standard.setToType(0, T2);
5525 ICS.Standard.setToType(1, T1);
5526 ICS.Standard.setToType(2, T1);
5527 ICS.Standard.ReferenceBinding = true;
5528 ICS.Standard.DirectBinding = BindsDirectly;
5529 ICS.Standard.IsLvalueReference = !isRValRef;
5531 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5534 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5535 ICS.Standard.FromBracedInitList = false;
5536 ICS.Standard.CopyConstructor = nullptr;
5538 };
5539
5540 // C++0x [dcl.init.ref]p5:
5541 // A reference to type "cv1 T1" is initialized by an expression
5542 // of type "cv2 T2" as follows:
5543
5544 // -- If reference is an lvalue reference and the initializer expression
5545 if (!isRValRef) {
5546 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5547 // reference-compatible with "cv2 T2," or
5548 //
5549 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5550 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5551 // C++ [over.ics.ref]p1:
5552 // When a parameter of reference type binds directly (8.5.3)
5553 // to an argument expression, the implicit conversion sequence
5554 // is the identity conversion, unless the argument expression
5555 // has a type that is a derived class of the parameter type,
5556 // in which case the implicit conversion sequence is a
5557 // derived-to-base Conversion (13.3.3.1).
5558 SetAsReferenceBinding(/*BindsDirectly=*/true);
5559
5560 // Nothing more to do: the inaccessibility/ambiguity check for
5561 // derived-to-base conversions is suppressed when we're
5562 // computing the implicit conversion sequence (C++
5563 // [over.best.ics]p2).
5564 return ICS;
5565 }
5566
5567 // -- has a class type (i.e., T2 is a class type), where T1 is
5568 // not reference-related to T2, and can be implicitly
5569 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5570 // is reference-compatible with "cv3 T3" 92) (this
5571 // conversion is selected by enumerating the applicable
5572 // conversion functions (13.3.1.6) and choosing the best
5573 // one through overload resolution (13.3)),
5574 if (!SuppressUserConversions && T2->isRecordType() &&
5575 S.isCompleteType(DeclLoc, T2) &&
5576 RefRelationship == Sema::Ref_Incompatible) {
5577 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5578 Init, T2, /*AllowRvalues=*/false,
5579 AllowExplicit))
5580 return ICS;
5581 }
5582 }
5583
5584 // -- Otherwise, the reference shall be an lvalue reference to a
5585 // non-volatile const type (i.e., cv1 shall be const), or the reference
5586 // shall be an rvalue reference.
5587 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5588 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5590 return ICS;
5591 }
5592
5593 // -- If the initializer expression
5594 //
5595 // -- is an xvalue, class prvalue, array prvalue or function
5596 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5597 if (RefRelationship == Sema::Ref_Compatible &&
5598 (InitCategory.isXValue() ||
5599 (InitCategory.isPRValue() &&
5600 (T2->isRecordType() || T2->isArrayType())) ||
5601 (InitCategory.isLValue() && T2->isFunctionType()))) {
5602 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5603 // binding unless we're binding to a class prvalue.
5604 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5605 // allow the use of rvalue references in C++98/03 for the benefit of
5606 // standard library implementors; therefore, we need the xvalue check here.
5607 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5608 !(InitCategory.isPRValue() || T2->isRecordType()));
5609 return ICS;
5610 }
5611
5612 // -- has a class type (i.e., T2 is a class type), where T1 is not
5613 // reference-related to T2, and can be implicitly converted to
5614 // an xvalue, class prvalue, or function lvalue of type
5615 // "cv3 T3", where "cv1 T1" is reference-compatible with
5616 // "cv3 T3",
5617 //
5618 // then the reference is bound to the value of the initializer
5619 // expression in the first case and to the result of the conversion
5620 // in the second case (or, in either case, to an appropriate base
5621 // class subobject).
5622 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5623 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5624 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5625 Init, T2, /*AllowRvalues=*/true,
5626 AllowExplicit)) {
5627 // In the second case, if the reference is an rvalue reference
5628 // and the second standard conversion sequence of the
5629 // user-defined conversion sequence includes an lvalue-to-rvalue
5630 // conversion, the program is ill-formed.
5631 if (ICS.isUserDefined() && isRValRef &&
5634
5635 return ICS;
5636 }
5637
5638 // A temporary of function type cannot be created; don't even try.
5639 if (T1->isFunctionType())
5640 return ICS;
5641
5642 // -- Otherwise, a temporary of type "cv1 T1" is created and
5643 // initialized from the initializer expression using the
5644 // rules for a non-reference copy initialization (8.5). The
5645 // reference is then bound to the temporary. If T1 is
5646 // reference-related to T2, cv1 must be the same
5647 // cv-qualification as, or greater cv-qualification than,
5648 // cv2; otherwise, the program is ill-formed.
5649 if (RefRelationship == Sema::Ref_Related) {
5650 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5651 // we would be reference-compatible or reference-compatible with
5652 // added qualification. But that wasn't the case, so the reference
5653 // initialization fails.
5654 //
5655 // Note that we only want to check address spaces and cvr-qualifiers here.
5656 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5657 Qualifiers T1Quals = T1.getQualifiers();
5658 Qualifiers T2Quals = T2.getQualifiers();
5659 T1Quals.removeObjCGCAttr();
5660 T1Quals.removeObjCLifetime();
5661 T2Quals.removeObjCGCAttr();
5662 T2Quals.removeObjCLifetime();
5663 // MS compiler ignores __unaligned qualifier for references; do the same.
5664 T1Quals.removeUnaligned();
5665 T2Quals.removeUnaligned();
5666 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5667 return ICS;
5668 }
5669
5670 // If at least one of the types is a class type, the types are not
5671 // related, and we aren't allowed any user conversions, the
5672 // reference binding fails. This case is important for breaking
5673 // recursion, since TryImplicitConversion below will attempt to
5674 // create a temporary through the use of a copy constructor.
5675 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5676 (T1->isRecordType() || T2->isRecordType()))
5677 return ICS;
5678
5679 // If T1 is reference-related to T2 and the reference is an rvalue
5680 // reference, the initializer expression shall not be an lvalue.
5681 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5682 Init->Classify(S.Context).isLValue()) {
5684 return ICS;
5685 }
5686
5687 // C++ [over.ics.ref]p2:
5688 // When a parameter of reference type is not bound directly to
5689 // an argument expression, the conversion sequence is the one
5690 // required to convert the argument expression to the
5691 // underlying type of the reference according to
5692 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5693 // to copy-initializing a temporary of the underlying type with
5694 // the argument expression. Any difference in top-level
5695 // cv-qualification is subsumed by the initialization itself
5696 // and does not constitute a conversion.
5697 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5698 AllowedExplicit::None,
5699 /*InOverloadResolution=*/false,
5700 /*CStyle=*/false,
5701 /*AllowObjCWritebackConversion=*/false,
5702 /*AllowObjCConversionOnExplicit=*/false);
5703
5704 // Of course, that's still a reference binding.
5705 if (ICS.isStandard()) {
5706 ICS.Standard.ReferenceBinding = true;
5707 ICS.Standard.IsLvalueReference = !isRValRef;
5708 ICS.Standard.BindsToFunctionLvalue = false;
5709 ICS.Standard.BindsToRvalue = true;
5712 } else if (ICS.isUserDefined()) {
5713 const ReferenceType *LValRefType =
5716
5717 // C++ [over.ics.ref]p3:
5718 // Except for an implicit object parameter, for which see 13.3.1, a
5719 // standard conversion sequence cannot be formed if it requires [...]
5720 // binding an rvalue reference to an lvalue other than a function
5721 // lvalue.
5722 // Note that the function case is not possible here.
5723 if (isRValRef && LValRefType) {
5725 return ICS;
5726 }
5727
5729 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5731 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5735 }
5736
5737 return ICS;
5738}
5739
5740static ImplicitConversionSequence
5741TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5742 bool SuppressUserConversions,
5743 bool InOverloadResolution,
5744 bool AllowObjCWritebackConversion,
5745 bool AllowExplicit = false);
5746
5747/// TryListConversion - Try to copy-initialize a value of type ToType from the
5748/// initializer list From.
5749static ImplicitConversionSequence
5751 bool SuppressUserConversions,
5752 bool InOverloadResolution,
5753 bool AllowObjCWritebackConversion) {
5754 // C++11 [over.ics.list]p1:
5755 // When an argument is an initializer list, it is not an expression and
5756 // special rules apply for converting it to a parameter type.
5757
5759 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5760
5761 // We need a complete type for what follows. With one C++20 exception,
5762 // incomplete types can never be initialized from init lists.
5763 QualType InitTy = ToType;
5764 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5765 if (AT && S.getLangOpts().CPlusPlus20)
5766 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5767 // C++20 allows list initialization of an incomplete array type.
5768 InitTy = IAT->getElementType();
5769 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5770 return Result;
5771
5772 // C++20 [over.ics.list]/2:
5773 // If the initializer list is a designated-initializer-list, a conversion
5774 // is only possible if the parameter has an aggregate type
5775 //
5776 // FIXME: The exception for reference initialization here is not part of the
5777 // language rules, but follow other compilers in adding it as a tentative DR
5778 // resolution.
5779 bool IsDesignatedInit = From->hasDesignatedInit();
5780 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5781 IsDesignatedInit)
5782 return Result;
5783
5784 // Per DR1467 and DR2137:
5785 // If the parameter type is an aggregate class X and the initializer list
5786 // has a single element of type cv U, where U is X or a class derived from
5787 // X, the implicit conversion sequence is the one required to convert the
5788 // element to the parameter type.
5789 //
5790 // Otherwise, if the parameter type is a character array [... ]
5791 // and the initializer list has a single element that is an
5792 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5793 // implicit conversion sequence is the identity conversion.
5794 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5795 if (ToType->isRecordType() && ToType->isAggregateType()) {
5796 QualType InitType = From->getInit(0)->getType();
5797 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5798 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5799 return TryCopyInitialization(S, From->getInit(0), ToType,
5800 SuppressUserConversions,
5801 InOverloadResolution,
5802 AllowObjCWritebackConversion);
5803 }
5804
5805 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5806 InitializedEntity Entity =
5808 /*Consumed=*/false);
5809 if (S.CanPerformCopyInitialization(Entity, From)) {
5810 Result.setStandard();
5811 Result.Standard.setAsIdentityConversion();
5812 Result.Standard.setFromType(ToType);
5813 Result.Standard.setAllToTypes(ToType);
5814 return Result;
5815 }
5816 }
5817 }
5818
5819 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5820 // C++11 [over.ics.list]p2:
5821 // If the parameter type is std::initializer_list<X> or "array of X" and
5822 // all the elements can be implicitly converted to X, the implicit
5823 // conversion sequence is the worst conversion necessary to convert an
5824 // element of the list to X.
5825 //
5826 // C++14 [over.ics.list]p3:
5827 // Otherwise, if the parameter type is "array of N X", if the initializer
5828 // list has exactly N elements or if it has fewer than N elements and X is
5829 // default-constructible, and if all the elements of the initializer list
5830 // can be implicitly converted to X, the implicit conversion sequence is
5831 // the worst conversion necessary to convert an element of the list to X.
5832 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5833 unsigned e = From->getNumInits();
5836 QualType());
5837 QualType ContTy = ToType;
5838 bool IsUnbounded = false;
5839 if (AT) {
5840 InitTy = AT->getElementType();
5841 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5842 if (CT->getSize().ult(e)) {
5843 // Too many inits, fatally bad
5845 ToType);
5846 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5847 return Result;
5848 }
5849 if (CT->getSize().ugt(e)) {
5850 // Need an init from empty {}, is there one?
5851 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5852 From->getEndLoc(), /*isExplicit=*/false);
5853 EmptyList.setType(S.Context.VoidTy);
5854 DfltElt = TryListConversion(
5855 S, &EmptyList, InitTy, SuppressUserConversions,
5856 InOverloadResolution, AllowObjCWritebackConversion);
5857 if (DfltElt.isBad()) {
5858 // No {} init, fatally bad
5860 ToType);
5861 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5862 return Result;
5863 }
5864 }
5865 } else {
5866 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5867 IsUnbounded = true;
5868 if (!e) {
5869 // Cannot convert to zero-sized.
5871 ToType);
5872 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5873 return Result;
5874 }
5875 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5876 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5878 }
5879 }
5880
5881 Result.setStandard();
5882 Result.Standard.setAsIdentityConversion();
5883 Result.Standard.setFromType(InitTy);
5884 Result.Standard.setAllToTypes(InitTy);
5885 for (unsigned i = 0; i < e; ++i) {
5886 Expr *Init = From->getInit(i);
5888 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5889 AllowObjCWritebackConversion);
5890
5891 // Keep the worse conversion seen so far.
5892 // FIXME: Sequences are not totally ordered, so 'worse' can be
5893 // ambiguous. CWG has been informed.
5895 Result) ==
5897 Result = ICS;
5898 // Bail as soon as we find something unconvertible.
5899 if (Result.isBad()) {
5900 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5901 return Result;
5902 }
5903 }
5904 }
5905
5906 // If we needed any implicit {} initialization, compare that now.
5907 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5908 // has been informed that this might not be the best thing.
5909 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5910 S, From->getEndLoc(), DfltElt, Result) ==
5912 Result = DfltElt;
5913 // Record the type being initialized so that we may compare sequences
5914 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5915 return Result;
5916 }
5917
5918 // C++14 [over.ics.list]p4:
5919 // C++11 [over.ics.list]p3:
5920 // Otherwise, if the parameter is a non-aggregate class X and overload
5921 // resolution chooses a single best constructor [...] the implicit
5922 // conversion sequence is a user-defined conversion sequence. If multiple
5923 // constructors are viable but none is better than the others, the
5924 // implicit conversion sequence is a user-defined conversion sequence.
5925 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5926 // This function can deal with initializer lists.
5927 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5928 AllowedExplicit::None,
5929 InOverloadResolution, /*CStyle=*/false,
5930 AllowObjCWritebackConversion,
5931 /*AllowObjCConversionOnExplicit=*/false);
5932 }
5933
5934 // C++14 [over.ics.list]p5:
5935 // C++11 [over.ics.list]p4:
5936 // Otherwise, if the parameter has an aggregate type which can be
5937 // initialized from the initializer list [...] the implicit conversion
5938 // sequence is a user-defined conversion sequence.
5939 if (ToType->isAggregateType()) {
5940 // Type is an aggregate, argument is an init list. At this point it comes
5941 // down to checking whether the initialization works.
5942 // FIXME: Find out whether this parameter is consumed or not.
5943 InitializedEntity Entity =
5945 /*Consumed=*/false);
5947 From)) {
5948 Result.setUserDefined();
5949 Result.UserDefined.Before.setAsIdentityConversion();
5950 // Initializer lists don't have a type.
5951 Result.UserDefined.Before.setFromType(QualType());
5952 Result.UserDefined.Before.setAllToTypes(QualType());
5953
5954 Result.UserDefined.After.setAsIdentityConversion();
5955 Result.UserDefined.After.setFromType(ToType);
5956 Result.UserDefined.After.setAllToTypes(ToType);
5957 Result.UserDefined.ConversionFunction = nullptr;
5958 }
5959 return Result;
5960 }
5961
5962 // C++14 [over.ics.list]p6:
5963 // C++11 [over.ics.list]p5:
5964 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5965 if (ToType->isReferenceType()) {
5966 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5967 // mention initializer lists in any way. So we go by what list-
5968 // initialization would do and try to extrapolate from that.
5969
5970 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5971
5972 // If the initializer list has a single element that is reference-related
5973 // to the parameter type, we initialize the reference from that.
5974 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5975 Expr *Init = From->getInit(0);
5976
5977 QualType T2 = Init->getType();
5978
5979 // If the initializer is the address of an overloaded function, try
5980 // to resolve the overloaded function. If all goes well, T2 is the
5981 // type of the resulting function.
5982 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5985 Init, ToType, false, Found))
5986 T2 = Fn->getType();
5987 }
5988
5989 // Compute some basic properties of the types and the initializer.
5990 Sema::ReferenceCompareResult RefRelationship =
5991 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5992
5993 if (RefRelationship >= Sema::Ref_Related) {
5994 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5995 SuppressUserConversions,
5996 /*AllowExplicit=*/false);
5997 }
5998 }
5999
6000 // Otherwise, we bind the reference to a temporary created from the
6001 // initializer list.
6002 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6003 InOverloadResolution,
6004 AllowObjCWritebackConversion);
6005 if (Result.isFailure())
6006 return Result;
6007 assert(!Result.isEllipsis() &&
6008 "Sub-initialization cannot result in ellipsis conversion.");
6009
6010 // Can we even bind to a temporary?
6011 if (ToType->isRValueReferenceType() ||
6012 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6013 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6014 Result.UserDefined.After;
6015 SCS.ReferenceBinding = true;
6017 SCS.BindsToRvalue = true;
6018 SCS.BindsToFunctionLvalue = false;
6021 SCS.FromBracedInitList = false;
6022
6023 } else
6025 From, ToType);
6026 return Result;
6027 }
6028
6029 // C++14 [over.ics.list]p7:
6030 // C++11 [over.ics.list]p6:
6031 // Otherwise, if the parameter type is not a class:
6032 if (!ToType->isRecordType()) {
6033 // - if the initializer list has one element that is not itself an
6034 // initializer list, the implicit conversion sequence is the one
6035 // required to convert the element to the parameter type.
6036 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6037 // single integer.
6038 unsigned NumInits = From->getNumInits();
6039 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6040 !isa<EmbedExpr>(From->getInit(0))) {
6042 S, From->getInit(0), ToType, SuppressUserConversions,
6043 InOverloadResolution, AllowObjCWritebackConversion);
6044 if (Result.isStandard())
6045 Result.Standard.FromBracedInitList = true;
6046 }
6047 // - if the initializer list has no elements, the implicit conversion
6048 // sequence is the identity conversion.
6049 else if (NumInits == 0) {
6050 Result.setStandard();
6051 Result.Standard.setAsIdentityConversion();
6052 Result.Standard.setFromType(ToType);
6053 Result.Standard.setAllToTypes(ToType);
6054 }
6055 return Result;
6056 }
6057
6058 // C++14 [over.ics.list]p8:
6059 // C++11 [over.ics.list]p7:
6060 // In all cases other than those enumerated above, no conversion is possible
6061 return Result;
6062}
6063
6064/// TryCopyInitialization - Try to copy-initialize a value of type
6065/// ToType from the expression From. Return the implicit conversion
6066/// sequence required to pass this argument, which may be a bad
6067/// conversion sequence (meaning that the argument cannot be passed to
6068/// a parameter of this type). If @p SuppressUserConversions, then we
6069/// do not permit any user-defined conversion sequences.
6070static ImplicitConversionSequence
6072 bool SuppressUserConversions,
6073 bool InOverloadResolution,
6074 bool AllowObjCWritebackConversion,
6075 bool AllowExplicit) {
6076 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6077 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6078 InOverloadResolution,AllowObjCWritebackConversion);
6079
6080 if (ToType->isReferenceType())
6081 return TryReferenceInit(S, From, ToType,
6082 /*FIXME:*/ From->getBeginLoc(),
6083 SuppressUserConversions, AllowExplicit);
6084
6085 return TryImplicitConversion(S, From, ToType,
6086 SuppressUserConversions,
6087 AllowedExplicit::None,
6088 InOverloadResolution,
6089 /*CStyle=*/false,
6090 AllowObjCWritebackConversion,
6091 /*AllowObjCConversionOnExplicit=*/false);
6092}
6093
6094static bool TryCopyInitialization(const CanQualType FromQTy,
6095 const CanQualType ToQTy,
6096 Sema &S,
6097 SourceLocation Loc,
6098 ExprValueKind FromVK) {
6099 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6101 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6102
6103 return !ICS.isBad();
6104}
6105
6106/// TryObjectArgumentInitialization - Try to initialize the object
6107/// parameter of the given member function (@c Method) from the
6108/// expression @p From.
6110 Sema &S, SourceLocation Loc, QualType FromType,
6111 Expr::Classification FromClassification, CXXMethodDecl *Method,
6112 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6113 QualType ExplicitParameterType = QualType(),
6114 bool SuppressUserConversion = false) {
6115
6116 // We need to have an object of class type.
6117 if (const auto *PT = FromType->getAs<PointerType>()) {
6118 FromType = PT->getPointeeType();
6119
6120 // When we had a pointer, it's implicitly dereferenced, so we
6121 // better have an lvalue.
6122 assert(FromClassification.isLValue());
6123 }
6124
6125 auto ValueKindFromClassification = [](Expr::Classification C) {
6126 if (C.isPRValue())
6127 return clang::VK_PRValue;
6128 if (C.isXValue())
6129 return VK_XValue;
6130 return clang::VK_LValue;
6131 };
6132
6133 if (Method->isExplicitObjectMemberFunction()) {
6134 if (ExplicitParameterType.isNull())
6135 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6136 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6137 ValueKindFromClassification(FromClassification));
6139 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6140 /*InOverloadResolution=*/true, false);
6141 if (ICS.isBad())
6142 ICS.Bad.FromExpr = nullptr;
6143 return ICS;
6144 }
6145
6146 assert(FromType->isRecordType());
6147
6148 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6149 // C++98 [class.dtor]p2:
6150 // A destructor can be invoked for a const, volatile or const volatile
6151 // object.
6152 // C++98 [over.match.funcs]p4:
6153 // For static member functions, the implicit object parameter is considered
6154 // to match any object (since if the function is selected, the object is
6155 // discarded).
6156 Qualifiers Quals = Method->getMethodQualifiers();
6157 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6158 Quals.addConst();
6159 Quals.addVolatile();
6160 }
6161
6162 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6163
6164 // Set up the conversion sequence as a "bad" conversion, to allow us
6165 // to exit early.
6167
6168 // C++0x [over.match.funcs]p4:
6169 // For non-static member functions, the type of the implicit object
6170 // parameter is
6171 //
6172 // - "lvalue reference to cv X" for functions declared without a
6173 // ref-qualifier or with the & ref-qualifier
6174 // - "rvalue reference to cv X" for functions declared with the &&
6175 // ref-qualifier
6176 //
6177 // where X is the class of which the function is a member and cv is the
6178 // cv-qualification on the member function declaration.
6179 //
6180 // However, when finding an implicit conversion sequence for the argument, we
6181 // are not allowed to perform user-defined conversions
6182 // (C++ [over.match.funcs]p5). We perform a simplified version of
6183 // reference binding here, that allows class rvalues to bind to
6184 // non-constant references.
6185
6186 // First check the qualifiers.
6187 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6188 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6189 if (ImplicitParamType.getCVRQualifiers() !=
6190 FromTypeCanon.getLocalCVRQualifiers() &&
6191 !ImplicitParamType.isAtLeastAsQualifiedAs(
6192 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6194 FromType, ImplicitParamType);
6195 return ICS;
6196 }
6197
6198 if (FromTypeCanon.hasAddressSpace()) {
6199 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6200 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6201 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6202 S.getASTContext())) {
6204 FromType, ImplicitParamType);
6205 return ICS;
6206 }
6207 }
6208
6209 // Check that we have either the same type or a derived type. It
6210 // affects the conversion rank.
6211 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6212 ImplicitConversionKind SecondKind;
6213 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6214 SecondKind = ICK_Identity;
6215 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6216 SecondKind = ICK_Derived_To_Base;
6217 } else if (!Method->isExplicitObjectMemberFunction()) {
6219 FromType, ImplicitParamType);
6220 return ICS;
6221 }
6222
6223 // Check the ref-qualifier.
6224 switch (Method->getRefQualifier()) {
6225 case RQ_None:
6226 // Do nothing; we don't care about lvalueness or rvalueness.
6227 break;
6228
6229 case RQ_LValue:
6230 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6231 // non-const lvalue reference cannot bind to an rvalue
6233 ImplicitParamType);
6234 return ICS;
6235 }
6236 break;
6237
6238 case RQ_RValue:
6239 if (!FromClassification.isRValue()) {
6240 // rvalue reference cannot bind to an lvalue
6242 ImplicitParamType);
6243 return ICS;
6244 }
6245 break;
6246 }
6247
6248 // Success. Mark this as a reference binding.
6249 ICS.setStandard();
6251 ICS.Standard.Second = SecondKind;
6252 ICS.Standard.setFromType(FromType);
6253 ICS.Standard.setAllToTypes(ImplicitParamType);
6254 ICS.Standard.ReferenceBinding = true;
6255 ICS.Standard.DirectBinding = true;
6256 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6257 ICS.Standard.BindsToFunctionLvalue = false;
6258 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6259 ICS.Standard.FromBracedInitList = false;
6261 = (Method->getRefQualifier() == RQ_None);
6262 return ICS;
6263}
6264
6265/// PerformObjectArgumentInitialization - Perform initialization of
6266/// the implicit object parameter for the given Method with the given
6267/// expression.
6269 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6271 QualType FromRecordType, DestType;
6272 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6273
6274 if (getLangOpts().HLSL &&
6277 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6278 /*BasePath=*/nullptr, VK_PRValue,
6280 }
6281
6282 Expr::Classification FromClassification;
6283 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6284 FromRecordType = PT->getPointeeType();
6285 DestType = Method->getThisType();
6286 FromClassification = Expr::Classification::makeSimpleLValue();
6287 } else {
6288 FromRecordType = From->getType();
6289 DestType = ImplicitParamRecordType;
6290 FromClassification = From->Classify(Context);
6291
6292 // CWG2813 [expr.call]p6:
6293 // If the function is an implicit object member function, the object
6294 // expression of the class member access shall be a glvalue [...]
6295 if (From->isPRValue()) {
6296 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6297 Method->getRefQualifier() !=
6299 }
6300 }
6301
6302 // Note that we always use the true parent context when performing
6303 // the actual argument initialization.
6305 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6306 Method->getParent());
6307 if (ICS.isBad()) {
6308 switch (ICS.Bad.Kind) {
6310 Qualifiers FromQs = FromRecordType.getQualifiers();
6311 Qualifiers ToQs = DestType.getQualifiers();
6312 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6313 if (CVR) {
6314 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6315 << Method->getDeclName() << FromRecordType << (CVR - 1)
6316 << From->getSourceRange();
6317 Diag(Method->getLocation(), diag::note_previous_decl)
6318 << Method->getDeclName();
6319 return ExprError();
6320 }
6321 break;
6322 }
6323
6326 bool IsRValueQualified =
6327 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6328 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6329 << Method->getDeclName() << FromClassification.isRValue()
6330 << IsRValueQualified;
6331 Diag(Method->getLocation(), diag::note_previous_decl)
6332 << Method->getDeclName();
6333 return ExprError();
6334 }
6335
6338 break;
6339
6342 llvm_unreachable("Lists are not objects");
6343 }
6344
6345 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6346 << ImplicitParamRecordType << FromRecordType
6347 << From->getSourceRange();
6348 }
6349
6350 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6351 ExprResult FromRes =
6352 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6353 if (FromRes.isInvalid())
6354 return ExprError();
6355 From = FromRes.get();
6356 }
6357
6358 if (!Context.hasSameType(From->getType(), DestType)) {
6359 CastKind CK;
6360 QualType PteeTy = DestType->getPointeeType();
6361 LangAS DestAS =
6362 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6363 if (FromRecordType.getAddressSpace() != DestAS)
6364 CK = CK_AddressSpaceConversion;
6365 else
6366 CK = CK_NoOp;
6367 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6368 }
6369 return From;
6370}
6371
6372/// TryContextuallyConvertToBool - Attempt to contextually convert the
6373/// expression From to bool (C++0x [conv]p3).
6376 // C++ [dcl.init]/17.8:
6377 // - Otherwise, if the initialization is direct-initialization, the source
6378 // type is std::nullptr_t, and the destination type is bool, the initial
6379 // value of the object being initialized is false.
6380 if (From->getType()->isNullPtrType())
6382 S.Context.BoolTy,
6383 From->isGLValue());
6384
6385 // All other direct-initialization of bool is equivalent to an implicit
6386 // conversion to bool in which explicit conversions are permitted.
6387 return TryImplicitConversion(S, From, S.Context.BoolTy,
6388 /*SuppressUserConversions=*/false,
6389 AllowedExplicit::Conversions,
6390 /*InOverloadResolution=*/false,
6391 /*CStyle=*/false,
6392 /*AllowObjCWritebackConversion=*/false,
6393 /*AllowObjCConversionOnExplicit=*/false);
6394}
6395
6397 if (checkPlaceholderForOverload(*this, From))
6398 return ExprError();
6399 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6400 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6401
6403 if (!ICS.isBad())
6404 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6407 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6408 << From->getType() << From->getSourceRange();
6409 return ExprError();
6410}
6411
6412/// Check that the specified conversion is permitted in a converted constant
6413/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6414/// is acceptable.
6417 // Since we know that the target type is an integral or unscoped enumeration
6418 // type, most conversion kinds are impossible. All possible First and Third
6419 // conversions are fine.
6420 switch (SCS.Second) {
6421 case ICK_Identity:
6423 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6425 return true;
6426
6428 // Conversion from an integral or unscoped enumeration type to bool is
6429 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6430 // conversion, so we allow it in a converted constant expression.
6431 //
6432 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6433 // a lot of popular code. We should at least add a warning for this
6434 // (non-conforming) extension.
6436 SCS.getToType(2)->isBooleanType();
6437
6439 case ICK_Pointer_Member:
6440 // C++1z: null pointer conversions and null member pointer conversions are
6441 // only permitted if the source type is std::nullptr_t.
6442 return SCS.getFromType()->isNullPtrType();
6443
6456 case ICK_Vector_Splat:
6457 case ICK_Complex_Real:
6467 return false;
6468
6473 llvm_unreachable("found a first conversion kind in Second");
6474
6476 case ICK_Qualification:
6477 llvm_unreachable("found a third conversion kind in Second");
6478
6480 break;
6481 }
6482
6483 llvm_unreachable("unknown conversion kind");
6484}
6485
6486/// BuildConvertedConstantExpression - Check that the expression From is a
6487/// converted constant expression of type T, perform the conversion but
6488/// does not evaluate the expression
6490 QualType T, CCEKind CCE,
6491 NamedDecl *Dest,
6492 APValue &PreNarrowingValue) {
6493 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6495 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6496 "converted constant expression outside C++11 or TTP matching");
6497
6498 if (checkPlaceholderForOverload(S, From))
6499 return ExprError();
6500
6501 if (From->containsErrors()) {
6502 if (S.Context.hasSameType(From->getType(), T))
6503 return From;
6504
6505 // The expression already has errors, so the correct cast kind can't be
6506 // determined. Use RecoveryExpr to keep the expected type T and mark the
6507 // result as invalid, preventing further cascading errors.
6508 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6509 T);
6510 }
6511
6512 // C++1z [expr.const]p3:
6513 // A converted constant expression of type T is an expression,
6514 // implicitly converted to type T, where the converted
6515 // expression is a constant expression and the implicit conversion
6516 // sequence contains only [... list of conversions ...].
6518 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6520 : TryCopyInitialization(S, From, T,
6521 /*SuppressUserConversions=*/false,
6522 /*InOverloadResolution=*/false,
6523 /*AllowObjCWritebackConversion=*/false,
6524 /*AllowExplicit=*/false);
6525 StandardConversionSequence *SCS = nullptr;
6526 switch (ICS.getKind()) {
6528 SCS = &ICS.Standard;
6529 break;
6531 if (T->isRecordType())
6532 SCS = &ICS.UserDefined.Before;
6533 else
6534 SCS = &ICS.UserDefined.After;
6535 break;
6539 return S.Diag(From->getBeginLoc(),
6540 diag::err_typecheck_converted_constant_expression)
6541 << From->getType() << From->getSourceRange() << T;
6542 return ExprError();
6543
6546 llvm_unreachable("bad conversion in converted constant expression");
6547 }
6548
6549 // Check that we would only use permitted conversions.
6550 if (!CheckConvertedConstantConversions(S, *SCS)) {
6551 return S.Diag(From->getBeginLoc(),
6552 diag::err_typecheck_converted_constant_expression_disallowed)
6553 << From->getType() << From->getSourceRange() << T;
6554 }
6555 // [...] and where the reference binding (if any) binds directly.
6556 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6557 return S.Diag(From->getBeginLoc(),
6558 diag::err_typecheck_converted_constant_expression_indirect)
6559 << From->getType() << From->getSourceRange() << T;
6560 }
6561 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6562 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6563 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6564 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6565 // case explicitly.
6566 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6567 return S.Diag(From->getBeginLoc(),
6568 diag::err_reference_bind_to_bitfield_in_cce)
6569 << From->getSourceRange();
6570 }
6571
6572 // Usually we can simply apply the ImplicitConversionSequence we formed
6573 // earlier, but that's not guaranteed to work when initializing an object of
6574 // class type.
6576 bool IsTemplateArgument =
6578 if (T->isRecordType()) {
6579 assert(IsTemplateArgument &&
6580 "unexpected class type converted constant expr");
6584 SourceLocation(), From);
6585 } else {
6586 Result =
6588 }
6589 if (Result.isInvalid())
6590 return Result;
6591
6592 // C++2a [intro.execution]p5:
6593 // A full-expression is [...] a constant-expression [...]
6594 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6595 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6596 IsTemplateArgument);
6597 if (Result.isInvalid())
6598 return Result;
6599
6600 // Check for a narrowing implicit conversion.
6601 bool ReturnPreNarrowingValue = false;
6602 QualType PreNarrowingType;
6603 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6604 PreNarrowingType)) {
6606 // Implicit conversion to a narrower type, and the value is not a constant
6607 // expression. We'll diagnose this in a moment.
6608 case NK_Not_Narrowing:
6609 break;
6610
6612 if (CCE == CCEKind::ArrayBound &&
6613 PreNarrowingType->isIntegralOrEnumerationType() &&
6614 PreNarrowingValue.isInt()) {
6615 // Don't diagnose array bound narrowing here; we produce more precise
6616 // errors by allowing the un-narrowed value through.
6617 ReturnPreNarrowingValue = true;
6618 break;
6619 }
6620 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6621 << CCE << /*Constant*/ 1
6622 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6623 // If this is an SFINAE Context, treat the result as invalid so it stops
6624 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6625 // FIXME: Should do this whenever the above diagnostic is an error, but
6626 // without further changes this would degrade some other diagnostics.
6627 if (S.isSFINAEContext())
6628 return ExprError();
6629 break;
6630
6632 // Implicit conversion to a narrower type, but the expression is
6633 // value-dependent so we can't tell whether it's actually narrowing.
6634 // For matching the parameters of a TTP, the conversion is ill-formed
6635 // if it may narrow.
6636 if (CCE != CCEKind::TempArgStrict)
6637 break;
6638 [[fallthrough]];
6639 case NK_Type_Narrowing:
6640 // FIXME: It would be better to diagnose that the expression is not a
6641 // constant expression.
6642 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6643 << CCE << /*Constant*/ 0 << From->getType() << T;
6644 if (S.isSFINAEContext())
6645 return ExprError();
6646 break;
6647 }
6648 if (!ReturnPreNarrowingValue)
6649 PreNarrowingValue = {};
6650
6651 return Result;
6652}
6653
6654/// CheckConvertedConstantExpression - Check that the expression From is a
6655/// converted constant expression of type T, perform the conversion and produce
6656/// the converted expression, per C++11 [expr.const]p3.
6659 CCEKind CCE, bool RequireInt,
6660 NamedDecl *Dest) {
6661
6662 APValue PreNarrowingValue;
6664 PreNarrowingValue);
6665 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6666 Value = APValue();
6667 return Result;
6668 }
6669 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6670 RequireInt, PreNarrowingValue);
6671}
6672
6674 CCEKind CCE,
6675 NamedDecl *Dest) {
6676 APValue PreNarrowingValue;
6677 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6678 PreNarrowingValue);
6679}
6680
6682 APValue &Value, CCEKind CCE,
6683 NamedDecl *Dest) {
6684 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6685 Dest);
6686}
6687
6689 llvm::APSInt &Value,
6690 CCEKind CCE) {
6691 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6692
6693 APValue V;
6694 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6695 /*Dest=*/nullptr);
6696 if (!R.isInvalid() && !R.get()->isValueDependent())
6697 Value = V.getInt();
6698 return R;
6699}
6700
6703 CCEKind CCE, bool RequireInt,
6704 const APValue &PreNarrowingValue) {
6705
6706 ExprResult Result = E;
6707 // Check the expression is a constant expression.
6709 Expr::EvalResult Eval;
6710 Eval.Diag = &Notes;
6711
6712 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6713
6714 ConstantExprKind Kind;
6715 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6716 Kind = ConstantExprKind::ClassTemplateArgument;
6717 else if (CCE == CCEKind::TemplateArg)
6718 Kind = ConstantExprKind::NonClassTemplateArgument;
6719 else
6720 Kind = ConstantExprKind::Normal;
6721
6722 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6723 (RequireInt && !Eval.Val.isInt())) {
6724 // The expression can't be folded, so we can't keep it at this position in
6725 // the AST.
6726 Result = ExprError();
6727 } else {
6728 Value = Eval.Val;
6729
6730 if (Notes.empty()) {
6731 // It's a constant expression.
6732 Expr *E = Result.get();
6733 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6734 // We expect a ConstantExpr to have a value associated with it
6735 // by this point.
6736 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6737 "ConstantExpr has no value associated with it");
6738 (void)CE;
6739 } else {
6741 }
6742 if (!PreNarrowingValue.isAbsent())
6743 Value = std::move(PreNarrowingValue);
6744 return E;
6745 }
6746 }
6747
6748 // It's not a constant expression. Produce an appropriate diagnostic.
6749 if (Notes.size() == 1 &&
6750 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6751 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6752 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6753 diag::note_constexpr_invalid_template_arg) {
6754 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6755 for (unsigned I = 0; I < Notes.size(); ++I)
6756 Diag(Notes[I].first, Notes[I].second);
6757 } else {
6758 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6759 << CCE << E->getSourceRange();
6760 for (unsigned I = 0; I < Notes.size(); ++I)
6761 Diag(Notes[I].first, Notes[I].second);
6762 }
6763 return ExprError();
6764}
6765
6766/// dropPointerConversions - If the given standard conversion sequence
6767/// involves any pointer conversions, remove them. This may change
6768/// the result type of the conversion sequence.
6770 if (SCS.Second == ICK_Pointer_Conversion) {
6771 SCS.Second = ICK_Identity;
6772 SCS.Dimension = ICK_Identity;
6773 SCS.Third = ICK_Identity;
6774 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6775 }
6776}
6777
6778/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6779/// convert the expression From to an Objective-C pointer type.
6780static ImplicitConversionSequence
6782 // Do an implicit conversion to 'id'.
6785 = TryImplicitConversion(S, From, Ty,
6786 // FIXME: Are these flags correct?
6787 /*SuppressUserConversions=*/false,
6788 AllowedExplicit::Conversions,
6789 /*InOverloadResolution=*/false,
6790 /*CStyle=*/false,
6791 /*AllowObjCWritebackConversion=*/false,
6792 /*AllowObjCConversionOnExplicit=*/true);
6793
6794 // Strip off any final conversions to 'id'.
6795 switch (ICS.getKind()) {
6800 break;
6801
6804 break;
6805
6808 break;
6809 }
6810
6811 return ICS;
6812}
6813
6815 if (checkPlaceholderForOverload(*this, From))
6816 return ExprError();
6817
6818 QualType Ty = Context.getObjCIdType();
6821 if (!ICS.isBad())
6822 return PerformImplicitConversion(From, Ty, ICS,
6824 return ExprResult();
6825}
6826
6827static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6828 const Expr *Base = nullptr;
6829 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6830 "expected a member expression");
6831
6832 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6833 M && !M->isImplicitAccess())
6834 Base = M->getBase();
6835 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6836 M && !M->isImplicitAccess())
6837 Base = M->getBase();
6838
6839 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6840
6841 if (T->isPointerType())
6842 T = T->getPointeeType();
6843
6844 return T;
6845}
6846
6848 const FunctionDecl *Fun) {
6849 QualType ObjType = Obj->getType();
6850 if (ObjType->isPointerType()) {
6851 ObjType = ObjType->getPointeeType();
6852 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6854 /*CanOverflow=*/false, FPOptionsOverride());
6855 }
6856 return Obj;
6857}
6858
6866
6868 Expr *Object, MultiExprArg &Args,
6869 SmallVectorImpl<Expr *> &NewArgs) {
6870 assert(Method->isExplicitObjectMemberFunction() &&
6871 "Method is not an explicit member function");
6872 assert(NewArgs.empty() && "NewArgs should be empty");
6873
6874 NewArgs.reserve(Args.size() + 1);
6875 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6876 NewArgs.push_back(This);
6877 NewArgs.append(Args.begin(), Args.end());
6878 Args = NewArgs;
6880 Method, Object->getBeginLoc());
6881}
6882
6883/// Determine whether the provided type is an integral type, or an enumeration
6884/// type of a permitted flavor.
6886 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6887 : T->isIntegralOrUnscopedEnumerationType();
6888}
6889
6890static ExprResult
6893 QualType T, UnresolvedSetImpl &ViableConversions) {
6894
6895 if (Converter.Suppress)
6896 return ExprError();
6897
6898 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6899 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6900 CXXConversionDecl *Conv =
6901 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6903 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6904 }
6905 return From;
6906}
6907
6908static bool
6911 QualType T, bool HadMultipleCandidates,
6912 UnresolvedSetImpl &ExplicitConversions) {
6913 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6914 DeclAccessPair Found = ExplicitConversions[0];
6915 CXXConversionDecl *Conversion =
6916 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6917
6918 // The user probably meant to invoke the given explicit
6919 // conversion; use it.
6920 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6921 std::string TypeStr;
6922 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6923
6924 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6926 "static_cast<" + TypeStr + ">(")
6928 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6929 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6930
6931 // If we aren't in a SFINAE context, build a call to the
6932 // explicit conversion function.
6933 if (SemaRef.isSFINAEContext())
6934 return true;
6935
6936 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6937 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6938 HadMultipleCandidates);
6939 if (Result.isInvalid())
6940 return true;
6941
6942 // Replace the conversion with a RecoveryExpr, so we don't try to
6943 // instantiate it later, but can further diagnose here.
6944 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6945 From, Result.get()->getType());
6946 if (Result.isInvalid())
6947 return true;
6948 From = Result.get();
6949 }
6950 return false;
6951}
6952
6953static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6955 QualType T, bool HadMultipleCandidates,
6957 CXXConversionDecl *Conversion =
6958 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6959 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6960
6961 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6962 if (!Converter.SuppressConversion) {
6963 if (SemaRef.isSFINAEContext())
6964 return true;
6965
6966 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6967 << From->getSourceRange();
6968 }
6969
6970 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6971 HadMultipleCandidates);
6972 if (Result.isInvalid())
6973 return true;
6974 // Record usage of conversion in an implicit cast.
6975 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6976 CK_UserDefinedConversion, Result.get(),
6977 nullptr, Result.get()->getValueKind(),
6978 SemaRef.CurFPFeatureOverrides());
6979 return false;
6980}
6981
6983 Sema &SemaRef, SourceLocation Loc, Expr *From,
6985 if (!Converter.match(From->getType()) && !Converter.Suppress)
6986 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6987 << From->getSourceRange();
6988
6989 return SemaRef.DefaultLvalueConversion(From);
6990}
6991
6992static void
6994 UnresolvedSetImpl &ViableConversions,
6995 OverloadCandidateSet &CandidateSet) {
6996 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6997 NamedDecl *D = FoundDecl.getDecl();
6998 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6999 if (isa<UsingShadowDecl>(D))
7000 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7001
7002 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7004 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7005 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7006 continue;
7007 }
7009 SemaRef.AddConversionCandidate(
7010 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7011 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7012 }
7013}
7014
7015/// Attempt to convert the given expression to a type which is accepted
7016/// by the given converter.
7017///
7018/// This routine will attempt to convert an expression of class type to a
7019/// type accepted by the specified converter. In C++11 and before, the class
7020/// must have a single non-explicit conversion function converting to a matching
7021/// type. In C++1y, there can be multiple such conversion functions, but only
7022/// one target type.
7023///
7024/// \param Loc The source location of the construct that requires the
7025/// conversion.
7026///
7027/// \param From The expression we're converting from.
7028///
7029/// \param Converter Used to control and diagnose the conversion process.
7030///
7031/// \returns The expression, converted to an integral or enumeration type if
7032/// successful.
7034 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7035 // We can't perform any more checking for type-dependent expressions.
7036 if (From->isTypeDependent())
7037 return From;
7038
7039 // Process placeholders immediately.
7040 if (From->hasPlaceholderType()) {
7041 ExprResult result = CheckPlaceholderExpr(From);
7042 if (result.isInvalid())
7043 return result;
7044 From = result.get();
7045 }
7046
7047 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7048 ExprResult Converted = DefaultLvalueConversion(From);
7049 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7050 From = Converted.isUsable() ? Converted.get() : nullptr;
7051 // If the expression already has a matching type, we're golden.
7052 if (Converter.match(T))
7053 return Converted;
7054
7055 // FIXME: Check for missing '()' if T is a function type?
7056
7057 // We can only perform contextual implicit conversions on objects of class
7058 // type.
7059 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7060 if (!RecordTy || !getLangOpts().CPlusPlus) {
7061 if (!Converter.Suppress)
7062 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7063 return From;
7064 }
7065
7066 // We must have a complete class type.
7067 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7068 ContextualImplicitConverter &Converter;
7069 Expr *From;
7070
7071 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7072 : Converter(Converter), From(From) {}
7073
7074 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7075 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7076 }
7077 } IncompleteDiagnoser(Converter, From);
7078
7079 if (Converter.Suppress ? !isCompleteType(Loc, T)
7080 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7081 return From;
7082
7083 // Look for a conversion to an integral or enumeration type.
7085 ViableConversions; // These are *potentially* viable in C++1y.
7086 UnresolvedSet<4> ExplicitConversions;
7087 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7088 ->getDefinitionOrSelf()
7089 ->getVisibleConversionFunctions();
7090
7091 bool HadMultipleCandidates =
7092 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7093
7094 // To check that there is only one target type, in C++1y:
7095 QualType ToType;
7096 bool HasUniqueTargetType = true;
7097
7098 // Collect explicit or viable (potentially in C++1y) conversions.
7099 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7100 NamedDecl *D = (*I)->getUnderlyingDecl();
7101 CXXConversionDecl *Conversion;
7102 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7103 if (ConvTemplate) {
7105 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7106 else
7107 continue; // C++11 does not consider conversion operator templates(?).
7108 } else
7109 Conversion = cast<CXXConversionDecl>(D);
7110
7111 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7112 "Conversion operator templates are considered potentially "
7113 "viable in C++1y");
7114
7115 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7116 if (Converter.match(CurToType) || ConvTemplate) {
7117
7118 if (Conversion->isExplicit()) {
7119 // FIXME: For C++1y, do we need this restriction?
7120 // cf. diagnoseNoViableConversion()
7121 if (!ConvTemplate)
7122 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7123 } else {
7124 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7125 if (ToType.isNull())
7126 ToType = CurToType.getUnqualifiedType();
7127 else if (HasUniqueTargetType &&
7128 (CurToType.getUnqualifiedType() != ToType))
7129 HasUniqueTargetType = false;
7130 }
7131 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7132 }
7133 }
7134 }
7135
7136 if (getLangOpts().CPlusPlus14) {
7137 // C++1y [conv]p6:
7138 // ... An expression e of class type E appearing in such a context
7139 // is said to be contextually implicitly converted to a specified
7140 // type T and is well-formed if and only if e can be implicitly
7141 // converted to a type T that is determined as follows: E is searched
7142 // for conversion functions whose return type is cv T or reference to
7143 // cv T such that T is allowed by the context. There shall be
7144 // exactly one such T.
7145
7146 // If no unique T is found:
7147 if (ToType.isNull()) {
7148 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7149 HadMultipleCandidates,
7150 ExplicitConversions))
7151 return ExprError();
7152 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7153 }
7154
7155 // If more than one unique Ts are found:
7156 if (!HasUniqueTargetType)
7157 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7158 ViableConversions);
7159
7160 // If one unique T is found:
7161 // First, build a candidate set from the previously recorded
7162 // potentially viable conversions.
7164 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7165 CandidateSet);
7166
7167 // Then, perform overload resolution over the candidate set.
7169 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7170 case OR_Success: {
7171 // Apply this conversion.
7173 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7174 if (recordConversion(*this, Loc, From, Converter, T,
7175 HadMultipleCandidates, Found))
7176 return ExprError();
7177 break;
7178 }
7179 case OR_Ambiguous:
7180 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7181 ViableConversions);
7183 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7184 HadMultipleCandidates,
7185 ExplicitConversions))
7186 return ExprError();
7187 [[fallthrough]];
7188 case OR_Deleted:
7189 // We'll complain below about a non-integral condition type.
7190 break;
7191 }
7192 } else {
7193 switch (ViableConversions.size()) {
7194 case 0: {
7195 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7196 HadMultipleCandidates,
7197 ExplicitConversions))
7198 return ExprError();
7199
7200 // We'll complain below about a non-integral condition type.
7201 break;
7202 }
7203 case 1: {
7204 // Apply this conversion.
7205 DeclAccessPair Found = ViableConversions[0];
7206 if (recordConversion(*this, Loc, From, Converter, T,
7207 HadMultipleCandidates, Found))
7208 return ExprError();
7209 break;
7210 }
7211 default:
7212 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7213 ViableConversions);
7214 }
7215 }
7216
7217 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7218}
7219
7220/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7221/// an acceptable non-member overloaded operator for a call whose
7222/// arguments have types T1 (and, if non-empty, T2). This routine
7223/// implements the check in C++ [over.match.oper]p3b2 concerning
7224/// enumeration types.
7226 FunctionDecl *Fn,
7227 ArrayRef<Expr *> Args) {
7228 QualType T1 = Args[0]->getType();
7229 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7230
7231 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7232 return true;
7233
7234 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7235 return true;
7236
7237 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7238 if (Proto->getNumParams() < 1)
7239 return false;
7240
7241 if (T1->isEnumeralType()) {
7242 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7243 if (Context.hasSameUnqualifiedType(T1, ArgType))
7244 return true;
7245 }
7246
7247 if (Proto->getNumParams() < 2)
7248 return false;
7249
7250 if (!T2.isNull() && T2->isEnumeralType()) {
7251 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7252 if (Context.hasSameUnqualifiedType(T2, ArgType))
7253 return true;
7254 }
7255
7256 return false;
7257}
7258
7261 return false;
7262
7263 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7264 return FD->isTargetMultiVersion();
7265
7266 if (!FD->isMultiVersion())
7267 return false;
7268
7269 // Among multiple target versions consider either the default,
7270 // or the first non-default in the absence of default version.
7271 unsigned SeenAt = 0;
7272 unsigned I = 0;
7273 bool HasDefault = false;
7275 FD, [&](const FunctionDecl *CurFD) {
7276 if (FD == CurFD)
7277 SeenAt = I;
7278 else if (CurFD->isTargetMultiVersionDefault())
7279 HasDefault = true;
7280 ++I;
7281 });
7282 return HasDefault || SeenAt != 0;
7283}
7284
7287 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7288 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7289 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7290 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7291 bool StrictPackMatch) {
7292 const FunctionProtoType *Proto
7293 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7294 assert(Proto && "Functions without a prototype cannot be overloaded");
7295 assert(!Function->getDescribedFunctionTemplate() &&
7296 "Use AddTemplateOverloadCandidate for function templates");
7297
7298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7300 // If we get here, it's because we're calling a member function
7301 // that is named without a member access expression (e.g.,
7302 // "this->f") that was either written explicitly or created
7303 // implicitly. This can happen with a qualified call to a member
7304 // function, e.g., X::f(). We use an empty type for the implied
7305 // object argument (C++ [over.call.func]p3), and the acting context
7306 // is irrelevant.
7307 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7309 CandidateSet, SuppressUserConversions,
7310 PartialOverloading, EarlyConversions, PO,
7311 StrictPackMatch);
7312 return;
7313 }
7314 // We treat a constructor like a non-member function, since its object
7315 // argument doesn't participate in overload resolution.
7316 }
7317
7318 if (!CandidateSet.isNewCandidate(Function, PO))
7319 return;
7320
7321 // C++11 [class.copy]p11: [DR1402]
7322 // A defaulted move constructor that is defined as deleted is ignored by
7323 // overload resolution.
7324 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7325 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7326 Constructor->isMoveConstructor())
7327 return;
7328
7329 // Overload resolution is always an unevaluated context.
7332
7333 // C++ [over.match.oper]p3:
7334 // if no operand has a class type, only those non-member functions in the
7335 // lookup set that have a first parameter of type T1 or "reference to
7336 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7337 // is a right operand) a second parameter of type T2 or "reference to
7338 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7339 // candidate functions.
7340 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7342 return;
7343
7344 // Add this candidate
7345 OverloadCandidate &Candidate =
7346 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7347 Candidate.FoundDecl = FoundDecl;
7348 Candidate.Function = Function;
7349 Candidate.Viable = true;
7350 Candidate.RewriteKind =
7351 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7352 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7353 Candidate.ExplicitCallArguments = Args.size();
7354 Candidate.StrictPackMatch = StrictPackMatch;
7355
7356 // Explicit functions are not actually candidates at all if we're not
7357 // allowing them in this context, but keep them around so we can point
7358 // to them in diagnostics.
7359 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7360 Candidate.Viable = false;
7361 Candidate.FailureKind = ovl_fail_explicit;
7362 return;
7363 }
7364
7365 // Functions with internal linkage are only viable in the same module unit.
7366 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7367 /// FIXME: Currently, the semantics of linkage in clang is slightly
7368 /// different from the semantics in C++ spec. In C++ spec, only names
7369 /// have linkage. So that all entities of the same should share one
7370 /// linkage. But in clang, different entities of the same could have
7371 /// different linkage.
7372 const NamedDecl *ND = Function;
7373 bool IsImplicitlyInstantiated = false;
7374 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7375 ND = SpecInfo->getTemplate();
7376 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7378 }
7379
7380 /// Don't remove inline functions with internal linkage from the overload
7381 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7382 /// However:
7383 /// - Inline functions with internal linkage are a common pattern in
7384 /// headers to avoid ODR issues.
7385 /// - The global module is meant to be a transition mechanism for C and C++
7386 /// headers, and the current rules as written work against that goal.
7387 const bool IsInlineFunctionInGMF =
7388 Function->isFromGlobalModule() &&
7389 (IsImplicitlyInstantiated || Function->isInlined());
7390
7391 // Don't exclude internal-linkage entities from the current TU's global
7392 // module fragment.
7393 const Module *CurrentModule = getCurrentModule();
7394 const bool IsCurrentUnitGMFDecl =
7395 Function->isFromGlobalModule() && CurrentModule &&
7396 Function->getOwningModule()->getTopLevelModule() ==
7397 CurrentModule->getTopLevelModule();
7398
7399 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7400 !IsCurrentUnitGMFDecl) {
7401 Candidate.Viable = false;
7403 return;
7404 }
7405 }
7406
7408 Candidate.Viable = false;
7410 return;
7411 }
7412
7413 if (Constructor) {
7414 // C++ [class.copy]p3:
7415 // A member function template is never instantiated to perform the copy
7416 // of a class object to an object of its class type.
7417 CanQualType ClassType =
7418 Context.getCanonicalTagType(Constructor->getParent());
7419 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7420 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7421 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7422 ClassType))) {
7423 Candidate.Viable = false;
7425 return;
7426 }
7427
7428 // C++ [over.match.funcs]p8: (proposed DR resolution)
7429 // A constructor inherited from class type C that has a first parameter
7430 // of type "reference to P" (including such a constructor instantiated
7431 // from a template) is excluded from the set of candidate functions when
7432 // constructing an object of type cv D if the argument list has exactly
7433 // one argument and D is reference-related to P and P is reference-related
7434 // to C.
7435 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7436 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7437 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7438 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7439 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7440 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7441 SourceLocation Loc = Args.front()->getExprLoc();
7442 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7443 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7444 Candidate.Viable = false;
7446 return;
7447 }
7448 }
7449
7450 // Check that the constructor is capable of constructing an object in the
7451 // destination address space.
7453 Constructor->getMethodQualifiers().getAddressSpace(),
7454 CandidateSet.getDestAS(), getASTContext())) {
7455 Candidate.Viable = false;
7457 }
7458 }
7459
7460 unsigned NumParams = Proto->getNumParams();
7461
7462 // (C++ 13.3.2p2): A candidate function having fewer than m
7463 // parameters is viable only if it has an ellipsis in its parameter
7464 // list (8.3.5).
7465 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7466 !Proto->isVariadic() &&
7467 shouldEnforceArgLimit(PartialOverloading, Function)) {
7468 Candidate.Viable = false;
7470 return;
7471 }
7472
7473 // (C++ 13.3.2p2): A candidate function having more than m parameters
7474 // is viable only if the (m+1)st parameter has a default argument
7475 // (8.3.6). For the purposes of overload resolution, the
7476 // parameter list is truncated on the right, so that there are
7477 // exactly m parameters.
7478 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7479 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7480 !PartialOverloading) {
7481 // Not enough arguments.
7482 Candidate.Viable = false;
7484 return;
7485 }
7486
7487 // (CUDA B.1): Check for invalid calls between targets.
7488 if (getLangOpts().CUDA) {
7489 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7490 // Skip the check for callers that are implicit members, because in this
7491 // case we may not yet know what the member's target is; the target is
7492 // inferred for the member automatically, based on the bases and fields of
7493 // the class.
7494 if (!(Caller && Caller->isImplicit()) &&
7495 !CUDA().IsAllowedCall(Caller, Function)) {
7496 Candidate.Viable = false;
7497 Candidate.FailureKind = ovl_fail_bad_target;
7498 return;
7499 }
7500 }
7501
7502 if (Function->getTrailingRequiresClause()) {
7503 ConstraintSatisfaction Satisfaction;
7504 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7505 /*ForOverloadResolution*/ true) ||
7506 !Satisfaction.IsSatisfied) {
7507 Candidate.Viable = false;
7509 return;
7510 }
7511 }
7512
7513 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7514 // Determine the implicit conversion sequences for each of the
7515 // arguments.
7516 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7517 unsigned ConvIdx =
7518 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7519 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7520 // We already formed a conversion sequence for this parameter during
7521 // template argument deduction.
7522 } else if (ArgIdx < NumParams) {
7523 // (C++ 13.3.2p3): for F to be a viable function, there shall
7524 // exist for each argument an implicit conversion sequence
7525 // (13.3.3.1) that converts that argument to the corresponding
7526 // parameter of F.
7527 QualType ParamType = Proto->getParamType(ArgIdx);
7528 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7529 if (ParamABI == ParameterABI::HLSLOut ||
7530 ParamABI == ParameterABI::HLSLInOut) {
7531 ParamType = ParamType.getNonReferenceType();
7532 if (ParamABI == ParameterABI::HLSLInOut &&
7533 Args[ArgIdx]->getType().getAddressSpace() ==
7535 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7536 }
7537 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7538 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7539 /*InOverloadResolution=*/true,
7540 /*AllowObjCWritebackConversion=*/
7541 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7542 if (Candidate.Conversions[ConvIdx].isBad()) {
7543 Candidate.Viable = false;
7545 return;
7546 }
7547 } else {
7548 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7549 // argument for which there is no corresponding parameter is
7550 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7551 Candidate.Conversions[ConvIdx].setEllipsis();
7552 }
7553 }
7554
7555 if (EnableIfAttr *FailedAttr =
7556 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7557 Candidate.Viable = false;
7558 Candidate.FailureKind = ovl_fail_enable_if;
7559 Candidate.DeductionFailure.Data = FailedAttr;
7560 return;
7561 }
7562}
7563
7567 if (Methods.size() <= 1)
7568 return nullptr;
7569
7570 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7571 bool Match = true;
7572 ObjCMethodDecl *Method = Methods[b];
7573 unsigned NumNamedArgs = Sel.getNumArgs();
7574 // Method might have more arguments than selector indicates. This is due
7575 // to addition of c-style arguments in method.
7576 if (Method->param_size() > NumNamedArgs)
7577 NumNamedArgs = Method->param_size();
7578 if (Args.size() < NumNamedArgs)
7579 continue;
7580
7581 for (unsigned i = 0; i < NumNamedArgs; i++) {
7582 // We can't do any type-checking on a type-dependent argument.
7583 if (Args[i]->isTypeDependent()) {
7584 Match = false;
7585 break;
7586 }
7587
7588 ParmVarDecl *param = Method->parameters()[i];
7589 Expr *argExpr = Args[i];
7590 assert(argExpr && "SelectBestMethod(): missing expression");
7591
7592 // Strip the unbridged-cast placeholder expression off unless it's
7593 // a consumed argument.
7594 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7595 !param->hasAttr<CFConsumedAttr>())
7596 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7597
7598 // If the parameter is __unknown_anytype, move on to the next method.
7599 if (param->getType() == Context.UnknownAnyTy) {
7600 Match = false;
7601 break;
7602 }
7603
7604 ImplicitConversionSequence ConversionState
7605 = TryCopyInitialization(*this, argExpr, param->getType(),
7606 /*SuppressUserConversions*/false,
7607 /*InOverloadResolution=*/true,
7608 /*AllowObjCWritebackConversion=*/
7609 getLangOpts().ObjCAutoRefCount,
7610 /*AllowExplicit*/false);
7611 // This function looks for a reasonably-exact match, so we consider
7612 // incompatible pointer conversions to be a failure here.
7613 if (ConversionState.isBad() ||
7614 (ConversionState.isStandard() &&
7615 ConversionState.Standard.Second ==
7617 Match = false;
7618 break;
7619 }
7620 }
7621 // Promote additional arguments to variadic methods.
7622 if (Match && Method->isVariadic()) {
7623 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7624 if (Args[i]->isTypeDependent()) {
7625 Match = false;
7626 break;
7627 }
7629 Args[i], VariadicCallType::Method, nullptr);
7630 if (Arg.isInvalid()) {
7631 Match = false;
7632 break;
7633 }
7634 }
7635 } else {
7636 // Check for extra arguments to non-variadic methods.
7637 if (Args.size() != NumNamedArgs)
7638 Match = false;
7639 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7640 // Special case when selectors have no argument. In this case, select
7641 // one with the most general result type of 'id'.
7642 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7643 QualType ReturnT = Methods[b]->getReturnType();
7644 if (ReturnT->isObjCIdType())
7645 return Methods[b];
7646 }
7647 }
7648 }
7649
7650 if (Match)
7651 return Method;
7652 }
7653 return nullptr;
7654}
7655
7657 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7658 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7659 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7660 if (ThisArg) {
7661 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7662 assert(!isa<CXXConstructorDecl>(Method) &&
7663 "Shouldn't have `this` for ctors!");
7664 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7666 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7667 if (R.isInvalid())
7668 return false;
7669 ConvertedThis = R.get();
7670 } else {
7671 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7672 (void)MD;
7673 assert((MissingImplicitThis || MD->isStatic() ||
7675 "Expected `this` for non-ctor instance methods");
7676 }
7677 ConvertedThis = nullptr;
7678 }
7679
7680 // Ignore any variadic arguments. Converting them is pointless, since the
7681 // user can't refer to them in the function condition.
7682 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7683
7684 // Convert the arguments.
7685 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7686 ExprResult R;
7688 S.Context, Function->getParamDecl(I)),
7689 SourceLocation(), Args[I]);
7690
7691 if (R.isInvalid())
7692 return false;
7693
7694 ConvertedArgs.push_back(R.get());
7695 }
7696
7697 if (Trap.hasErrorOccurred())
7698 return false;
7699
7700 // Push default arguments if needed.
7701 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7702 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7703 ParmVarDecl *P = Function->getParamDecl(i);
7704 if (!P->hasDefaultArg())
7705 return false;
7706 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7707 if (R.isInvalid())
7708 return false;
7709 ConvertedArgs.push_back(R.get());
7710 }
7711
7712 if (Trap.hasErrorOccurred())
7713 return false;
7714 }
7715 return true;
7716}
7717
7719 SourceLocation CallLoc,
7720 ArrayRef<Expr *> Args,
7721 bool MissingImplicitThis) {
7722 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7723 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7724 return nullptr;
7725
7726 SFINAETrap Trap(*this);
7727 // Perform the access checking immediately so any access diagnostics are
7728 // caught by the SFINAE trap.
7729 llvm::scope_exit UndelayDiags(
7730 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7731 DelayedDiagnostics.popUndelayed(CurrentState);
7732 });
7733 SmallVector<Expr *, 16> ConvertedArgs;
7734 // FIXME: We should look into making enable_if late-parsed.
7735 Expr *DiscardedThis;
7737 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7738 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7739 return *EnableIfAttrs.begin();
7740
7741 for (auto *EIA : EnableIfAttrs) {
7743 // FIXME: This doesn't consider value-dependent cases, because doing so is
7744 // very difficult. Ideally, we should handle them more gracefully.
7745 if (EIA->getCond()->isValueDependent() ||
7746 !EIA->getCond()->EvaluateWithSubstitution(
7747 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7748 return EIA;
7749
7750 if (!Result.isInt() || !Result.getInt().getBoolValue())
7751 return EIA;
7752 }
7753 return nullptr;
7754}
7755
7756template <typename CheckFn>
7758 bool ArgDependent, SourceLocation Loc,
7759 CheckFn &&IsSuccessful) {
7761 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7762 if (ArgDependent == DIA->getArgDependent())
7763 Attrs.push_back(DIA);
7764 }
7765
7766 // Common case: No diagnose_if attributes, so we can quit early.
7767 if (Attrs.empty())
7768 return false;
7769
7770 auto WarningBegin = std::stable_partition(
7771 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7772 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7773 DIA->getWarningGroup().empty();
7774 });
7775
7776 // Note that diagnose_if attributes are late-parsed, so they appear in the
7777 // correct order (unlike enable_if attributes).
7778 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7779 IsSuccessful);
7780 if (ErrAttr != WarningBegin) {
7781 const DiagnoseIfAttr *DIA = *ErrAttr;
7782 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7783 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7784 << DIA->getParent() << DIA->getCond()->getSourceRange();
7785 return true;
7786 }
7787
7788 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7789 switch (Sev) {
7790 case DiagnoseIfAttr::DS_warning:
7792 case DiagnoseIfAttr::DS_error:
7793 return diag::Severity::Error;
7794 }
7795 llvm_unreachable("Fully covered switch above!");
7796 };
7797
7798 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7799 if (IsSuccessful(DIA)) {
7800 if (DIA->getWarningGroup().empty() &&
7801 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7802 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7803 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7804 << DIA->getParent() << DIA->getCond()->getSourceRange();
7805 } else {
7806 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7807 DIA->getWarningGroup());
7808 assert(DiagGroup);
7809 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7810 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7811 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7812 S.Diag(Loc, DiagID) << DIA->getMessage();
7813 }
7814 }
7815
7816 return false;
7817}
7818
7820 const Expr *ThisArg,
7822 SourceLocation Loc) {
7824 *this, Function, /*ArgDependent=*/true, Loc,
7825 [&](const DiagnoseIfAttr *DIA) {
7827 // It's sane to use the same Args for any redecl of this function, since
7828 // EvaluateWithSubstitution only cares about the position of each
7829 // argument in the arg list, not the ParmVarDecl* it maps to.
7830 if (!DIA->getCond()->EvaluateWithSubstitution(
7831 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7832 return false;
7833 return Result.isInt() && Result.getInt().getBoolValue();
7834 });
7835}
7836
7838 SourceLocation Loc) {
7840 *this, ND, /*ArgDependent=*/false, Loc,
7841 [&](const DiagnoseIfAttr *DIA) {
7842 bool Result;
7843 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7844 Result;
7845 });
7846}
7847
7849 ArrayRef<Expr *> Args,
7850 OverloadCandidateSet &CandidateSet,
7851 TemplateArgumentListInfo *ExplicitTemplateArgs,
7852 bool SuppressUserConversions,
7853 bool PartialOverloading,
7854 bool FirstArgumentIsBase) {
7855 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7856 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7857 ArrayRef<Expr *> FunctionArgs = Args;
7858
7859 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7860 FunctionDecl *FD =
7861 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7862
7863 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7864 QualType ObjectType;
7865 Expr::Classification ObjectClassification;
7866 if (Args.size() > 0) {
7867 if (Expr *E = Args[0]) {
7868 // Use the explicit base to restrict the lookup:
7869 ObjectType = E->getType();
7870 // Pointers in the object arguments are implicitly dereferenced, so we
7871 // always classify them as l-values.
7872 if (!ObjectType.isNull() && ObjectType->isPointerType())
7873 ObjectClassification = Expr::Classification::makeSimpleLValue();
7874 else
7875 ObjectClassification = E->Classify(Context);
7876 } // .. else there is an implicit base.
7877 FunctionArgs = Args.slice(1);
7878 }
7879 if (FunTmpl) {
7881 FunTmpl, F.getPair(),
7883 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7884 FunctionArgs, CandidateSet, SuppressUserConversions,
7885 PartialOverloading);
7886 } else {
7887 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7888 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7889 ObjectClassification, FunctionArgs, CandidateSet,
7890 SuppressUserConversions, PartialOverloading);
7891 }
7892 } else {
7893 // This branch handles both standalone functions and static methods.
7894
7895 // Slice the first argument (which is the base) when we access
7896 // static method as non-static.
7897 if (Args.size() > 0 &&
7898 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7899 !isa<CXXConstructorDecl>(FD)))) {
7900 assert(cast<CXXMethodDecl>(FD)->isStatic());
7901 FunctionArgs = Args.slice(1);
7902 }
7903 if (FunTmpl) {
7904 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7905 ExplicitTemplateArgs, FunctionArgs,
7906 CandidateSet, SuppressUserConversions,
7907 PartialOverloading);
7908 } else {
7909 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7910 SuppressUserConversions, PartialOverloading);
7911 }
7912 }
7913 }
7914}
7915
7917 Expr::Classification ObjectClassification,
7918 ArrayRef<Expr *> Args,
7919 OverloadCandidateSet &CandidateSet,
7920 bool SuppressUserConversions,
7922 NamedDecl *Decl = FoundDecl.getDecl();
7924
7926 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7927
7928 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7929 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7930 "Expected a member function template");
7931 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7932 /*ExplicitArgs*/ nullptr, ObjectType,
7933 ObjectClassification, Args, CandidateSet,
7934 SuppressUserConversions, false, PO);
7935 } else {
7936 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7937 ObjectType, ObjectClassification, Args, CandidateSet,
7938 SuppressUserConversions, false, {}, PO);
7939 }
7940}
7941
7944 CXXRecordDecl *ActingContext, QualType ObjectType,
7945 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7946 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7947 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7948 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7949 const FunctionProtoType *Proto
7950 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7951 assert(Proto && "Methods without a prototype cannot be overloaded");
7953 "Use AddOverloadCandidate for constructors");
7954
7955 if (!CandidateSet.isNewCandidate(Method, PO))
7956 return;
7957
7958 // C++11 [class.copy]p23: [DR1402]
7959 // A defaulted move assignment operator that is defined as deleted is
7960 // ignored by overload resolution.
7961 if (Method->isDefaulted() && Method->isDeleted() &&
7962 Method->isMoveAssignmentOperator())
7963 return;
7964
7965 // Overload resolution is always an unevaluated context.
7968
7969 bool IgnoreExplicitObject =
7970 (Method->isExplicitObjectMemberFunction() &&
7971 CandidateSet.getKind() ==
7973 bool ImplicitObjectMethodTreatedAsStatic =
7974 CandidateSet.getKind() ==
7976 Method->isImplicitObjectMemberFunction();
7977
7978 unsigned ExplicitOffset =
7979 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7980
7981 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7982 int(ImplicitObjectMethodTreatedAsStatic);
7983
7984 unsigned ExtraArgs =
7986 ? 0
7987 : 1;
7988
7989 // Add this candidate
7990 OverloadCandidate &Candidate =
7991 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7992 Candidate.FoundDecl = FoundDecl;
7993 Candidate.Function = Method;
7994 Candidate.RewriteKind =
7995 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7996 Candidate.TookAddressOfOverload =
7998 Candidate.ExplicitCallArguments = Args.size();
7999 Candidate.StrictPackMatch = StrictPackMatch;
8000
8001 // (C++ 13.3.2p2): A candidate function having fewer than m
8002 // parameters is viable only if it has an ellipsis in its parameter
8003 // list (8.3.5).
8004 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
8005 !Proto->isVariadic() &&
8006 shouldEnforceArgLimit(PartialOverloading, Method)) {
8007 Candidate.Viable = false;
8009 return;
8010 }
8011
8012 // (C++ 13.3.2p2): A candidate function having more than m parameters
8013 // is viable only if the (m+1)st parameter has a default argument
8014 // (8.3.6). For the purposes of overload resolution, the
8015 // parameter list is truncated on the right, so that there are
8016 // exactly m parameters.
8017 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8018 ExplicitOffset +
8019 int(ImplicitObjectMethodTreatedAsStatic);
8020
8021 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8022 // Not enough arguments.
8023 Candidate.Viable = false;
8025 return;
8026 }
8027
8028 Candidate.Viable = true;
8029
8030 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8031 if (!IgnoreExplicitObject) {
8032 if (ObjectType.isNull())
8033 Candidate.IgnoreObjectArgument = true;
8034 else if (Method->isStatic()) {
8035 // [over.best.ics.general]p8
8036 // When the parameter is the implicit object parameter of a static member
8037 // function, the implicit conversion sequence is a standard conversion
8038 // sequence that is neither better nor worse than any other standard
8039 // conversion sequence.
8040 //
8041 // This is a rule that was introduced in C++23 to support static lambdas.
8042 // We apply it retroactively because we want to support static lambdas as
8043 // an extension and it doesn't hurt previous code.
8044 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8045 } else {
8046 // Determine the implicit conversion sequence for the object
8047 // parameter.
8048 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8049 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8050 Method, ActingContext, /*InOverloadResolution=*/true);
8051 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8052 Candidate.Viable = false;
8054 return;
8055 }
8056 }
8057 }
8058
8059 // (CUDA B.1): Check for invalid calls between targets.
8060 if (getLangOpts().CUDA)
8061 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8062 Method)) {
8063 Candidate.Viable = false;
8064 Candidate.FailureKind = ovl_fail_bad_target;
8065 return;
8066 }
8067
8068 if (Method->getTrailingRequiresClause()) {
8069 ConstraintSatisfaction Satisfaction;
8070 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8071 /*ForOverloadResolution*/ true) ||
8072 !Satisfaction.IsSatisfied) {
8073 Candidate.Viable = false;
8075 return;
8076 }
8077 }
8078
8079 // Determine the implicit conversion sequences for each of the
8080 // arguments.
8081 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8082 unsigned ConvIdx =
8083 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8084 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8085 // We already formed a conversion sequence for this parameter during
8086 // template argument deduction.
8087 } else if (ArgIdx < NumParams) {
8088 // (C++ 13.3.2p3): for F to be a viable function, there shall
8089 // exist for each argument an implicit conversion sequence
8090 // (13.3.3.1) that converts that argument to the corresponding
8091 // parameter of F.
8092 QualType ParamType;
8093 if (ImplicitObjectMethodTreatedAsStatic) {
8094 ParamType = ArgIdx == 0
8095 ? Method->getFunctionObjectParameterReferenceType()
8096 : Proto->getParamType(ArgIdx - 1);
8097 } else {
8098 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8099 }
8100 Candidate.Conversions[ConvIdx]
8101 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8102 SuppressUserConversions,
8103 /*InOverloadResolution=*/true,
8104 /*AllowObjCWritebackConversion=*/
8105 getLangOpts().ObjCAutoRefCount);
8106 if (Candidate.Conversions[ConvIdx].isBad()) {
8107 Candidate.Viable = false;
8109 return;
8110 }
8111 } else {
8112 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8113 // argument for which there is no corresponding parameter is
8114 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8115 Candidate.Conversions[ConvIdx].setEllipsis();
8116 }
8117 }
8118
8119 if (EnableIfAttr *FailedAttr =
8120 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8121 Candidate.Viable = false;
8122 Candidate.FailureKind = ovl_fail_enable_if;
8123 Candidate.DeductionFailure.Data = FailedAttr;
8124 return;
8125 }
8126
8128 Candidate.Viable = false;
8130 }
8131}
8132
8134 Sema &S, OverloadCandidateSet &CandidateSet,
8135 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8136 CXXRecordDecl *ActingContext,
8137 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8138 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8139 bool SuppressUserConversions, bool PartialOverloading,
8141
8142 // C++ [over.match.funcs]p7:
8143 // In each case where a candidate is a function template, candidate
8144 // function template specializations are generated using template argument
8145 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8146 // candidate functions in the usual way.113) A given name can refer to one
8147 // or more function templates and also to a set of overloaded non-template
8148 // functions. In such a case, the candidate functions generated from each
8149 // function template are combined with the set of non-template candidate
8150 // functions.
8151 TemplateDeductionInfo Info(CandidateSet.getLocation());
8152 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8153 FunctionDecl *Specialization = nullptr;
8154 ConversionSequenceList Conversions;
8156 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8157 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8158 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8159 CandidateSet.getKind() ==
8161 [&](ArrayRef<QualType> ParamTypes,
8162 bool OnlyInitializeNonUserDefinedConversions) {
8163 return S.CheckNonDependentConversions(
8164 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8165 Sema::CheckNonDependentConversionsFlag(
8166 SuppressUserConversions,
8167 OnlyInitializeNonUserDefinedConversions),
8168 ActingContext, ObjectType, ObjectClassification, PO);
8169 });
8171 OverloadCandidate &Candidate =
8172 CandidateSet.addCandidate(Conversions.size(), Conversions);
8173 Candidate.FoundDecl = FoundDecl;
8174 Candidate.Function = Method;
8175 Candidate.Viable = false;
8176 Candidate.RewriteKind =
8177 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8178 Candidate.IsSurrogate = false;
8179 Candidate.TookAddressOfOverload =
8180 CandidateSet.getKind() ==
8182
8183 Candidate.IgnoreObjectArgument =
8184 Method->isStatic() ||
8185 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8186 Candidate.ExplicitCallArguments = Args.size();
8189 else {
8191 Candidate.DeductionFailure =
8193 }
8194 return;
8195 }
8196
8197 // Add the function template specialization produced by template argument
8198 // deduction as a candidate.
8199 assert(Specialization && "Missing member function template specialization?");
8201 "Specialization is not a member function?");
8203 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8204 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8205 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8206}
8207
8209 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8210 CXXRecordDecl *ActingContext,
8211 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8212 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8213 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8214 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8215 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8216 return;
8217
8218 if (ExplicitTemplateArgs ||
8219 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8221 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8222 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8223 SuppressUserConversions, PartialOverloading, PO);
8224 return;
8225 }
8226
8228 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8229 Args, SuppressUserConversions, PartialOverloading, PO);
8230}
8231
8232/// Determine whether a given function template has a simple explicit specifier
8233/// or a non-value-dependent explicit-specification that evaluates to true.
8237
8242
8244 Sema &S, OverloadCandidateSet &CandidateSet,
8246 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8247 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8249 bool AggregateCandidateDeduction) {
8250
8251 // If the function template has a non-dependent explicit specification,
8252 // exclude it now if appropriate; we are not permitted to perform deduction
8253 // and substitution in this case.
8254 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8255 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8256 Candidate.FoundDecl = FoundDecl;
8257 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8258 Candidate.Viable = false;
8259 Candidate.FailureKind = ovl_fail_explicit;
8260 return;
8261 }
8262
8263 // C++ [over.match.funcs]p7:
8264 // In each case where a candidate is a function template, candidate
8265 // function template specializations are generated using template argument
8266 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8267 // candidate functions in the usual way.113) A given name can refer to one
8268 // or more function templates and also to a set of overloaded non-template
8269 // functions. In such a case, the candidate functions generated from each
8270 // function template are combined with the set of non-template candidate
8271 // functions.
8272 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8273 FunctionTemplate->getTemplateDepth());
8274 FunctionDecl *Specialization = nullptr;
8275 ConversionSequenceList Conversions;
8277 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8278 PartialOverloading, AggregateCandidateDeduction,
8279 /*PartialOrdering=*/false,
8280 /*ObjectType=*/QualType(),
8281 /*ObjectClassification=*/Expr::Classification(),
8282 CandidateSet.getKind() ==
8284 [&](ArrayRef<QualType> ParamTypes,
8285 bool OnlyInitializeNonUserDefinedConversions) {
8286 return S.CheckNonDependentConversions(
8287 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8288 Sema::CheckNonDependentConversionsFlag(
8289 SuppressUserConversions,
8290 OnlyInitializeNonUserDefinedConversions),
8291 nullptr, QualType(), {}, PO);
8292 });
8294 OverloadCandidate &Candidate =
8295 CandidateSet.addCandidate(Conversions.size(), Conversions);
8296 Candidate.FoundDecl = FoundDecl;
8297 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8298 Candidate.Viable = false;
8299 Candidate.RewriteKind =
8300 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8301 Candidate.IsSurrogate = false;
8302 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8303 // Ignore the object argument if there is one, since we don't have an object
8304 // type.
8305 Candidate.TookAddressOfOverload =
8306 CandidateSet.getKind() ==
8308
8309 Candidate.IgnoreObjectArgument =
8310 isa<CXXMethodDecl>(Candidate.Function) &&
8311 !cast<CXXMethodDecl>(Candidate.Function)
8312 ->isExplicitObjectMemberFunction() &&
8314
8315 Candidate.ExplicitCallArguments = Args.size();
8318 else {
8320 Candidate.DeductionFailure =
8322 }
8323 return;
8324 }
8325
8326 // Add the function template specialization produced by template argument
8327 // deduction as a candidate.
8328 assert(Specialization && "Missing function template specialization?");
8330 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8331 PartialOverloading, AllowExplicit,
8332 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8333 Info.AggregateDeductionCandidateHasMismatchedArity,
8334 Info.hasStrictPackMatch());
8335}
8336
8339 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8340 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8341 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8342 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8343 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8344 return;
8345
8346 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8347
8348 if (ExplicitTemplateArgs ||
8349 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8350 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8351 DependentExplicitSpecifier)) {
8352
8354 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8355 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8356 IsADLCandidate, PO, AggregateCandidateDeduction);
8357
8358 if (DependentExplicitSpecifier)
8360 return;
8361 }
8362
8363 CandidateSet.AddDeferredTemplateCandidate(
8364 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8365 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8366 AggregateCandidateDeduction);
8367}
8368
8371 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8373 CheckNonDependentConversionsFlag UserConversionFlag,
8374 CXXRecordDecl *ActingContext, QualType ObjectType,
8375 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8376 // FIXME: The cases in which we allow explicit conversions for constructor
8377 // arguments never consider calling a constructor template. It's not clear
8378 // that is correct.
8379 const bool AllowExplicit = false;
8380
8381 bool ForOverloadSetAddressResolution =
8383 auto *FD = FunctionTemplate->getTemplatedDecl();
8384 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8385 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8387 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8388
8389 if (Conversions.empty())
8390 Conversions =
8391 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8392
8393 // Overload resolution is always an unevaluated context.
8396
8397 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8398 // require that, but this check should never result in a hard error, and
8399 // overload resolution is permitted to sidestep instantiations.
8400 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8401 !ObjectType.isNull()) {
8402 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8403 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8404 !ParamTypes[0]->isDependentType()) {
8406 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8407 Method, ActingContext, /*InOverloadResolution=*/true,
8408 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8409 : QualType());
8410 if (Conversions[ConvIdx].isBad())
8411 return true;
8412 }
8413 }
8414
8415 // A speculative workaround for self-dependent constraint bugs that manifest
8416 // after CWG2369.
8417 // FIXME: Add references to the standard once P3606 is adopted.
8418 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8419 QualType ArgType) {
8420 ParamType = ParamType.getNonReferenceType();
8421 ArgType = ArgType.getNonReferenceType();
8422 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8423 if (PointerConv) {
8424 ParamType = ParamType->getPointeeType();
8425 ArgType = ArgType->getPointeeType();
8426 }
8427
8428 if (auto *RD = ParamType->getAsCXXRecordDecl();
8429 RD && RD->hasDefinition() &&
8430 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8431 auto Info = getConstructorInfo(ND);
8432 if (!Info)
8433 return false;
8434 CXXConstructorDecl *Ctor = Info.Constructor;
8435 /// isConvertingConstructor takes copy/move constructors into
8436 /// account!
8437 return !Ctor->isCopyOrMoveConstructor() &&
8439 /*AllowExplicit=*/true);
8440 }))
8441 return true;
8442 if (auto *RD = ArgType->getAsCXXRecordDecl();
8443 RD && RD->hasDefinition() &&
8444 !RD->getVisibleConversionFunctions().empty())
8445 return true;
8446
8447 return false;
8448 };
8449
8450 unsigned Offset =
8451 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8452 : 0;
8453
8454 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8455 I != N; ++I) {
8456 QualType ParamType = ParamTypes[I + Offset];
8457 if (!ParamType->isDependentType()) {
8458 unsigned ConvIdx;
8460 ConvIdx = Args.size() - 1 - I;
8461 assert(Args.size() + ThisConversions == 2 &&
8462 "number of args (including 'this') must be exactly 2 for "
8463 "reversed order");
8464 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8465 // would also be 0. 'this' got ConvIdx = 1 previously.
8466 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8467 } else {
8468 // For members, 'this' got ConvIdx = 0 previously.
8469 ConvIdx = ThisConversions + I;
8470 }
8471 if (Conversions[ConvIdx].isInitialized())
8472 continue;
8473 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8474 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8475 continue;
8477 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8478 /*InOverloadResolution=*/true,
8479 /*AllowObjCWritebackConversion=*/
8480 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8481 if (Conversions[ConvIdx].isBad())
8482 return true;
8483 }
8484 }
8485
8486 return false;
8487}
8488
8489/// Determine whether this is an allowable conversion from the result
8490/// of an explicit conversion operator to the expected type, per C++
8491/// [over.match.conv]p1 and [over.match.ref]p1.
8492///
8493/// \param ConvType The return type of the conversion function.
8494///
8495/// \param ToType The type we are converting to.
8496///
8497/// \param AllowObjCPointerConversion Allow a conversion from one
8498/// Objective-C pointer to another.
8499///
8500/// \returns true if the conversion is allowable, false otherwise.
8502 QualType ConvType, QualType ToType,
8503 bool AllowObjCPointerConversion) {
8504 QualType ToNonRefType = ToType.getNonReferenceType();
8505
8506 // Easy case: the types are the same.
8507 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8508 return true;
8509
8510 // Allow qualification conversions.
8511 bool ObjCLifetimeConversion;
8512 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8513 ObjCLifetimeConversion))
8514 return true;
8515
8516 // If we're not allowed to consider Objective-C pointer conversions,
8517 // we're done.
8518 if (!AllowObjCPointerConversion)
8519 return false;
8520
8521 // Is this an Objective-C pointer conversion?
8522 bool IncompatibleObjC = false;
8523 QualType ConvertedType;
8524 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8525 IncompatibleObjC);
8526}
8527
8529 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8530 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8531 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8532 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8533 assert(!Conversion->getDescribedFunctionTemplate() &&
8534 "Conversion function templates use AddTemplateConversionCandidate");
8535 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8536 if (!CandidateSet.isNewCandidate(Conversion))
8537 return;
8538
8539 // If the conversion function has an undeduced return type, trigger its
8540 // deduction now.
8541 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8542 if (DeduceReturnType(Conversion, From->getExprLoc()))
8543 return;
8544 ConvType = Conversion->getConversionType().getNonReferenceType();
8545 }
8546
8547 // If we don't allow any conversion of the result type, ignore conversion
8548 // functions that don't convert to exactly (possibly cv-qualified) T.
8549 if (!AllowResultConversion &&
8550 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8551 return;
8552
8553 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8554 // operator is only a candidate if its return type is the target type or
8555 // can be converted to the target type with a qualification conversion.
8556 //
8557 // FIXME: Include such functions in the candidate list and explain why we
8558 // can't select them.
8559 if (Conversion->isExplicit() &&
8560 !isAllowableExplicitConversion(*this, ConvType, ToType,
8561 AllowObjCConversionOnExplicit))
8562 return;
8563
8564 // Overload resolution is always an unevaluated context.
8567
8568 // Add this candidate
8569 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8570 Candidate.FoundDecl = FoundDecl;
8571 Candidate.Function = Conversion;
8573 Candidate.FinalConversion.setFromType(ConvType);
8574 Candidate.FinalConversion.setAllToTypes(ToType);
8575 Candidate.HasFinalConversion = true;
8576 Candidate.Viable = true;
8577 Candidate.ExplicitCallArguments = 1;
8578 Candidate.StrictPackMatch = StrictPackMatch;
8579
8580 // Explicit functions are not actually candidates at all if we're not
8581 // allowing them in this context, but keep them around so we can point
8582 // to them in diagnostics.
8583 if (!AllowExplicit && Conversion->isExplicit()) {
8584 Candidate.Viable = false;
8585 Candidate.FailureKind = ovl_fail_explicit;
8586 return;
8587 }
8588
8589 // C++ [over.match.funcs]p4:
8590 // For conversion functions, the function is considered to be a member of
8591 // the class of the implicit implied object argument for the purpose of
8592 // defining the type of the implicit object parameter.
8593 //
8594 // Determine the implicit conversion sequence for the implicit
8595 // object parameter.
8596 QualType ObjectType = From->getType();
8597 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8598 ObjectType = FromPtrType->getPointeeType();
8599 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8600 // C++23 [over.best.ics.general]
8601 // However, if the target is [...]
8602 // - the object parameter of a user-defined conversion function
8603 // [...] user-defined conversion sequences are not considered.
8605 *this, CandidateSet.getLocation(), From->getType(),
8606 From->Classify(Context), Conversion, ConversionContext,
8607 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8608 /*SuppressUserConversion*/ true);
8609
8610 if (Candidate.Conversions[0].isBad()) {
8611 Candidate.Viable = false;
8613 return;
8614 }
8615
8616 if (Conversion->getTrailingRequiresClause()) {
8617 ConstraintSatisfaction Satisfaction;
8618 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8619 !Satisfaction.IsSatisfied) {
8620 Candidate.Viable = false;
8622 return;
8623 }
8624 }
8625
8626 // We won't go through a user-defined type conversion function to convert a
8627 // derived to base as such conversions are given Conversion Rank. They only
8628 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8629 QualType FromCanon
8630 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8631 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8632 if (FromCanon == ToCanon ||
8633 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8634 Candidate.Viable = false;
8636 return;
8637 }
8638
8639 // To determine what the conversion from the result of calling the
8640 // conversion function to the type we're eventually trying to
8641 // convert to (ToType), we need to synthesize a call to the
8642 // conversion function and attempt copy initialization from it. This
8643 // makes sure that we get the right semantics with respect to
8644 // lvalues/rvalues and the type. Fortunately, we can allocate this
8645 // call on the stack and we don't need its arguments to be
8646 // well-formed.
8647 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8648 VK_LValue, From->getBeginLoc());
8650 Context.getPointerType(Conversion->getType()),
8651 CK_FunctionToPointerDecay, &ConversionRef,
8653
8654 QualType ConversionType = Conversion->getConversionType();
8655 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8656 Candidate.Viable = false;
8658 return;
8659 }
8660
8661 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8662
8663 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8664
8665 // Introduce a temporary expression with the right type and value category
8666 // that we can use for deduction purposes.
8667 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8668
8670 TryCopyInitialization(*this, &FakeCall, ToType,
8671 /*SuppressUserConversions=*/true,
8672 /*InOverloadResolution=*/false,
8673 /*AllowObjCWritebackConversion=*/false);
8674
8675 switch (ICS.getKind()) {
8677 Candidate.FinalConversion = ICS.Standard;
8678 Candidate.HasFinalConversion = true;
8679
8680 // C++ [over.ics.user]p3:
8681 // If the user-defined conversion is specified by a specialization of a
8682 // conversion function template, the second standard conversion sequence
8683 // shall have exact match rank.
8684 if (Conversion->getPrimaryTemplate() &&
8686 Candidate.Viable = false;
8688 return;
8689 }
8690
8691 // C++0x [dcl.init.ref]p5:
8692 // In the second case, if the reference is an rvalue reference and
8693 // the second standard conversion sequence of the user-defined
8694 // conversion sequence includes an lvalue-to-rvalue conversion, the
8695 // program is ill-formed.
8696 if (ToType->isRValueReferenceType() &&
8698 Candidate.Viable = false;
8700 return;
8701 }
8702 break;
8703
8705 Candidate.Viable = false;
8707 return;
8708
8709 default:
8710 llvm_unreachable(
8711 "Can only end up with a standard conversion sequence or failure");
8712 }
8713
8714 if (EnableIfAttr *FailedAttr =
8715 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8716 Candidate.Viable = false;
8717 Candidate.FailureKind = ovl_fail_enable_if;
8718 Candidate.DeductionFailure.Data = FailedAttr;
8719 return;
8720 }
8721
8722 if (isNonViableMultiVersionOverload(Conversion)) {
8723 Candidate.Viable = false;
8725 }
8726}
8727
8729 Sema &S, OverloadCandidateSet &CandidateSet,
8731 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8732 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8733 bool AllowResultConversion) {
8734
8735 // If the function template has a non-dependent explicit specification,
8736 // exclude it now if appropriate; we are not permitted to perform deduction
8737 // and substitution in this case.
8738 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8739 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8740 Candidate.FoundDecl = FoundDecl;
8741 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8742 Candidate.Viable = false;
8743 Candidate.FailureKind = ovl_fail_explicit;
8744 return;
8745 }
8746
8747 QualType ObjectType = From->getType();
8748 Expr::Classification ObjectClassification = From->Classify(S.Context);
8749
8750 TemplateDeductionInfo Info(CandidateSet.getLocation());
8753 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8754 Specialization, Info);
8756 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8757 Candidate.FoundDecl = FoundDecl;
8758 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8759 Candidate.Viable = false;
8761 Candidate.ExplicitCallArguments = 1;
8762 Candidate.DeductionFailure =
8764 return;
8765 }
8766
8767 // Add the conversion function template specialization produced by
8768 // template argument deduction as a candidate.
8769 assert(Specialization && "Missing function template specialization?");
8770 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8771 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8772 AllowExplicit, AllowResultConversion,
8773 Info.hasStrictPackMatch());
8774}
8775
8778 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8779 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8780 bool AllowExplicit, bool AllowResultConversion) {
8781 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8782 "Only conversion function templates permitted here");
8783
8784 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8785 return;
8786
8787 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8788 CandidateSet.getKind() ==
8792 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8793 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8794 AllowResultConversion);
8795
8797 return;
8798 }
8799
8801 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8802 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8803}
8804
8806 DeclAccessPair FoundDecl,
8807 CXXRecordDecl *ActingContext,
8808 const FunctionProtoType *Proto,
8809 Expr *Object,
8810 ArrayRef<Expr *> Args,
8811 OverloadCandidateSet& CandidateSet) {
8812 if (!CandidateSet.isNewCandidate(Conversion))
8813 return;
8814
8815 // Overload resolution is always an unevaluated context.
8818
8819 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8820 Candidate.FoundDecl = FoundDecl;
8821 Candidate.Function = nullptr;
8822 Candidate.Surrogate = Conversion;
8823 Candidate.IsSurrogate = true;
8824 Candidate.Viable = true;
8825 Candidate.ExplicitCallArguments = Args.size();
8826
8827 // Determine the implicit conversion sequence for the implicit
8828 // object parameter.
8829 ImplicitConversionSequence ObjectInit;
8830 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8831 ObjectInit = TryCopyInitialization(*this, Object,
8832 Conversion->getParamDecl(0)->getType(),
8833 /*SuppressUserConversions=*/false,
8834 /*InOverloadResolution=*/true, false);
8835 } else {
8837 *this, CandidateSet.getLocation(), Object->getType(),
8838 Object->Classify(Context), Conversion, ActingContext);
8839 }
8840
8841 if (ObjectInit.isBad()) {
8842 Candidate.Viable = false;
8844 Candidate.Conversions[0] = ObjectInit;
8845 return;
8846 }
8847
8848 // The first conversion is actually a user-defined conversion whose
8849 // first conversion is ObjectInit's standard conversion (which is
8850 // effectively a reference binding). Record it as such.
8851 Candidate.Conversions[0].setUserDefined();
8852 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8853 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8854 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8855 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8856 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8857 Candidate.Conversions[0].UserDefined.After
8858 = Candidate.Conversions[0].UserDefined.Before;
8859 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8860
8861 // Find the
8862 unsigned NumParams = Proto->getNumParams();
8863
8864 // (C++ 13.3.2p2): A candidate function having fewer than m
8865 // parameters is viable only if it has an ellipsis in its parameter
8866 // list (8.3.5).
8867 if (Args.size() > NumParams && !Proto->isVariadic()) {
8868 Candidate.Viable = false;
8870 return;
8871 }
8872
8873 // Function types don't have any default arguments, so just check if
8874 // we have enough arguments.
8875 if (Args.size() < NumParams) {
8876 // Not enough arguments.
8877 Candidate.Viable = false;
8879 return;
8880 }
8881
8882 // Determine the implicit conversion sequences for each of the
8883 // arguments.
8884 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8885 if (ArgIdx < NumParams) {
8886 // (C++ 13.3.2p3): for F to be a viable function, there shall
8887 // exist for each argument an implicit conversion sequence
8888 // (13.3.3.1) that converts that argument to the corresponding
8889 // parameter of F.
8890 QualType ParamType = Proto->getParamType(ArgIdx);
8891 Candidate.Conversions[ArgIdx + 1]
8892 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8893 /*SuppressUserConversions=*/false,
8894 /*InOverloadResolution=*/false,
8895 /*AllowObjCWritebackConversion=*/
8896 getLangOpts().ObjCAutoRefCount);
8897 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8898 Candidate.Viable = false;
8900 return;
8901 }
8902 } else {
8903 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8904 // argument for which there is no corresponding parameter is
8905 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8906 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8907 }
8908 }
8909
8910 if (Conversion->getTrailingRequiresClause()) {
8911 ConstraintSatisfaction Satisfaction;
8912 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8913 /*ForOverloadResolution*/ true) ||
8914 !Satisfaction.IsSatisfied) {
8915 Candidate.Viable = false;
8917 return;
8918 }
8919 }
8920
8921 if (EnableIfAttr *FailedAttr =
8922 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8923 Candidate.Viable = false;
8924 Candidate.FailureKind = ovl_fail_enable_if;
8925 Candidate.DeductionFailure.Data = FailedAttr;
8926 return;
8927 }
8928}
8929
8931 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8932 OverloadCandidateSet &CandidateSet,
8933 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8934 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8935 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8936 ArrayRef<Expr *> FunctionArgs = Args;
8937
8938 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8939 FunctionDecl *FD =
8940 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8941
8942 // Don't consider rewritten functions if we're not rewriting.
8943 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8944 continue;
8945
8946 assert(!isa<CXXMethodDecl>(FD) &&
8947 "unqualified operator lookup found a member function");
8948
8949 if (FunTmpl) {
8950 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8951 FunctionArgs, CandidateSet);
8952 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8953
8954 // As template candidates are not deduced immediately,
8955 // persist the array in the overload set.
8957 FunctionArgs[1], FunctionArgs[0]);
8958 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8959 Reversed, CandidateSet, false, false, true,
8960 ADLCallKind::NotADL,
8962 }
8963 } else {
8964 if (ExplicitTemplateArgs)
8965 continue;
8966 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8967 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8968 AddOverloadCandidate(FD, F.getPair(),
8969 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8970 false, false, true, false, ADLCallKind::NotADL, {},
8972 }
8973 }
8974}
8975
8977 SourceLocation OpLoc,
8978 ArrayRef<Expr *> Args,
8979 OverloadCandidateSet &CandidateSet,
8981 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8982
8983 // C++ [over.match.oper]p3:
8984 // For a unary operator @ with an operand of a type whose
8985 // cv-unqualified version is T1, and for a binary operator @ with
8986 // a left operand of a type whose cv-unqualified version is T1 and
8987 // a right operand of a type whose cv-unqualified version is T2,
8988 // three sets of candidate functions, designated member
8989 // candidates, non-member candidates and built-in candidates, are
8990 // constructed as follows:
8991 QualType T1 = Args[0]->getType();
8992
8993 // -- If T1 is a complete class type or a class currently being
8994 // defined, the set of member candidates is the result of the
8995 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8996 // the set of member candidates is empty.
8997 if (T1->isRecordType()) {
8998 bool IsComplete = isCompleteType(OpLoc, T1);
8999 auto *T1RD = T1->getAsCXXRecordDecl();
9000 // Complete the type if it can be completed.
9001 // If the type is neither complete nor being defined, bail out now.
9002 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9003 return;
9004
9005 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9006 LookupQualifiedName(Operators, T1RD);
9007 Operators.suppressAccessDiagnostics();
9008
9009 for (LookupResult::iterator Oper = Operators.begin(),
9010 OperEnd = Operators.end();
9011 Oper != OperEnd; ++Oper) {
9012 if (Oper->getAsFunction() &&
9014 !CandidateSet.getRewriteInfo().shouldAddReversed(
9015 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9016 continue;
9017 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9018 Args[0]->Classify(Context), Args.slice(1),
9019 CandidateSet, /*SuppressUserConversion=*/false, PO);
9020 }
9021 }
9022}
9023
9025 OverloadCandidateSet& CandidateSet,
9026 bool IsAssignmentOperator,
9027 unsigned NumContextualBoolArguments) {
9028 // Overload resolution is always an unevaluated context.
9031
9032 // Add this candidate
9033 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9034 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9035 Candidate.Function = nullptr;
9036 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9037
9038 // Determine the implicit conversion sequences for each of the
9039 // arguments.
9040 Candidate.Viable = true;
9041 Candidate.ExplicitCallArguments = Args.size();
9042 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9043 // C++ [over.match.oper]p4:
9044 // For the built-in assignment operators, conversions of the
9045 // left operand are restricted as follows:
9046 // -- no temporaries are introduced to hold the left operand, and
9047 // -- no user-defined conversions are applied to the left
9048 // operand to achieve a type match with the left-most
9049 // parameter of a built-in candidate.
9050 //
9051 // We block these conversions by turning off user-defined
9052 // conversions, since that is the only way that initialization of
9053 // a reference to a non-class type can occur from something that
9054 // is not of the same type.
9055 if (ArgIdx < NumContextualBoolArguments) {
9056 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9057 "Contextual conversion to bool requires bool type");
9058 Candidate.Conversions[ArgIdx]
9059 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9060 } else {
9061 Candidate.Conversions[ArgIdx]
9062 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9063 ArgIdx == 0 && IsAssignmentOperator,
9064 /*InOverloadResolution=*/false,
9065 /*AllowObjCWritebackConversion=*/
9066 getLangOpts().ObjCAutoRefCount);
9067 }
9068 if (Candidate.Conversions[ArgIdx].isBad()) {
9069 Candidate.Viable = false;
9071 break;
9072 }
9073 }
9074}
9075
9076namespace {
9077
9078/// BuiltinCandidateTypeSet - A set of types that will be used for the
9079/// candidate operator functions for built-in operators (C++
9080/// [over.built]). The types are separated into pointer types and
9081/// enumeration types.
9082class BuiltinCandidateTypeSet {
9083 /// TypeSet - A set of types.
9084 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9085
9086 /// PointerTypes - The set of pointer types that will be used in the
9087 /// built-in candidates.
9088 TypeSet PointerTypes;
9089
9090 /// MemberPointerTypes - The set of member pointer types that will be
9091 /// used in the built-in candidates.
9092 TypeSet MemberPointerTypes;
9093
9094 /// EnumerationTypes - The set of enumeration types that will be
9095 /// used in the built-in candidates.
9096 TypeSet EnumerationTypes;
9097
9098 /// The set of vector types that will be used in the built-in
9099 /// candidates.
9100 TypeSet VectorTypes;
9101
9102 /// The set of matrix types that will be used in the built-in
9103 /// candidates.
9104 TypeSet MatrixTypes;
9105
9106 /// The set of _BitInt types that will be used in the built-in candidates.
9107 TypeSet BitIntTypes;
9108
9109 /// A flag indicating non-record types are viable candidates
9110 bool HasNonRecordTypes;
9111
9112 /// A flag indicating whether either arithmetic or enumeration types
9113 /// were present in the candidate set.
9114 bool HasArithmeticOrEnumeralTypes;
9115
9116 /// A flag indicating whether the nullptr type was present in the
9117 /// candidate set.
9118 bool HasNullPtrType;
9119
9120 /// Sema - The semantic analysis instance where we are building the
9121 /// candidate type set.
9122 Sema &SemaRef;
9123
9124 /// Context - The AST context in which we will build the type sets.
9125 ASTContext &Context;
9126
9127 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9128 const Qualifiers &VisibleQuals);
9129 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9130
9131public:
9132 /// iterator - Iterates through the types that are part of the set.
9133 typedef TypeSet::iterator iterator;
9134
9135 BuiltinCandidateTypeSet(Sema &SemaRef)
9136 : HasNonRecordTypes(false),
9137 HasArithmeticOrEnumeralTypes(false),
9138 HasNullPtrType(false),
9139 SemaRef(SemaRef),
9140 Context(SemaRef.Context) { }
9141
9142 void AddTypesConvertedFrom(QualType Ty,
9143 SourceLocation Loc,
9144 bool AllowUserConversions,
9145 bool AllowExplicitConversions,
9146 const Qualifiers &VisibleTypeConversionsQuals);
9147
9148 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9149 llvm::iterator_range<iterator> member_pointer_types() {
9150 return MemberPointerTypes;
9151 }
9152 llvm::iterator_range<iterator> enumeration_types() {
9153 return EnumerationTypes;
9154 }
9155 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9156 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9157 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9158
9159 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9160 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9161 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9162 bool hasNullPtrType() const { return HasNullPtrType; }
9163};
9164
9165} // end anonymous namespace
9166
9167/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9168/// the set of pointer types along with any more-qualified variants of
9169/// that type. For example, if @p Ty is "int const *", this routine
9170/// will add "int const *", "int const volatile *", "int const
9171/// restrict *", and "int const volatile restrict *" to the set of
9172/// pointer types. Returns true if the add of @p Ty itself succeeded,
9173/// false otherwise.
9174///
9175/// FIXME: what to do about extended qualifiers?
9176bool
9177BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9178 const Qualifiers &VisibleQuals) {
9179
9180 // Insert this type.
9181 if (!PointerTypes.insert(Ty))
9182 return false;
9183
9184 QualType PointeeTy;
9185 const PointerType *PointerTy = Ty->getAs<PointerType>();
9186 bool buildObjCPtr = false;
9187 if (!PointerTy) {
9188 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9189 PointeeTy = PTy->getPointeeType();
9190 buildObjCPtr = true;
9191 } else {
9192 PointeeTy = PointerTy->getPointeeType();
9193 }
9194
9195 // Don't add qualified variants of arrays. For one, they're not allowed
9196 // (the qualifier would sink to the element type), and for another, the
9197 // only overload situation where it matters is subscript or pointer +- int,
9198 // and those shouldn't have qualifier variants anyway.
9199 if (PointeeTy->isArrayType())
9200 return true;
9201
9202 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9203 bool hasVolatile = VisibleQuals.hasVolatile();
9204 bool hasRestrict = VisibleQuals.hasRestrict();
9205
9206 // Iterate through all strict supersets of BaseCVR.
9207 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9208 if ((CVR | BaseCVR) != CVR) continue;
9209 // Skip over volatile if no volatile found anywhere in the types.
9210 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9211
9212 // Skip over restrict if no restrict found anywhere in the types, or if
9213 // the type cannot be restrict-qualified.
9214 if ((CVR & Qualifiers::Restrict) &&
9215 (!hasRestrict ||
9216 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9217 continue;
9218
9219 // Build qualified pointee type.
9220 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9221
9222 // Build qualified pointer type.
9223 QualType QPointerTy;
9224 if (!buildObjCPtr)
9225 QPointerTy = Context.getPointerType(QPointeeTy);
9226 else
9227 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9228
9229 // Insert qualified pointer type.
9230 PointerTypes.insert(QPointerTy);
9231 }
9232
9233 return true;
9234}
9235
9236/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9237/// to the set of pointer types along with any more-qualified variants of
9238/// that type. For example, if @p Ty is "int const *", this routine
9239/// will add "int const *", "int const volatile *", "int const
9240/// restrict *", and "int const volatile restrict *" to the set of
9241/// pointer types. Returns true if the add of @p Ty itself succeeded,
9242/// false otherwise.
9243///
9244/// FIXME: what to do about extended qualifiers?
9245bool
9246BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9247 QualType Ty) {
9248 // Insert this type.
9249 if (!MemberPointerTypes.insert(Ty))
9250 return false;
9251
9252 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9253 assert(PointerTy && "type was not a member pointer type!");
9254
9255 QualType PointeeTy = PointerTy->getPointeeType();
9256 // Don't add qualified variants of arrays. For one, they're not allowed
9257 // (the qualifier would sink to the element type), and for another, the
9258 // only overload situation where it matters is subscript or pointer +- int,
9259 // and those shouldn't have qualifier variants anyway.
9260 if (PointeeTy->isArrayType())
9261 return true;
9262 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9263
9264 // Iterate through all strict supersets of the pointee type's CVR
9265 // qualifiers.
9266 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9267 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9268 if ((CVR | BaseCVR) != CVR) continue;
9269
9270 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9271 MemberPointerTypes.insert(Context.getMemberPointerType(
9272 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9273 }
9274
9275 return true;
9276}
9277
9278/// AddTypesConvertedFrom - Add each of the types to which the type @p
9279/// Ty can be implicit converted to the given set of @p Types. We're
9280/// primarily interested in pointer types and enumeration types. We also
9281/// take member pointer types, for the conditional operator.
9282/// AllowUserConversions is true if we should look at the conversion
9283/// functions of a class type, and AllowExplicitConversions if we
9284/// should also include the explicit conversion functions of a class
9285/// type.
9286void
9287BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9288 SourceLocation Loc,
9289 bool AllowUserConversions,
9290 bool AllowExplicitConversions,
9291 const Qualifiers &VisibleQuals) {
9292 // Only deal with canonical types.
9293 Ty = Context.getCanonicalType(Ty);
9294
9295 // Look through reference types; they aren't part of the type of an
9296 // expression for the purposes of conversions.
9297 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9298 Ty = RefTy->getPointeeType();
9299
9300 // If we're dealing with an array type, decay to the pointer.
9301 if (Ty->isArrayType())
9302 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9303
9304 // Otherwise, we don't care about qualifiers on the type.
9305 Ty = Ty.getLocalUnqualifiedType();
9306
9307 // Flag if we ever add a non-record type.
9308 bool TyIsRec = Ty->isRecordType();
9309 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9310
9311 // Flag if we encounter an arithmetic type.
9312 HasArithmeticOrEnumeralTypes =
9313 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9314
9315 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9316 PointerTypes.insert(Ty);
9317 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9318 // Insert our type, and its more-qualified variants, into the set
9319 // of types.
9320 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9321 return;
9322 } else if (Ty->isMemberPointerType()) {
9323 // Member pointers are far easier, since the pointee can't be converted.
9324 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9325 return;
9326 } else if (Ty->isEnumeralType()) {
9327 HasArithmeticOrEnumeralTypes = true;
9328 EnumerationTypes.insert(Ty);
9329 } else if (Ty->isBitIntType()) {
9330 HasArithmeticOrEnumeralTypes = true;
9331 BitIntTypes.insert(Ty);
9332 } else if (Ty->isVectorType()) {
9333 // We treat vector types as arithmetic types in many contexts as an
9334 // extension.
9335 HasArithmeticOrEnumeralTypes = true;
9336 VectorTypes.insert(Ty);
9337 } else if (Ty->isMatrixType()) {
9338 // Similar to vector types, we treat vector types as arithmetic types in
9339 // many contexts as an extension.
9340 HasArithmeticOrEnumeralTypes = true;
9341 MatrixTypes.insert(Ty);
9342 } else if (Ty->isNullPtrType()) {
9343 HasNullPtrType = true;
9344 } else if (AllowUserConversions && TyIsRec) {
9345 // No conversion functions in incomplete types.
9346 if (!SemaRef.isCompleteType(Loc, Ty))
9347 return;
9348
9349 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9350 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9351 if (isa<UsingShadowDecl>(D))
9352 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9353
9354 // Skip conversion function templates; they don't tell us anything
9355 // about which builtin types we can convert to.
9357 continue;
9358
9359 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9360 if (AllowExplicitConversions || !Conv->isExplicit()) {
9361 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9362 VisibleQuals);
9363 }
9364 }
9365 }
9366}
9367/// Helper function for adjusting address spaces for the pointer or reference
9368/// operands of builtin operators depending on the argument.
9373
9374/// Helper function for AddBuiltinOperatorCandidates() that adds
9375/// the volatile- and non-volatile-qualified assignment operators for the
9376/// given type to the candidate set.
9378 QualType T,
9379 ArrayRef<Expr *> Args,
9380 OverloadCandidateSet &CandidateSet) {
9381 QualType ParamTypes[2];
9382
9383 // T& operator=(T&, T)
9384 ParamTypes[0] = S.Context.getLValueReferenceType(
9386 ParamTypes[1] = T;
9387 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9388 /*IsAssignmentOperator=*/true);
9389
9391 // volatile T& operator=(volatile T&, T)
9392 ParamTypes[0] = S.Context.getLValueReferenceType(
9394 Args[0]));
9395 ParamTypes[1] = T;
9396 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9397 /*IsAssignmentOperator=*/true);
9398 }
9399}
9400
9401/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9402/// if any, found in visible type conversion functions found in ArgExpr's type.
9403static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9404 Qualifiers VRQuals;
9405 CXXRecordDecl *ClassDecl;
9406 if (const MemberPointerType *RHSMPType =
9407 ArgExpr->getType()->getAs<MemberPointerType>())
9408 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9409 else
9410 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9411 if (!ClassDecl) {
9412 // Just to be safe, assume the worst case.
9413 VRQuals.addVolatile();
9414 VRQuals.addRestrict();
9415 return VRQuals;
9416 }
9417 if (!ClassDecl->hasDefinition())
9418 return VRQuals;
9419
9420 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9421 if (isa<UsingShadowDecl>(D))
9422 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9423 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9424 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9425 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9426 CanTy = ResTypeRef->getPointeeType();
9427 // Need to go down the pointer/mempointer chain and add qualifiers
9428 // as see them.
9429 bool done = false;
9430 while (!done) {
9431 if (CanTy.isRestrictQualified())
9432 VRQuals.addRestrict();
9433 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9434 CanTy = ResTypePtr->getPointeeType();
9435 else if (const MemberPointerType *ResTypeMPtr =
9436 CanTy->getAs<MemberPointerType>())
9437 CanTy = ResTypeMPtr->getPointeeType();
9438 else
9439 done = true;
9440 if (CanTy.isVolatileQualified())
9441 VRQuals.addVolatile();
9442 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9443 return VRQuals;
9444 }
9445 }
9446 }
9447 return VRQuals;
9448}
9449
9450// Note: We're currently only handling qualifiers that are meaningful for the
9451// LHS of compound assignment overloading.
9453 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9454 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9455 // _Atomic
9456 if (Available.hasAtomic()) {
9457 Available.removeAtomic();
9458 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9459 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9460 return;
9461 }
9462
9463 // volatile
9464 if (Available.hasVolatile()) {
9465 Available.removeVolatile();
9466 assert(!Applied.hasVolatile());
9467 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9468 Callback);
9469 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9470 return;
9471 }
9472
9473 Callback(Applied);
9474}
9475
9477 QualifiersAndAtomic Quals,
9478 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9480 Callback);
9481}
9482
9484 QualifiersAndAtomic Quals,
9485 Sema &S) {
9486 if (Quals.hasAtomic())
9488 if (Quals.hasVolatile())
9491}
9492
9493namespace {
9494
9495/// Helper class to manage the addition of builtin operator overload
9496/// candidates. It provides shared state and utility methods used throughout
9497/// the process, as well as a helper method to add each group of builtin
9498/// operator overloads from the standard to a candidate set.
9499class BuiltinOperatorOverloadBuilder {
9500 // Common instance state available to all overload candidate addition methods.
9501 Sema &S;
9502 ArrayRef<Expr *> Args;
9503 QualifiersAndAtomic VisibleTypeConversionsQuals;
9504 bool HasArithmeticOrEnumeralCandidateType;
9505 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9506 OverloadCandidateSet &CandidateSet;
9507
9508 static constexpr int ArithmeticTypesCap = 26;
9509 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9510
9511 // Define some indices used to iterate over the arithmetic types in
9512 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9513 // types are that preserved by promotion (C++ [over.built]p2).
9514 unsigned FirstIntegralType,
9515 LastIntegralType;
9516 unsigned FirstPromotedIntegralType,
9517 LastPromotedIntegralType;
9518 unsigned FirstPromotedArithmeticType,
9519 LastPromotedArithmeticType;
9520 unsigned NumArithmeticTypes;
9521
9522 void InitArithmeticTypes() {
9523 // Start of promoted types.
9524 FirstPromotedArithmeticType = 0;
9525 ArithmeticTypes.push_back(S.Context.FloatTy);
9526 ArithmeticTypes.push_back(S.Context.DoubleTy);
9527 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9529 ArithmeticTypes.push_back(S.Context.Float128Ty);
9531 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9532
9533 // Start of integral types.
9534 FirstIntegralType = ArithmeticTypes.size();
9535 FirstPromotedIntegralType = ArithmeticTypes.size();
9536 ArithmeticTypes.push_back(S.Context.IntTy);
9537 ArithmeticTypes.push_back(S.Context.LongTy);
9538 ArithmeticTypes.push_back(S.Context.LongLongTy);
9542 ArithmeticTypes.push_back(S.Context.Int128Ty);
9543 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9544 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9545 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9549 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9550
9551 /// We add candidates for the unique, unqualified _BitInt types present in
9552 /// the candidate type set. The candidate set already handled ensuring the
9553 /// type is unqualified and canonical, but because we're adding from N
9554 /// different sets, we need to do some extra work to unique things. Insert
9555 /// the candidates into a unique set, then move from that set into the list
9556 /// of arithmetic types.
9557 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9558 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9559 for (QualType BitTy : Candidate.bitint_types())
9560 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9561 }
9562 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9563 LastPromotedIntegralType = ArithmeticTypes.size();
9564 LastPromotedArithmeticType = ArithmeticTypes.size();
9565 // End of promoted types.
9566
9567 ArithmeticTypes.push_back(S.Context.BoolTy);
9568 ArithmeticTypes.push_back(S.Context.CharTy);
9569 ArithmeticTypes.push_back(S.Context.WCharTy);
9570 if (S.Context.getLangOpts().Char8)
9571 ArithmeticTypes.push_back(S.Context.Char8Ty);
9572 ArithmeticTypes.push_back(S.Context.Char16Ty);
9573 ArithmeticTypes.push_back(S.Context.Char32Ty);
9574 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9575 ArithmeticTypes.push_back(S.Context.ShortTy);
9576 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9577 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9578 LastIntegralType = ArithmeticTypes.size();
9579 NumArithmeticTypes = ArithmeticTypes.size();
9580 // End of integral types.
9581 // FIXME: What about complex? What about half?
9582
9583 // We don't know for sure how many bit-precise candidates were involved, so
9584 // we subtract those from the total when testing whether we're under the
9585 // cap or not.
9586 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9587 ArithmeticTypesCap &&
9588 "Enough inline storage for all arithmetic types.");
9589 }
9590
9591 /// Helper method to factor out the common pattern of adding overloads
9592 /// for '++' and '--' builtin operators.
9593 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9594 bool HasVolatile,
9595 bool HasRestrict) {
9596 QualType ParamTypes[2] = {
9597 S.Context.getLValueReferenceType(CandidateTy),
9598 S.Context.IntTy
9599 };
9600
9601 // Non-volatile version.
9602 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9603
9604 // Use a heuristic to reduce number of builtin candidates in the set:
9605 // add volatile version only if there are conversions to a volatile type.
9606 if (HasVolatile) {
9607 ParamTypes[0] =
9609 S.Context.getVolatileType(CandidateTy));
9610 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9611 }
9612
9613 // Add restrict version only if there are conversions to a restrict type
9614 // and our candidate type is a non-restrict-qualified pointer.
9615 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9616 !CandidateTy.isRestrictQualified()) {
9617 ParamTypes[0]
9620 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9621
9622 if (HasVolatile) {
9623 ParamTypes[0]
9625 S.Context.getCVRQualifiedType(CandidateTy,
9628 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9629 }
9630 }
9631
9632 }
9633
9634 /// Helper to add an overload candidate for a binary builtin with types \p L
9635 /// and \p R.
9636 void AddCandidate(QualType L, QualType R) {
9637 QualType LandR[2] = {L, R};
9638 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9639 }
9640
9641public:
9642 BuiltinOperatorOverloadBuilder(
9643 Sema &S, ArrayRef<Expr *> Args,
9644 QualifiersAndAtomic VisibleTypeConversionsQuals,
9645 bool HasArithmeticOrEnumeralCandidateType,
9646 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9647 OverloadCandidateSet &CandidateSet)
9648 : S(S), Args(Args),
9649 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9650 HasArithmeticOrEnumeralCandidateType(
9651 HasArithmeticOrEnumeralCandidateType),
9652 CandidateTypes(CandidateTypes),
9653 CandidateSet(CandidateSet) {
9654
9655 InitArithmeticTypes();
9656 }
9657
9658 // Increment is deprecated for bool since C++17.
9659 //
9660 // C++ [over.built]p3:
9661 //
9662 // For every pair (T, VQ), where T is an arithmetic type other
9663 // than bool, and VQ is either volatile or empty, there exist
9664 // candidate operator functions of the form
9665 //
9666 // VQ T& operator++(VQ T&);
9667 // T operator++(VQ T&, int);
9668 //
9669 // C++ [over.built]p4:
9670 //
9671 // For every pair (T, VQ), where T is an arithmetic type other
9672 // than bool, and VQ is either volatile or empty, there exist
9673 // candidate operator functions of the form
9674 //
9675 // VQ T& operator--(VQ T&);
9676 // T operator--(VQ T&, int);
9677 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9678 if (!HasArithmeticOrEnumeralCandidateType)
9679 return;
9680
9681 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9682 const auto TypeOfT = ArithmeticTypes[Arith];
9683 if (TypeOfT == S.Context.BoolTy) {
9684 if (Op == OO_MinusMinus)
9685 continue;
9686 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9687 continue;
9688 }
9689 addPlusPlusMinusMinusStyleOverloads(
9690 TypeOfT,
9691 VisibleTypeConversionsQuals.hasVolatile(),
9692 VisibleTypeConversionsQuals.hasRestrict());
9693 }
9694 }
9695
9696 // C++ [over.built]p5:
9697 //
9698 // For every pair (T, VQ), where T is a cv-qualified or
9699 // cv-unqualified object type, and VQ is either volatile or
9700 // empty, there exist candidate operator functions of the form
9701 //
9702 // T*VQ& operator++(T*VQ&);
9703 // T*VQ& operator--(T*VQ&);
9704 // T* operator++(T*VQ&, int);
9705 // T* operator--(T*VQ&, int);
9706 void addPlusPlusMinusMinusPointerOverloads() {
9707 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9708 // Skip pointer types that aren't pointers to object types.
9709 if (!PtrTy->getPointeeType()->isObjectType())
9710 continue;
9711
9712 addPlusPlusMinusMinusStyleOverloads(
9713 PtrTy,
9714 (!PtrTy.isVolatileQualified() &&
9715 VisibleTypeConversionsQuals.hasVolatile()),
9716 (!PtrTy.isRestrictQualified() &&
9717 VisibleTypeConversionsQuals.hasRestrict()));
9718 }
9719 }
9720
9721 // C++ [over.built]p6:
9722 // For every cv-qualified or cv-unqualified object type T, there
9723 // exist candidate operator functions of the form
9724 //
9725 // T& operator*(T*);
9726 //
9727 // C++ [over.built]p7:
9728 // For every function type T that does not have cv-qualifiers or a
9729 // ref-qualifier, there exist candidate operator functions of the form
9730 // T& operator*(T*);
9731 void addUnaryStarPointerOverloads() {
9732 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9733 QualType PointeeTy = ParamTy->getPointeeType();
9734 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9735 continue;
9736
9737 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9738 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9739 continue;
9740
9741 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9742 }
9743 }
9744
9745 // C++ [over.built]p9:
9746 // For every promoted arithmetic type T, there exist candidate
9747 // operator functions of the form
9748 //
9749 // T operator+(T);
9750 // T operator-(T);
9751 void addUnaryPlusOrMinusArithmeticOverloads() {
9752 if (!HasArithmeticOrEnumeralCandidateType)
9753 return;
9754
9755 for (unsigned Arith = FirstPromotedArithmeticType;
9756 Arith < LastPromotedArithmeticType; ++Arith) {
9757 QualType ArithTy = ArithmeticTypes[Arith];
9758 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9759 }
9760
9761 // Extension: We also add these operators for vector types.
9762 for (QualType VecTy : CandidateTypes[0].vector_types())
9763 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9764 }
9765
9766 // C++ [over.built]p8:
9767 // For every type T, there exist candidate operator functions of
9768 // the form
9769 //
9770 // T* operator+(T*);
9771 void addUnaryPlusPointerOverloads() {
9772 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9773 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9774 }
9775
9776 // C++ [over.built]p10:
9777 // For every promoted integral type T, there exist candidate
9778 // operator functions of the form
9779 //
9780 // T operator~(T);
9781 void addUnaryTildePromotedIntegralOverloads() {
9782 if (!HasArithmeticOrEnumeralCandidateType)
9783 return;
9784
9785 for (unsigned Int = FirstPromotedIntegralType;
9786 Int < LastPromotedIntegralType; ++Int) {
9787 QualType IntTy = ArithmeticTypes[Int];
9788 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9789 }
9790
9791 // Extension: We also add this operator for vector types.
9792 for (QualType VecTy : CandidateTypes[0].vector_types())
9793 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9794 }
9795
9796 // C++ [over.match.oper]p16:
9797 // For every pointer to member type T or type std::nullptr_t, there
9798 // exist candidate operator functions of the form
9799 //
9800 // bool operator==(T,T);
9801 // bool operator!=(T,T);
9802 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9803 /// Set of (canonical) types that we've already handled.
9804 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9805
9806 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9807 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9808 // Don't add the same builtin candidate twice.
9809 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9810 continue;
9811
9812 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9813 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9814 }
9815
9816 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9818 if (AddedTypes.insert(NullPtrTy).second) {
9819 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9820 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9821 }
9822 }
9823 }
9824 }
9825
9826 // C++ [over.built]p15:
9827 //
9828 // For every T, where T is an enumeration type or a pointer type,
9829 // there exist candidate operator functions of the form
9830 //
9831 // bool operator<(T, T);
9832 // bool operator>(T, T);
9833 // bool operator<=(T, T);
9834 // bool operator>=(T, T);
9835 // bool operator==(T, T);
9836 // bool operator!=(T, T);
9837 // R operator<=>(T, T)
9838 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9839 // C++ [over.match.oper]p3:
9840 // [...]the built-in candidates include all of the candidate operator
9841 // functions defined in 13.6 that, compared to the given operator, [...]
9842 // do not have the same parameter-type-list as any non-template non-member
9843 // candidate.
9844 //
9845 // Note that in practice, this only affects enumeration types because there
9846 // aren't any built-in candidates of record type, and a user-defined operator
9847 // must have an operand of record or enumeration type. Also, the only other
9848 // overloaded operator with enumeration arguments, operator=,
9849 // cannot be overloaded for enumeration types, so this is the only place
9850 // where we must suppress candidates like this.
9851 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9852 UserDefinedBinaryOperators;
9853
9854 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9855 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9856 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9857 CEnd = CandidateSet.end();
9858 C != CEnd; ++C) {
9859 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9860 continue;
9861
9862 if (C->Function->isFunctionTemplateSpecialization())
9863 continue;
9864
9865 // We interpret "same parameter-type-list" as applying to the
9866 // "synthesized candidate, with the order of the two parameters
9867 // reversed", not to the original function.
9868 bool Reversed = C->isReversed();
9869 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9870 ->getType()
9871 .getUnqualifiedType();
9872 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9873 ->getType()
9874 .getUnqualifiedType();
9875
9876 // Skip if either parameter isn't of enumeral type.
9877 if (!FirstParamType->isEnumeralType() ||
9878 !SecondParamType->isEnumeralType())
9879 continue;
9880
9881 // Add this operator to the set of known user-defined operators.
9882 UserDefinedBinaryOperators.insert(
9883 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9884 S.Context.getCanonicalType(SecondParamType)));
9885 }
9886 }
9887 }
9888
9889 /// Set of (canonical) types that we've already handled.
9890 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9891
9892 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9893 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9894 // Don't add the same builtin candidate twice.
9895 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9896 continue;
9897 if (IsSpaceship && PtrTy->isFunctionPointerType())
9898 continue;
9899
9900 QualType ParamTypes[2] = {PtrTy, PtrTy};
9901 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9902 }
9903 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9904 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9905
9906 // Don't add the same builtin candidate twice, or if a user defined
9907 // candidate exists.
9908 if (!AddedTypes.insert(CanonType).second ||
9909 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9910 CanonType)))
9911 continue;
9912 QualType ParamTypes[2] = {EnumTy, EnumTy};
9913 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9914 }
9915 }
9916 }
9917
9918 // C++ [over.built]p13:
9919 //
9920 // For every cv-qualified or cv-unqualified object type T
9921 // there exist candidate operator functions of the form
9922 //
9923 // T* operator+(T*, ptrdiff_t);
9924 // T& operator[](T*, ptrdiff_t); [BELOW]
9925 // T* operator-(T*, ptrdiff_t);
9926 // T* operator+(ptrdiff_t, T*);
9927 // T& operator[](ptrdiff_t, T*); [BELOW]
9928 //
9929 // C++ [over.built]p14:
9930 //
9931 // For every T, where T is a pointer to object type, there
9932 // exist candidate operator functions of the form
9933 //
9934 // ptrdiff_t operator-(T, T);
9935 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9936 /// Set of (canonical) types that we've already handled.
9937 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9938
9939 for (int Arg = 0; Arg < 2; ++Arg) {
9940 QualType AsymmetricParamTypes[2] = {
9943 };
9944 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9945 QualType PointeeTy = PtrTy->getPointeeType();
9946 if (!PointeeTy->isObjectType())
9947 continue;
9948
9949 AsymmetricParamTypes[Arg] = PtrTy;
9950 if (Arg == 0 || Op == OO_Plus) {
9951 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9952 // T* operator+(ptrdiff_t, T*);
9953 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9954 }
9955 if (Op == OO_Minus) {
9956 // ptrdiff_t operator-(T, T);
9957 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9958 continue;
9959
9960 QualType ParamTypes[2] = {PtrTy, PtrTy};
9961 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9962 }
9963 }
9964 }
9965 }
9966
9967 // C++ [over.built]p12:
9968 //
9969 // For every pair of promoted arithmetic types L and R, there
9970 // exist candidate operator functions of the form
9971 //
9972 // LR operator*(L, R);
9973 // LR operator/(L, R);
9974 // LR operator+(L, R);
9975 // LR operator-(L, R);
9976 // bool operator<(L, R);
9977 // bool operator>(L, R);
9978 // bool operator<=(L, R);
9979 // bool operator>=(L, R);
9980 // bool operator==(L, R);
9981 // bool operator!=(L, R);
9982 //
9983 // where LR is the result of the usual arithmetic conversions
9984 // between types L and R.
9985 //
9986 // C++ [over.built]p24:
9987 //
9988 // For every pair of promoted arithmetic types L and R, there exist
9989 // candidate operator functions of the form
9990 //
9991 // LR operator?(bool, L, R);
9992 //
9993 // where LR is the result of the usual arithmetic conversions
9994 // between types L and R.
9995 // Our candidates ignore the first parameter.
9996 void addGenericBinaryArithmeticOverloads() {
9997 if (!HasArithmeticOrEnumeralCandidateType)
9998 return;
9999
10000 for (unsigned Left = FirstPromotedArithmeticType;
10001 Left < LastPromotedArithmeticType; ++Left) {
10002 for (unsigned Right = FirstPromotedArithmeticType;
10003 Right < LastPromotedArithmeticType; ++Right) {
10004 QualType LandR[2] = { ArithmeticTypes[Left],
10005 ArithmeticTypes[Right] };
10006 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10007 }
10008 }
10009
10010 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10011 // conditional operator for vector types.
10012 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10013 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10014 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10015 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10016 }
10017 }
10018
10019 /// Add binary operator overloads for each candidate matrix type M1, M2:
10020 /// * (M1, M1) -> M1
10021 /// * (M1, M1.getElementType()) -> M1
10022 /// * (M2.getElementType(), M2) -> M2
10023 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10024 void addMatrixBinaryArithmeticOverloads() {
10025 if (!HasArithmeticOrEnumeralCandidateType)
10026 return;
10027
10028 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10029 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10030 AddCandidate(M1, M1);
10031 }
10032
10033 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10034 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10035 if (!CandidateTypes[0].containsMatrixType(M2))
10036 AddCandidate(M2, M2);
10037 }
10038 }
10039
10040 // C++2a [over.built]p14:
10041 //
10042 // For every integral type T there exists a candidate operator function
10043 // of the form
10044 //
10045 // std::strong_ordering operator<=>(T, T)
10046 //
10047 // C++2a [over.built]p15:
10048 //
10049 // For every pair of floating-point types L and R, there exists a candidate
10050 // operator function of the form
10051 //
10052 // std::partial_ordering operator<=>(L, R);
10053 //
10054 // FIXME: The current specification for integral types doesn't play nice with
10055 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10056 // comparisons. Under the current spec this can lead to ambiguity during
10057 // overload resolution. For example:
10058 //
10059 // enum A : int {a};
10060 // auto x = (a <=> (long)42);
10061 //
10062 // error: call is ambiguous for arguments 'A' and 'long'.
10063 // note: candidate operator<=>(int, int)
10064 // note: candidate operator<=>(long, long)
10065 //
10066 // To avoid this error, this function deviates from the specification and adds
10067 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10068 // arithmetic types (the same as the generic relational overloads).
10069 //
10070 // For now this function acts as a placeholder.
10071 void addThreeWayArithmeticOverloads() {
10072 addGenericBinaryArithmeticOverloads();
10073 }
10074
10075 // C++ [over.built]p17:
10076 //
10077 // For every pair of promoted integral types L and R, there
10078 // exist candidate operator functions of the form
10079 //
10080 // LR operator%(L, R);
10081 // LR operator&(L, R);
10082 // LR operator^(L, R);
10083 // LR operator|(L, R);
10084 // L operator<<(L, R);
10085 // L operator>>(L, R);
10086 //
10087 // where LR is the result of the usual arithmetic conversions
10088 // between types L and R.
10089 void addBinaryBitwiseArithmeticOverloads() {
10090 if (!HasArithmeticOrEnumeralCandidateType)
10091 return;
10092
10093 for (unsigned Left = FirstPromotedIntegralType;
10094 Left < LastPromotedIntegralType; ++Left) {
10095 for (unsigned Right = FirstPromotedIntegralType;
10096 Right < LastPromotedIntegralType; ++Right) {
10097 QualType LandR[2] = { ArithmeticTypes[Left],
10098 ArithmeticTypes[Right] };
10099 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10100 }
10101 }
10102 }
10103
10104 // C++ [over.built]p20:
10105 //
10106 // For every pair (T, VQ), where T is an enumeration or
10107 // pointer to member type and VQ is either volatile or
10108 // empty, there exist candidate operator functions of the form
10109 //
10110 // VQ T& operator=(VQ T&, T);
10111 void addAssignmentMemberPointerOrEnumeralOverloads() {
10112 /// Set of (canonical) types that we've already handled.
10113 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10114
10115 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10116 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10117 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10118 continue;
10119
10120 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10121 }
10122
10123 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10124 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10125 continue;
10126
10127 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10128 }
10129 }
10130 }
10131
10132 // C++ [over.built]p19:
10133 //
10134 // For every pair (T, VQ), where T is any type and VQ is either
10135 // volatile or empty, there exist candidate operator functions
10136 // of the form
10137 //
10138 // T*VQ& operator=(T*VQ&, T*);
10139 //
10140 // C++ [over.built]p21:
10141 //
10142 // For every pair (T, VQ), where T is a cv-qualified or
10143 // cv-unqualified object type and VQ is either volatile or
10144 // empty, there exist candidate operator functions of the form
10145 //
10146 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10147 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10148 void addAssignmentPointerOverloads(bool isEqualOp) {
10149 /// Set of (canonical) types that we've already handled.
10150 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10151
10152 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10153 // If this is operator=, keep track of the builtin candidates we added.
10154 if (isEqualOp)
10155 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10156 else if (!PtrTy->getPointeeType()->isObjectType())
10157 continue;
10158
10159 // non-volatile version
10160 QualType ParamTypes[2] = {
10162 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10163 };
10164 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10165 /*IsAssignmentOperator=*/ isEqualOp);
10166
10167 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10168 VisibleTypeConversionsQuals.hasVolatile();
10169 if (NeedVolatile) {
10170 // volatile version
10171 ParamTypes[0] =
10173 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10174 /*IsAssignmentOperator=*/isEqualOp);
10175 }
10176
10177 if (!PtrTy.isRestrictQualified() &&
10178 VisibleTypeConversionsQuals.hasRestrict()) {
10179 // restrict version
10180 ParamTypes[0] =
10182 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10183 /*IsAssignmentOperator=*/isEqualOp);
10184
10185 if (NeedVolatile) {
10186 // volatile restrict version
10187 ParamTypes[0] =
10190 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10191 /*IsAssignmentOperator=*/isEqualOp);
10192 }
10193 }
10194 }
10195
10196 if (isEqualOp) {
10197 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10198 // Make sure we don't add the same candidate twice.
10199 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10200 continue;
10201
10202 QualType ParamTypes[2] = {
10204 PtrTy,
10205 };
10206
10207 // non-volatile version
10208 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10209 /*IsAssignmentOperator=*/true);
10210
10211 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10212 VisibleTypeConversionsQuals.hasVolatile();
10213 if (NeedVolatile) {
10214 // volatile version
10215 ParamTypes[0] = S.Context.getLValueReferenceType(
10216 S.Context.getVolatileType(PtrTy));
10217 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10218 /*IsAssignmentOperator=*/true);
10219 }
10220
10221 if (!PtrTy.isRestrictQualified() &&
10222 VisibleTypeConversionsQuals.hasRestrict()) {
10223 // restrict version
10224 ParamTypes[0] = S.Context.getLValueReferenceType(
10225 S.Context.getRestrictType(PtrTy));
10226 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10227 /*IsAssignmentOperator=*/true);
10228
10229 if (NeedVolatile) {
10230 // volatile restrict version
10231 ParamTypes[0] =
10234 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10235 /*IsAssignmentOperator=*/true);
10236 }
10237 }
10238 }
10239 }
10240 }
10241
10242 // C++ [over.built]p18:
10243 //
10244 // For every triple (L, VQ, R), where L is an arithmetic type,
10245 // VQ is either volatile or empty, and R is a promoted
10246 // arithmetic type, there exist candidate operator functions of
10247 // the form
10248 //
10249 // VQ L& operator=(VQ L&, R);
10250 // VQ L& operator*=(VQ L&, R);
10251 // VQ L& operator/=(VQ L&, R);
10252 // VQ L& operator+=(VQ L&, R);
10253 // VQ L& operator-=(VQ L&, R);
10254 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10255 if (!HasArithmeticOrEnumeralCandidateType)
10256 return;
10257
10258 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10259 for (unsigned Right = FirstPromotedArithmeticType;
10260 Right < LastPromotedArithmeticType; ++Right) {
10261 QualType ParamTypes[2];
10262 ParamTypes[1] = ArithmeticTypes[Right];
10264 S, ArithmeticTypes[Left], Args[0]);
10265
10267 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10268 ParamTypes[0] =
10269 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10270 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10271 /*IsAssignmentOperator=*/isEqualOp);
10272 });
10273 }
10274 }
10275
10276 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10277 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10278 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10279 QualType ParamTypes[2];
10280 ParamTypes[1] = Vec2Ty;
10281 // Add this built-in operator as a candidate (VQ is empty).
10282 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10283 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10284 /*IsAssignmentOperator=*/isEqualOp);
10285
10286 // Add this built-in operator as a candidate (VQ is 'volatile').
10287 if (VisibleTypeConversionsQuals.hasVolatile()) {
10288 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10289 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10290 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10291 /*IsAssignmentOperator=*/isEqualOp);
10292 }
10293 }
10294 }
10295
10296 // C++ [over.built]p22:
10297 //
10298 // For every triple (L, VQ, R), where L is an integral type, VQ
10299 // is either volatile or empty, and R is a promoted integral
10300 // type, there exist candidate operator functions of the form
10301 //
10302 // VQ L& operator%=(VQ L&, R);
10303 // VQ L& operator<<=(VQ L&, R);
10304 // VQ L& operator>>=(VQ L&, R);
10305 // VQ L& operator&=(VQ L&, R);
10306 // VQ L& operator^=(VQ L&, R);
10307 // VQ L& operator|=(VQ L&, R);
10308 void addAssignmentIntegralOverloads() {
10309 if (!HasArithmeticOrEnumeralCandidateType)
10310 return;
10311
10312 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10313 for (unsigned Right = FirstPromotedIntegralType;
10314 Right < LastPromotedIntegralType; ++Right) {
10315 QualType ParamTypes[2];
10316 ParamTypes[1] = ArithmeticTypes[Right];
10318 S, ArithmeticTypes[Left], Args[0]);
10319
10321 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10322 ParamTypes[0] =
10323 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10324 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10325 });
10326 }
10327 }
10328 }
10329
10330 // C++ [over.operator]p23:
10331 //
10332 // There also exist candidate operator functions of the form
10333 //
10334 // bool operator!(bool);
10335 // bool operator&&(bool, bool);
10336 // bool operator||(bool, bool);
10337 void addExclaimOverload() {
10338 QualType ParamTy = S.Context.BoolTy;
10339 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10340 /*IsAssignmentOperator=*/false,
10341 /*NumContextualBoolArguments=*/1);
10342 }
10343 void addAmpAmpOrPipePipeOverload() {
10344 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10345 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10346 /*IsAssignmentOperator=*/false,
10347 /*NumContextualBoolArguments=*/2);
10348 }
10349
10350 // C++ [over.built]p13:
10351 //
10352 // For every cv-qualified or cv-unqualified object type T there
10353 // exist candidate operator functions of the form
10354 //
10355 // T* operator+(T*, ptrdiff_t); [ABOVE]
10356 // T& operator[](T*, ptrdiff_t);
10357 // T* operator-(T*, ptrdiff_t); [ABOVE]
10358 // T* operator+(ptrdiff_t, T*); [ABOVE]
10359 // T& operator[](ptrdiff_t, T*);
10360 void addSubscriptOverloads() {
10361 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10362 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10363 QualType PointeeType = PtrTy->getPointeeType();
10364 if (!PointeeType->isObjectType())
10365 continue;
10366
10367 // T& operator[](T*, ptrdiff_t)
10368 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10369 }
10370
10371 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10372 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10373 QualType PointeeType = PtrTy->getPointeeType();
10374 if (!PointeeType->isObjectType())
10375 continue;
10376
10377 // T& operator[](ptrdiff_t, T*)
10378 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10379 }
10380 }
10381
10382 // C++ [over.built]p11:
10383 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10384 // C1 is the same type as C2 or is a derived class of C2, T is an object
10385 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10386 // there exist candidate operator functions of the form
10387 //
10388 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10389 //
10390 // where CV12 is the union of CV1 and CV2.
10391 void addArrowStarOverloads() {
10392 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10393 QualType C1Ty = PtrTy;
10394 QualType C1;
10395 QualifierCollector Q1;
10396 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10397 if (!isa<RecordType>(C1))
10398 continue;
10399 // heuristic to reduce number of builtin candidates in the set.
10400 // Add volatile/restrict version only if there are conversions to a
10401 // volatile/restrict type.
10402 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10403 continue;
10404 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10405 continue;
10406 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10407 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10408 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10409 *D2 = mptr->getMostRecentCXXRecordDecl();
10410 if (!declaresSameEntity(D1, D2) &&
10411 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10412 break;
10413 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10414 // build CV12 T&
10415 QualType T = mptr->getPointeeType();
10416 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10417 T.isVolatileQualified())
10418 continue;
10419 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10420 T.isRestrictQualified())
10421 continue;
10422 T = Q1.apply(S.Context, T);
10423 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10424 }
10425 }
10426 }
10427
10428 // Note that we don't consider the first argument, since it has been
10429 // contextually converted to bool long ago. The candidates below are
10430 // therefore added as binary.
10431 //
10432 // C++ [over.built]p25:
10433 // For every type T, where T is a pointer, pointer-to-member, or scoped
10434 // enumeration type, there exist candidate operator functions of the form
10435 //
10436 // T operator?(bool, T, T);
10437 //
10438 void addConditionalOperatorOverloads() {
10439 /// Set of (canonical) types that we've already handled.
10440 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10441
10442 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10443 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10444 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10445 continue;
10446
10447 QualType ParamTypes[2] = {PtrTy, PtrTy};
10448 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10449 }
10450
10451 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10452 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10453 continue;
10454
10455 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10456 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10457 }
10458
10459 if (S.getLangOpts().CPlusPlus11) {
10460 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10461 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10462 continue;
10463
10464 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10465 continue;
10466
10467 QualType ParamTypes[2] = {EnumTy, EnumTy};
10468 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10469 }
10470 }
10471 }
10472 }
10473};
10474
10475} // end anonymous namespace
10476
10478 SourceLocation OpLoc,
10479 ArrayRef<Expr *> Args,
10480 OverloadCandidateSet &CandidateSet) {
10481 // Find all of the types that the arguments can convert to, but only
10482 // if the operator we're looking at has built-in operator candidates
10483 // that make use of these types. Also record whether we encounter non-record
10484 // candidate types or either arithmetic or enumeral candidate types.
10485 QualifiersAndAtomic VisibleTypeConversionsQuals;
10486 VisibleTypeConversionsQuals.addConst();
10487 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10488 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10489 if (Args[ArgIdx]->getType()->isAtomicType())
10490 VisibleTypeConversionsQuals.addAtomic();
10491 }
10492
10493 bool HasNonRecordCandidateType = false;
10494 bool HasArithmeticOrEnumeralCandidateType = false;
10496 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10497 CandidateTypes.emplace_back(*this);
10498 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10499 OpLoc,
10500 true,
10501 (Op == OO_Exclaim ||
10502 Op == OO_AmpAmp ||
10503 Op == OO_PipePipe),
10504 VisibleTypeConversionsQuals);
10505 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10506 CandidateTypes[ArgIdx].hasNonRecordTypes();
10507 HasArithmeticOrEnumeralCandidateType =
10508 HasArithmeticOrEnumeralCandidateType ||
10509 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10510 }
10511
10512 // Exit early when no non-record types have been added to the candidate set
10513 // for any of the arguments to the operator.
10514 //
10515 // We can't exit early for !, ||, or &&, since there we have always have
10516 // 'bool' overloads.
10517 if (!HasNonRecordCandidateType &&
10518 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10519 return;
10520
10521 // Setup an object to manage the common state for building overloads.
10522 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10523 VisibleTypeConversionsQuals,
10524 HasArithmeticOrEnumeralCandidateType,
10525 CandidateTypes, CandidateSet);
10526
10527 // Dispatch over the operation to add in only those overloads which apply.
10528 switch (Op) {
10529 case OO_None:
10531 llvm_unreachable("Expected an overloaded operator");
10532
10533 case OO_New:
10534 case OO_Delete:
10535 case OO_Array_New:
10536 case OO_Array_Delete:
10537 case OO_Call:
10538 llvm_unreachable(
10539 "Special operators don't use AddBuiltinOperatorCandidates");
10540
10541 case OO_Comma:
10542 case OO_Arrow:
10543 case OO_Coawait:
10544 // C++ [over.match.oper]p3:
10545 // -- For the operator ',', the unary operator '&', the
10546 // operator '->', or the operator 'co_await', the
10547 // built-in candidates set is empty.
10548 break;
10549
10550 case OO_Plus: // '+' is either unary or binary
10551 if (Args.size() == 1)
10552 OpBuilder.addUnaryPlusPointerOverloads();
10553 [[fallthrough]];
10554
10555 case OO_Minus: // '-' is either unary or binary
10556 if (Args.size() == 1) {
10557 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10558 } else {
10559 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10560 OpBuilder.addGenericBinaryArithmeticOverloads();
10561 OpBuilder.addMatrixBinaryArithmeticOverloads();
10562 }
10563 break;
10564
10565 case OO_Star: // '*' is either unary or binary
10566 if (Args.size() == 1)
10567 OpBuilder.addUnaryStarPointerOverloads();
10568 else {
10569 OpBuilder.addGenericBinaryArithmeticOverloads();
10570 OpBuilder.addMatrixBinaryArithmeticOverloads();
10571 }
10572 break;
10573
10574 case OO_Slash:
10575 OpBuilder.addGenericBinaryArithmeticOverloads();
10576 break;
10577
10578 case OO_PlusPlus:
10579 case OO_MinusMinus:
10580 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10581 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10582 break;
10583
10584 case OO_EqualEqual:
10585 case OO_ExclaimEqual:
10586 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10587 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10588 OpBuilder.addGenericBinaryArithmeticOverloads();
10589 break;
10590
10591 case OO_Less:
10592 case OO_Greater:
10593 case OO_LessEqual:
10594 case OO_GreaterEqual:
10595 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10596 OpBuilder.addGenericBinaryArithmeticOverloads();
10597 break;
10598
10599 case OO_Spaceship:
10600 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10601 OpBuilder.addThreeWayArithmeticOverloads();
10602 break;
10603
10604 case OO_Percent:
10605 case OO_Caret:
10606 case OO_Pipe:
10607 case OO_LessLess:
10608 case OO_GreaterGreater:
10609 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10610 break;
10611
10612 case OO_Amp: // '&' is either unary or binary
10613 if (Args.size() == 1)
10614 // C++ [over.match.oper]p3:
10615 // -- For the operator ',', the unary operator '&', or the
10616 // operator '->', the built-in candidates set is empty.
10617 break;
10618
10619 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10620 break;
10621
10622 case OO_Tilde:
10623 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10624 break;
10625
10626 case OO_Equal:
10627 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10628 [[fallthrough]];
10629
10630 case OO_PlusEqual:
10631 case OO_MinusEqual:
10632 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10633 [[fallthrough]];
10634
10635 case OO_StarEqual:
10636 case OO_SlashEqual:
10637 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10638 break;
10639
10640 case OO_PercentEqual:
10641 case OO_LessLessEqual:
10642 case OO_GreaterGreaterEqual:
10643 case OO_AmpEqual:
10644 case OO_CaretEqual:
10645 case OO_PipeEqual:
10646 OpBuilder.addAssignmentIntegralOverloads();
10647 break;
10648
10649 case OO_Exclaim:
10650 OpBuilder.addExclaimOverload();
10651 break;
10652
10653 case OO_AmpAmp:
10654 case OO_PipePipe:
10655 OpBuilder.addAmpAmpOrPipePipeOverload();
10656 break;
10657
10658 case OO_Subscript:
10659 if (Args.size() == 2)
10660 OpBuilder.addSubscriptOverloads();
10661 break;
10662
10663 case OO_ArrowStar:
10664 OpBuilder.addArrowStarOverloads();
10665 break;
10666
10667 case OO_Conditional:
10668 OpBuilder.addConditionalOperatorOverloads();
10669 OpBuilder.addGenericBinaryArithmeticOverloads();
10670 break;
10671 }
10672}
10673
10674void
10676 SourceLocation Loc,
10677 ArrayRef<Expr *> Args,
10678 TemplateArgumentListInfo *ExplicitTemplateArgs,
10679 OverloadCandidateSet& CandidateSet,
10680 bool PartialOverloading) {
10681 ADLResult Fns;
10682
10683 // FIXME: This approach for uniquing ADL results (and removing
10684 // redundant candidates from the set) relies on pointer-equality,
10685 // which means we need to key off the canonical decl. However,
10686 // always going back to the canonical decl might not get us the
10687 // right set of default arguments. What default arguments are
10688 // we supposed to consider on ADL candidates, anyway?
10689
10690 // FIXME: Pass in the explicit template arguments?
10691 ArgumentDependentLookup(Name, Loc, Args, Fns);
10692
10693 ArrayRef<Expr *> ReversedArgs;
10694
10695 // Erase all of the candidates we already knew about.
10696 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10697 CandEnd = CandidateSet.end();
10698 Cand != CandEnd; ++Cand)
10699 if (Cand->Function) {
10700 FunctionDecl *Fn = Cand->Function;
10701 Fns.erase(Fn);
10702 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10703 Fns.erase(FunTmpl);
10704 }
10705
10706 // For each of the ADL candidates we found, add it to the overload
10707 // set.
10708 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10710
10711 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10712 if (ExplicitTemplateArgs)
10713 continue;
10714
10716 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10717 PartialOverloading, /*AllowExplicit=*/true,
10718 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10719 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10721 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10722 /*SuppressUserConversions=*/false, PartialOverloading,
10723 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10724 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10725 }
10726 } else {
10727 auto *FTD = cast<FunctionTemplateDecl>(*I);
10729 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10730 /*SuppressUserConversions=*/false, PartialOverloading,
10731 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10732 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10733 *this, Args, FTD->getTemplatedDecl())) {
10734
10735 // As template candidates are not deduced immediately,
10736 // persist the array in the overload set.
10737 if (ReversedArgs.empty())
10738 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10739
10741 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10742 /*SuppressUserConversions=*/false, PartialOverloading,
10743 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10745 }
10746 }
10747 }
10748}
10749
10750namespace {
10751enum class Comparison { Equal, Better, Worse };
10752}
10753
10754/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10755/// overload resolution.
10756///
10757/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10758/// Cand1's first N enable_if attributes have precisely the same conditions as
10759/// Cand2's first N enable_if attributes (where N = the number of enable_if
10760/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10761///
10762/// Note that you can have a pair of candidates such that Cand1's enable_if
10763/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10764/// worse than Cand1's.
10765static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10766 const FunctionDecl *Cand2) {
10767 // Common case: One (or both) decls don't have enable_if attrs.
10768 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10769 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10770 if (!Cand1Attr || !Cand2Attr) {
10771 if (Cand1Attr == Cand2Attr)
10772 return Comparison::Equal;
10773 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10774 }
10775
10776 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10777 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10778
10779 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10780 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10781 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10782 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10783
10784 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10785 // has fewer enable_if attributes than Cand2, and vice versa.
10786 if (!Cand1A)
10787 return Comparison::Worse;
10788 if (!Cand2A)
10789 return Comparison::Better;
10790
10791 Cand1ID.clear();
10792 Cand2ID.clear();
10793
10794 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10795 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10796 if (Cand1ID != Cand2ID)
10797 return Comparison::Worse;
10798 }
10799
10800 return Comparison::Equal;
10801}
10802
10803static Comparison
10805 const OverloadCandidate &Cand2) {
10806 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10807 !Cand2.Function->isMultiVersion())
10808 return Comparison::Equal;
10809
10810 // If both are invalid, they are equal. If one of them is invalid, the other
10811 // is better.
10812 if (Cand1.Function->isInvalidDecl()) {
10813 if (Cand2.Function->isInvalidDecl())
10814 return Comparison::Equal;
10815 return Comparison::Worse;
10816 }
10817 if (Cand2.Function->isInvalidDecl())
10818 return Comparison::Better;
10819
10820 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10821 // cpu_dispatch, else arbitrarily based on the identifiers.
10822 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10823 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10824 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10825 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10826
10827 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10828 return Comparison::Equal;
10829
10830 if (Cand1CPUDisp && !Cand2CPUDisp)
10831 return Comparison::Better;
10832 if (Cand2CPUDisp && !Cand1CPUDisp)
10833 return Comparison::Worse;
10834
10835 if (Cand1CPUSpec && Cand2CPUSpec) {
10836 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10837 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10838 ? Comparison::Better
10839 : Comparison::Worse;
10840
10841 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10842 FirstDiff = std::mismatch(
10843 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10844 Cand2CPUSpec->cpus_begin(),
10845 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10846 return LHS->getName() == RHS->getName();
10847 });
10848
10849 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10850 "Two different cpu-specific versions should not have the same "
10851 "identifier list, otherwise they'd be the same decl!");
10852 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10853 ? Comparison::Better
10854 : Comparison::Worse;
10855 }
10856 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10857}
10858
10859/// Compute the type of the implicit object parameter for the given function,
10860/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10861/// null QualType if there is a 'matches anything' implicit object parameter.
10862static std::optional<QualType>
10865 return std::nullopt;
10866
10867 auto *M = cast<CXXMethodDecl>(F);
10868 // Static member functions' object parameters match all types.
10869 if (M->isStatic())
10870 return QualType();
10871 return M->getFunctionObjectParameterReferenceType();
10872}
10873
10874// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10875// represent the same entity.
10876static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10877 const FunctionDecl *F2) {
10878 if (declaresSameEntity(F1, F2))
10879 return true;
10880 auto PT1 = F1->getPrimaryTemplate();
10881 auto PT2 = F2->getPrimaryTemplate();
10882 if (PT1 && PT2) {
10883 if (declaresSameEntity(PT1, PT2) ||
10884 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10885 PT2->getInstantiatedFromMemberTemplate()))
10886 return true;
10887 }
10888 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10889 // different functions with same params). Consider removing this (as no test
10890 // fail w/o it).
10891 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10892 if (First) {
10893 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10894 return *T;
10895 }
10896 assert(I < F->getNumParams());
10897 return F->getParamDecl(I++)->getType();
10898 };
10899
10900 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10901 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10902
10903 if (F1NumParams != F2NumParams)
10904 return false;
10905
10906 unsigned I1 = 0, I2 = 0;
10907 for (unsigned I = 0; I != F1NumParams; ++I) {
10908 QualType T1 = NextParam(F1, I1, I == 0);
10909 QualType T2 = NextParam(F2, I2, I == 0);
10910 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10911 if (!Context.hasSameUnqualifiedType(T1, T2))
10912 return false;
10913 }
10914 return true;
10915}
10916
10917/// We're allowed to use constraints partial ordering only if the candidates
10918/// have the same parameter types:
10919/// [over.match.best.general]p2.6
10920/// F1 and F2 are non-template functions with the same
10921/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10923 FunctionDecl *Fn2,
10924 bool IsFn1Reversed,
10925 bool IsFn2Reversed) {
10926 assert(Fn1 && Fn2);
10927 if (Fn1->isVariadic() != Fn2->isVariadic())
10928 return false;
10929
10930 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10931 IsFn1Reversed ^ IsFn2Reversed))
10932 return false;
10933
10934 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10935 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10936 if (Mem1 && Mem2) {
10937 // if they are member functions, both are direct members of the same class,
10938 // and
10939 if (Mem1->getParent() != Mem2->getParent())
10940 return false;
10941 // if both are non-static member functions, they have the same types for
10942 // their object parameters
10943 if (Mem1->isInstance() && Mem2->isInstance() &&
10945 Mem1->getFunctionObjectParameterReferenceType(),
10946 Mem1->getFunctionObjectParameterReferenceType()))
10947 return false;
10948 }
10949 return true;
10950}
10951
10952static FunctionDecl *
10954 bool IsFn1Reversed, bool IsFn2Reversed) {
10955 if (!Fn1 || !Fn2)
10956 return nullptr;
10957
10958 // C++ [temp.constr.order]:
10959 // A non-template function F1 is more partial-ordering-constrained than a
10960 // non-template function F2 if:
10961 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10962 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10963
10964 if (Cand1IsSpecialization || Cand2IsSpecialization)
10965 return nullptr;
10966
10967 // - they have the same non-object-parameter-type-lists, and [...]
10968 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10969 IsFn2Reversed))
10970 return nullptr;
10971
10972 // - the declaration of F1 is more constrained than the declaration of F2.
10973 return S.getMoreConstrainedFunction(Fn1, Fn2);
10974}
10975
10976/// isBetterOverloadCandidate - Determines whether the first overload
10977/// candidate is a better candidate than the second (C++ 13.3.3p1).
10979 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10981 bool PartialOverloading) {
10982 // Define viable functions to be better candidates than non-viable
10983 // functions.
10984 if (!Cand2.Viable)
10985 return Cand1.Viable;
10986 else if (!Cand1.Viable)
10987 return false;
10988
10989 // [CUDA] A function with 'never' preference is marked not viable, therefore
10990 // is never shown up here. The worst preference shown up here is 'wrong side',
10991 // e.g. an H function called by a HD function in device compilation. This is
10992 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10993 // function which is called only by an H function. A deferred diagnostic will
10994 // be triggered if it is emitted. However a wrong-sided function is still
10995 // a viable candidate here.
10996 //
10997 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10998 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10999 // can be emitted, Cand1 is not better than Cand2. This rule should have
11000 // precedence over other rules.
11001 //
11002 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11003 // other rules should be used to determine which is better. This is because
11004 // host/device based overloading resolution is mostly for determining
11005 // viability of a function. If two functions are both viable, other factors
11006 // should take precedence in preference, e.g. the standard-defined preferences
11007 // like argument conversion ranks or enable_if partial-ordering. The
11008 // preference for pass-object-size parameters is probably most similar to a
11009 // type-based-overloading decision and so should take priority.
11010 //
11011 // If other rules cannot determine which is better, CUDA preference will be
11012 // used again to determine which is better.
11013 //
11014 // TODO: Currently IdentifyPreference does not return correct values
11015 // for functions called in global variable initializers due to missing
11016 // correct context about device/host. Therefore we can only enforce this
11017 // rule when there is a caller. We should enforce this rule for functions
11018 // in global variable initializers once proper context is added.
11019 //
11020 // TODO: We can only enable the hostness based overloading resolution when
11021 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11022 // overloading resolution diagnostics.
11023 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11024 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11025 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11026 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11027 bool IsCand1ImplicitHD =
11029 bool IsCand2ImplicitHD =
11031 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11032 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11033 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11034 // The implicit HD function may be a function in a system header which
11035 // is forced by pragma. In device compilation, if we prefer HD candidates
11036 // over wrong-sided candidates, overloading resolution may change, which
11037 // may result in non-deferrable diagnostics. As a workaround, we let
11038 // implicit HD candidates take equal preference as wrong-sided candidates.
11039 // This will preserve the overloading resolution.
11040 // TODO: We still need special handling of implicit HD functions since
11041 // they may incur other diagnostics to be deferred. We should make all
11042 // host/device related diagnostics deferrable and remove special handling
11043 // of implicit HD functions.
11044 auto EmitThreshold =
11045 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11046 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11049 auto Cand1Emittable = P1 > EmitThreshold;
11050 auto Cand2Emittable = P2 > EmitThreshold;
11051 if (Cand1Emittable && !Cand2Emittable)
11052 return true;
11053 if (!Cand1Emittable && Cand2Emittable)
11054 return false;
11055 }
11056 }
11057
11058 // C++ [over.match.best]p1: (Changed in C++23)
11059 //
11060 // -- if F is a static member function, ICS1(F) is defined such
11061 // that ICS1(F) is neither better nor worse than ICS1(G) for
11062 // any function G, and, symmetrically, ICS1(G) is neither
11063 // better nor worse than ICS1(F).
11064 unsigned StartArg = 0;
11065 if (!Cand1.TookAddressOfOverload &&
11067 StartArg = 1;
11068
11069 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11070 // We don't allow incompatible pointer conversions in C++.
11071 if (!S.getLangOpts().CPlusPlus)
11072 return ICS.isStandard() &&
11073 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11074
11075 // The only ill-formed conversion we allow in C++ is the string literal to
11076 // char* conversion, which is only considered ill-formed after C++11.
11077 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11079 };
11080
11081 // Define functions that don't require ill-formed conversions for a given
11082 // argument to be better candidates than functions that do.
11083 unsigned NumArgs = Cand1.Conversions.size();
11084 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11085 bool HasBetterConversion = false;
11086 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11087 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11088 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11089 if (Cand1Bad != Cand2Bad) {
11090 if (Cand1Bad)
11091 return false;
11092 HasBetterConversion = true;
11093 }
11094 }
11095
11096 if (HasBetterConversion)
11097 return true;
11098
11099 // C++ [over.match.best]p1:
11100 // A viable function F1 is defined to be a better function than another
11101 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11102 // conversion sequence than ICSi(F2), and then...
11103 bool HasWorseConversion = false;
11104 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11106 Cand1.Conversions[ArgIdx],
11107 Cand2.Conversions[ArgIdx])) {
11109 // Cand1 has a better conversion sequence.
11110 HasBetterConversion = true;
11111 break;
11112
11114 if (Cand1.Function && Cand2.Function &&
11115 Cand1.isReversed() != Cand2.isReversed() &&
11116 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11117 // Work around large-scale breakage caused by considering reversed
11118 // forms of operator== in C++20:
11119 //
11120 // When comparing a function against a reversed function, if we have a
11121 // better conversion for one argument and a worse conversion for the
11122 // other, the implicit conversion sequences are treated as being equally
11123 // good.
11124 //
11125 // This prevents a comparison function from being considered ambiguous
11126 // with a reversed form that is written in the same way.
11127 //
11128 // We diagnose this as an extension from CreateOverloadedBinOp.
11129 HasWorseConversion = true;
11130 break;
11131 }
11132
11133 // Cand1 can't be better than Cand2.
11134 return false;
11135
11137 // Do nothing.
11138 break;
11139 }
11140 }
11141
11142 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11143 // ICSj(F2), or, if not that,
11144 if (HasBetterConversion && !HasWorseConversion)
11145 return true;
11146
11147 // -- the context is an initialization by user-defined conversion
11148 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11149 // from the return type of F1 to the destination type (i.e.,
11150 // the type of the entity being initialized) is a better
11151 // conversion sequence than the standard conversion sequence
11152 // from the return type of F2 to the destination type.
11154 Cand1.Function && Cand2.Function &&
11157
11158 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11159 // First check whether we prefer one of the conversion functions over the
11160 // other. This only distinguishes the results in non-standard, extension
11161 // cases such as the conversion from a lambda closure type to a function
11162 // pointer or block.
11167 Cand1.FinalConversion,
11168 Cand2.FinalConversion);
11169
11172
11173 // FIXME: Compare kind of reference binding if conversion functions
11174 // convert to a reference type used in direct reference binding, per
11175 // C++14 [over.match.best]p1 section 2 bullet 3.
11176 }
11177
11178 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11179 // as combined with the resolution to CWG issue 243.
11180 //
11181 // When the context is initialization by constructor ([over.match.ctor] or
11182 // either phase of [over.match.list]), a constructor is preferred over
11183 // a conversion function.
11184 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11185 Cand1.Function && Cand2.Function &&
11188 return isa<CXXConstructorDecl>(Cand1.Function);
11189
11190 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11191 return Cand2.StrictPackMatch;
11192
11193 // -- F1 is a non-template function and F2 is a function template
11194 // specialization, or, if not that,
11195 bool Cand1IsSpecialization = Cand1.Function &&
11197 bool Cand2IsSpecialization = Cand2.Function &&
11199 if (Cand1IsSpecialization != Cand2IsSpecialization)
11200 return Cand2IsSpecialization;
11201
11202 // -- F1 and F2 are function template specializations, and the function
11203 // template for F1 is more specialized than the template for F2
11204 // according to the partial ordering rules described in 14.5.5.2, or,
11205 // if not that,
11206 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11207 const auto *Obj1Context =
11208 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11209 const auto *Obj2Context =
11210 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11211 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11213 Cand2.Function->getPrimaryTemplate(), Loc,
11215 : TPOC_Call,
11217 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11218 : QualType{},
11219 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11220 : QualType{},
11221 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11222 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11223 }
11224 }
11225
11226 // -— F1 and F2 are non-template functions and F1 is more
11227 // partial-ordering-constrained than F2 [...],
11229 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11230 Cand2.isReversed());
11231 F && F == Cand1.Function)
11232 return true;
11233
11234 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11235 // class B of D, and for all arguments the corresponding parameters of
11236 // F1 and F2 have the same type.
11237 // FIXME: Implement the "all parameters have the same type" check.
11238 bool Cand1IsInherited =
11239 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11240 bool Cand2IsInherited =
11241 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11242 if (Cand1IsInherited != Cand2IsInherited)
11243 return Cand2IsInherited;
11244 else if (Cand1IsInherited) {
11245 assert(Cand2IsInherited);
11246 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11247 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11248 if (Cand1Class->isDerivedFrom(Cand2Class))
11249 return true;
11250 if (Cand2Class->isDerivedFrom(Cand1Class))
11251 return false;
11252 // Inherited from sibling base classes: still ambiguous.
11253 }
11254
11255 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11256 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11257 // with reversed order of parameters and F1 is not
11258 //
11259 // We rank reversed + different operator as worse than just reversed, but
11260 // that comparison can never happen, because we only consider reversing for
11261 // the maximally-rewritten operator (== or <=>).
11262 if (Cand1.RewriteKind != Cand2.RewriteKind)
11263 return Cand1.RewriteKind < Cand2.RewriteKind;
11264
11265 // Check C++17 tie-breakers for deduction guides.
11266 {
11267 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11268 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11269 if (Guide1 && Guide2) {
11270 // -- F1 is generated from a deduction-guide and F2 is not
11271 if (Guide1->isImplicit() != Guide2->isImplicit())
11272 return Guide2->isImplicit();
11273
11274 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11275 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11276 return true;
11277 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11278 return false;
11279
11280 // --F1 is generated from a non-template constructor and F2 is generated
11281 // from a constructor template
11282 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11283 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11284 if (Constructor1 && Constructor2) {
11285 bool isC1Templated = Constructor1->getTemplatedKind() !=
11287 bool isC2Templated = Constructor2->getTemplatedKind() !=
11289 if (isC1Templated != isC2Templated)
11290 return isC2Templated;
11291 }
11292 }
11293 }
11294
11295 // Check for enable_if value-based overload resolution.
11296 if (Cand1.Function && Cand2.Function) {
11298 if (Cmp != Comparison::Equal)
11299 return Cmp == Comparison::Better;
11300 }
11301
11302 bool HasPS1 = Cand1.Function != nullptr &&
11304 bool HasPS2 = Cand2.Function != nullptr &&
11306 if (HasPS1 != HasPS2 && HasPS1)
11307 return true;
11308
11309 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11310 if (MV == Comparison::Better)
11311 return true;
11312 if (MV == Comparison::Worse)
11313 return false;
11314
11315 // If other rules cannot determine which is better, CUDA preference is used
11316 // to determine which is better.
11317 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11318 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11319 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11320 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11321 }
11322
11323 // General member function overloading is handled above, so this only handles
11324 // constructors with address spaces.
11325 // This only handles address spaces since C++ has no other
11326 // qualifier that can be used with constructors.
11327 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11328 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11329 if (CD1 && CD2) {
11330 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11331 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11332 if (AS1 != AS2) {
11334 return true;
11336 return false;
11337 }
11338 }
11339
11340 return false;
11341}
11342
11343/// Determine whether two declarations are "equivalent" for the purposes of
11344/// name lookup and overload resolution. This applies when the same internal/no
11345/// linkage entity is defined by two modules (probably by textually including
11346/// the same header). In such a case, we don't consider the declarations to
11347/// declare the same entity, but we also don't want lookups with both
11348/// declarations visible to be ambiguous in some cases (this happens when using
11349/// a modularized libstdc++).
11351 const NamedDecl *B) {
11352 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11353 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11354 if (!VA || !VB)
11355 return false;
11356
11357 // The declarations must be declaring the same name as an internal linkage
11358 // entity in different modules.
11359 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11360 VB->getDeclContext()->getRedeclContext()) ||
11361 getOwningModule(VA) == getOwningModule(VB) ||
11362 VA->isExternallyVisible() || VB->isExternallyVisible())
11363 return false;
11364
11365 // Check that the declarations appear to be equivalent.
11366 //
11367 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11368 // For constants and functions, we should check the initializer or body is
11369 // the same. For non-constant variables, we shouldn't allow it at all.
11370 if (Context.hasSameType(VA->getType(), VB->getType()))
11371 return true;
11372
11373 // Enum constants within unnamed enumerations will have different types, but
11374 // may still be similar enough to be interchangeable for our purposes.
11375 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11376 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11377 // Only handle anonymous enums. If the enumerations were named and
11378 // equivalent, they would have been merged to the same type.
11379 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11380 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11381 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11382 !Context.hasSameType(EnumA->getIntegerType(),
11383 EnumB->getIntegerType()))
11384 return false;
11385 // Allow this only if the value is the same for both enumerators.
11386 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11387 }
11388 }
11389
11390 // Nothing else is sufficiently similar.
11391 return false;
11392}
11393
11396 assert(D && "Unknown declaration");
11397 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11398
11399 Module *M = getOwningModule(D);
11400 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11401 << !M << (M ? M->getFullModuleName() : "");
11402
11403 for (auto *E : Equiv) {
11404 Module *M = getOwningModule(E);
11405 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11406 << !M << (M ? M->getFullModuleName() : "");
11407 }
11408}
11409
11412 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11414 static_cast<CNSInfo *>(DeductionFailure.Data)
11415 ->Satisfaction.ContainsErrors;
11416}
11417
11420 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11421 bool PartialOverloading, bool AllowExplicit,
11423 bool AggregateCandidateDeduction) {
11424
11425 auto *C =
11426 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11427
11430 /*AllowObjCConversionOnExplicit=*/false,
11431 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11432 PartialOverloading, AggregateCandidateDeduction},
11434 FoundDecl,
11435 Args,
11436 IsADLCandidate,
11437 PO};
11438
11439 HasDeferredTemplateConstructors |=
11440 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11441}
11442
11444 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11445 CXXRecordDecl *ActingContext, QualType ObjectType,
11446 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11447 bool SuppressUserConversions, bool PartialOverloading,
11449
11450 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11451
11452 auto *C =
11453 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11454
11457 /*AllowObjCConversionOnExplicit=*/false,
11458 /*AllowResultConversion=*/false,
11459 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11460 /*AggregateCandidateDeduction=*/false},
11461 MethodTmpl,
11462 FoundDecl,
11463 Args,
11464 ActingContext,
11465 ObjectClassification,
11466 ObjectType,
11467 PO};
11468}
11469
11472 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11473 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11474 bool AllowResultConversion) {
11475
11476 auto *C =
11477 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11478
11481 AllowObjCConversionOnExplicit, AllowResultConversion,
11482 /*AllowExplicit=*/false,
11483 /*SuppressUserConversions=*/false,
11484 /*PartialOverloading*/ false,
11485 /*AggregateCandidateDeduction=*/false},
11487 FoundDecl,
11488 ActingContext,
11489 From,
11490 ToType};
11491}
11492
11493static void
11496
11498 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11499 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11500 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11501}
11502
11503static void
11507 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11508 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11509 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11510 C.AggregateCandidateDeduction);
11511}
11512
11513static void
11517 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11518 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11519 C.AllowResultConversion);
11520}
11521
11523 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11524 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11525 while (Cand) {
11526 switch (Cand->Kind) {
11529 S, *this,
11530 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11531 break;
11534 S, *this,
11535 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11536 break;
11539 S, *this,
11540 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11541 break;
11542 }
11543 Cand = Cand->Next;
11544 }
11545 FirstDeferredCandidate = nullptr;
11546 DeferredCandidatesCount = 0;
11547}
11548
11550OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11551 Best->Best = true;
11552 if (Best->Function && Best->Function->isDeleted())
11553 return OR_Deleted;
11554 return OR_Success;
11555}
11556
11557void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11559 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11560 // are accepted by both clang and NVCC. However, during a particular
11561 // compilation mode only one call variant is viable. We need to
11562 // exclude non-viable overload candidates from consideration based
11563 // only on their host/device attributes. Specifically, if one
11564 // candidate call is WrongSide and the other is SameSide, we ignore
11565 // the WrongSide candidate.
11566 // We only need to remove wrong-sided candidates here if
11567 // -fgpu-exclude-wrong-side-overloads is off. When
11568 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11569 // uniformly in isBetterOverloadCandidate.
11570 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11571 return;
11572 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11573
11574 bool ContainsSameSideCandidate =
11575 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11576 // Check viable function only.
11577 return Cand->Viable && Cand->Function &&
11578 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11580 });
11581
11582 if (!ContainsSameSideCandidate)
11583 return;
11584
11585 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11586 // Check viable function only to avoid unnecessary data copying/moving.
11587 return Cand->Viable && Cand->Function &&
11588 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11590 };
11591 llvm::erase_if(Candidates, IsWrongSideCandidate);
11592}
11593
11594/// Computes the best viable function (C++ 13.3.3)
11595/// within an overload candidate set.
11596///
11597/// \param Loc The location of the function name (or operator symbol) for
11598/// which overload resolution occurs.
11599///
11600/// \param Best If overload resolution was successful or found a deleted
11601/// function, \p Best points to the candidate function found.
11602///
11603/// \returns The result of overload resolution.
11605 SourceLocation Loc,
11606 iterator &Best) {
11607
11609 DeferredCandidatesCount == 0) &&
11610 "Unexpected deferred template candidates");
11611
11612 bool TwoPhaseResolution =
11613 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11614
11615 if (TwoPhaseResolution) {
11616 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11617 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11618 if (!(HasDeferredTemplateConstructors &&
11619 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11620 return Res;
11621 }
11622 }
11623
11625 return BestViableFunctionImpl(S, Loc, Best);
11626}
11627
11628OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11630
11632 Candidates.reserve(this->Candidates.size());
11633 std::transform(this->Candidates.begin(), this->Candidates.end(),
11634 std::back_inserter(Candidates),
11635 [](OverloadCandidate &Cand) { return &Cand; });
11636
11637 if (S.getLangOpts().CUDA)
11638 CudaExcludeWrongSideCandidates(S, Candidates);
11639
11640 Best = end();
11641 for (auto *Cand : Candidates) {
11642 Cand->Best = false;
11643 if (Cand->Viable) {
11644 if (Best == end() ||
11645 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11646 Best = Cand;
11647 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11648 // This candidate has constraint that we were unable to evaluate because
11649 // it referenced an expression that contained an error. Rather than fall
11650 // back onto a potentially unintended candidate (made worse by
11651 // subsuming constraints), treat this as 'no viable candidate'.
11652 Best = end();
11653 return OR_No_Viable_Function;
11654 }
11655 }
11656
11657 // If we didn't find any viable functions, abort.
11658 if (Best == end())
11659 return OR_No_Viable_Function;
11660
11661 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11662 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11663 PendingBest.push_back(&*Best);
11664 Best->Best = true;
11665
11666 // Make sure that this function is better than every other viable
11667 // function. If not, we have an ambiguity.
11668 while (!PendingBest.empty()) {
11669 auto *Curr = PendingBest.pop_back_val();
11670 for (auto *Cand : Candidates) {
11671 if (Cand->Viable && !Cand->Best &&
11672 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11673 PendingBest.push_back(Cand);
11674 Cand->Best = true;
11675
11677 Curr->Function))
11678 EquivalentCands.push_back(Cand->Function);
11679 else
11680 Best = end();
11681 }
11682 }
11683 }
11684
11685 if (Best == end())
11686 return OR_Ambiguous;
11687
11688 OverloadingResult R = ResultForBestCandidate(Best);
11689
11690 if (!EquivalentCands.empty())
11692 EquivalentCands);
11693 return R;
11694}
11695
11696namespace {
11697
11698enum OverloadCandidateKind {
11699 oc_function,
11700 oc_method,
11701 oc_reversed_binary_operator,
11702 oc_constructor,
11703 oc_implicit_default_constructor,
11704 oc_implicit_copy_constructor,
11705 oc_implicit_move_constructor,
11706 oc_implicit_copy_assignment,
11707 oc_implicit_move_assignment,
11708 oc_implicit_equality_comparison,
11709 oc_inherited_constructor
11710};
11711
11712enum OverloadCandidateSelect {
11713 ocs_non_template,
11714 ocs_template,
11715 ocs_described_template,
11716};
11717
11718static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11719ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11720 const FunctionDecl *Fn,
11722 std::string &Description) {
11723
11724 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11725 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11726 isTemplate = true;
11727 Description = S.getTemplateArgumentBindingsText(
11728 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11729 }
11730
11731 OverloadCandidateSelect Select = [&]() {
11732 if (!Description.empty())
11733 return ocs_described_template;
11734 return isTemplate ? ocs_template : ocs_non_template;
11735 }();
11736
11737 OverloadCandidateKind Kind = [&]() {
11738 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11739 return oc_implicit_equality_comparison;
11740
11741 if (CRK & CRK_Reversed)
11742 return oc_reversed_binary_operator;
11743
11744 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11745 if (!Ctor->isImplicit()) {
11747 return oc_inherited_constructor;
11748 else
11749 return oc_constructor;
11750 }
11751
11752 if (Ctor->isDefaultConstructor())
11753 return oc_implicit_default_constructor;
11754
11755 if (Ctor->isMoveConstructor())
11756 return oc_implicit_move_constructor;
11757
11758 assert(Ctor->isCopyConstructor() &&
11759 "unexpected sort of implicit constructor");
11760 return oc_implicit_copy_constructor;
11761 }
11762
11763 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11764 // This actually gets spelled 'candidate function' for now, but
11765 // it doesn't hurt to split it out.
11766 if (!Meth->isImplicit())
11767 return oc_method;
11768
11769 if (Meth->isMoveAssignmentOperator())
11770 return oc_implicit_move_assignment;
11771
11772 if (Meth->isCopyAssignmentOperator())
11773 return oc_implicit_copy_assignment;
11774
11775 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11776 return oc_method;
11777 }
11778
11779 return oc_function;
11780 }();
11781
11782 return std::make_pair(Kind, Select);
11783}
11784
11785void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11786 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11787 // set.
11788 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11789 S.Diag(FoundDecl->getLocation(),
11790 diag::note_ovl_candidate_inherited_constructor)
11791 << Shadow->getNominatedBaseClass();
11792}
11793
11794} // end anonymous namespace
11795
11797 const FunctionDecl *FD) {
11798 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11799 bool AlwaysTrue;
11800 if (EnableIf->getCond()->isValueDependent() ||
11801 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11802 return false;
11803 if (!AlwaysTrue)
11804 return false;
11805 }
11806 return true;
11807}
11808
11809/// Returns true if we can take the address of the function.
11810///
11811/// \param Complain - If true, we'll emit a diagnostic
11812/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11813/// we in overload resolution?
11814/// \param Loc - The location of the statement we're complaining about. Ignored
11815/// if we're not complaining, or if we're in overload resolution.
11817 bool Complain,
11818 bool InOverloadResolution,
11819 SourceLocation Loc) {
11820 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11821 if (Complain) {
11822 if (InOverloadResolution)
11823 S.Diag(FD->getBeginLoc(),
11824 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11825 else
11826 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11827 }
11828 return false;
11829 }
11830
11831 if (FD->getTrailingRequiresClause()) {
11832 ConstraintSatisfaction Satisfaction;
11833 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11834 return false;
11835 if (!Satisfaction.IsSatisfied) {
11836 if (Complain) {
11837 if (InOverloadResolution) {
11838 SmallString<128> TemplateArgString;
11839 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11840 TemplateArgString += " ";
11841 TemplateArgString += S.getTemplateArgumentBindingsText(
11842 FunTmpl->getTemplateParameters(),
11844 }
11845
11846 S.Diag(FD->getBeginLoc(),
11847 diag::note_ovl_candidate_unsatisfied_constraints)
11848 << TemplateArgString;
11849 } else
11850 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11851 << FD;
11852 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11853 }
11854 return false;
11855 }
11856 }
11857
11858 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11859 return P->hasAttr<PassObjectSizeAttr>();
11860 });
11861 if (I == FD->param_end())
11862 return true;
11863
11864 if (Complain) {
11865 // Add one to ParamNo because it's user-facing
11866 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11867 if (InOverloadResolution)
11868 S.Diag(FD->getLocation(),
11869 diag::note_ovl_candidate_has_pass_object_size_params)
11870 << ParamNo;
11871 else
11872 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11873 << FD << ParamNo;
11874 }
11875 return false;
11876}
11877
11879 const FunctionDecl *FD) {
11880 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11881 /*InOverloadResolution=*/true,
11882 /*Loc=*/SourceLocation());
11883}
11884
11886 bool Complain,
11887 SourceLocation Loc) {
11888 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11889 /*InOverloadResolution=*/false,
11890 Loc);
11891}
11892
11893// Don't print candidates other than the one that matches the calling
11894// convention of the call operator, since that is guaranteed to exist.
11896 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11897
11898 if (!ConvD)
11899 return false;
11900 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11901 if (!RD->isLambda())
11902 return false;
11903
11904 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11905 CallingConv CallOpCC =
11906 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11907 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11908 CallingConv ConvToCC =
11909 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11910
11911 return ConvToCC != CallOpCC;
11912}
11913
11914// Notes the location of an overload candidate.
11916 OverloadCandidateRewriteKind RewriteKind,
11917 QualType DestType, bool TakingAddress) {
11918 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11919 return;
11920 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11921 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11922 return;
11923 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11924 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11925 return;
11927 return;
11928
11929 std::string FnDesc;
11930 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11931 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11932 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11933 << (unsigned)KSPair.first << (unsigned)KSPair.second
11934 << Fn << FnDesc;
11935
11936 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11937 Diag(Fn->getLocation(), PD);
11938 MaybeEmitInheritedConstructorNote(*this, Found);
11939}
11940
11941static void
11943 // Perhaps the ambiguity was caused by two atomic constraints that are
11944 // 'identical' but not equivalent:
11945 //
11946 // void foo() requires (sizeof(T) > 4) { } // #1
11947 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11948 //
11949 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11950 // #2 to subsume #1, but these constraint are not considered equivalent
11951 // according to the subsumption rules because they are not the same
11952 // source-level construct. This behavior is quite confusing and we should try
11953 // to help the user figure out what happened.
11954
11955 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11956 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11957 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11958 if (!I->Function)
11959 continue;
11961 if (auto *Template = I->Function->getPrimaryTemplate())
11962 Template->getAssociatedConstraints(AC);
11963 else
11964 I->Function->getAssociatedConstraints(AC);
11965 if (AC.empty())
11966 continue;
11967 if (FirstCand == nullptr) {
11968 FirstCand = I->Function;
11969 FirstAC = AC;
11970 } else if (SecondCand == nullptr) {
11971 SecondCand = I->Function;
11972 SecondAC = AC;
11973 } else {
11974 // We have more than one pair of constrained functions - this check is
11975 // expensive and we'd rather not try to diagnose it.
11976 return;
11977 }
11978 }
11979 if (!SecondCand)
11980 return;
11981 // The diagnostic can only happen if there are associated constraints on
11982 // both sides (there needs to be some identical atomic constraint).
11983 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11984 SecondCand, SecondAC))
11985 // Just show the user one diagnostic, they'll probably figure it out
11986 // from here.
11987 return;
11988}
11989
11990// Notes the location of all overload candidates designated through
11991// OverloadedExpr
11992void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11993 bool TakingAddress) {
11994 assert(OverloadedExpr->getType() == Context.OverloadTy);
11995
11996 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11997 OverloadExpr *OvlExpr = Ovl.Expression;
11998
11999 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12000 IEnd = OvlExpr->decls_end();
12001 I != IEnd; ++I) {
12002 if (FunctionTemplateDecl *FunTmpl =
12003 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
12004 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
12005 TakingAddress);
12006 } else if (FunctionDecl *Fun
12007 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
12008 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
12009 }
12010 }
12011}
12012
12013/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12014/// "lead" diagnostic; it will be given two arguments, the source and
12015/// target types of the conversion.
12017 Sema &S,
12018 SourceLocation CaretLoc,
12019 const PartialDiagnostic &PDiag) const {
12020 S.Diag(CaretLoc, PDiag)
12021 << Ambiguous.getFromType() << Ambiguous.getToType();
12022 unsigned CandsShown = 0;
12024 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12025 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12026 break;
12027 ++CandsShown;
12028 S.NoteOverloadCandidate(I->first, I->second);
12029 }
12030 S.Diags.overloadCandidatesShown(CandsShown);
12031 if (I != E)
12032 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12033}
12034
12036 unsigned I, bool TakingCandidateAddress) {
12037 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12038 assert(Conv.isBad());
12039 assert(Cand->Function && "for now, candidate must be a function");
12040 FunctionDecl *Fn = Cand->Function;
12041
12042 // There's a conversion slot for the object argument if this is a
12043 // non-constructor method. Note that 'I' corresponds the
12044 // conversion-slot index.
12045 bool isObjectArgument = false;
12046 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12048 if (I == 0)
12049 isObjectArgument = true;
12050 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12051 I--;
12052 }
12053
12054 std::string FnDesc;
12055 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12056 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12057 FnDesc);
12058
12059 Expr *FromExpr = Conv.Bad.FromExpr;
12060 QualType FromTy = Conv.Bad.getFromType();
12061 QualType ToTy = Conv.Bad.getToType();
12062 SourceRange ToParamRange;
12063
12064 // FIXME: In presence of parameter packs we can't determine parameter range
12065 // reliably, as we don't have access to instantiation.
12066 bool HasParamPack =
12067 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12068 return Parm->isParameterPack();
12069 });
12070 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12071 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12072
12073 if (FromTy == S.Context.OverloadTy) {
12074 assert(FromExpr && "overload set argument came from implicit argument?");
12075 Expr *E = FromExpr->IgnoreParens();
12076 if (isa<UnaryOperator>(E))
12077 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12078 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12079
12080 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12081 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12082 << ToParamRange << ToTy << Name << I + 1;
12083 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12084 return;
12085 }
12086
12087 // Do some hand-waving analysis to see if the non-viability is due
12088 // to a qualifier mismatch.
12089 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12090 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12091 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12092 CToTy = RT->getPointeeType();
12093 else {
12094 // TODO: detect and diagnose the full richness of const mismatches.
12095 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12096 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12097 CFromTy = FromPT->getPointeeType();
12098 CToTy = ToPT->getPointeeType();
12099 }
12100 }
12101
12102 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12103 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12104 Qualifiers FromQs = CFromTy.getQualifiers();
12105 Qualifiers ToQs = CToTy.getQualifiers();
12106
12107 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12108 if (isObjectArgument)
12109 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12110 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12111 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12112 else
12113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12114 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12115 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12116 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12117 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12118 return;
12119 }
12120
12121 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12123 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12124 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12125 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12126 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12127 return;
12128 }
12129
12130 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12131 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12132 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12133 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12134 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12135 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12136 return;
12137 }
12138
12139 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12140 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12141 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12142 << FromTy << !!FromQs.getPointerAuth()
12143 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12144 << ToQs.getPointerAuth().getAsString() << I + 1
12145 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12146 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12147 return;
12148 }
12149
12150 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12151 assert(CVR && "expected qualifiers mismatch");
12152
12153 if (isObjectArgument) {
12154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12155 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12156 << FromTy << (CVR - 1);
12157 } else {
12158 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12159 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12160 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12161 }
12162 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12163 return;
12164 }
12165
12168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12169 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12170 << (unsigned)isObjectArgument << I + 1
12172 << ToParamRange;
12173 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12174 return;
12175 }
12176
12177 // Special diagnostic for failure to convert an initializer list, since
12178 // telling the user that it has type void is not useful.
12179 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12180 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12181 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12182 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12185 ? 2
12186 : 0);
12187 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12188 return;
12189 }
12190
12191 // Diagnose references or pointers to incomplete types differently,
12192 // since it's far from impossible that the incompleteness triggered
12193 // the failure.
12194 QualType TempFromTy = FromTy.getNonReferenceType();
12195 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12196 TempFromTy = PTy->getPointeeType();
12197 if (TempFromTy->isIncompleteType()) {
12198 // Emit the generic diagnostic and, optionally, add the hints to it.
12199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12200 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12201 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12202 << (unsigned)(Cand->Fix.Kind);
12203
12204 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12205 return;
12206 }
12207
12208 // Diagnose base -> derived pointer conversions.
12209 unsigned BaseToDerivedConversion = 0;
12210 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12211 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12212 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12213 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12214 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12215 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12216 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12217 FromPtrTy->getPointeeType()))
12218 BaseToDerivedConversion = 1;
12219 }
12220 } else if (const ObjCObjectPointerType *FromPtrTy
12221 = FromTy->getAs<ObjCObjectPointerType>()) {
12222 if (const ObjCObjectPointerType *ToPtrTy
12223 = ToTy->getAs<ObjCObjectPointerType>())
12224 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12225 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12226 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12227 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12228 FromIface->isSuperClassOf(ToIface))
12229 BaseToDerivedConversion = 2;
12230 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12231 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12232 S.getASTContext()) &&
12233 !FromTy->isIncompleteType() &&
12234 !ToRefTy->getPointeeType()->isIncompleteType() &&
12235 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12236 BaseToDerivedConversion = 3;
12237 }
12238 }
12239
12240 if (BaseToDerivedConversion) {
12241 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12242 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12243 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12244 << I + 1;
12245 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12246 return;
12247 }
12248
12249 if (isa<ObjCObjectPointerType>(CFromTy) &&
12250 isa<PointerType>(CToTy)) {
12251 Qualifiers FromQs = CFromTy.getQualifiers();
12252 Qualifiers ToQs = CToTy.getQualifiers();
12253 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12254 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12255 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12256 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12257 << I + 1;
12258 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12259 return;
12260 }
12261 }
12262
12263 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12264 return;
12265
12266 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12267 // although this is almost always an error and we advise against it.
12268 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12269 ToTy == S.Context.getLogicalOperationType()) {
12270 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12271 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12272 << Conv.Bad.FromExpr << ToTy;
12273 return;
12274 }
12275
12276 // Emit the generic diagnostic and, optionally, add the hints to it.
12277 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12278 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12279 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12280 << (unsigned)(Cand->Fix.Kind);
12281
12282 // Check that location of Fn is not in system header.
12283 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12284 // If we can fix the conversion, suggest the FixIts.
12285 for (const FixItHint &HI : Cand->Fix.Hints)
12286 FDiag << HI;
12287 }
12288
12289 S.Diag(Fn->getLocation(), FDiag);
12290
12291 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12292}
12293
12294/// Additional arity mismatch diagnosis specific to a function overload
12295/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12296/// over a candidate in any candidate set.
12298 unsigned NumArgs, bool IsAddressOf = false) {
12299 assert(Cand->Function && "Candidate is required to be a function.");
12300 FunctionDecl *Fn = Cand->Function;
12301 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12302 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12303
12304 // With invalid overloaded operators, it's possible that we think we
12305 // have an arity mismatch when in fact it looks like we have the
12306 // right number of arguments, because only overloaded operators have
12307 // the weird behavior of overloading member and non-member functions.
12308 // Just don't report anything.
12309 if (Fn->isInvalidDecl() &&
12310 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12311 return true;
12312
12313 if (NumArgs < MinParams) {
12314 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12316 Cand->DeductionFailure.getResult() ==
12318 } else {
12319 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12321 Cand->DeductionFailure.getResult() ==
12323 }
12324
12325 return false;
12326}
12327
12328/// General arity mismatch diagnosis over a candidate in a candidate set.
12330 unsigned NumFormalArgs,
12331 bool IsAddressOf = false) {
12332 assert(isa<FunctionDecl>(D) &&
12333 "The templated declaration should at least be a function"
12334 " when diagnosing bad template argument deduction due to too many"
12335 " or too few arguments");
12336
12338
12339 // TODO: treat calls to a missing default constructor as a special case
12340 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12341 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12342 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12343
12344 // at least / at most / exactly
12345 bool HasExplicitObjectParam =
12346 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12347
12348 unsigned ParamCount =
12349 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12350 unsigned mode, modeCount;
12351
12352 if (NumFormalArgs < MinParams) {
12353 if (MinParams != ParamCount || FnTy->isVariadic() ||
12354 FnTy->isTemplateVariadic())
12355 mode = 0; // "at least"
12356 else
12357 mode = 2; // "exactly"
12358 modeCount = MinParams;
12359 } else {
12360 if (MinParams != ParamCount)
12361 mode = 1; // "at most"
12362 else
12363 mode = 2; // "exactly"
12364 modeCount = ParamCount;
12365 }
12366
12367 std::string Description;
12368 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12369 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12370
12371 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12372 if (modeCount == 1 && !IsAddressOf &&
12373 FirstNonObjectParamIdx < Fn->getNumParams() &&
12374 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12375 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12376 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12377 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12378 << NumFormalArgs << HasExplicitObjectParam
12379 << Fn->getParametersSourceRange();
12380 else
12381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12382 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12383 << Description << mode << modeCount << NumFormalArgs
12384 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12385
12386 MaybeEmitInheritedConstructorNote(S, Found);
12387}
12388
12389/// Arity mismatch diagnosis specific to a function overload candidate.
12391 unsigned NumFormalArgs) {
12392 assert(Cand->Function && "Candidate must be a function");
12393 FunctionDecl *Fn = Cand->Function;
12394 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12395 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12396 Cand->TookAddressOfOverload);
12397}
12398
12400 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12401 return TD;
12402 llvm_unreachable("Unsupported: Getting the described template declaration"
12403 " for bad deduction diagnosis");
12404}
12405
12406/// Diagnose a failed template-argument deduction.
12407static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12408 DeductionFailureInfo &DeductionFailure,
12409 unsigned NumArgs,
12410 bool TakingCandidateAddress) {
12411 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12412 NamedDecl *ParamD;
12413 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12414 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12415 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12416 switch (DeductionFailure.getResult()) {
12418 llvm_unreachable(
12419 "TemplateDeductionResult::Success while diagnosing bad deduction");
12421 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12422 "while diagnosing bad deduction");
12425 return;
12426
12428 assert(ParamD && "no parameter found for incomplete deduction result");
12429 S.Diag(Templated->getLocation(),
12430 diag::note_ovl_candidate_incomplete_deduction)
12431 << ParamD->getDeclName();
12432 MaybeEmitInheritedConstructorNote(S, Found);
12433 return;
12434 }
12435
12437 assert(ParamD && "no parameter found for incomplete deduction result");
12438 S.Diag(Templated->getLocation(),
12439 diag::note_ovl_candidate_incomplete_deduction_pack)
12440 << ParamD->getDeclName()
12441 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12442 << *DeductionFailure.getFirstArg();
12443 MaybeEmitInheritedConstructorNote(S, Found);
12444 return;
12445 }
12446
12448 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12450
12451 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12452
12453 // Param will have been canonicalized, but it should just be a
12454 // qualified version of ParamD, so move the qualifiers to that.
12456 Qs.strip(Param);
12457 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12458 assert(S.Context.hasSameType(Param, NonCanonParam));
12459
12460 // Arg has also been canonicalized, but there's nothing we can do
12461 // about that. It also doesn't matter as much, because it won't
12462 // have any template parameters in it (because deduction isn't
12463 // done on dependent types).
12464 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12465
12466 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12467 << ParamD->getDeclName() << Arg << NonCanonParam;
12468 MaybeEmitInheritedConstructorNote(S, Found);
12469 return;
12470 }
12471
12473 assert(ParamD && "no parameter found for inconsistent deduction result");
12474 int which = 0;
12475 if (isa<TemplateTypeParmDecl>(ParamD))
12476 which = 0;
12477 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12478 // Deduction might have failed because we deduced arguments of two
12479 // different types for a non-type template parameter.
12480 // FIXME: Use a different TDK value for this.
12481 QualType T1 =
12482 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12483 QualType T2 =
12484 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12485 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12486 S.Diag(Templated->getLocation(),
12487 diag::note_ovl_candidate_inconsistent_deduction_types)
12488 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12489 << *DeductionFailure.getSecondArg() << T2;
12490 MaybeEmitInheritedConstructorNote(S, Found);
12491 return;
12492 }
12493
12494 which = 1;
12495 } else {
12496 which = 2;
12497 }
12498
12499 // Tweak the diagnostic if the problem is that we deduced packs of
12500 // different arities. We'll print the actual packs anyway in case that
12501 // includes additional useful information.
12502 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12503 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12504 DeductionFailure.getFirstArg()->pack_size() !=
12505 DeductionFailure.getSecondArg()->pack_size()) {
12506 which = 3;
12507 }
12508
12509 S.Diag(Templated->getLocation(),
12510 diag::note_ovl_candidate_inconsistent_deduction)
12511 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12512 << *DeductionFailure.getSecondArg();
12513 MaybeEmitInheritedConstructorNote(S, Found);
12514 return;
12515 }
12516
12518 assert(ParamD && "no parameter found for invalid explicit arguments");
12519
12520 auto Diag = S.Diag(Templated->getLocation(),
12521 diag::note_ovl_candidate_explicit_arg_mismatch);
12522 if (ParamD->getDeclName())
12523 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12524 else
12525 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12526 << (getDepthAndIndex(ParamD).second + 1);
12527 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12528 SmallString<128> DiagContent;
12529 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12530 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12531 } else {
12532 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12533 }
12534
12535 MaybeEmitInheritedConstructorNote(S, Found);
12536 return;
12537 }
12539 // Format the template argument list into the argument string.
12540 SmallString<128> TemplateArgString;
12541 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12542 TemplateArgString = " ";
12543 TemplateArgString += S.getTemplateArgumentBindingsText(
12544 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12545 if (TemplateArgString.size() == 1)
12546 TemplateArgString.clear();
12547 S.Diag(Templated->getLocation(),
12548 diag::note_ovl_candidate_unsatisfied_constraints)
12549 << TemplateArgString;
12550
12552 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12553 return;
12554 }
12557 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12558 return;
12559
12561 S.Diag(Templated->getLocation(),
12562 diag::note_ovl_candidate_instantiation_depth);
12563 MaybeEmitInheritedConstructorNote(S, Found);
12564 return;
12565
12567 // Format the template argument list into the argument string.
12568 SmallString<128> TemplateArgString;
12569 if (TemplateArgumentList *Args =
12570 DeductionFailure.getTemplateArgumentList()) {
12571 TemplateArgString = " ";
12572 TemplateArgString += S.getTemplateArgumentBindingsText(
12573 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12574 if (TemplateArgString.size() == 1)
12575 TemplateArgString.clear();
12576 }
12577
12578 // If this candidate was disabled by enable_if, say so.
12579 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12580 if (PDiag && PDiag->second.getDiagID() ==
12581 diag::err_typename_nested_not_found_enable_if) {
12582 // FIXME: Use the source range of the condition, and the fully-qualified
12583 // name of the enable_if template. These are both present in PDiag.
12584 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12585 << "'enable_if'" << TemplateArgString;
12586 return;
12587 }
12588
12589 // We found a specific requirement that disabled the enable_if.
12590 if (PDiag && PDiag->second.getDiagID() ==
12591 diag::err_typename_nested_not_found_requirement) {
12592 S.Diag(Templated->getLocation(),
12593 diag::note_ovl_candidate_disabled_by_requirement)
12594 << PDiag->second.getStringArg(0) << TemplateArgString;
12595 return;
12596 }
12597
12598 // Format the SFINAE diagnostic into the argument string.
12599 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12600 // formatted message in another diagnostic.
12601 SmallString<128> SFINAEArgString;
12602 SourceRange R;
12603 if (PDiag) {
12604 SFINAEArgString = ": ";
12605 R = SourceRange(PDiag->first, PDiag->first);
12606 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12607 }
12608
12609 S.Diag(Templated->getLocation(),
12610 diag::note_ovl_candidate_substitution_failure)
12611 << TemplateArgString << SFINAEArgString << R;
12612 MaybeEmitInheritedConstructorNote(S, Found);
12613 return;
12614 }
12615
12618 // Format the template argument list into the argument string.
12619 SmallString<128> TemplateArgString;
12620 if (TemplateArgumentList *Args =
12621 DeductionFailure.getTemplateArgumentList()) {
12622 TemplateArgString = " ";
12623 TemplateArgString += S.getTemplateArgumentBindingsText(
12624 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12625 if (TemplateArgString.size() == 1)
12626 TemplateArgString.clear();
12627 }
12628
12629 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12630 << (*DeductionFailure.getCallArgIndex() + 1)
12631 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12632 << TemplateArgString
12633 << (DeductionFailure.getResult() ==
12635 break;
12636 }
12637
12639 // FIXME: Provide a source location to indicate what we couldn't match.
12640 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12641 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12642 if (FirstTA.getKind() == TemplateArgument::Template &&
12643 SecondTA.getKind() == TemplateArgument::Template) {
12644 TemplateName FirstTN = FirstTA.getAsTemplate();
12645 TemplateName SecondTN = SecondTA.getAsTemplate();
12646 if (FirstTN.getKind() == TemplateName::Template &&
12647 SecondTN.getKind() == TemplateName::Template) {
12648 if (FirstTN.getAsTemplateDecl()->getName() ==
12649 SecondTN.getAsTemplateDecl()->getName()) {
12650 // FIXME: This fixes a bad diagnostic where both templates are named
12651 // the same. This particular case is a bit difficult since:
12652 // 1) It is passed as a string to the diagnostic printer.
12653 // 2) The diagnostic printer only attempts to find a better
12654 // name for types, not decls.
12655 // Ideally, this should folded into the diagnostic printer.
12656 S.Diag(Templated->getLocation(),
12657 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12658 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12659 return;
12660 }
12661 }
12662 }
12663
12664 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12666 return;
12667
12668 // FIXME: For generic lambda parameters, check if the function is a lambda
12669 // call operator, and if so, emit a prettier and more informative
12670 // diagnostic that mentions 'auto' and lambda in addition to
12671 // (or instead of?) the canonical template type parameters.
12672 S.Diag(Templated->getLocation(),
12673 diag::note_ovl_candidate_non_deduced_mismatch)
12674 << FirstTA << SecondTA;
12675 return;
12676 }
12677 // TODO: diagnose these individually, then kill off
12678 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12680 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12681 MaybeEmitInheritedConstructorNote(S, Found);
12682 return;
12684 S.Diag(Templated->getLocation(),
12685 diag::note_cuda_ovl_candidate_target_mismatch);
12686 return;
12687 }
12688}
12689
12690/// Diagnose a failed template-argument deduction, for function calls.
12692 unsigned NumArgs,
12693 bool TakingCandidateAddress) {
12694 assert(Cand->Function && "Candidate must be a function");
12695 FunctionDecl *Fn = Cand->Function;
12699 if (CheckArityMismatch(S, Cand, NumArgs))
12700 return;
12701 }
12702 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12703 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12704}
12705
12706/// CUDA: diagnose an invalid call across targets.
12708 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12709 assert(Cand->Function && "Candidate must be a Function.");
12710 FunctionDecl *Callee = Cand->Function;
12711
12712 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12713 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12714
12715 std::string FnDesc;
12716 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12717 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12718 Cand->getRewriteKind(), FnDesc);
12719
12720 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12721 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12722 << FnDesc /* Ignored */
12723 << CalleeTarget << CallerTarget;
12724
12725 // This could be an implicit constructor for which we could not infer the
12726 // target due to a collsion. Diagnose that case.
12727 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12728 if (Meth != nullptr && Meth->isImplicit()) {
12729 CXXRecordDecl *ParentClass = Meth->getParent();
12731
12732 switch (FnKindPair.first) {
12733 default:
12734 return;
12735 case oc_implicit_default_constructor:
12737 break;
12738 case oc_implicit_copy_constructor:
12740 break;
12741 case oc_implicit_move_constructor:
12743 break;
12744 case oc_implicit_copy_assignment:
12746 break;
12747 case oc_implicit_move_assignment:
12749 break;
12750 };
12751
12752 bool ConstRHS = false;
12753 if (Meth->getNumParams()) {
12754 if (const ReferenceType *RT =
12755 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12756 ConstRHS = RT->getPointeeType().isConstQualified();
12757 }
12758 }
12759
12760 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12761 /* ConstRHS */ ConstRHS,
12762 /* Diagnose */ true);
12763 }
12764}
12765
12767 assert(Cand->Function && "Candidate must be a function");
12768 FunctionDecl *Callee = Cand->Function;
12769 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12770
12771 S.Diag(Callee->getLocation(),
12772 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12773 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12774}
12775
12777 assert(Cand->Function && "Candidate must be a function");
12778 FunctionDecl *Fn = Cand->Function;
12780 assert(ES.isExplicit() && "not an explicit candidate");
12781
12782 unsigned Kind;
12783 switch (Fn->getDeclKind()) {
12784 case Decl::Kind::CXXConstructor:
12785 Kind = 0;
12786 break;
12787 case Decl::Kind::CXXConversion:
12788 Kind = 1;
12789 break;
12790 case Decl::Kind::CXXDeductionGuide:
12791 Kind = Fn->isImplicit() ? 0 : 2;
12792 break;
12793 default:
12794 llvm_unreachable("invalid Decl");
12795 }
12796
12797 // Note the location of the first (in-class) declaration; a redeclaration
12798 // (particularly an out-of-class definition) will typically lack the
12799 // 'explicit' specifier.
12800 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12801 FunctionDecl *First = Fn->getFirstDecl();
12802 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12803 First = Pattern->getFirstDecl();
12804
12805 S.Diag(First->getLocation(),
12806 diag::note_ovl_candidate_explicit)
12807 << Kind << (ES.getExpr() ? 1 : 0)
12808 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12809}
12810
12812 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12813 if (!DG)
12814 return;
12815 TemplateDecl *OriginTemplate =
12817 // We want to always print synthesized deduction guides for type aliases.
12818 // They would retain the explicit bit of the corresponding constructor.
12819 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12820 return;
12821 std::string FunctionProto;
12822 llvm::raw_string_ostream OS(FunctionProto);
12823 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12824 if (!Template) {
12825 // This also could be an instantiation. Find out the primary template.
12826 FunctionDecl *Pattern =
12827 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12828 if (!Pattern) {
12829 // The implicit deduction guide is built on an explicit non-template
12830 // deduction guide. Currently, this might be the case only for type
12831 // aliases.
12832 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12833 // gets merged.
12834 assert(OriginTemplate->isTypeAlias() &&
12835 "Non-template implicit deduction guides are only possible for "
12836 "type aliases");
12837 DG->print(OS);
12838 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12839 << FunctionProto;
12840 return;
12841 }
12843 assert(Template && "Cannot find the associated function template of "
12844 "CXXDeductionGuideDecl?");
12845 }
12846 Template->print(OS);
12847 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12848 << FunctionProto;
12849}
12850
12851/// Generates a 'note' diagnostic for an overload candidate. We've
12852/// already generated a primary error at the call site.
12853///
12854/// It really does need to be a single diagnostic with its caret
12855/// pointed at the candidate declaration. Yes, this creates some
12856/// major challenges of technical writing. Yes, this makes pointing
12857/// out problems with specific arguments quite awkward. It's still
12858/// better than generating twenty screens of text for every failed
12859/// overload.
12860///
12861/// It would be great to be able to express per-candidate problems
12862/// more richly for those diagnostic clients that cared, but we'd
12863/// still have to be just as careful with the default diagnostics.
12864/// \param CtorDestAS Addr space of object being constructed (for ctor
12865/// candidates only).
12867 unsigned NumArgs,
12868 bool TakingCandidateAddress,
12869 LangAS CtorDestAS = LangAS::Default) {
12870 assert(Cand->Function && "Candidate must be a function");
12871 FunctionDecl *Fn = Cand->Function;
12873 return;
12874
12875 // There is no physical candidate declaration to point to for OpenCL builtins.
12876 // Except for failed conversions, the notes are identical for each candidate,
12877 // so do not generate such notes.
12878 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12880 return;
12881
12882 // Skip implicit member functions when trying to resolve
12883 // the address of a an overload set for a function pointer.
12884 if (Cand->TookAddressOfOverload &&
12885 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12886 return;
12887
12888 // Note deleted candidates, but only if they're viable.
12889 if (Cand->Viable) {
12890 if (Fn->isDeleted()) {
12891 std::string FnDesc;
12892 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12893 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12894 Cand->getRewriteKind(), FnDesc);
12895
12896 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12897 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12898 << (Fn->isDeleted()
12899 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12900 : 0);
12901 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12902 return;
12903 }
12904
12905 // We don't really have anything else to say about viable candidates.
12906 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12907 return;
12908 }
12909
12910 // If this is a synthesized deduction guide we're deducing against, add a note
12911 // for it. These deduction guides are not explicitly spelled in the source
12912 // code, so simply printing a deduction failure note mentioning synthesized
12913 // template parameters or pointing to the header of the surrounding RecordDecl
12914 // would be confusing.
12915 //
12916 // We prefer adding such notes at the end of the deduction failure because
12917 // duplicate code snippets appearing in the diagnostic would likely become
12918 // noisy.
12919 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12920
12921 switch (Cand->FailureKind) {
12924 return DiagnoseArityMismatch(S, Cand, NumArgs);
12925
12927 return DiagnoseBadDeduction(S, Cand, NumArgs,
12928 TakingCandidateAddress);
12929
12931 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12932 << (Fn->getPrimaryTemplate() ? 1 : 0);
12933 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12934 return;
12935 }
12936
12938 Qualifiers QualsForPrinting;
12939 QualsForPrinting.setAddressSpace(CtorDestAS);
12940 S.Diag(Fn->getLocation(),
12941 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12942 << QualsForPrinting;
12943 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12944 return;
12945 }
12946
12950 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12951
12953 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12954 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12955 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12956 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12957
12958 // FIXME: this currently happens when we're called from SemaInit
12959 // when user-conversion overload fails. Figure out how to handle
12960 // those conditions and diagnose them well.
12961 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12962 }
12963
12965 return DiagnoseBadTarget(S, Cand);
12966
12967 case ovl_fail_enable_if:
12968 return DiagnoseFailedEnableIfAttr(S, Cand);
12969
12970 case ovl_fail_explicit:
12971 return DiagnoseFailedExplicitSpec(S, Cand);
12972
12974 // It's generally not interesting to note copy/move constructors here.
12975 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12976 return;
12977 S.Diag(Fn->getLocation(),
12978 diag::note_ovl_candidate_inherited_constructor_slice)
12979 << (Fn->getPrimaryTemplate() ? 1 : 0)
12980 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12981 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12982 return;
12983
12985 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12986 (void)Available;
12987 assert(!Available);
12988 break;
12989 }
12991 // Do nothing, these should simply be ignored.
12992 break;
12993
12995 std::string FnDesc;
12996 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12997 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12998 Cand->getRewriteKind(), FnDesc);
12999
13000 S.Diag(Fn->getLocation(),
13001 diag::note_ovl_candidate_constraints_not_satisfied)
13002 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13003 << FnDesc /* Ignored */;
13004 ConstraintSatisfaction Satisfaction;
13005 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
13006 /*ForOverloadResolution=*/true))
13007 break;
13008 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13009 }
13010 }
13011}
13012
13015 return;
13016
13017 // Desugar the type of the surrogate down to a function type,
13018 // retaining as many typedefs as possible while still showing
13019 // the function type (and, therefore, its parameter types).
13020 QualType FnType = Cand->Surrogate->getConversionType();
13021 bool isLValueReference = false;
13022 bool isRValueReference = false;
13023 bool isPointer = false;
13024 if (const LValueReferenceType *FnTypeRef =
13025 FnType->getAs<LValueReferenceType>()) {
13026 FnType = FnTypeRef->getPointeeType();
13027 isLValueReference = true;
13028 } else if (const RValueReferenceType *FnTypeRef =
13029 FnType->getAs<RValueReferenceType>()) {
13030 FnType = FnTypeRef->getPointeeType();
13031 isRValueReference = true;
13032 }
13033 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13034 FnType = FnTypePtr->getPointeeType();
13035 isPointer = true;
13036 }
13037 // Desugar down to a function type.
13038 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13039 // Reconstruct the pointer/reference as appropriate.
13040 if (isPointer) FnType = S.Context.getPointerType(FnType);
13041 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13042 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13043
13044 if (!Cand->Viable &&
13046 S.Diag(Cand->Surrogate->getLocation(),
13047 diag::note_ovl_surrogate_constraints_not_satisfied)
13048 << Cand->Surrogate;
13049 ConstraintSatisfaction Satisfaction;
13050 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13051 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13052 } else {
13053 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13054 << FnType;
13055 }
13056}
13057
13058static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13059 SourceLocation OpLoc,
13060 OverloadCandidate *Cand) {
13061 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13062 std::string TypeStr("operator");
13063 TypeStr += Opc;
13064 TypeStr += "(";
13065 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13066 if (Cand->Conversions.size() == 1) {
13067 TypeStr += ")";
13068 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13069 } else {
13070 TypeStr += ", ";
13071 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13072 TypeStr += ")";
13073 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13074 }
13075}
13076
13078 OverloadCandidate *Cand) {
13079 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13080 if (ICS.isBad()) break; // all meaningless after first invalid
13081 if (!ICS.isAmbiguous()) continue;
13082
13084 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13085 }
13086}
13087
13089 if (Cand->Function)
13090 return Cand->Function->getLocation();
13091 if (Cand->IsSurrogate)
13092 return Cand->Surrogate->getLocation();
13093 return SourceLocation();
13094}
13095
13096static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13097 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13101 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13102
13106 return 1;
13107
13110 return 2;
13111
13119 return 3;
13120
13122 return 4;
13123
13125 return 5;
13126
13129 return 6;
13130 }
13131 llvm_unreachable("Unhandled deduction result");
13132}
13133
13134namespace {
13135
13136struct CompareOverloadCandidatesForDisplay {
13137 Sema &S;
13138 SourceLocation Loc;
13139 size_t NumArgs;
13141
13142 CompareOverloadCandidatesForDisplay(
13143 Sema &S, SourceLocation Loc, size_t NArgs,
13145 : S(S), NumArgs(NArgs), CSK(CSK) {}
13146
13147 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13148 // If there are too many or too few arguments, that's the high-order bit we
13149 // want to sort by, even if the immediate failure kind was something else.
13150 if (C->FailureKind == ovl_fail_too_many_arguments ||
13151 C->FailureKind == ovl_fail_too_few_arguments)
13152 return static_cast<OverloadFailureKind>(C->FailureKind);
13153
13154 if (C->Function) {
13155 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13157 if (NumArgs < C->Function->getMinRequiredArguments())
13159 }
13160
13161 return static_cast<OverloadFailureKind>(C->FailureKind);
13162 }
13163
13164 bool operator()(const OverloadCandidate *L,
13165 const OverloadCandidate *R) {
13166 // Fast-path this check.
13167 if (L == R) return false;
13168
13169 // Order first by viability.
13170 if (L->Viable) {
13171 if (!R->Viable) return true;
13172
13173 if (int Ord = CompareConversions(*L, *R))
13174 return Ord < 0;
13175 // Use other tie breakers.
13176 } else if (R->Viable)
13177 return false;
13178
13179 assert(L->Viable == R->Viable);
13180
13181 // Criteria by which we can sort non-viable candidates:
13182 if (!L->Viable) {
13183 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13184 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13185
13186 // 1. Arity mismatches come after other candidates.
13187 if (LFailureKind == ovl_fail_too_many_arguments ||
13188 LFailureKind == ovl_fail_too_few_arguments) {
13189 if (RFailureKind == ovl_fail_too_many_arguments ||
13190 RFailureKind == ovl_fail_too_few_arguments) {
13191 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13192 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13193 if (LDist == RDist) {
13194 if (LFailureKind == RFailureKind)
13195 // Sort non-surrogates before surrogates.
13196 return !L->IsSurrogate && R->IsSurrogate;
13197 // Sort candidates requiring fewer parameters than there were
13198 // arguments given after candidates requiring more parameters
13199 // than there were arguments given.
13200 return LFailureKind == ovl_fail_too_many_arguments;
13201 }
13202 return LDist < RDist;
13203 }
13204 return false;
13205 }
13206 if (RFailureKind == ovl_fail_too_many_arguments ||
13207 RFailureKind == ovl_fail_too_few_arguments)
13208 return true;
13209
13210 // 2. Bad conversions come first and are ordered by the number
13211 // of bad conversions and quality of good conversions.
13212 if (LFailureKind == ovl_fail_bad_conversion) {
13213 if (RFailureKind != ovl_fail_bad_conversion)
13214 return true;
13215
13216 // The conversion that can be fixed with a smaller number of changes,
13217 // comes first.
13218 unsigned numLFixes = L->Fix.NumConversionsFixed;
13219 unsigned numRFixes = R->Fix.NumConversionsFixed;
13220 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13221 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13222 if (numLFixes != numRFixes) {
13223 return numLFixes < numRFixes;
13224 }
13225
13226 // If there's any ordering between the defined conversions...
13227 if (int Ord = CompareConversions(*L, *R))
13228 return Ord < 0;
13229 } else if (RFailureKind == ovl_fail_bad_conversion)
13230 return false;
13231
13232 if (LFailureKind == ovl_fail_bad_deduction) {
13233 if (RFailureKind != ovl_fail_bad_deduction)
13234 return true;
13235
13236 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13237 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13238 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13239 if (LRank != RRank)
13240 return LRank < RRank;
13241 }
13242 } else if (RFailureKind == ovl_fail_bad_deduction)
13243 return false;
13244
13245 // TODO: others?
13246 }
13247
13248 // Sort everything else by location.
13249 SourceLocation LLoc = GetLocationForCandidate(L);
13250 SourceLocation RLoc = GetLocationForCandidate(R);
13251
13252 // Put candidates without locations (e.g. builtins) at the end.
13253 if (LLoc.isValid() && RLoc.isValid())
13254 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13255 if (LLoc.isValid() && !RLoc.isValid())
13256 return true;
13257 if (RLoc.isValid() && !LLoc.isValid())
13258 return false;
13259 assert(!LLoc.isValid() && !RLoc.isValid());
13260 // For builtins and other functions without locations, fallback to the order
13261 // in which they were added into the candidate set.
13262 return L < R;
13263 }
13264
13265private:
13266 struct ConversionSignals {
13267 unsigned KindRank = 0;
13269
13270 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13271 ConversionSignals Sig;
13272 Sig.KindRank = Seq.getKindRank();
13273 if (Seq.isStandard())
13274 Sig.Rank = Seq.Standard.getRank();
13275 else if (Seq.isUserDefined())
13276 Sig.Rank = Seq.UserDefined.After.getRank();
13277 // We intend StaticObjectArgumentConversion to compare the same as
13278 // StandardConversion with ICR_ExactMatch rank.
13279 return Sig;
13280 }
13281
13282 static ConversionSignals ForObjectArgument() {
13283 // We intend StaticObjectArgumentConversion to compare the same as
13284 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13285 return {};
13286 }
13287 };
13288
13289 // Returns -1 if conversions in L are considered better.
13290 // 0 if they are considered indistinguishable.
13291 // 1 if conversions in R are better.
13292 int CompareConversions(const OverloadCandidate &L,
13293 const OverloadCandidate &R) {
13294 // We cannot use `isBetterOverloadCandidate` because it is defined
13295 // according to the C++ standard and provides a partial order, but we need
13296 // a total order as this function is used in sort.
13297 assert(L.Conversions.size() == R.Conversions.size());
13298 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13299 auto LS = L.IgnoreObjectArgument && I == 0
13300 ? ConversionSignals::ForObjectArgument()
13301 : ConversionSignals::ForSequence(L.Conversions[I]);
13302 auto RS = R.IgnoreObjectArgument
13303 ? ConversionSignals::ForObjectArgument()
13304 : ConversionSignals::ForSequence(R.Conversions[I]);
13305 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13306 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13307 ? -1
13308 : 1;
13309 }
13310 // FIXME: find a way to compare templates for being more or less
13311 // specialized that provides a strict weak ordering.
13312 return 0;
13313 }
13314};
13315}
13316
13317/// CompleteNonViableCandidate - Normally, overload resolution only
13318/// computes up to the first bad conversion. Produces the FixIt set if
13319/// possible.
13320static void
13322 ArrayRef<Expr *> Args,
13324 assert(!Cand->Viable);
13325
13326 // Don't do anything on failures other than bad conversion.
13328 return;
13329
13330 // We only want the FixIts if all the arguments can be corrected.
13331 bool Unfixable = false;
13332 // Use a implicit copy initialization to check conversion fixes.
13334
13335 // Attempt to fix the bad conversion.
13336 unsigned ConvCount = Cand->Conversions.size();
13337 for (unsigned ConvIdx =
13338 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13339 : 0);
13340 /**/; ++ConvIdx) {
13341 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13342 if (Cand->Conversions[ConvIdx].isInitialized() &&
13343 Cand->Conversions[ConvIdx].isBad()) {
13344 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13345 break;
13346 }
13347 }
13348
13349 // FIXME: this should probably be preserved from the overload
13350 // operation somehow.
13351 bool SuppressUserConversions = false;
13352
13353 unsigned ConvIdx = 0;
13354 unsigned ArgIdx = 0;
13355 ArrayRef<QualType> ParamTypes;
13356 bool Reversed = Cand->isReversed();
13357
13358 if (Cand->IsSurrogate) {
13359 QualType ConvType
13361 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13362 ConvType = ConvPtrType->getPointeeType();
13363 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13364 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13365 ConvIdx = 1;
13366 } else if (Cand->Function) {
13367 ParamTypes =
13368 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13369 if (isa<CXXMethodDecl>(Cand->Function) &&
13372 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13373 ConvIdx = 1;
13375 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13377 OO_Subscript)
13378 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13379 ArgIdx = 1;
13380 }
13381 } else {
13382 // Builtin operator.
13383 assert(ConvCount <= 3);
13384 ParamTypes = Cand->BuiltinParamTypes;
13385 }
13386
13387 // Fill in the rest of the conversions.
13388 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13389 ConvIdx != ConvCount && ArgIdx < Args.size();
13390 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13391 if (Cand->Conversions[ConvIdx].isInitialized()) {
13392 // We've already checked this conversion.
13393 } else if (ParamIdx < ParamTypes.size()) {
13394 if (ParamTypes[ParamIdx]->isDependentType())
13395 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13396 Args[ArgIdx]->getType());
13397 else {
13398 Cand->Conversions[ConvIdx] =
13399 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13400 SuppressUserConversions,
13401 /*InOverloadResolution=*/true,
13402 /*AllowObjCWritebackConversion=*/
13403 S.getLangOpts().ObjCAutoRefCount);
13404 // Store the FixIt in the candidate if it exists.
13405 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13406 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13407 }
13408 } else
13409 Cand->Conversions[ConvIdx].setEllipsis();
13410 }
13411}
13412
13415 SourceLocation OpLoc,
13416 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13417
13419
13420 // Sort the candidates by viability and position. Sorting directly would
13421 // be prohibitive, so we make a set of pointers and sort those.
13423 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13424 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13425 Cand != LastCand; ++Cand) {
13426 if (!Filter(*Cand))
13427 continue;
13428 switch (OCD) {
13429 case OCD_AllCandidates:
13430 if (!Cand->Viable) {
13431 if (!Cand->Function && !Cand->IsSurrogate) {
13432 // This a non-viable builtin candidate. We do not, in general,
13433 // want to list every possible builtin candidate.
13434 continue;
13435 }
13436 CompleteNonViableCandidate(S, Cand, Args, Kind);
13437 }
13438 break;
13439
13441 if (!Cand->Viable)
13442 continue;
13443 break;
13444
13446 if (!Cand->Best)
13447 continue;
13448 break;
13449 }
13450
13451 Cands.push_back(Cand);
13452 }
13453
13454 llvm::stable_sort(
13455 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13456
13457 return Cands;
13458}
13459
13461 SourceLocation OpLoc) {
13462 bool DeferHint = false;
13463 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13464 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13465 // host device candidates.
13466 auto WrongSidedCands =
13467 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13468 return (Cand.Viable == false &&
13470 (Cand.Function &&
13471 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13472 Cand.Function->template hasAttr<CUDADeviceAttr>());
13473 });
13474 DeferHint = !WrongSidedCands.empty();
13475 }
13476 return DeferHint;
13477}
13478
13479/// When overload resolution fails, prints diagnostic messages containing the
13480/// candidates in the candidate set.
13483 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13484 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13485
13486 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13487
13488 {
13489 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13490 S.Diag(PD.first, PD.second);
13491 }
13492
13493 // In WebAssembly we don't want to emit further diagnostics if a table is
13494 // passed as an argument to a function.
13495 bool NoteCands = true;
13496 for (const Expr *Arg : Args) {
13497 if (Arg->getType()->isWebAssemblyTableType())
13498 NoteCands = false;
13499 }
13500
13501 if (NoteCands)
13502 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13503
13504 if (OCD == OCD_AmbiguousCandidates)
13506 {Candidates.begin(), Candidates.end()});
13507}
13508
13511 StringRef Opc, SourceLocation OpLoc) {
13512 bool ReportedAmbiguousConversions = false;
13513
13514 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13515 unsigned CandsShown = 0;
13516 auto I = Cands.begin(), E = Cands.end();
13517 for (; I != E; ++I) {
13518 OverloadCandidate *Cand = *I;
13519
13520 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13521 ShowOverloads == Ovl_Best) {
13522 break;
13523 }
13524 ++CandsShown;
13525
13526 if (Cand->Function)
13527 NoteFunctionCandidate(S, Cand, Args.size(),
13528 Kind == CSK_AddressOfOverloadSet, DestAS);
13529 else if (Cand->IsSurrogate)
13530 NoteSurrogateCandidate(S, Cand);
13531 else {
13532 assert(Cand->Viable &&
13533 "Non-viable built-in candidates are not added to Cands.");
13534 // Generally we only see ambiguities including viable builtin
13535 // operators if overload resolution got screwed up by an
13536 // ambiguous user-defined conversion.
13537 //
13538 // FIXME: It's quite possible for different conversions to see
13539 // different ambiguities, though.
13540 if (!ReportedAmbiguousConversions) {
13541 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13542 ReportedAmbiguousConversions = true;
13543 }
13544
13545 // If this is a viable builtin, print it.
13546 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13547 }
13548 }
13549
13550 // Inform S.Diags that we've shown an overload set with N elements. This may
13551 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13552 S.Diags.overloadCandidatesShown(CandsShown);
13553
13554 if (I != E) {
13555 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13556 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13557 }
13558}
13559
13561 const Sema &S) const {
13562 if (S.getLangOpts().CUDA) {
13563 auto *Caller = S.getCurFunctionDecl(true);
13564 // Overloading based on __host__ and __device__ attributes takes
13565 // higher priority, HD functions may favor template candidates even when a
13566 // non-template candidate would be a perfect match.
13567 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13568 Caller->hasAttr<CUDADeviceAttr>())
13569 return false;
13570 }
13571
13572 return
13573 // For user defined conversion we need to check against different
13574 // combination of CV qualifiers and look at any explicit specifier, so
13575 // always deduce template candidates.
13577 // When doing code completion, we want to see all the
13578 // viable candidates.
13579 && Kind != CSK_CodeCompletion;
13580}
13581
13582static SourceLocation
13584 return Cand->Specialization ? Cand->Specialization->getLocation()
13585 : SourceLocation();
13586}
13587
13588namespace {
13589struct CompareTemplateSpecCandidatesForDisplay {
13590 Sema &S;
13591 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13592
13593 bool operator()(const TemplateSpecCandidate *L,
13594 const TemplateSpecCandidate *R) {
13595 // Fast-path this check.
13596 if (L == R)
13597 return false;
13598
13599 // Assuming that both candidates are not matches...
13600
13601 // Sort by the ranking of deduction failures.
13602 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13604 RankDeductionFailure(R->DeductionFailure);
13605
13606 // Sort everything else by location.
13607 SourceLocation LLoc = GetLocationForCandidate(L);
13608 SourceLocation RLoc = GetLocationForCandidate(R);
13609
13610 // Put candidates without locations (e.g. builtins) at the end.
13611 if (LLoc.isInvalid())
13612 return false;
13613 if (RLoc.isInvalid())
13614 return true;
13615
13616 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13617 }
13618};
13619}
13620
13621/// Diagnose a template argument deduction failure.
13622/// We are treating these failures as overload failures due to bad
13623/// deductions.
13625 bool ForTakingAddress) {
13627 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13628}
13629
13630void TemplateSpecCandidateSet::destroyCandidates() {
13631 for (iterator i = begin(), e = end(); i != e; ++i) {
13632 i->DeductionFailure.Destroy();
13633 }
13634}
13635
13637 destroyCandidates();
13638 Candidates.clear();
13639}
13640
13641/// NoteCandidates - When no template specialization match is found, prints
13642/// diagnostic messages containing the non-matching specializations that form
13643/// the candidate set.
13644/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13645/// OCD == OCD_AllCandidates and Cand->Viable == false.
13647 // Sort the candidates by position (assuming no candidate is a match).
13648 // Sorting directly would be prohibitive, so we make a set of pointers
13649 // and sort those.
13651 Cands.reserve(size());
13652 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13653 if (Cand->Specialization)
13654 Cands.push_back(Cand);
13655 // Otherwise, this is a non-matching builtin candidate. We do not,
13656 // in general, want to list every possible builtin candidate.
13657 }
13658
13659 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13660
13661 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13662 // for generalization purposes (?).
13663 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13664
13666 unsigned CandsShown = 0;
13667 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13668 TemplateSpecCandidate *Cand = *I;
13669
13670 // Set an arbitrary limit on the number of candidates we'll spam
13671 // the user with. FIXME: This limit should depend on details of the
13672 // candidate list.
13673 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13674 break;
13675 ++CandsShown;
13676
13677 assert(Cand->Specialization &&
13678 "Non-matching built-in candidates are not added to Cands.");
13679 Cand->NoteDeductionFailure(S, ForTakingAddress);
13680 }
13681
13682 if (I != E)
13683 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13684}
13685
13686// [PossiblyAFunctionType] --> [Return]
13687// NonFunctionType --> NonFunctionType
13688// R (A) --> R(A)
13689// R (*)(A) --> R (A)
13690// R (&)(A) --> R (A)
13691// R (S::*)(A) --> R (A)
13693 QualType Ret = PossiblyAFunctionType;
13694 if (const PointerType *ToTypePtr =
13695 PossiblyAFunctionType->getAs<PointerType>())
13696 Ret = ToTypePtr->getPointeeType();
13697 else if (const ReferenceType *ToTypeRef =
13698 PossiblyAFunctionType->getAs<ReferenceType>())
13699 Ret = ToTypeRef->getPointeeType();
13700 else if (const MemberPointerType *MemTypePtr =
13701 PossiblyAFunctionType->getAs<MemberPointerType>())
13702 Ret = MemTypePtr->getPointeeType();
13703 Ret =
13704 Context.getCanonicalType(Ret).getUnqualifiedType();
13705 return Ret;
13706}
13707
13709 bool Complain = true) {
13710 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13711 S.DeduceReturnType(FD, Loc, Complain))
13712 return true;
13713
13714 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13715 if (S.getLangOpts().CPlusPlus17 &&
13716 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13717 !S.ResolveExceptionSpec(Loc, FPT))
13718 return true;
13719
13720 return false;
13721}
13722
13723namespace {
13724// A helper class to help with address of function resolution
13725// - allows us to avoid passing around all those ugly parameters
13726class AddressOfFunctionResolver {
13727 Sema& S;
13728 Expr* SourceExpr;
13729 const QualType& TargetType;
13730 QualType TargetFunctionType; // Extracted function type from target type
13731
13732 bool Complain;
13733 //DeclAccessPair& ResultFunctionAccessPair;
13734 ASTContext& Context;
13735
13736 bool TargetTypeIsNonStaticMemberFunction;
13737 bool FoundNonTemplateFunction;
13738 bool StaticMemberFunctionFromBoundPointer;
13739 bool HasComplained;
13740
13741 OverloadExpr::FindResult OvlExprInfo;
13742 OverloadExpr *OvlExpr;
13743 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13744 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13745 TemplateSpecCandidateSet FailedCandidates;
13746
13747public:
13748 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13749 const QualType &TargetType, bool Complain)
13750 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13751 Complain(Complain), Context(S.getASTContext()),
13752 TargetTypeIsNonStaticMemberFunction(
13753 !!TargetType->getAs<MemberPointerType>()),
13754 FoundNonTemplateFunction(false),
13755 StaticMemberFunctionFromBoundPointer(false),
13756 HasComplained(false),
13757 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13758 OvlExpr(OvlExprInfo.Expression),
13759 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13760 ExtractUnqualifiedFunctionTypeFromTargetType();
13761
13762 if (TargetFunctionType->isFunctionType()) {
13763 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13764 if (!UME->isImplicitAccess() &&
13766 StaticMemberFunctionFromBoundPointer = true;
13767 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13768 DeclAccessPair dap;
13769 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13770 OvlExpr, false, &dap)) {
13771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13772 if (!Method->isStatic()) {
13773 // If the target type is a non-function type and the function found
13774 // is a non-static member function, pretend as if that was the
13775 // target, it's the only possible type to end up with.
13776 TargetTypeIsNonStaticMemberFunction = true;
13777
13778 // And skip adding the function if its not in the proper form.
13779 // We'll diagnose this due to an empty set of functions.
13780 if (!OvlExprInfo.HasFormOfMemberPointer)
13781 return;
13782 }
13783
13784 Matches.push_back(std::make_pair(dap, Fn));
13785 }
13786 return;
13787 }
13788
13789 if (OvlExpr->hasExplicitTemplateArgs())
13790 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13791
13792 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13793 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13794 EliminateSuboptimalCudaMatches();
13795
13796 // C++ [over.over]p4:
13797 // If more than one function is selected, [...]
13798 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13799 if (FoundNonTemplateFunction) {
13800 EliminateAllTemplateMatches();
13801 EliminateLessPartialOrderingConstrainedMatches();
13802 } else
13803 EliminateAllExceptMostSpecializedTemplate();
13804 }
13805 }
13806 }
13807
13808 bool hasComplained() const { return HasComplained; }
13809
13810private:
13811 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13812 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13813 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13814 }
13815
13816 /// \return true if A is considered a better overload candidate for the
13817 /// desired type than B.
13818 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13819 // If A doesn't have exactly the correct type, we don't want to classify it
13820 // as "better" than anything else. This way, the user is required to
13821 // disambiguate for us if there are multiple candidates and no exact match.
13822 return candidateHasExactlyCorrectType(A) &&
13823 (!candidateHasExactlyCorrectType(B) ||
13824 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13825 }
13826
13827 /// \return true if we were able to eliminate all but one overload candidate,
13828 /// false otherwise.
13829 bool eliminiateSuboptimalOverloadCandidates() {
13830 // Same algorithm as overload resolution -- one pass to pick the "best",
13831 // another pass to be sure that nothing is better than the best.
13832 auto Best = Matches.begin();
13833 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13834 if (isBetterCandidate(I->second, Best->second))
13835 Best = I;
13836
13837 const FunctionDecl *BestFn = Best->second;
13838 auto IsBestOrInferiorToBest = [this, BestFn](
13839 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13840 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13841 };
13842
13843 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13844 // option, so we can potentially give the user a better error
13845 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13846 return false;
13847 Matches[0] = *Best;
13848 Matches.resize(1);
13849 return true;
13850 }
13851
13852 bool isTargetTypeAFunction() const {
13853 return TargetFunctionType->isFunctionType();
13854 }
13855
13856 // [ToType] [Return]
13857
13858 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13859 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13860 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13861 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13862 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13863 }
13864
13865 // return true if any matching specializations were found
13866 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13867 const DeclAccessPair& CurAccessFunPair) {
13868 if (CXXMethodDecl *Method
13869 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13870 // Skip non-static function templates when converting to pointer, and
13871 // static when converting to member pointer.
13872 bool CanConvertToFunctionPointer =
13873 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13874 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13875 return false;
13876 }
13877 else if (TargetTypeIsNonStaticMemberFunction)
13878 return false;
13879
13880 // C++ [over.over]p2:
13881 // If the name is a function template, template argument deduction is
13882 // done (14.8.2.2), and if the argument deduction succeeds, the
13883 // resulting template argument list is used to generate a single
13884 // function template specialization, which is added to the set of
13885 // overloaded functions considered.
13886 FunctionDecl *Specialization = nullptr;
13887 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13889 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13890 Specialization, Info, /*IsAddressOfFunction*/ true);
13891 Result != TemplateDeductionResult::Success) {
13892 // Make a note of the failed deduction for diagnostics.
13893 FailedCandidates.addCandidate()
13894 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13895 MakeDeductionFailureInfo(Context, Result, Info));
13896 return false;
13897 }
13898
13899 // Template argument deduction ensures that we have an exact match or
13900 // compatible pointer-to-function arguments that would be adjusted by ICS.
13901 // This function template specicalization works.
13903 Context.getCanonicalType(Specialization->getType()),
13904 Context.getCanonicalType(TargetFunctionType)));
13905
13907 return false;
13908
13909 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13910 return true;
13911 }
13912
13913 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13914 const DeclAccessPair& CurAccessFunPair) {
13915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13916 // Skip non-static functions when converting to pointer, and static
13917 // when converting to member pointer.
13918 bool CanConvertToFunctionPointer =
13919 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13920 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13921 return false;
13922 }
13923 else if (TargetTypeIsNonStaticMemberFunction)
13924 return false;
13925
13926 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13927 if (S.getLangOpts().CUDA) {
13928 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13929 if (!(Caller && Caller->isImplicit()) &&
13930 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13931 return false;
13932 }
13933 if (FunDecl->isMultiVersion()) {
13934 const auto *TA = FunDecl->getAttr<TargetAttr>();
13935 if (TA && !TA->isDefaultVersion())
13936 return false;
13937 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13938 if (TVA && !TVA->isDefaultVersion())
13939 return false;
13940 }
13941
13942 // If any candidate has a placeholder return type, trigger its deduction
13943 // now.
13944 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13945 Complain)) {
13946 HasComplained |= Complain;
13947 return false;
13948 }
13949
13950 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13951 return false;
13952
13953 // If we're in C, we need to support types that aren't exactly identical.
13954 if (!S.getLangOpts().CPlusPlus ||
13955 candidateHasExactlyCorrectType(FunDecl)) {
13956 Matches.push_back(std::make_pair(
13957 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13958 FoundNonTemplateFunction = true;
13959 return true;
13960 }
13961 }
13962
13963 return false;
13964 }
13965
13966 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13967 bool Ret = false;
13968
13969 // If the overload expression doesn't have the form of a pointer to
13970 // member, don't try to convert it to a pointer-to-member type.
13971 if (IsInvalidFormOfPointerToMemberFunction())
13972 return false;
13973
13974 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13975 E = OvlExpr->decls_end();
13976 I != E; ++I) {
13977 // Look through any using declarations to find the underlying function.
13978 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13979
13980 // C++ [over.over]p3:
13981 // Non-member functions and static member functions match
13982 // targets of type "pointer-to-function" or "reference-to-function."
13983 // Nonstatic member functions match targets of
13984 // type "pointer-to-member-function."
13985 // Note that according to DR 247, the containing class does not matter.
13986 if (FunctionTemplateDecl *FunctionTemplate
13987 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13988 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13989 Ret = true;
13990 }
13991 // If we have explicit template arguments supplied, skip non-templates.
13992 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13993 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13994 Ret = true;
13995 }
13996 assert(Ret || Matches.empty());
13997 return Ret;
13998 }
13999
14000 void EliminateAllExceptMostSpecializedTemplate() {
14001 // [...] and any given function template specialization F1 is
14002 // eliminated if the set contains a second function template
14003 // specialization whose function template is more specialized
14004 // than the function template of F1 according to the partial
14005 // ordering rules of 14.5.5.2.
14006
14007 // The algorithm specified above is quadratic. We instead use a
14008 // two-pass algorithm (similar to the one used to identify the
14009 // best viable function in an overload set) that identifies the
14010 // best function template (if it exists).
14011
14012 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14013 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14014 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14015
14016 // TODO: It looks like FailedCandidates does not serve much purpose
14017 // here, since the no_viable diagnostic has index 0.
14018 UnresolvedSetIterator Result = S.getMostSpecialized(
14019 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14020 SourceExpr->getBeginLoc(), S.PDiag(),
14021 S.PDiag(diag::err_addr_ovl_ambiguous)
14022 << Matches[0].second->getDeclName(),
14023 S.PDiag(diag::note_ovl_candidate)
14024 << (unsigned)oc_function << (unsigned)ocs_described_template,
14025 Complain, TargetFunctionType);
14026
14027 if (Result != MatchesCopy.end()) {
14028 // Make it the first and only element
14029 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14030 Matches[0].second = cast<FunctionDecl>(*Result);
14031 Matches.resize(1);
14032 } else
14033 HasComplained |= Complain;
14034 }
14035
14036 void EliminateAllTemplateMatches() {
14037 // [...] any function template specializations in the set are
14038 // eliminated if the set also contains a non-template function, [...]
14039 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14040 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14041 ++I;
14042 else {
14043 Matches[I] = Matches[--N];
14044 Matches.resize(N);
14045 }
14046 }
14047 }
14048
14049 void EliminateLessPartialOrderingConstrainedMatches() {
14050 // C++ [over.over]p5:
14051 // [...] Any given non-template function F0 is eliminated if the set
14052 // contains a second non-template function that is more
14053 // partial-ordering-constrained than F0. [...]
14054 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14055 "Call EliminateAllTemplateMatches() first");
14056 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14057 Results.push_back(Matches[0]);
14058 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14059 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14060 FunctionDecl *F = getMorePartialOrderingConstrained(
14061 S, Matches[I].second, Results[0].second,
14062 /*IsFn1Reversed=*/false,
14063 /*IsFn2Reversed=*/false);
14064 if (!F) {
14065 Results.push_back(Matches[I]);
14066 continue;
14067 }
14068 if (F == Matches[I].second) {
14069 Results.clear();
14070 Results.push_back(Matches[I]);
14071 }
14072 }
14073 std::swap(Matches, Results);
14074 }
14075
14076 void EliminateSuboptimalCudaMatches() {
14077 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14078 Matches);
14079 }
14080
14081public:
14082 void ComplainNoMatchesFound() const {
14083 assert(Matches.empty());
14084 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14085 << OvlExpr->getName() << TargetFunctionType
14086 << OvlExpr->getSourceRange();
14087 if (FailedCandidates.empty())
14088 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14089 /*TakingAddress=*/true);
14090 else {
14091 // We have some deduction failure messages. Use them to diagnose
14092 // the function templates, and diagnose the non-template candidates
14093 // normally.
14094 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14095 IEnd = OvlExpr->decls_end();
14096 I != IEnd; ++I)
14097 if (FunctionDecl *Fun =
14098 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14100 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14101 /*TakingAddress=*/true);
14102 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14103 }
14104 }
14105
14106 bool IsInvalidFormOfPointerToMemberFunction() const {
14107 return TargetTypeIsNonStaticMemberFunction &&
14108 !OvlExprInfo.HasFormOfMemberPointer;
14109 }
14110
14111 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14112 // TODO: Should we condition this on whether any functions might
14113 // have matched, or is it more appropriate to do that in callers?
14114 // TODO: a fixit wouldn't hurt.
14115 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14116 << TargetType << OvlExpr->getSourceRange();
14117 }
14118
14119 bool IsStaticMemberFunctionFromBoundPointer() const {
14120 return StaticMemberFunctionFromBoundPointer;
14121 }
14122
14123 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14124 S.Diag(OvlExpr->getBeginLoc(),
14125 diag::err_invalid_form_pointer_member_function)
14126 << OvlExpr->getSourceRange();
14127 }
14128
14129 void ComplainOfInvalidConversion() const {
14130 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14131 << OvlExpr->getName() << TargetType;
14132 }
14133
14134 void ComplainMultipleMatchesFound() const {
14135 assert(Matches.size() > 1);
14136 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14137 << OvlExpr->getName() << OvlExpr->getSourceRange();
14138 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14139 /*TakingAddress=*/true);
14140 }
14141
14142 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14143
14144 int getNumMatches() const { return Matches.size(); }
14145
14146 FunctionDecl* getMatchingFunctionDecl() const {
14147 if (Matches.size() != 1) return nullptr;
14148 return Matches[0].second;
14149 }
14150
14151 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14152 if (Matches.size() != 1) return nullptr;
14153 return &Matches[0].first;
14154 }
14155};
14156}
14157
14158FunctionDecl *
14160 QualType TargetType,
14161 bool Complain,
14162 DeclAccessPair &FoundResult,
14163 bool *pHadMultipleCandidates) {
14164 assert(AddressOfExpr->getType() == Context.OverloadTy);
14165
14166 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14167 Complain);
14168 int NumMatches = Resolver.getNumMatches();
14169 FunctionDecl *Fn = nullptr;
14170 bool ShouldComplain = Complain && !Resolver.hasComplained();
14171 if (NumMatches == 0 && ShouldComplain) {
14172 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14173 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14174 else
14175 Resolver.ComplainNoMatchesFound();
14176 }
14177 else if (NumMatches > 1 && ShouldComplain)
14178 Resolver.ComplainMultipleMatchesFound();
14179 else if (NumMatches == 1) {
14180 Fn = Resolver.getMatchingFunctionDecl();
14181 assert(Fn);
14182 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14183 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14184 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14185 if (Complain) {
14186 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14187 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14188 else
14189 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14190 }
14191 }
14192
14193 if (pHadMultipleCandidates)
14194 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14195 return Fn;
14196}
14197
14201 OverloadExpr *Ovl = R.Expression;
14202 bool IsResultAmbiguous = false;
14203 FunctionDecl *Result = nullptr;
14204 DeclAccessPair DAP;
14205 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14206
14207 // Return positive for better, negative for worse, 0 for equal preference.
14208 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14209 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14210 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14211 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14212 };
14213
14214 // Don't use the AddressOfResolver because we're specifically looking for
14215 // cases where we have one overload candidate that lacks
14216 // enable_if/pass_object_size/...
14217 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14218 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14219 if (!FD)
14220 return nullptr;
14221
14223 continue;
14224
14225 // If we found a better result, update Result.
14226 auto FoundBetter = [&]() {
14227 IsResultAmbiguous = false;
14228 DAP = I.getPair();
14229 Result = FD;
14230 };
14231
14232 // We have more than one result - see if it is more
14233 // partial-ordering-constrained than the previous one.
14234 if (Result) {
14235 // Check CUDA preference first. If the candidates have differennt CUDA
14236 // preference, choose the one with higher CUDA preference. Otherwise,
14237 // choose the one with more constraints.
14238 if (getLangOpts().CUDA) {
14239 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14240 // FD has different preference than Result.
14241 if (PreferenceByCUDA != 0) {
14242 // FD is more preferable than Result.
14243 if (PreferenceByCUDA > 0)
14244 FoundBetter();
14245 continue;
14246 }
14247 }
14248 // FD has the same CUDA preference than Result. Continue to check
14249 // constraints.
14250
14251 // C++ [over.over]p5:
14252 // [...] Any given non-template function F0 is eliminated if the set
14253 // contains a second non-template function that is more
14254 // partial-ordering-constrained than F0 [...]
14255 FunctionDecl *MoreConstrained =
14257 /*IsFn1Reversed=*/false,
14258 /*IsFn2Reversed=*/false);
14259 if (MoreConstrained != FD) {
14260 if (!MoreConstrained) {
14261 IsResultAmbiguous = true;
14262 AmbiguousDecls.push_back(FD);
14263 }
14264 continue;
14265 }
14266 // FD is more constrained - replace Result with it.
14267 }
14268 FoundBetter();
14269 }
14270
14271 if (IsResultAmbiguous)
14272 return nullptr;
14273
14274 if (Result) {
14275 // We skipped over some ambiguous declarations which might be ambiguous with
14276 // the selected result.
14277 for (FunctionDecl *Skipped : AmbiguousDecls) {
14278 // If skipped candidate has different CUDA preference than the result,
14279 // there is no ambiguity. Otherwise check whether they have different
14280 // constraints.
14281 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14282 continue;
14283 if (!getMoreConstrainedFunction(Skipped, Result))
14284 return nullptr;
14285 }
14286 Pair = DAP;
14287 }
14288 return Result;
14289}
14290
14292 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14293 Expr *E = SrcExpr.get();
14294 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14295
14296 DeclAccessPair DAP;
14298 if (!Found || Found->isCPUDispatchMultiVersion() ||
14299 Found->isCPUSpecificMultiVersion())
14300 return false;
14301
14302 // Emitting multiple diagnostics for a function that is both inaccessible and
14303 // unavailable is consistent with our behavior elsewhere. So, always check
14304 // for both.
14308 if (Res.isInvalid())
14309 return false;
14310 Expr *Fixed = Res.get();
14311 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14312 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14313 else
14314 SrcExpr = Fixed;
14315 return true;
14316}
14317
14319 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14320 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14321 // C++ [over.over]p1:
14322 // [...] [Note: any redundant set of parentheses surrounding the
14323 // overloaded function name is ignored (5.1). ]
14324 // C++ [over.over]p1:
14325 // [...] The overloaded function name can be preceded by the &
14326 // operator.
14327
14328 // If we didn't actually find any template-ids, we're done.
14329 if (!ovl->hasExplicitTemplateArgs())
14330 return nullptr;
14331
14332 TemplateArgumentListInfo ExplicitTemplateArgs;
14333 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14334
14335 // Look through all of the overloaded functions, searching for one
14336 // whose type matches exactly.
14337 FunctionDecl *Matched = nullptr;
14338 for (UnresolvedSetIterator I = ovl->decls_begin(),
14339 E = ovl->decls_end(); I != E; ++I) {
14340 // C++0x [temp.arg.explicit]p3:
14341 // [...] In contexts where deduction is done and fails, or in contexts
14342 // where deduction is not done, if a template argument list is
14343 // specified and it, along with any default template arguments,
14344 // identifies a single function template specialization, then the
14345 // template-id is an lvalue for the function template specialization.
14347 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14348 if (!FunctionTemplate)
14349 continue;
14350
14351 // C++ [over.over]p2:
14352 // If the name is a function template, template argument deduction is
14353 // done (14.8.2.2), and if the argument deduction succeeds, the
14354 // resulting template argument list is used to generate a single
14355 // function template specialization, which is added to the set of
14356 // overloaded functions considered.
14357 FunctionDecl *Specialization = nullptr;
14358 TemplateDeductionInfo Info(ovl->getNameLoc());
14360 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14361 /*IsAddressOfFunction*/ true);
14363 // Make a note of the failed deduction for diagnostics.
14364 if (FailedTSC)
14365 FailedTSC->addCandidate().set(
14366 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14368 continue;
14369 }
14370
14371 assert(Specialization && "no specialization and no error?");
14372
14373 // C++ [temp.deduct.call]p6:
14374 // [...] If all successful deductions yield the same deduced A, that
14375 // deduced A is the result of deduction; otherwise, the parameter is
14376 // treated as a non-deduced context.
14377 if (Matched) {
14378 if (ForTypeDeduction &&
14380 Specialization->getType()))
14381 continue;
14382 // Multiple matches; we can't resolve to a single declaration.
14383 if (Complain) {
14384 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14385 << ovl->getName();
14387 }
14388 return nullptr;
14389 }
14390
14391 Matched = Specialization;
14392 if (FoundResult) *FoundResult = I.getPair();
14393 }
14394
14395 if (Matched &&
14396 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14397 return nullptr;
14398
14399 return Matched;
14400}
14401
14403 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14404 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14405 unsigned DiagIDForComplaining) {
14406 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14407
14409
14410 DeclAccessPair found;
14411 ExprResult SingleFunctionExpression;
14413 ovl.Expression, /*complain*/ false, &found)) {
14414 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14415 SrcExpr = ExprError();
14416 return true;
14417 }
14418
14419 // It is only correct to resolve to an instance method if we're
14420 // resolving a form that's permitted to be a pointer to member.
14421 // Otherwise we'll end up making a bound member expression, which
14422 // is illegal in all the contexts we resolve like this.
14423 if (!ovl.HasFormOfMemberPointer &&
14424 isa<CXXMethodDecl>(fn) &&
14425 cast<CXXMethodDecl>(fn)->isInstance()) {
14426 if (!complain) return false;
14427
14428 Diag(ovl.Expression->getExprLoc(),
14429 diag::err_bound_member_function)
14430 << 0 << ovl.Expression->getSourceRange();
14431
14432 // TODO: I believe we only end up here if there's a mix of
14433 // static and non-static candidates (otherwise the expression
14434 // would have 'bound member' type, not 'overload' type).
14435 // Ideally we would note which candidate was chosen and why
14436 // the static candidates were rejected.
14437 SrcExpr = ExprError();
14438 return true;
14439 }
14440
14441 // Fix the expression to refer to 'fn'.
14442 SingleFunctionExpression =
14443 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14444
14445 // If desired, do function-to-pointer decay.
14446 if (doFunctionPointerConversion) {
14447 SingleFunctionExpression =
14448 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14449 if (SingleFunctionExpression.isInvalid()) {
14450 SrcExpr = ExprError();
14451 return true;
14452 }
14453 }
14454 }
14455
14456 if (!SingleFunctionExpression.isUsable()) {
14457 if (complain) {
14458 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14459 << ovl.Expression->getName()
14460 << DestTypeForComplaining
14461 << OpRangeForComplaining
14463 NoteAllOverloadCandidates(SrcExpr.get());
14464
14465 SrcExpr = ExprError();
14466 return true;
14467 }
14468
14469 return false;
14470 }
14471
14472 SrcExpr = SingleFunctionExpression;
14473 return true;
14474}
14475
14476/// Add a single candidate to the overload set.
14478 DeclAccessPair FoundDecl,
14479 TemplateArgumentListInfo *ExplicitTemplateArgs,
14480 ArrayRef<Expr *> Args,
14481 OverloadCandidateSet &CandidateSet,
14482 bool PartialOverloading,
14483 bool KnownValid) {
14484 NamedDecl *Callee = FoundDecl.getDecl();
14485 if (isa<UsingShadowDecl>(Callee))
14486 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14487
14488 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14489 if (ExplicitTemplateArgs) {
14490 assert(!KnownValid && "Explicit template arguments?");
14491 return;
14492 }
14493 // Prevent ill-formed function decls to be added as overload candidates.
14494 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14495 return;
14496
14497 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14498 /*SuppressUserConversions=*/false,
14499 PartialOverloading);
14500 return;
14501 }
14502
14503 if (FunctionTemplateDecl *FuncTemplate
14504 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14505 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14506 ExplicitTemplateArgs, Args, CandidateSet,
14507 /*SuppressUserConversions=*/false,
14508 PartialOverloading);
14509 return;
14510 }
14511
14512 assert(!KnownValid && "unhandled case in overloaded call candidate");
14513}
14514
14516 ArrayRef<Expr *> Args,
14517 OverloadCandidateSet &CandidateSet,
14518 bool PartialOverloading) {
14519
14520#ifndef NDEBUG
14521 // Verify that ArgumentDependentLookup is consistent with the rules
14522 // in C++0x [basic.lookup.argdep]p3:
14523 //
14524 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14525 // and let Y be the lookup set produced by argument dependent
14526 // lookup (defined as follows). If X contains
14527 //
14528 // -- a declaration of a class member, or
14529 //
14530 // -- a block-scope function declaration that is not a
14531 // using-declaration, or
14532 //
14533 // -- a declaration that is neither a function or a function
14534 // template
14535 //
14536 // then Y is empty.
14537
14538 if (ULE->requiresADL()) {
14540 E = ULE->decls_end(); I != E; ++I) {
14541 assert(!(*I)->getDeclContext()->isRecord());
14542 assert(isa<UsingShadowDecl>(*I) ||
14543 !(*I)->getDeclContext()->isFunctionOrMethod());
14544 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14545 }
14546 }
14547#endif
14548
14549 // It would be nice to avoid this copy.
14550 TemplateArgumentListInfo TABuffer;
14551 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14552 if (ULE->hasExplicitTemplateArgs()) {
14553 ULE->copyTemplateArgumentsInto(TABuffer);
14554 ExplicitTemplateArgs = &TABuffer;
14555 }
14556
14558 E = ULE->decls_end(); I != E; ++I)
14559 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14560 CandidateSet, PartialOverloading,
14561 /*KnownValid*/ true);
14562
14563 if (ULE->requiresADL())
14565 Args, ExplicitTemplateArgs,
14566 CandidateSet, PartialOverloading);
14567}
14568
14570 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14571 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14572 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14573 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14574 CandidateSet, false, /*KnownValid*/ false);
14575}
14576
14577/// Determine whether a declaration with the specified name could be moved into
14578/// a different namespace.
14580 switch (Name.getCXXOverloadedOperator()) {
14581 case OO_New: case OO_Array_New:
14582 case OO_Delete: case OO_Array_Delete:
14583 return false;
14584
14585 default:
14586 return true;
14587 }
14588}
14589
14590/// Attempt to recover from an ill-formed use of a non-dependent name in a
14591/// template, where the non-dependent name was declared after the template
14592/// was defined. This is common in code written for a compilers which do not
14593/// correctly implement two-stage name lookup.
14594///
14595/// Returns true if a viable candidate was found and a diagnostic was issued.
14597 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14599 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14600 CXXRecordDecl **FoundInClass = nullptr) {
14601 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14602 return false;
14603
14604 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14605 if (DC->isTransparentContext())
14606 continue;
14607
14608 SemaRef.LookupQualifiedName(R, DC);
14609
14610 if (!R.empty()) {
14611 R.suppressDiagnostics();
14612
14613 OverloadCandidateSet Candidates(FnLoc, CSK);
14614 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14615 Candidates);
14616
14619 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14620
14621 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14622 // We either found non-function declarations or a best viable function
14623 // at class scope. A class-scope lookup result disables ADL. Don't
14624 // look past this, but let the caller know that we found something that
14625 // either is, or might be, usable in this class.
14626 if (FoundInClass) {
14627 *FoundInClass = RD;
14628 if (OR == OR_Success) {
14629 R.clear();
14630 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14631 R.resolveKind();
14632 }
14633 }
14634 return false;
14635 }
14636
14637 if (OR != OR_Success) {
14638 // There wasn't a unique best function or function template.
14639 return false;
14640 }
14641
14642 // Find the namespaces where ADL would have looked, and suggest
14643 // declaring the function there instead.
14644 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14645 Sema::AssociatedClassSet AssociatedClasses;
14646 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14647 AssociatedNamespaces,
14648 AssociatedClasses);
14649 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14650 if (canBeDeclaredInNamespace(R.getLookupName())) {
14651 DeclContext *Std = SemaRef.getStdNamespace();
14652 for (Sema::AssociatedNamespaceSet::iterator
14653 it = AssociatedNamespaces.begin(),
14654 end = AssociatedNamespaces.end(); it != end; ++it) {
14655 // Never suggest declaring a function within namespace 'std'.
14656 if (Std && Std->Encloses(*it))
14657 continue;
14658
14659 // Never suggest declaring a function within a namespace with a
14660 // reserved name, like __gnu_cxx.
14661 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14662 if (NS &&
14663 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14664 continue;
14665
14666 SuggestedNamespaces.insert(*it);
14667 }
14668 }
14669
14670 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14671 << R.getLookupName();
14672 if (SuggestedNamespaces.empty()) {
14673 SemaRef.Diag(Best->Function->getLocation(),
14674 diag::note_not_found_by_two_phase_lookup)
14675 << R.getLookupName() << 0;
14676 } else if (SuggestedNamespaces.size() == 1) {
14677 SemaRef.Diag(Best->Function->getLocation(),
14678 diag::note_not_found_by_two_phase_lookup)
14679 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14680 } else {
14681 // FIXME: It would be useful to list the associated namespaces here,
14682 // but the diagnostics infrastructure doesn't provide a way to produce
14683 // a localized representation of a list of items.
14684 SemaRef.Diag(Best->Function->getLocation(),
14685 diag::note_not_found_by_two_phase_lookup)
14686 << R.getLookupName() << 2;
14687 }
14688
14689 // Try to recover by calling this function.
14690 return true;
14691 }
14692
14693 R.clear();
14694 }
14695
14696 return false;
14697}
14698
14699/// Attempt to recover from ill-formed use of a non-dependent operator in a
14700/// template, where the non-dependent operator was declared after the template
14701/// was defined.
14702///
14703/// Returns true if a viable candidate was found and a diagnostic was issued.
14704static bool
14706 SourceLocation OpLoc,
14707 ArrayRef<Expr *> Args) {
14708 DeclarationName OpName =
14710 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14711 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14713 /*ExplicitTemplateArgs=*/nullptr, Args);
14714}
14715
14716namespace {
14717class BuildRecoveryCallExprRAII {
14718 Sema &SemaRef;
14719 Sema::SatisfactionStackResetRAII SatStack;
14720
14721public:
14722 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14723 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14724 SemaRef.IsBuildingRecoveryCallExpr = true;
14725 }
14726
14727 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14728};
14729}
14730
14731/// Attempts to recover from a call where no functions were found.
14732///
14733/// This function will do one of three things:
14734/// * Diagnose, recover, and return a recovery expression.
14735/// * Diagnose, fail to recover, and return ExprError().
14736/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14737/// expected to diagnose as appropriate.
14738static ExprResult
14741 SourceLocation LParenLoc,
14743 SourceLocation RParenLoc,
14744 bool EmptyLookup, bool AllowTypoCorrection) {
14745 // Do not try to recover if it is already building a recovery call.
14746 // This stops infinite loops for template instantiations like
14747 //
14748 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14749 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14750 if (SemaRef.IsBuildingRecoveryCallExpr)
14751 return ExprResult();
14752 BuildRecoveryCallExprRAII RCE(SemaRef);
14753
14754 CXXScopeSpec SS;
14755 SS.Adopt(ULE->getQualifierLoc());
14756 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14757
14758 TemplateArgumentListInfo TABuffer;
14759 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14760 if (ULE->hasExplicitTemplateArgs()) {
14761 ULE->copyTemplateArgumentsInto(TABuffer);
14762 ExplicitTemplateArgs = &TABuffer;
14763 }
14764
14765 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14767 CXXRecordDecl *FoundInClass = nullptr;
14768 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14770 ExplicitTemplateArgs, Args, &FoundInClass)) {
14771 // OK, diagnosed a two-phase lookup issue.
14772 } else if (EmptyLookup) {
14773 // Try to recover from an empty lookup with typo correction.
14774 R.clear();
14775 NoTypoCorrectionCCC NoTypoValidator{};
14776 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14777 ExplicitTemplateArgs != nullptr,
14778 dyn_cast<MemberExpr>(Fn));
14779 CorrectionCandidateCallback &Validator =
14780 AllowTypoCorrection
14781 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14782 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14783 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14784 Args))
14785 return ExprError();
14786 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14787 // We found a usable declaration of the name in a dependent base of some
14788 // enclosing class.
14789 // FIXME: We should also explain why the candidates found by name lookup
14790 // were not viable.
14791 if (SemaRef.DiagnoseDependentMemberLookup(R))
14792 return ExprError();
14793 } else {
14794 // We had viable candidates and couldn't recover; let the caller diagnose
14795 // this.
14796 return ExprResult();
14797 }
14798
14799 // If we get here, we should have issued a diagnostic and formed a recovery
14800 // lookup result.
14801 assert(!R.empty() && "lookup results empty despite recovery");
14802
14803 // If recovery created an ambiguity, just bail out.
14804 if (R.isAmbiguous()) {
14805 R.suppressDiagnostics();
14806 return ExprError();
14807 }
14808
14809 // Build an implicit member call if appropriate. Just drop the
14810 // casts and such from the call, we don't really care.
14811 ExprResult NewFn = ExprError();
14812 if ((*R.begin())->isCXXClassMember())
14813 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14814 ExplicitTemplateArgs, S);
14815 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14816 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14817 ExplicitTemplateArgs);
14818 else
14819 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14820
14821 if (NewFn.isInvalid())
14822 return ExprError();
14823
14824 // This shouldn't cause an infinite loop because we're giving it
14825 // an expression with viable lookup results, which should never
14826 // end up here.
14827 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14828 MultiExprArg(Args.data(), Args.size()),
14829 RParenLoc);
14830}
14831
14834 MultiExprArg Args,
14835 SourceLocation RParenLoc,
14836 OverloadCandidateSet *CandidateSet,
14837 ExprResult *Result) {
14838#ifndef NDEBUG
14839 if (ULE->requiresADL()) {
14840 // To do ADL, we must have found an unqualified name.
14841 assert(!ULE->getQualifier() && "qualified name with ADL");
14842
14843 // We don't perform ADL for implicit declarations of builtins.
14844 // Verify that this was correctly set up.
14845 FunctionDecl *F;
14846 if (ULE->decls_begin() != ULE->decls_end() &&
14847 ULE->decls_begin() + 1 == ULE->decls_end() &&
14848 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14849 F->getBuiltinID() && F->isImplicit())
14850 llvm_unreachable("performing ADL for builtin");
14851
14852 // We don't perform ADL in C.
14853 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14854 }
14855#endif
14856
14857 UnbridgedCastsSet UnbridgedCasts;
14858 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14859 *Result = ExprError();
14860 return true;
14861 }
14862
14863 // Add the functions denoted by the callee to the set of candidate
14864 // functions, including those from argument-dependent lookup.
14865 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14866
14867 if (getLangOpts().MSVCCompat &&
14868 CurContext->isDependentContext() && !isSFINAEContext() &&
14870
14872 if (CandidateSet->empty() ||
14873 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14875 // In Microsoft mode, if we are inside a template class member function
14876 // then create a type dependent CallExpr. The goal is to postpone name
14877 // lookup to instantiation time to be able to search into type dependent
14878 // base classes.
14879 CallExpr *CE =
14880 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14881 RParenLoc, CurFPFeatureOverrides());
14883 *Result = CE;
14884 return true;
14885 }
14886 }
14887
14888 if (CandidateSet->empty())
14889 return false;
14890
14891 UnbridgedCasts.restore();
14892 return false;
14893}
14894
14895// Guess at what the return type for an unresolvable overload should be.
14898 std::optional<QualType> Result;
14899 // Adjust Type after seeing a candidate.
14900 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14901 if (!Candidate.Function)
14902 return;
14903 if (Candidate.Function->isInvalidDecl())
14904 return;
14905 QualType T = Candidate.Function->getReturnType();
14906 if (T.isNull())
14907 return;
14908 if (!Result)
14909 Result = T;
14910 else if (Result != T)
14911 Result = QualType();
14912 };
14913
14914 // Look for an unambiguous type from a progressively larger subset.
14915 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14916 //
14917 // First, consider only the best candidate.
14918 if (Best && *Best != CS.end())
14919 ConsiderCandidate(**Best);
14920 // Next, consider only viable candidates.
14921 if (!Result)
14922 for (const auto &C : CS)
14923 if (C.Viable)
14924 ConsiderCandidate(C);
14925 // Finally, consider all candidates.
14926 if (!Result)
14927 for (const auto &C : CS)
14928 ConsiderCandidate(C);
14929
14930 if (!Result)
14931 return QualType();
14932 auto Value = *Result;
14933 if (Value.isNull() || Value->isUndeducedType())
14934 return QualType();
14935 return Value;
14936}
14937
14938/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14939/// the completed call expression. If overload resolution fails, emits
14940/// diagnostics and returns ExprError()
14943 SourceLocation LParenLoc,
14944 MultiExprArg Args,
14945 SourceLocation RParenLoc,
14946 Expr *ExecConfig,
14947 OverloadCandidateSet *CandidateSet,
14949 OverloadingResult OverloadResult,
14950 bool AllowTypoCorrection) {
14951 switch (OverloadResult) {
14952 case OR_Success: {
14953 FunctionDecl *FDecl = (*Best)->Function;
14954 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14955 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14956 return ExprError();
14957 ExprResult Res =
14958 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14959 if (Res.isInvalid())
14960 return ExprError();
14961 return SemaRef.BuildResolvedCallExpr(
14962 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14963 /*IsExecConfig=*/false,
14964 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14965 }
14966
14967 case OR_No_Viable_Function: {
14968 if (*Best != CandidateSet->end() &&
14969 CandidateSet->getKind() ==
14971 if (CXXMethodDecl *M =
14972 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14974 CandidateSet->NoteCandidates(
14976 Fn->getBeginLoc(),
14977 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14978 SemaRef, OCD_AmbiguousCandidates, Args);
14979 return ExprError();
14980 }
14981 }
14982
14983 // Try to recover by looking for viable functions which the user might
14984 // have meant to call.
14985 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14986 Args, RParenLoc,
14987 CandidateSet->empty(),
14988 AllowTypoCorrection);
14989 if (Recovery.isInvalid() || Recovery.isUsable())
14990 return Recovery;
14991
14992 // If the user passes in a function that we can't take the address of, we
14993 // generally end up emitting really bad error messages. Here, we attempt to
14994 // emit better ones.
14995 for (const Expr *Arg : Args) {
14996 if (!Arg->getType()->isFunctionType())
14997 continue;
14998 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14999 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15000 if (FD &&
15001 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15002 Arg->getExprLoc()))
15003 return ExprError();
15004 }
15005 }
15006
15007 CandidateSet->NoteCandidates(
15009 Fn->getBeginLoc(),
15010 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15011 << ULE->getName() << Fn->getSourceRange()),
15012 SemaRef, OCD_AllCandidates, Args);
15013 break;
15014 }
15015
15016 case OR_Ambiguous:
15017 CandidateSet->NoteCandidates(
15018 PartialDiagnosticAt(Fn->getBeginLoc(),
15019 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15020 << ULE->getName() << Fn->getSourceRange()),
15021 SemaRef, OCD_AmbiguousCandidates, Args);
15022 break;
15023
15024 case OR_Deleted: {
15025 FunctionDecl *FDecl = (*Best)->Function;
15026 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15027 Fn->getSourceRange(), ULE->getName(),
15028 *CandidateSet, FDecl, Args);
15029
15030 // We emitted an error for the unavailable/deleted function call but keep
15031 // the call in the AST.
15032 ExprResult Res =
15033 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15034 if (Res.isInvalid())
15035 return ExprError();
15036 return SemaRef.BuildResolvedCallExpr(
15037 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15038 /*IsExecConfig=*/false,
15039 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15040 }
15041 }
15042
15043 // Overload resolution failed, try to recover.
15044 SmallVector<Expr *, 8> SubExprs = {Fn};
15045 SubExprs.append(Args.begin(), Args.end());
15046 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15047 chooseRecoveryType(*CandidateSet, Best));
15048}
15049
15052 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15053 if (I->Viable &&
15054 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15055 I->Viable = false;
15056 I->FailureKind = ovl_fail_addr_not_available;
15057 }
15058 }
15059}
15060
15063 SourceLocation LParenLoc,
15064 MultiExprArg Args,
15065 SourceLocation RParenLoc,
15066 Expr *ExecConfig,
15067 bool AllowTypoCorrection,
15068 bool CalleesAddressIsTaken) {
15069
15073
15074 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15075 ExprResult result;
15076
15077 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15078 &result))
15079 return result;
15080
15081 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15082 // functions that aren't addressible are considered unviable.
15083 if (CalleesAddressIsTaken)
15084 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15085
15087 OverloadingResult OverloadResult =
15088 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15089
15090 // [C++23][over.call.func]
15091 // if overload resolution selects a non-static member function,
15092 // the call is ill-formed;
15094 Best != CandidateSet.end()) {
15095 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15096 M && M->isImplicitObjectMemberFunction()) {
15097 OverloadResult = OR_No_Viable_Function;
15098 }
15099 }
15100
15101 // Model the case with a call to a templated function whose definition
15102 // encloses the call and whose return type contains a placeholder type as if
15103 // the UnresolvedLookupExpr was type-dependent.
15104 if (OverloadResult == OR_Success) {
15105 const FunctionDecl *FDecl = Best->Function;
15106 if (LangOpts.CUDA)
15107 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15108 if (FDecl && FDecl->isTemplateInstantiation() &&
15109 FDecl->getReturnType()->isUndeducedType()) {
15110
15111 // Creating dependent CallExpr is not okay if the enclosing context itself
15112 // is not dependent. This situation notably arises if a non-dependent
15113 // member function calls the later-defined overloaded static function.
15114 //
15115 // For example, in
15116 // class A {
15117 // void c() { callee(1); }
15118 // static auto callee(auto x) { }
15119 // };
15120 //
15121 // Here callee(1) is unresolved at the call site, but is not inside a
15122 // dependent context. There will be no further attempt to resolve this
15123 // call if it is made dependent.
15124
15125 if (const auto *TP =
15126 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15127 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15128 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15129 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15130 }
15131 }
15132 }
15133
15134 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15135 ExecConfig, &CandidateSet, &Best,
15136 OverloadResult, AllowTypoCorrection);
15137}
15138
15142 const UnresolvedSetImpl &Fns,
15143 bool PerformADL) {
15145 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15146 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15147}
15148
15151 bool HadMultipleCandidates) {
15152 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15153 // the FoundDecl as it impedes TransformMemberExpr.
15154 // We go a bit further here: if there's no difference in UnderlyingDecl,
15155 // then using FoundDecl vs Method shouldn't make a difference either.
15156 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15157 FoundDecl = Method;
15158 // Convert the expression to match the conversion function's implicit object
15159 // parameter.
15160 ExprResult Exp;
15161 if (Method->isExplicitObjectMemberFunction())
15163 else
15165 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15166 if (Exp.isInvalid())
15167 return true;
15168
15169 if (Method->getParent()->isLambda() &&
15170 Method->getConversionType()->isBlockPointerType()) {
15171 // This is a lambda conversion to block pointer; check if the argument
15172 // was a LambdaExpr.
15173 Expr *SubE = E;
15174 auto *CE = dyn_cast<CastExpr>(SubE);
15175 if (CE && CE->getCastKind() == CK_NoOp)
15176 SubE = CE->getSubExpr();
15177 SubE = SubE->IgnoreParens();
15178 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15179 SubE = BE->getSubExpr();
15180 if (isa<LambdaExpr>(SubE)) {
15181 // For the conversion to block pointer on a lambda expression, we
15182 // construct a special BlockLiteral instead; this doesn't really make
15183 // a difference in ARC, but outside of ARC the resulting block literal
15184 // follows the normal lifetime rules for block literals instead of being
15185 // autoreleased.
15189 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15191
15192 // FIXME: This note should be produced by a CodeSynthesisContext.
15193 if (BlockExp.isInvalid())
15194 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15195 return BlockExp;
15196 }
15197 }
15198 CallExpr *CE;
15199 QualType ResultType = Method->getReturnType();
15201 ResultType = ResultType.getNonLValueExprType(Context);
15202 if (Method->isExplicitObjectMemberFunction()) {
15203 ExprResult FnExpr =
15204 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15205 HadMultipleCandidates, E->getBeginLoc());
15206 if (FnExpr.isInvalid())
15207 return ExprError();
15208 Expr *ObjectParam = Exp.get();
15209 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15210 ResultType, VK, Exp.get()->getEndLoc(),
15212 CE->setUsesMemberSyntax(true);
15213 } else {
15214 MemberExpr *ME =
15215 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15217 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15218 HadMultipleCandidates, DeclarationNameInfo(),
15219 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15220
15221 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15222 Exp.get()->getEndLoc(),
15224 }
15225
15226 if (CheckFunctionCall(Method, CE,
15227 Method->getType()->castAs<FunctionProtoType>()))
15228 return ExprError();
15229
15231}
15232
15235 const UnresolvedSetImpl &Fns,
15236 ArrayRef<Expr *> Args, bool PerformADL) {
15237 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15238
15239 SourceLocation OpLoc = CandidateSet.getLocation();
15240 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15241
15242 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15243 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15244 if (PerformADL)
15245 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15246 /*ExplicitTemplateArgs*/ nullptr,
15247 CandidateSet);
15248 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15249}
15250
15253 const UnresolvedSetImpl &Fns,
15254 Expr *Input, bool PerformADL) {
15256 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15257 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15258 // TODO: provide better source location info.
15259 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15260
15261 if (checkPlaceholderForOverload(*this, Input))
15262 return ExprError();
15263
15264 Expr *Args[2] = { Input, nullptr };
15265 unsigned NumArgs = 1;
15266
15267 // For post-increment and post-decrement, add the implicit '0' as
15268 // the second argument, so that we know this is a post-increment or
15269 // post-decrement.
15270 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15271 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15272 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15273 SourceLocation());
15274 NumArgs = 2;
15275 }
15276
15277 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15278
15279 if (Input->isTypeDependent()) {
15281 // [C++26][expr.unary.op][expr.pre.incr]
15282 // The * operator yields an lvalue of type
15283 // The pre/post increment operators yied an lvalue.
15284 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15285 VK = VK_LValue;
15286
15287 if (Fns.empty())
15288 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15289 OK_Ordinary, OpLoc, false,
15291
15292 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15294 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15295 if (Fn.isInvalid())
15296 return ExprError();
15297 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15298 Context.DependentTy, VK_PRValue, OpLoc,
15300 }
15301
15302 // Build an empty overload set.
15304 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, ArgsArray, PerformADL);
15305
15306 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15307
15308 // Perform overload resolution.
15310 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15311 case OR_Success: {
15312 // We found a built-in operator or an overloaded operator.
15313 FunctionDecl *FnDecl = Best->Function;
15314
15315 if (FnDecl) {
15316 Expr *Base = nullptr;
15317 // We matched an overloaded operator. Build a call to that
15318 // operator.
15319
15320 // Convert the arguments.
15321 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15322 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15323
15324 ExprResult InputInit;
15325 if (Method->isExplicitObjectMemberFunction())
15326 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15327 else
15329 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15330 if (InputInit.isInvalid())
15331 return ExprError();
15332 Base = Input = InputInit.get();
15333 } else {
15334 // Convert the arguments.
15335 ExprResult InputInit
15337 Context,
15338 FnDecl->getParamDecl(0)),
15340 Input);
15341 if (InputInit.isInvalid())
15342 return ExprError();
15343 Input = InputInit.get();
15344 }
15345
15346 // Build the actual expression node.
15347 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15348 Base, HadMultipleCandidates,
15349 OpLoc);
15350 if (FnExpr.isInvalid())
15351 return ExprError();
15352
15353 // Determine the result type.
15354 QualType ResultTy = FnDecl->getReturnType();
15356 ResultTy = ResultTy.getNonLValueExprType(Context);
15357
15358 Args[0] = Input;
15360 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15362 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15363
15364 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15365 return ExprError();
15366
15367 if (CheckFunctionCall(FnDecl, TheCall,
15368 FnDecl->getType()->castAs<FunctionProtoType>()))
15369 return ExprError();
15370 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15371 } else {
15372 // We matched a built-in operator. Convert the arguments, then
15373 // break out so that we will build the appropriate built-in
15374 // operator node.
15376 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15379 if (InputRes.isInvalid())
15380 return ExprError();
15381 Input = InputRes.get();
15382 break;
15383 }
15384 }
15385
15387 // This is an erroneous use of an operator which can be overloaded by
15388 // a non-member function. Check for non-member operators which were
15389 // defined too late to be candidates.
15390 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15391 // FIXME: Recover by calling the found function.
15392 return ExprError();
15393
15394 // No viable function; fall through to handling this as a
15395 // built-in operator, which will produce an error message for us.
15396 break;
15397
15398 case OR_Ambiguous:
15399 CandidateSet.NoteCandidates(
15400 PartialDiagnosticAt(OpLoc,
15401 PDiag(diag::err_ovl_ambiguous_oper_unary)
15403 << Input->getType() << Input->getSourceRange()),
15404 *this, OCD_AmbiguousCandidates, ArgsArray,
15405 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15406 return ExprError();
15407
15408 case OR_Deleted: {
15409 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15410 // object whose method was called. Later in NoteCandidates size of ArgsArray
15411 // is passed further and it eventually ends up compared to number of
15412 // function candidate parameters which never includes the object parameter,
15413 // so slice ArgsArray to make sure apples are compared to apples.
15414 StringLiteral *Msg = Best->Function->getDeletedMessage();
15415 CandidateSet.NoteCandidates(
15416 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15418 << (Msg != nullptr)
15419 << (Msg ? Msg->getString() : StringRef())
15420 << Input->getSourceRange()),
15421 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15422 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15423 return ExprError();
15424 }
15425 }
15426
15427 // Either we found no viable overloaded operator or we matched a
15428 // built-in operator. In either case, fall through to trying to
15429 // build a built-in operation.
15430 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15431}
15432
15435 const UnresolvedSetImpl &Fns,
15436 ArrayRef<Expr *> Args, bool PerformADL) {
15437 SourceLocation OpLoc = CandidateSet.getLocation();
15438
15439 OverloadedOperatorKind ExtraOp =
15442 : OO_None;
15443
15444 // Add the candidates from the given function set. This also adds the
15445 // rewritten candidates using these functions if necessary.
15446 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15447
15448 // As template candidates are not deduced immediately,
15449 // persist the array in the overload set.
15450 ArrayRef<Expr *> ReversedArgs;
15451 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15452 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15453 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15454
15455 // Add operator candidates that are member functions.
15456 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15457 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15458 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15460
15461 // In C++20, also add any rewritten member candidates.
15462 if (ExtraOp) {
15463 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15464 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15465 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15467 }
15468
15469 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15470 // performed for an assignment operator (nor for operator[] nor operator->,
15471 // which don't get here).
15472 if (Op != OO_Equal && PerformADL) {
15473 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15474 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15475 /*ExplicitTemplateArgs*/ nullptr,
15476 CandidateSet);
15477 if (ExtraOp) {
15478 DeclarationName ExtraOpName =
15479 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15480 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15481 /*ExplicitTemplateArgs*/ nullptr,
15482 CandidateSet);
15483 }
15484 }
15485
15486 // Add builtin operator candidates.
15487 //
15488 // FIXME: We don't add any rewritten candidates here. This is strictly
15489 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15490 // resulting in our selecting a rewritten builtin candidate. For example:
15491 //
15492 // enum class E { e };
15493 // bool operator!=(E, E) requires false;
15494 // bool k = E::e != E::e;
15495 //
15496 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15497 // it seems unreasonable to consider rewritten builtin candidates. A core
15498 // issue has been filed proposing to removed this requirement.
15499 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15500}
15501
15504 const UnresolvedSetImpl &Fns, Expr *LHS,
15505 Expr *RHS, bool PerformADL,
15506 bool AllowRewrittenCandidates,
15507 FunctionDecl *DefaultedFn) {
15508 Expr *Args[2] = { LHS, RHS };
15509 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15510
15511 if (!getLangOpts().CPlusPlus20)
15512 AllowRewrittenCandidates = false;
15513
15515
15516 // If either side is type-dependent, create an appropriate dependent
15517 // expression.
15518 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15519 if (Fns.empty()) {
15520 // If there are no functions to store, just build a dependent
15521 // BinaryOperator or CompoundAssignment.
15524 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15525 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15526 Context.DependentTy);
15528 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15530 }
15531
15532 // FIXME: save results of ADL from here?
15533 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15534 // TODO: provide better source location info in DNLoc component.
15535 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15536 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15538 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15539 if (Fn.isInvalid())
15540 return ExprError();
15541 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15542 Context.DependentTy, VK_PRValue, OpLoc,
15544 }
15545
15546 // If this is the .* operator, which is not overloadable, just
15547 // create a built-in binary operator.
15548 if (Opc == BO_PtrMemD) {
15549 auto CheckPlaceholder = [&](Expr *&Arg) {
15551 if (Res.isUsable())
15552 Arg = Res.get();
15553 return !Res.isUsable();
15554 };
15555
15556 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15557 // expression that contains placeholders (in either the LHS or RHS).
15558 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15559 return ExprError();
15560 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15561 }
15562
15563 // Always do placeholder-like conversions on the RHS.
15564 if (checkPlaceholderForOverload(*this, Args[1]))
15565 return ExprError();
15566
15567 // Do placeholder-like conversion on the LHS; note that we should
15568 // not get here with a PseudoObject LHS.
15569 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15570 if (checkPlaceholderForOverload(*this, Args[0]))
15571 return ExprError();
15572
15573 // If this is the assignment operator, we only perform overload resolution
15574 // if the left-hand side is a class or enumeration type. This is actually
15575 // a hack. The standard requires that we do overload resolution between the
15576 // various built-in candidates, but as DR507 points out, this can lead to
15577 // problems. So we do it this way, which pretty much follows what GCC does.
15578 // Note that we go the traditional code path for compound assignment forms.
15579 // In HLSL, user-defined structs/classes do not have constructors or
15580 // overloadable assignment operators, so we can take this shortcut too.
15581 const Type *LHSTy = Args[0]->getType().getTypePtr();
15582 if (Opc == BO_Assign &&
15583 (!LHSTy->isOverloadableType() ||
15584 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15586 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15587
15588 // Build the overload set.
15591 Op, OpLoc, AllowRewrittenCandidates));
15592 if (DefaultedFn)
15593 CandidateSet.exclude(DefaultedFn);
15594 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15595
15596 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15597
15598 // Perform overload resolution.
15600 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15601 case OR_Success: {
15602 // We found a built-in operator or an overloaded operator.
15603 FunctionDecl *FnDecl = Best->Function;
15604
15605 bool IsReversed = Best->isReversed();
15606 if (IsReversed)
15607 std::swap(Args[0], Args[1]);
15608
15609 if (FnDecl) {
15610
15611 if (FnDecl->isInvalidDecl())
15612 return ExprError();
15613
15614 Expr *Base = nullptr;
15615 // We matched an overloaded operator. Build a call to that
15616 // operator.
15617
15618 OverloadedOperatorKind ChosenOp =
15620
15621 // C++2a [over.match.oper]p9:
15622 // If a rewritten operator== candidate is selected by overload
15623 // resolution for an operator@, its return type shall be cv bool
15624 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15625 !FnDecl->getReturnType()->isBooleanType()) {
15626 bool IsExtension =
15628 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15629 : diag::err_ovl_rewrite_equalequal_not_bool)
15630 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15631 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15632 Diag(FnDecl->getLocation(), diag::note_declared_at);
15633 if (!IsExtension)
15634 return ExprError();
15635 }
15636
15637 if (AllowRewrittenCandidates && !IsReversed &&
15638 CandidateSet.getRewriteInfo().isReversible()) {
15639 // We could have reversed this operator, but didn't. Check if some
15640 // reversed form was a viable candidate, and if so, if it had a
15641 // better conversion for either parameter. If so, this call is
15642 // formally ambiguous, and allowing it is an extension.
15644 for (OverloadCandidate &Cand : CandidateSet) {
15645 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15646 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15647 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15649 *this, OpLoc, Cand.Conversions[ArgIdx],
15650 Best->Conversions[ArgIdx]) ==
15652 AmbiguousWith.push_back(Cand.Function);
15653 break;
15654 }
15655 }
15656 }
15657 }
15658
15659 if (!AmbiguousWith.empty()) {
15660 bool AmbiguousWithSelf =
15661 AmbiguousWith.size() == 1 &&
15662 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15663 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15665 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15666 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15667 if (AmbiguousWithSelf) {
15668 Diag(FnDecl->getLocation(),
15669 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15670 // Mark member== const or provide matching != to disallow reversed
15671 // args. Eg.
15672 // struct S { bool operator==(const S&); };
15673 // S()==S();
15674 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15675 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15676 !MD->isConst() &&
15677 !MD->hasCXXExplicitFunctionObjectParameter() &&
15678 Context.hasSameUnqualifiedType(
15679 MD->getFunctionObjectParameterType(),
15680 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15681 Context.hasSameUnqualifiedType(
15682 MD->getFunctionObjectParameterType(),
15683 Args[0]->getType()) &&
15684 Context.hasSameUnqualifiedType(
15685 MD->getFunctionObjectParameterType(),
15686 Args[1]->getType()))
15687 Diag(FnDecl->getLocation(),
15688 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15689 } else {
15690 Diag(FnDecl->getLocation(),
15691 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15692 for (auto *F : AmbiguousWith)
15693 Diag(F->getLocation(),
15694 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15695 }
15696 }
15697 }
15698
15699 // Check for nonnull = nullable.
15700 // This won't be caught in the arg's initialization: the parameter to
15701 // the assignment operator is not marked nonnull.
15702 if (Op == OO_Equal)
15704 Args[1]->getType(), OpLoc);
15705
15706 // Convert the arguments.
15707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15708 // Best->Access is only meaningful for class members.
15709 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15710
15711 ExprResult Arg0, Arg1;
15712 unsigned ParamIdx = 0;
15713 if (Method->isExplicitObjectMemberFunction()) {
15714 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15715 ParamIdx = 1;
15716 } else {
15718 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15719 }
15722 Context, FnDecl->getParamDecl(ParamIdx)),
15723 SourceLocation(), Args[1]);
15724 if (Arg0.isInvalid() || Arg1.isInvalid())
15725 return ExprError();
15726
15727 Base = Args[0] = Arg0.getAs<Expr>();
15728 Args[1] = RHS = Arg1.getAs<Expr>();
15729 } else {
15730 // Convert the arguments.
15733 FnDecl->getParamDecl(0)),
15734 SourceLocation(), Args[0]);
15735 if (Arg0.isInvalid())
15736 return ExprError();
15737
15738 ExprResult Arg1 =
15741 FnDecl->getParamDecl(1)),
15742 SourceLocation(), Args[1]);
15743 if (Arg1.isInvalid())
15744 return ExprError();
15745 Args[0] = LHS = Arg0.getAs<Expr>();
15746 Args[1] = RHS = Arg1.getAs<Expr>();
15747 }
15748
15749 // Build the actual expression node.
15750 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15751 Best->FoundDecl, Base,
15752 HadMultipleCandidates, OpLoc);
15753 if (FnExpr.isInvalid())
15754 return ExprError();
15755
15756 // Determine the result type.
15757 QualType ResultTy = FnDecl->getReturnType();
15759 ResultTy = ResultTy.getNonLValueExprType(Context);
15760
15761 CallExpr *TheCall;
15762 ArrayRef<const Expr *> ArgsArray(Args, 2);
15763 const Expr *ImplicitThis = nullptr;
15764
15765 // We always create a CXXOperatorCallExpr, even for explicit object
15766 // members; CodeGen should take care not to emit the this pointer.
15768 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15770 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15771 IsReversed);
15772
15773 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15774 Method && Method->isImplicitObjectMemberFunction()) {
15775 // Cut off the implicit 'this'.
15776 ImplicitThis = ArgsArray[0];
15777 ArgsArray = ArgsArray.slice(1);
15778 }
15779
15780 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15781 FnDecl))
15782 return ExprError();
15783
15784 if (Op == OO_Equal) {
15785 // Check for a self move.
15786 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15787 // lifetime check.
15789 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15790 Args[1]);
15791 }
15792 if (ImplicitThis) {
15793 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15794 QualType ThisTypeFromDecl = Context.getPointerType(
15795 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15796
15797 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15798 ThisTypeFromDecl);
15799 }
15800
15801 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15802 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15804
15805 ExprResult R = MaybeBindToTemporary(TheCall);
15806 if (R.isInvalid())
15807 return ExprError();
15808
15809 R = CheckForImmediateInvocation(R, FnDecl);
15810 if (R.isInvalid())
15811 return ExprError();
15812
15813 // For a rewritten candidate, we've already reversed the arguments
15814 // if needed. Perform the rest of the rewrite now.
15815 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15816 (Op == OO_Spaceship && IsReversed)) {
15817 if (Op == OO_ExclaimEqual) {
15818 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15819 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15820 } else {
15821 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15822 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15823 Expr *ZeroLiteral =
15825
15828 Ctx.Entity = FnDecl;
15830
15832 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15833 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15834 /*AllowRewrittenCandidates=*/false);
15835
15837 }
15838 if (R.isInvalid())
15839 return ExprError();
15840 } else {
15841 assert(ChosenOp == Op && "unexpected operator name");
15842 }
15843
15844 // Make a note in the AST if we did any rewriting.
15845 if (Best->RewriteKind != CRK_None)
15846 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15847
15848 return R;
15849 } else {
15850 // We matched a built-in operator. Convert the arguments, then
15851 // break out so that we will build the appropriate built-in
15852 // operator node.
15854 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15857 if (ArgsRes0.isInvalid())
15858 return ExprError();
15859 Args[0] = ArgsRes0.get();
15860
15862 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15865 if (ArgsRes1.isInvalid())
15866 return ExprError();
15867 Args[1] = ArgsRes1.get();
15868 break;
15869 }
15870 }
15871
15872 case OR_No_Viable_Function: {
15873 // C++ [over.match.oper]p9:
15874 // If the operator is the operator , [...] and there are no
15875 // viable functions, then the operator is assumed to be the
15876 // built-in operator and interpreted according to clause 5.
15877 if (Opc == BO_Comma)
15878 break;
15879
15880 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15881 // compare result using '==' and '<'.
15882 if (DefaultedFn && Opc == BO_Cmp) {
15883 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15884 Args[1], DefaultedFn);
15885 if (E.isInvalid() || E.isUsable())
15886 return E;
15887 }
15888
15889 // For class as left operand for assignment or compound assignment
15890 // operator do not fall through to handling in built-in, but report that
15891 // no overloaded assignment operator found
15893 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15894 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15895 Args, OpLoc);
15896 DeferDiagsRAII DDR(*this,
15897 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15898 if (Args[0]->getType()->isRecordType() &&
15899 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15900 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15902 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15903 if (Args[0]->getType()->isIncompleteType()) {
15904 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15905 << Args[0]->getType()
15906 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15907 }
15908 } else {
15909 // This is an erroneous use of an operator which can be overloaded by
15910 // a non-member function. Check for non-member operators which were
15911 // defined too late to be candidates.
15912 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15913 // FIXME: Recover by calling the found function.
15914 return ExprError();
15915
15916 // No viable function; try to create a built-in operation, which will
15917 // produce an error. Then, show the non-viable candidates.
15918 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15919 }
15920 assert(Result.isInvalid() &&
15921 "C++ binary operator overloading is missing candidates!");
15922 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15923 return Result;
15924 }
15925
15926 case OR_Ambiguous:
15927 CandidateSet.NoteCandidates(
15928 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15930 << Args[0]->getType()
15931 << Args[1]->getType()
15932 << Args[0]->getSourceRange()
15933 << Args[1]->getSourceRange()),
15935 OpLoc);
15936 return ExprError();
15937
15938 case OR_Deleted: {
15939 if (isImplicitlyDeleted(Best->Function)) {
15940 FunctionDecl *DeletedFD = Best->Function;
15942 if (DFK.isSpecialMember()) {
15943 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15944 << Args[0]->getType() << DFK.asSpecialMember();
15945 } else {
15946 assert(DFK.isComparison());
15947 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15948 << Args[0]->getType() << DeletedFD;
15949 }
15950
15951 // The user probably meant to call this special member. Just
15952 // explain why it's deleted.
15953 NoteDeletedFunction(DeletedFD);
15954 return ExprError();
15955 }
15956
15957 StringLiteral *Msg = Best->Function->getDeletedMessage();
15958 CandidateSet.NoteCandidates(
15960 OpLoc,
15961 PDiag(diag::err_ovl_deleted_oper)
15962 << getOperatorSpelling(Best->Function->getDeclName()
15963 .getCXXOverloadedOperator())
15964 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15965 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15967 OpLoc);
15968 return ExprError();
15969 }
15970 }
15971
15972 // We matched a built-in operator; build it.
15973 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15974}
15975
15977 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15978 FunctionDecl *DefaultedFn) {
15979 const ComparisonCategoryInfo *Info =
15980 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15981 // If we're not producing a known comparison category type, we can't
15982 // synthesize a three-way comparison. Let the caller diagnose this.
15983 if (!Info)
15984 return ExprResult((Expr*)nullptr);
15985
15986 // If we ever want to perform this synthesis more generally, we will need to
15987 // apply the temporary materialization conversion to the operands.
15988 assert(LHS->isGLValue() && RHS->isGLValue() &&
15989 "cannot use prvalue expressions more than once");
15990 Expr *OrigLHS = LHS;
15991 Expr *OrigRHS = RHS;
15992
15993 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15994 // each of them multiple times below.
15995 LHS = new (Context)
15996 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15997 LHS->getObjectKind(), LHS);
15998 RHS = new (Context)
15999 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16000 RHS->getObjectKind(), RHS);
16001
16002 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
16003 DefaultedFn);
16004 if (Eq.isInvalid())
16005 return ExprError();
16006
16007 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
16008 true, DefaultedFn);
16009 if (Less.isInvalid())
16010 return ExprError();
16011
16013 if (Info->isPartial()) {
16014 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16015 DefaultedFn);
16016 if (Greater.isInvalid())
16017 return ExprError();
16018 }
16019
16020 // Form the list of comparisons we're going to perform.
16021 struct Comparison {
16024 } Comparisons[4] =
16030 };
16031
16032 int I = Info->isPartial() ? 3 : 2;
16033
16034 // Combine the comparisons with suitable conditional expressions.
16036 for (; I >= 0; --I) {
16037 // Build a reference to the comparison category constant.
16038 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16039 // FIXME: Missing a constant for a comparison category. Diagnose this?
16040 if (!VI)
16041 return ExprResult((Expr*)nullptr);
16042 ExprResult ThisResult =
16044 if (ThisResult.isInvalid())
16045 return ExprError();
16046
16047 // Build a conditional unless this is the final case.
16048 if (Result.get()) {
16049 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16050 ThisResult.get(), Result.get());
16051 if (Result.isInvalid())
16052 return ExprError();
16053 } else {
16054 Result = ThisResult;
16055 }
16056 }
16057
16058 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16059 // bind the OpaqueValueExprs before they're (repeatedly) used.
16060 Expr *SyntacticForm = BinaryOperator::Create(
16061 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16062 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16064 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16065 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16066}
16067
16069 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16070 MultiExprArg Args, SourceLocation LParenLoc) {
16071
16072 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16073 unsigned NumParams = Proto->getNumParams();
16074 unsigned NumArgsSlots =
16075 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16076 // Build the full argument list for the method call (the implicit object
16077 // parameter is placed at the beginning of the list).
16078 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16079 bool IsError = false;
16080 // Initialize the implicit object parameter.
16081 // Check the argument types.
16082 for (unsigned i = 0; i != NumParams; i++) {
16083 Expr *Arg;
16084 if (i < Args.size()) {
16085 Arg = Args[i];
16086 ExprResult InputInit =
16088 S.Context, Method->getParamDecl(i)),
16089 SourceLocation(), Arg);
16090 IsError |= InputInit.isInvalid();
16091 Arg = InputInit.getAs<Expr>();
16092 } else {
16093 ExprResult DefArg =
16094 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16095 if (DefArg.isInvalid()) {
16096 IsError = true;
16097 break;
16098 }
16099 Arg = DefArg.getAs<Expr>();
16100 }
16101
16102 MethodArgs.push_back(Arg);
16103 }
16104 return IsError;
16105}
16106
16108 SourceLocation RLoc,
16109 Expr *Base,
16110 MultiExprArg ArgExpr) {
16112 Args.push_back(Base);
16113 for (auto *e : ArgExpr) {
16114 Args.push_back(e);
16115 }
16116 DeclarationName OpName =
16117 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16118
16119 SourceRange Range = ArgExpr.empty()
16120 ? SourceRange{}
16121 : SourceRange(ArgExpr.front()->getBeginLoc(),
16122 ArgExpr.back()->getEndLoc());
16123
16124 // If either side is type-dependent, create an appropriate dependent
16125 // expression.
16127
16128 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16129 // CHECKME: no 'operator' keyword?
16130 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16131 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16133 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16134 if (Fn.isInvalid())
16135 return ExprError();
16136 // Can't add any actual overloads yet
16137
16138 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16139 Context.DependentTy, VK_PRValue, RLoc,
16141 }
16142
16143 // Handle placeholders
16144 UnbridgedCastsSet UnbridgedCasts;
16145 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16146 return ExprError();
16147 }
16148 // Build an empty overload set.
16150
16151 // Subscript can only be overloaded as a member function.
16152
16153 // Add operator candidates that are member functions.
16154 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16155
16156 // Add builtin operator candidates.
16157 if (Args.size() == 2)
16158 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16159
16160 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16161
16162 // Perform overload resolution.
16164 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16165 case OR_Success: {
16166 // We found a built-in operator or an overloaded operator.
16167 FunctionDecl *FnDecl = Best->Function;
16168
16169 if (FnDecl) {
16170 // We matched an overloaded operator. Build a call to that
16171 // operator.
16172
16173 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16174
16175 // Convert the arguments.
16177 SmallVector<Expr *, 2> MethodArgs;
16178
16179 // Initialize the object parameter.
16180 if (Method->isExplicitObjectMemberFunction()) {
16181 ExprResult Res =
16183 if (Res.isInvalid())
16184 return ExprError();
16185 Args[0] = Res.get();
16186 ArgExpr = Args;
16187 } else {
16189 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16190 if (Arg0.isInvalid())
16191 return ExprError();
16192
16193 MethodArgs.push_back(Arg0.get());
16194 }
16195
16197 *this, MethodArgs, Method, ArgExpr, LLoc);
16198 if (IsError)
16199 return ExprError();
16200
16201 // Build the actual expression node.
16202 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16203 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16205 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16206 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16207 if (FnExpr.isInvalid())
16208 return ExprError();
16209
16210 // Determine the result type
16211 QualType ResultTy = FnDecl->getReturnType();
16213 ResultTy = ResultTy.getNonLValueExprType(Context);
16214
16216 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16218
16219 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16220 return ExprError();
16221
16222 if (CheckFunctionCall(Method, TheCall,
16223 Method->getType()->castAs<FunctionProtoType>()))
16224 return ExprError();
16225
16227 FnDecl);
16228 } else {
16229 // We matched a built-in operator. Convert the arguments, then
16230 // break out so that we will build the appropriate built-in
16231 // operator node.
16233 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16236 if (ArgsRes0.isInvalid())
16237 return ExprError();
16238 Args[0] = ArgsRes0.get();
16239
16241 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16244 if (ArgsRes1.isInvalid())
16245 return ExprError();
16246 Args[1] = ArgsRes1.get();
16247
16248 break;
16249 }
16250 }
16251
16252 case OR_No_Viable_Function: {
16254 CandidateSet.empty()
16255 ? (PDiag(diag::err_ovl_no_oper)
16256 << Args[0]->getType() << /*subscript*/ 0
16257 << Args[0]->getSourceRange() << Range)
16258 : (PDiag(diag::err_ovl_no_viable_subscript)
16259 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16260 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16261 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16262 return ExprError();
16263 }
16264
16265 case OR_Ambiguous:
16266 if (Args.size() == 2) {
16267 CandidateSet.NoteCandidates(
16269 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16270 << "[]" << Args[0]->getType() << Args[1]->getType()
16271 << Args[0]->getSourceRange() << Range),
16272 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16273 } else {
16274 CandidateSet.NoteCandidates(
16276 PDiag(diag::err_ovl_ambiguous_subscript_call)
16277 << Args[0]->getType()
16278 << Args[0]->getSourceRange() << Range),
16279 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16280 }
16281 return ExprError();
16282
16283 case OR_Deleted: {
16284 StringLiteral *Msg = Best->Function->getDeletedMessage();
16285 CandidateSet.NoteCandidates(
16287 PDiag(diag::err_ovl_deleted_oper)
16288 << "[]" << (Msg != nullptr)
16289 << (Msg ? Msg->getString() : StringRef())
16290 << Args[0]->getSourceRange() << Range),
16291 *this, OCD_AllCandidates, Args, "[]", LLoc);
16292 return ExprError();
16293 }
16294 }
16295
16296 // We matched a built-in operator; build it.
16297 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16298}
16299
16301 SourceLocation LParenLoc,
16302 MultiExprArg Args,
16303 SourceLocation RParenLoc,
16304 Expr *ExecConfig, bool IsExecConfig,
16305 bool AllowRecovery) {
16306 assert(MemExprE->getType() == Context.BoundMemberTy ||
16307 MemExprE->getType() == Context.OverloadTy);
16308
16309 // Dig out the member expression. This holds both the object
16310 // argument and the member function we're referring to.
16311 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16312
16313 // Determine whether this is a call to a pointer-to-member function.
16314 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16315 assert(op->getType() == Context.BoundMemberTy);
16316 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16317
16318 QualType fnType =
16319 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16320
16321 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16322 QualType resultType = proto->getCallResultType(Context);
16324
16325 // Check that the object type isn't more qualified than the
16326 // member function we're calling.
16327 Qualifiers funcQuals = proto->getMethodQuals();
16328
16329 QualType objectType = op->getLHS()->getType();
16330 if (op->getOpcode() == BO_PtrMemI)
16331 objectType = objectType->castAs<PointerType>()->getPointeeType();
16332 Qualifiers objectQuals = objectType.getQualifiers();
16333
16334 Qualifiers difference = objectQuals - funcQuals;
16335 difference.removeObjCGCAttr();
16336 difference.removeAddressSpace();
16337 if (difference) {
16338 std::string qualsString = difference.getAsString();
16339 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16340 << fnType.getUnqualifiedType()
16341 << qualsString
16342 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16343 }
16344
16346 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16348
16349 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16350 call, nullptr))
16351 return ExprError();
16352
16353 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16354 return ExprError();
16355
16356 if (CheckOtherCall(call, proto))
16357 return ExprError();
16358
16359 return MaybeBindToTemporary(call);
16360 }
16361
16362 // We only try to build a recovery expr at this level if we can preserve
16363 // the return type, otherwise we return ExprError() and let the caller
16364 // recover.
16365 auto BuildRecoveryExpr = [&](QualType Type) {
16366 if (!AllowRecovery)
16367 return ExprError();
16368 std::vector<Expr *> SubExprs = {MemExprE};
16369 llvm::append_range(SubExprs, Args);
16370 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16371 Type);
16372 };
16373 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16374 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16375 RParenLoc, CurFPFeatureOverrides());
16376
16377 UnbridgedCastsSet UnbridgedCasts;
16378 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16379 return ExprError();
16380
16381 MemberExpr *MemExpr;
16382 CXXMethodDecl *Method = nullptr;
16383 bool HadMultipleCandidates = false;
16384 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16385 NestedNameSpecifier Qualifier = std::nullopt;
16386 if (isa<MemberExpr>(NakedMemExpr)) {
16387 MemExpr = cast<MemberExpr>(NakedMemExpr);
16389 FoundDecl = MemExpr->getFoundDecl();
16390 Qualifier = MemExpr->getQualifier();
16391 UnbridgedCasts.restore();
16392 } else {
16393 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16394 Qualifier = UnresExpr->getQualifier();
16395
16396 QualType ObjectType = UnresExpr->getBaseType();
16397 Expr::Classification ObjectClassification
16399 : UnresExpr->getBase()->Classify(Context);
16400
16401 // Add overload candidates
16402 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16404
16405 // FIXME: avoid copy.
16406 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16407 if (UnresExpr->hasExplicitTemplateArgs()) {
16408 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16409 TemplateArgs = &TemplateArgsBuffer;
16410 }
16411
16413 E = UnresExpr->decls_end(); I != E; ++I) {
16414
16415 QualType ExplicitObjectType = ObjectType;
16416
16417 NamedDecl *Func = *I;
16418 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16420 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16421
16422 bool HasExplicitParameter = false;
16423 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16424 M && M->hasCXXExplicitFunctionObjectParameter())
16425 HasExplicitParameter = true;
16426 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16427 M &&
16428 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16429 HasExplicitParameter = true;
16430
16431 if (HasExplicitParameter)
16432 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16433
16434 // Microsoft supports direct constructor calls.
16435 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16437 CandidateSet,
16438 /*SuppressUserConversions*/ false);
16439 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16440 // If explicit template arguments were provided, we can't call a
16441 // non-template member function.
16442 if (TemplateArgs)
16443 continue;
16444
16445 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16446 ObjectClassification, Args, CandidateSet,
16447 /*SuppressUserConversions=*/false);
16448 } else {
16450 I.getPair(), ActingDC, TemplateArgs,
16451 ExplicitObjectType, ObjectClassification,
16452 Args, CandidateSet,
16453 /*SuppressUserConversions=*/false);
16454 }
16455 }
16456
16457 HadMultipleCandidates = (CandidateSet.size() > 1);
16458
16459 DeclarationName DeclName = UnresExpr->getMemberName();
16460
16461 UnbridgedCasts.restore();
16462
16464 bool Succeeded = false;
16465 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16466 Best)) {
16467 case OR_Success:
16468 Method = cast<CXXMethodDecl>(Best->Function);
16469 FoundDecl = Best->FoundDecl;
16470 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16471 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16472 break;
16473 // If FoundDecl is different from Method (such as if one is a template
16474 // and the other a specialization), make sure DiagnoseUseOfDecl is
16475 // called on both.
16476 // FIXME: This would be more comprehensively addressed by modifying
16477 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16478 // being used.
16479 if (Method != FoundDecl.getDecl() &&
16481 break;
16482 Succeeded = true;
16483 break;
16484
16486 CandidateSet.NoteCandidates(
16488 UnresExpr->getMemberLoc(),
16489 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16490 << DeclName << MemExprE->getSourceRange()),
16491 *this, OCD_AllCandidates, Args);
16492 break;
16493 case OR_Ambiguous:
16494 CandidateSet.NoteCandidates(
16495 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16496 PDiag(diag::err_ovl_ambiguous_member_call)
16497 << DeclName << MemExprE->getSourceRange()),
16498 *this, OCD_AmbiguousCandidates, Args);
16499 break;
16500 case OR_Deleted:
16502 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16503 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16504 break;
16505 }
16506 // Overload resolution fails, try to recover.
16507 if (!Succeeded)
16508 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16509
16510 ExprResult Res =
16511 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16512 if (Res.isInvalid())
16513 return ExprError();
16514 MemExprE = Res.get();
16515
16516 // If overload resolution picked a static member
16517 // build a non-member call based on that function.
16518 if (Method->isStatic()) {
16519 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16520 ExecConfig, IsExecConfig);
16521 }
16522
16523 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16524 }
16525
16526 QualType ResultType = Method->getReturnType();
16528 ResultType = ResultType.getNonLValueExprType(Context);
16529
16530 assert(Method && "Member call to something that isn't a method?");
16531 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16532
16533 CallExpr *TheCall = nullptr;
16535 if (Method->isExplicitObjectMemberFunction()) {
16536 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16537 NewArgs))
16538 return ExprError();
16539
16540 // Build the actual expression node.
16541 ExprResult FnExpr =
16542 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16543 HadMultipleCandidates, MemExpr->getExprLoc());
16544 if (FnExpr.isInvalid())
16545 return ExprError();
16546
16547 TheCall =
16548 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16549 CurFPFeatureOverrides(), Proto->getNumParams());
16550 TheCall->setUsesMemberSyntax(true);
16551 } else {
16552 // Convert the object argument (for a non-static member function call).
16554 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16555 if (ObjectArg.isInvalid())
16556 return ExprError();
16557 MemExpr->setBase(ObjectArg.get());
16558 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16559 RParenLoc, CurFPFeatureOverrides(),
16560 Proto->getNumParams());
16561 }
16562
16563 // Check for a valid return type.
16564 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16565 TheCall, Method))
16566 return BuildRecoveryExpr(ResultType);
16567
16568 // Convert the rest of the arguments
16569 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16570 RParenLoc))
16571 return BuildRecoveryExpr(ResultType);
16572
16573 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16574
16575 if (CheckFunctionCall(Method, TheCall, Proto))
16576 return ExprError();
16577
16578 // In the case the method to call was not selected by the overloading
16579 // resolution process, we still need to handle the enable_if attribute. Do
16580 // that here, so it will not hide previous -- and more relevant -- errors.
16581 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16582 if (const EnableIfAttr *Attr =
16583 CheckEnableIf(Method, LParenLoc, Args, true)) {
16584 Diag(MemE->getMemberLoc(),
16585 diag::err_ovl_no_viable_member_function_in_call)
16586 << Method << Method->getSourceRange();
16587 Diag(Method->getLocation(),
16588 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16589 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16590 return ExprError();
16591 }
16592 }
16593
16595 TheCall->getDirectCallee()->isPureVirtual()) {
16596 const FunctionDecl *MD = TheCall->getDirectCallee();
16597
16598 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16600 Diag(MemExpr->getBeginLoc(),
16601 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16603 << MD->getParent();
16604
16605 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16606 if (getLangOpts().AppleKext)
16607 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16608 << MD->getParent() << MD->getDeclName();
16609 }
16610 }
16611
16612 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16613 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16614 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16615 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16616 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16617 MemExpr->getMemberLoc());
16618 }
16619
16621 TheCall->getDirectCallee());
16622}
16623
16626 SourceLocation LParenLoc,
16627 MultiExprArg Args,
16628 SourceLocation RParenLoc) {
16629 if (checkPlaceholderForOverload(*this, Obj))
16630 return ExprError();
16631 ExprResult Object = Obj;
16632
16633 UnbridgedCastsSet UnbridgedCasts;
16634 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16635 return ExprError();
16636
16637 assert(Object.get()->getType()->isRecordType() &&
16638 "Requires object type argument");
16639
16640 // C++ [over.call.object]p1:
16641 // If the primary-expression E in the function call syntax
16642 // evaluates to a class object of type "cv T", then the set of
16643 // candidate functions includes at least the function call
16644 // operators of T. The function call operators of T are obtained by
16645 // ordinary lookup of the name operator() in the context of
16646 // (E).operator().
16647 OverloadCandidateSet CandidateSet(LParenLoc,
16649 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16650
16651 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16652 diag::err_incomplete_object_call, Object.get()))
16653 return true;
16654
16655 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16656 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16658 R.suppressAccessDiagnostics();
16659
16660 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16661 Oper != OperEnd; ++Oper) {
16662 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16663 Object.get()->Classify(Context), Args, CandidateSet,
16664 /*SuppressUserConversion=*/false);
16665 }
16666
16667 // When calling a lambda, both the call operator, and
16668 // the conversion operator to function pointer
16669 // are considered. But when constraint checking
16670 // on the call operator fails, it will also fail on the
16671 // conversion operator as the constraints are always the same.
16672 // As the user probably does not intend to perform a surrogate call,
16673 // we filter them out to produce better error diagnostics, ie to avoid
16674 // showing 2 failed overloads instead of one.
16675 bool IgnoreSurrogateFunctions = false;
16676 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16677 const OverloadCandidate &Candidate = *CandidateSet.begin();
16678 if (!Candidate.Viable &&
16680 IgnoreSurrogateFunctions = true;
16681 }
16682
16683 // C++ [over.call.object]p2:
16684 // In addition, for each (non-explicit in C++0x) conversion function
16685 // declared in T of the form
16686 //
16687 // operator conversion-type-id () cv-qualifier;
16688 //
16689 // where cv-qualifier is the same cv-qualification as, or a
16690 // greater cv-qualification than, cv, and where conversion-type-id
16691 // denotes the type "pointer to function of (P1,...,Pn) returning
16692 // R", or the type "reference to pointer to function of
16693 // (P1,...,Pn) returning R", or the type "reference to function
16694 // of (P1,...,Pn) returning R", a surrogate call function [...]
16695 // is also considered as a candidate function. Similarly,
16696 // surrogate call functions are added to the set of candidate
16697 // functions for each conversion function declared in an
16698 // accessible base class provided the function is not hidden
16699 // within T by another intervening declaration.
16700 const auto &Conversions = Record->getVisibleConversionFunctions();
16701 for (auto I = Conversions.begin(), E = Conversions.end();
16702 !IgnoreSurrogateFunctions && I != E; ++I) {
16703 NamedDecl *D = *I;
16704 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16705 if (isa<UsingShadowDecl>(D))
16706 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16707
16708 // Skip over templated conversion functions; they aren't
16709 // surrogates.
16711 continue;
16712
16714 if (!Conv->isExplicit()) {
16715 // Strip the reference type (if any) and then the pointer type (if
16716 // any) to get down to what might be a function type.
16717 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16718 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16719 ConvType = ConvPtrType->getPointeeType();
16720
16721 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16722 {
16723 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16724 Object.get(), Args, CandidateSet);
16725 }
16726 }
16727 }
16728
16729 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16730
16731 // Perform overload resolution.
16733 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16734 Best)) {
16735 case OR_Success:
16736 // Overload resolution succeeded; we'll build the appropriate call
16737 // below.
16738 break;
16739
16740 case OR_No_Viable_Function: {
16742 CandidateSet.empty()
16743 ? (PDiag(diag::err_ovl_no_oper)
16744 << Object.get()->getType() << /*call*/ 1
16745 << Object.get()->getSourceRange())
16746 : (PDiag(diag::err_ovl_no_viable_object_call)
16747 << Object.get()->getType() << Object.get()->getSourceRange());
16748 CandidateSet.NoteCandidates(
16749 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16750 OCD_AllCandidates, Args);
16751 break;
16752 }
16753 case OR_Ambiguous:
16754 if (!R.isAmbiguous())
16755 CandidateSet.NoteCandidates(
16756 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16757 PDiag(diag::err_ovl_ambiguous_object_call)
16758 << Object.get()->getType()
16759 << Object.get()->getSourceRange()),
16760 *this, OCD_AmbiguousCandidates, Args);
16761 break;
16762
16763 case OR_Deleted: {
16764 // FIXME: Is this diagnostic here really necessary? It seems that
16765 // 1. we don't have any tests for this diagnostic, and
16766 // 2. we already issue err_deleted_function_use for this later on anyway.
16767 StringLiteral *Msg = Best->Function->getDeletedMessage();
16768 CandidateSet.NoteCandidates(
16769 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16770 PDiag(diag::err_ovl_deleted_object_call)
16771 << Object.get()->getType() << (Msg != nullptr)
16772 << (Msg ? Msg->getString() : StringRef())
16773 << Object.get()->getSourceRange()),
16774 *this, OCD_AllCandidates, Args);
16775 break;
16776 }
16777 }
16778
16779 if (Best == CandidateSet.end())
16780 return true;
16781
16782 UnbridgedCasts.restore();
16783
16784 if (Best->Function == nullptr) {
16785 // Since there is no function declaration, this is one of the
16786 // surrogate candidates. Dig out the conversion function.
16787 CXXConversionDecl *Conv
16789 Best->Conversions[0].UserDefined.ConversionFunction);
16790
16791 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16792 Best->FoundDecl);
16793 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16794 return ExprError();
16795 assert(Conv == Best->FoundDecl.getDecl() &&
16796 "Found Decl & conversion-to-functionptr should be same, right?!");
16797 // We selected one of the surrogate functions that converts the
16798 // object parameter to a function pointer. Perform the conversion
16799 // on the object argument, then let BuildCallExpr finish the job.
16800
16801 // Create an implicit member expr to refer to the conversion operator.
16802 // and then call it.
16803 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16804 Conv, HadMultipleCandidates);
16805 if (Call.isInvalid())
16806 return ExprError();
16807 // Record usage of conversion in an implicit cast.
16809 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16810 nullptr, VK_PRValue, CurFPFeatureOverrides());
16811
16812 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16813 }
16814
16815 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16816
16817 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16818 // that calls this method, using Object for the implicit object
16819 // parameter and passing along the remaining arguments.
16820 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16821
16822 // An error diagnostic has already been printed when parsing the declaration.
16823 if (Method->isInvalidDecl())
16824 return ExprError();
16825
16826 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16827 unsigned NumParams = Proto->getNumParams();
16828
16829 DeclarationNameInfo OpLocInfo(
16830 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16831 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16832 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16833 Obj, HadMultipleCandidates,
16834 OpLocInfo.getLoc(),
16835 OpLocInfo.getInfo());
16836 if (NewFn.isInvalid())
16837 return true;
16838
16839 SmallVector<Expr *, 8> MethodArgs;
16840 MethodArgs.reserve(NumParams + 1);
16841
16842 bool IsError = false;
16843
16844 // Initialize the object parameter.
16846 if (Method->isExplicitObjectMemberFunction()) {
16847 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16848 } else {
16850 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16851 if (ObjRes.isInvalid())
16852 IsError = true;
16853 else
16854 Object = ObjRes;
16855 MethodArgs.push_back(Object.get());
16856 }
16857
16859 *this, MethodArgs, Method, Args, LParenLoc);
16860
16861 // If this is a variadic call, handle args passed through "...".
16862 if (Proto->isVariadic()) {
16863 // Promote the arguments (C99 6.5.2.2p7).
16864 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16866 Args[i], VariadicCallType::Method, nullptr);
16867 IsError |= Arg.isInvalid();
16868 MethodArgs.push_back(Arg.get());
16869 }
16870 }
16871
16872 if (IsError)
16873 return true;
16874
16875 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16876
16877 // Once we've built TheCall, all of the expressions are properly owned.
16878 QualType ResultTy = Method->getReturnType();
16880 ResultTy = ResultTy.getNonLValueExprType(Context);
16881
16883 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16885
16886 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16887 return true;
16888
16889 if (CheckFunctionCall(Method, TheCall, Proto))
16890 return true;
16891
16893}
16894
16896 SourceLocation OpLoc,
16897 bool *NoArrowOperatorFound) {
16898 assert(Base->getType()->isRecordType() &&
16899 "left-hand side must have class type");
16900
16902 return ExprError();
16903
16904 SourceLocation Loc = Base->getExprLoc();
16905
16906 // C++ [over.ref]p1:
16907 //
16908 // [...] An expression x->m is interpreted as (x.operator->())->m
16909 // for a class object x of type T if T::operator->() exists and if
16910 // the operator is selected as the best match function by the
16911 // overload resolution mechanism (13.3).
16912 DeclarationName OpName =
16913 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16915
16916 if (RequireCompleteType(Loc, Base->getType(),
16917 diag::err_typecheck_incomplete_tag, Base))
16918 return ExprError();
16919
16920 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16921 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16922 R.suppressAccessDiagnostics();
16923
16924 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16925 Oper != OperEnd; ++Oper) {
16926 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16927 {}, CandidateSet,
16928 /*SuppressUserConversion=*/false);
16929 }
16930
16931 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16932
16933 // Perform overload resolution.
16935 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16936 case OR_Success:
16937 // Overload resolution succeeded; we'll build the call below.
16938 break;
16939
16940 case OR_No_Viable_Function: {
16941 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16942 if (CandidateSet.empty()) {
16943 QualType BaseType = Base->getType();
16944 if (NoArrowOperatorFound) {
16945 // Report this specific error to the caller instead of emitting a
16946 // diagnostic, as requested.
16947 *NoArrowOperatorFound = true;
16948 return ExprError();
16949 }
16950 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16951 << BaseType << Base->getSourceRange();
16952 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16953 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16954 << FixItHint::CreateReplacement(OpLoc, ".");
16955 }
16956 } else
16957 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16958 << "operator->" << Base->getSourceRange();
16959 CandidateSet.NoteCandidates(*this, Base, Cands);
16960 return ExprError();
16961 }
16962 case OR_Ambiguous:
16963 if (!R.isAmbiguous())
16964 CandidateSet.NoteCandidates(
16965 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16966 << "->" << Base->getType()
16967 << Base->getSourceRange()),
16969 return ExprError();
16970
16971 case OR_Deleted: {
16972 StringLiteral *Msg = Best->Function->getDeletedMessage();
16973 CandidateSet.NoteCandidates(
16974 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16975 << "->" << (Msg != nullptr)
16976 << (Msg ? Msg->getString() : StringRef())
16977 << Base->getSourceRange()),
16978 *this, OCD_AllCandidates, Base);
16979 return ExprError();
16980 }
16981 }
16982
16983 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16984
16985 // Convert the object parameter.
16986 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16987
16988 if (Method->isExplicitObjectMemberFunction()) {
16990 if (R.isInvalid())
16991 return ExprError();
16992 Base = R.get();
16993 } else {
16995 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16996 if (BaseResult.isInvalid())
16997 return ExprError();
16998 Base = BaseResult.get();
16999 }
17000
17001 // Build the operator call.
17002 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
17003 Base, HadMultipleCandidates, OpLoc);
17004 if (FnExpr.isInvalid())
17005 return ExprError();
17006
17007 QualType ResultTy = Method->getReturnType();
17009 ResultTy = ResultTy.getNonLValueExprType(Context);
17010
17011 CallExpr *TheCall =
17012 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17013 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17014
17015 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17016 return ExprError();
17017
17018 if (CheckFunctionCall(Method, TheCall,
17019 Method->getType()->castAs<FunctionProtoType>()))
17020 return ExprError();
17021
17023}
17024
17026 DeclarationNameInfo &SuffixInfo,
17027 ArrayRef<Expr*> Args,
17028 SourceLocation LitEndLoc,
17029 TemplateArgumentListInfo *TemplateArgs) {
17030 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17031
17032 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17034 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17035 TemplateArgs);
17036
17037 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17038
17039 // Perform overload resolution. This will usually be trivial, but might need
17040 // to perform substitutions for a literal operator template.
17042 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17043 case OR_Success:
17044 case OR_Deleted:
17045 break;
17046
17048 CandidateSet.NoteCandidates(
17049 PartialDiagnosticAt(UDSuffixLoc,
17050 PDiag(diag::err_ovl_no_viable_function_in_call)
17051 << R.getLookupName()),
17052 *this, OCD_AllCandidates, Args);
17053 return ExprError();
17054
17055 case OR_Ambiguous:
17056 CandidateSet.NoteCandidates(
17057 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17058 << R.getLookupName()),
17059 *this, OCD_AmbiguousCandidates, Args);
17060 return ExprError();
17061 }
17062
17063 FunctionDecl *FD = Best->Function;
17064 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
17065 nullptr, HadMultipleCandidates,
17066 SuffixInfo.getLoc(),
17067 SuffixInfo.getInfo());
17068 if (Fn.isInvalid())
17069 return true;
17070
17071 // Check the argument types. This should almost always be a no-op, except
17072 // that array-to-pointer decay is applied to string literals.
17073 Expr *ConvArgs[2];
17074 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17077 SourceLocation(), Args[ArgIdx]);
17078 if (InputInit.isInvalid())
17079 return true;
17080 ConvArgs[ArgIdx] = InputInit.get();
17081 }
17082
17083 QualType ResultTy = FD->getReturnType();
17085 ResultTy = ResultTy.getNonLValueExprType(Context);
17086
17088 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17089 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17090
17091 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17092 return ExprError();
17093
17094 if (CheckFunctionCall(FD, UDL, nullptr))
17095 return ExprError();
17096
17098}
17099
17102 SourceLocation RangeLoc,
17103 const DeclarationNameInfo &NameInfo,
17104 LookupResult &MemberLookup,
17105 OverloadCandidateSet *CandidateSet,
17106 Expr *Range, ExprResult *CallExpr) {
17107 Scope *S = nullptr;
17108
17110 if (!MemberLookup.empty()) {
17111 ExprResult MemberRef =
17112 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17113 /*IsPtr=*/false, CXXScopeSpec(),
17114 /*TemplateKWLoc=*/SourceLocation(),
17115 /*FirstQualifierInScope=*/nullptr,
17116 MemberLookup,
17117 /*TemplateArgs=*/nullptr, S);
17118 if (MemberRef.isInvalid()) {
17119 *CallExpr = ExprError();
17120 return FRS_DiagnosticIssued;
17121 }
17122 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17123 if (CallExpr->isInvalid()) {
17124 *CallExpr = ExprError();
17125 return FRS_DiagnosticIssued;
17126 }
17127 } else {
17128 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17130 NameInfo, UnresolvedSet<0>());
17131 if (FnR.isInvalid())
17132 return FRS_DiagnosticIssued;
17134
17135 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17136 CandidateSet, CallExpr);
17137 if (CandidateSet->empty() || CandidateSetError) {
17138 *CallExpr = ExprError();
17139 return FRS_NoViableFunction;
17140 }
17142 OverloadingResult OverloadResult =
17143 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17144
17145 if (OverloadResult == OR_No_Viable_Function) {
17146 *CallExpr = ExprError();
17147 return FRS_NoViableFunction;
17148 }
17149 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17150 Loc, nullptr, CandidateSet, &Best,
17151 OverloadResult,
17152 /*AllowTypoCorrection=*/false);
17153 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17154 *CallExpr = ExprError();
17155 return FRS_DiagnosticIssued;
17156 }
17157 }
17158 return FRS_Success;
17159}
17160
17162 FunctionDecl *Fn) {
17163 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17164 ExprResult SubExpr =
17165 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17166 if (SubExpr.isInvalid())
17167 return ExprError();
17168 if (SubExpr.get() == PE->getSubExpr())
17169 return PE;
17170
17171 return new (Context)
17172 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17173 }
17174
17175 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17176 ExprResult SubExpr =
17177 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17178 if (SubExpr.isInvalid())
17179 return ExprError();
17180 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17181 SubExpr.get()->getType()) &&
17182 "Implicit cast type cannot be determined from overload");
17183 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17184 if (SubExpr.get() == ICE->getSubExpr())
17185 return ICE;
17186
17187 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17188 SubExpr.get(), nullptr, ICE->getValueKind(),
17190 }
17191
17192 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17193 if (!GSE->isResultDependent()) {
17194 ExprResult SubExpr =
17195 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17196 if (SubExpr.isInvalid())
17197 return ExprError();
17198 if (SubExpr.get() == GSE->getResultExpr())
17199 return GSE;
17200
17201 // Replace the resulting type information before rebuilding the generic
17202 // selection expression.
17203 ArrayRef<Expr *> A = GSE->getAssocExprs();
17204 SmallVector<Expr *, 4> AssocExprs(A);
17205 unsigned ResultIdx = GSE->getResultIndex();
17206 AssocExprs[ResultIdx] = SubExpr.get();
17207
17208 if (GSE->isExprPredicate())
17210 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17211 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17212 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17213 ResultIdx);
17215 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17216 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17217 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17218 ResultIdx);
17219 }
17220 // Rather than fall through to the unreachable, return the original generic
17221 // selection expression.
17222 return GSE;
17223 }
17224
17225 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17226 assert(UnOp->getOpcode() == UO_AddrOf &&
17227 "Can only take the address of an overloaded function");
17228 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17229 if (!Method->isImplicitObjectMemberFunction()) {
17230 // Do nothing: the address of static and
17231 // explicit object member functions is a (non-member) function pointer.
17232 } else {
17233 // Fix the subexpression, which really has to be an
17234 // UnresolvedLookupExpr holding an overloaded member function
17235 // or template.
17236 ExprResult SubExpr =
17237 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17238 if (SubExpr.isInvalid())
17239 return ExprError();
17240 if (SubExpr.get() == UnOp->getSubExpr())
17241 return UnOp;
17242
17243 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17244 SubExpr.get(), Method))
17245 return ExprError();
17246
17247 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17248 "fixed to something other than a decl ref");
17249 NestedNameSpecifier Qualifier =
17250 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17251 assert(Qualifier &&
17252 "fixed to a member ref with no nested name qualifier");
17253
17254 // We have taken the address of a pointer to member
17255 // function. Perform the computation here so that we get the
17256 // appropriate pointer to member type.
17257 QualType MemPtrType = Context.getMemberPointerType(
17258 Fn->getType(), Qualifier,
17259 cast<CXXRecordDecl>(Method->getDeclContext()));
17260 // Under the MS ABI, lock down the inheritance model now.
17261 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17262 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17263
17264 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17265 MemPtrType, VK_PRValue, OK_Ordinary,
17266 UnOp->getOperatorLoc(), false,
17268 }
17269 }
17270 ExprResult SubExpr =
17271 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17272 if (SubExpr.isInvalid())
17273 return ExprError();
17274 if (SubExpr.get() == UnOp->getSubExpr())
17275 return UnOp;
17276
17277 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17278 SubExpr.get());
17279 }
17280
17281 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17282 if (Found.getAccess() == AS_none) {
17284 }
17285 // FIXME: avoid copy.
17286 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17287 if (ULE->hasExplicitTemplateArgs()) {
17288 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17289 TemplateArgs = &TemplateArgsBuffer;
17290 }
17291
17292 QualType Type = Fn->getType();
17293 ExprValueKind ValueKind =
17294 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17295 ? VK_LValue
17296 : VK_PRValue;
17297
17298 // FIXME: Duplicated from BuildDeclarationNameExpr.
17299 if (unsigned BID = Fn->getBuiltinID()) {
17300 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17301 Type = Context.BuiltinFnTy;
17302 ValueKind = VK_PRValue;
17303 }
17304 }
17305
17307 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17308 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17309 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17310 return DRE;
17311 }
17312
17313 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17314 // FIXME: avoid copy.
17315 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17316 if (MemExpr->hasExplicitTemplateArgs()) {
17317 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17318 TemplateArgs = &TemplateArgsBuffer;
17319 }
17320
17321 Expr *Base;
17322
17323 // If we're filling in a static method where we used to have an
17324 // implicit member access, rewrite to a simple decl ref.
17325 if (MemExpr->isImplicitAccess()) {
17326 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17328 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17329 MemExpr->getQualifierLoc(), Found.getDecl(),
17330 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17331 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17332 return DRE;
17333 } else {
17334 SourceLocation Loc = MemExpr->getMemberLoc();
17335 if (MemExpr->getQualifier())
17336 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17337 Base =
17338 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17339 }
17340 } else
17341 Base = MemExpr->getBase();
17342
17343 ExprValueKind valueKind;
17344 QualType type;
17345 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17346 valueKind = VK_LValue;
17347 type = Fn->getType();
17348 } else {
17349 valueKind = VK_PRValue;
17350 type = Context.BoundMemberTy;
17351 }
17352
17353 return BuildMemberExpr(
17354 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17355 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17356 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17357 type, valueKind, OK_Ordinary, TemplateArgs);
17358 }
17359
17360 llvm_unreachable("Invalid reference to overloaded function");
17361}
17362
17368
17369bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17371 if (!PartialOverloading || !Function)
17372 return true;
17373 if (Function->isVariadic())
17374 return false;
17375 if (const auto *Proto =
17376 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17377 if (Proto->isTemplateVariadic())
17378 return false;
17379 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17380 if (const auto *Proto =
17381 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17382 if (Proto->isTemplateVariadic())
17383 return false;
17384 return true;
17385}
17386
17388 DeclarationName Name,
17389 OverloadCandidateSet &CandidateSet,
17390 FunctionDecl *Fn, MultiExprArg Args,
17391 bool IsMember) {
17392 StringLiteral *Msg = Fn->getDeletedMessage();
17393 CandidateSet.NoteCandidates(
17394 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17395 << IsMember << Name << (Msg != nullptr)
17396 << (Msg ? Msg->getString() : StringRef())
17397 << Range),
17398 *this, OCD_AllCandidates, Args);
17399}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
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.
llvm::json::Object Object
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:183
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
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...
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 sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
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 void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
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 bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static 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 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 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 bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
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 hasDependentExplicit(FunctionTemplateDecl *FTD)
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 CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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 ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
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 ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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 void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
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 ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
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)
Sema::AllowedExplicit AllowedExplicit
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 IsMatrixConversion(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 matrix conversion.
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 AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
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 FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
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, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:484
bool isFloat() const
Definition APValue.h:489
bool isInt() const
Definition APValue.h:488
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:993
APFloat & getFloat()
Definition APValue.h:525
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
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.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:812
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
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 NullPtrTy
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:965
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
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...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
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>.
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
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:928
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
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.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
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:927
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
CanQualType getCanonicalTagType(const TagDecl *TD) const
CanQualType WCharTy
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType Char8Ty
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:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3991
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:316
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
QualType getElementType() const
Definition TypeBase.h:3833
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8288
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2189
StringRef getOpcodeStr() const
Definition Expr.h:4110
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2142
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:5107
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Pointer to a block type.
Definition TypeBase.h:3641
This class is used for builtin types like 'int'.
Definition TypeBase.h:3229
Kind getKind() const
Definition TypeBase.h:3277
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3106
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3000
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3004
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:182
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:699
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
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:2719
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:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Definition ExprCXX.cpp:629
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:1023
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1989
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1564
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:289
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
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:1523
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3113
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3331
Represents a canonical, potentially-qualified type.
bool isAtLeastAsQualifiedAs(CanQual< T > Other, const ASTContext &Ctx) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
static CanQual< Type > CreateUnsafe(QualType Other)
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 isVolatileQualified() const
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
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 TypeBase.h:3340
QualType getElementType() const
Definition TypeBase.h:3350
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:5129
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3859
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4486
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4505
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4502
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
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:1469
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:285
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
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...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:787
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:772
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:763
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:599
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4055
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4273
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4171
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1968
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1952
const Expr * getExpr() const
Definition DeclCXX.h:1953
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2370
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:398
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3106
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3350
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4241
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
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:4080
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
ExtVectorType - Extended vector type.
Definition TypeBase.h:4366
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3204
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
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:105
Represents a function declaration or definition.
Definition Decl.h:2029
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2729
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4173
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3742
param_iterator param_end()
Definition Decl.h:2827
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3646
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3845
QualType getReturnType() const
Definition Decl.h:2885
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2814
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:4244
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4293
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3727
param_iterator param_begin()
Definition Decl.h:2826
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3112
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4309
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4237
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3849
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2506
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4110
bool isConsteval() const
Definition Decl.h:2518
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3690
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:2902
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:3695
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3806
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2725
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5910
unsigned getNumParams() const
Definition TypeBase.h:5684
Qualifiers getMethodQuals() const
Definition TypeBase.h:5832
QualType getParamType(unsigned i) const
Definition TypeBase.h:5686
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5810
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5846
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4713
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4784
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4641
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
ExtInfo getExtInfo() const
Definition TypeBase.h:4958
CallingConv getCallConv() const
Definition TypeBase.h:4957
QualType getReturnType() const
Definition TypeBase.h:4942
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4970
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:4728
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:3859
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2081
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
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:673
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:770
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
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:827
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:681
bool hasInitializerListContainerType() const
Definition Overload.h:809
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:734
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:816
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:685
QualType getInitializerListContainerType() const
Definition Overload.h:819
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5314
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5430
unsigned getNumInits() const
Definition Expr.h:5347
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2507
const Expr * getInit(unsigned Init) const
Definition Expr.h:5369
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2525
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, NamedDecl *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:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3716
bool isCompatibleWithMSVC() const
Represents the results of name lookup.
Definition Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition Lookup.h:488
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
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:643
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4450
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3559
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3481
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3467
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3588
Expr * getBase() const
Definition Expr.h:3447
void setBase(Expr *E)
Definition Expr.h:3446
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1802
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3457
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3784
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5646
QualType getPointeeType() const
Definition TypeBase.h:3770
Describes a module or submodule.
Definition Module.h:340
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:240
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
Represent a C++ namespace.
Definition Decl.h:592
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:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8051
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8107
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8196
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8165
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8119
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8159
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8171
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void AddDeferredTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition Overload.h:1360
bool shouldDeferTemplateArgumentDeduction(const Sema &S) const
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1458
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1392
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1408
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1350
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1185
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1190
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
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:1368
SourceLocation getLocation() const
Definition Overload.h:1348
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1349
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1383
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:3131
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3283
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3192
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3247
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3244
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3222
decls_iterator decls_begin() const
Definition ExprCXX.h:3224
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3235
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3257
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3253
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3341
decls_iterator decls_end() const
Definition ExprCXX.h:3227
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3241
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1819
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3037
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5201
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8573
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8567
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8578
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3686
QualType withConst() const
Definition TypeBase.h:1175
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8489
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8615
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8529
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 TypeBase.h:8674
QualType getCanonicalType() const
Definition TypeBase.h:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8643
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8562
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8610
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8535
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8654
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8521
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8429
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8436
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4796
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:854
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:861
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
GC getObjCGCAttr() const
Definition TypeBase.h:520
bool hasOnlyConst() const
Definition TypeBase.h:459
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasConst() const
Definition TypeBase.h:458
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasRestrict() const
Definition TypeBase.h:478
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
void removeObjCGCAttr()
Definition TypeBase.h:524
void removeUnaligned()
Definition TypeBase.h:516
void removeAddressSpace()
Definition TypeBase.h:597
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
bool hasVolatile() const
Definition TypeBase.h:468
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
void removeVolatile()
Definition TypeBase.h:470
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:572
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:751
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3734
Represents a struct/union/class.
Definition Decl.h:4369
field_range fields() const
Definition Decl.h:4572
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4557
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3672
QualType getPointeeType() const
Definition TypeBase.h:3690
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
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...
Definition SemaARM.cpp:1516
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1561
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:187
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
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:459
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:396
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:406
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:308
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
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:10411
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:6448
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6477
RAII class to control scope of DeferDiags.
Definition Sema.h:10134
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1387
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1422
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:12600
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12634
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1449
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
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.
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10152
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9447
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9432
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:417
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:170
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
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:1474
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
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:10494
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10497
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10503
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10501
@ AR_dependent
Definition Sema.h:1689
@ AR_accessible
Definition Sema.h:1687
@ AR_inaccessible
Definition Sema.h:1688
@ AR_delayed
Definition Sema.h:1690
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.
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
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:2078
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.
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.
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:1748
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1309
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:693
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:937
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 CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, 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...
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:1519
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...
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:763
ASTContext & getASTContext() const
Definition Sema.h:940
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)
void PopExpressionEvaluationContext()
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:769
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....
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
@ FRS_Success
Definition Sema.h:10882
@ FRS_DiagnosticIssued
Definition Sema.h:10884
@ FRS_NoViableFunction
Definition Sema.h:10883
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9413
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
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.
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...
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10203
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:1213
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3648
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
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:12298
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
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...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
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...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
const LangOptions & getLangOpts() const
Definition Sema.h:933
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,...
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
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.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
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={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1307
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.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
SemaHLSL & HLSL()
Definition Sema.h:1484
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9412
MemberPointerConversionDirection
Definition Sema.h:10335
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)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10522
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
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.
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...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15647
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9948
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7070
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
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:1447
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
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.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
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:14088
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 ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
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...
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7567
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
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 isSFINAEContext() const
Definition Sema.h:13836
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:15602
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
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,...
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.
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 NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
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...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6833
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6802
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
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.
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
MemberPointerConversionResult
Definition Sema.h:10327
SourceManager & SourceMgr
Definition Sema.h:1312
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1311
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:523
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
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...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
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.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6510
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
SemaARM & ARM()
Definition Sema.h:1454
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8748
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
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:298
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:392
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:362
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:339
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:324
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:391
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:334
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:367
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:318
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:329
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
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:384
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:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
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...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
StringRef getString() const
Definition Expr.h:1873
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:682
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:736
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:721
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
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.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
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.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3582
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2546
bool isBlockPointerType() const
Definition TypeBase.h:8746
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
bool isObjCBuiltinType() const
Definition TypeBase.h:8956
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
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:2000
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isIncompleteArrayType() const
Definition TypeBase.h:8833
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isFloat16Type() const
Definition TypeBase.h:9101
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
bool isRValueReferenceType() const
Definition TypeBase.h:8758
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8829
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9259
bool isArrayType() const
Definition TypeBase.h:8825
bool isCharType() const
Definition Type.cpp:2197
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9164
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2426
bool isPointerType() const
Definition TypeBase.h:8726
bool isArrayParameterType() const
Definition TypeBase.h:8841
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9136
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2671
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isEnumeralType() const
Definition TypeBase.h:8857
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2160
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8926
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9214
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2233
bool isExtVectorBoolType() const
Definition TypeBase.h:8873
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8913
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2855
bool isLValueReferenceType() const
Definition TypeBase.h:8754
bool isBitIntType() const
Definition TypeBase.h:9001
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2507
bool isAnyComplexType() const
Definition TypeBase.h:8861
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9152
bool isHalfType() const
Definition TypeBase.h:9096
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9074
bool isQueueT() const
Definition TypeBase.h:8982
bool isMemberPointerType() const
Definition TypeBase.h:8807
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9242
bool isObjCIdType() const
Definition TypeBase.h:8938
bool isMatrixType() const
Definition TypeBase.h:8889
bool isOverflowBehaviorType() const
Definition TypeBase.h:8897
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9235
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2571
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8974
bool isBFloat16Type() const
Definition TypeBase.h:9113
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8722
bool isObjCObjectPointerType() const
Definition TypeBase.h:8905
bool isVectorType() const
Definition TypeBase.h:8865
bool isObjCClassType() const
Definition TypeBase.h:8944
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2692
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2986
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9049
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:2336
bool isAnyPointerType() const
Definition TypeBase.h:8734
TypeClass getTypeClass() const
Definition TypeBase.h:2446
bool isSamplerT() const
Definition TypeBase.h:8970
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9129
bool isRecordType() const
Definition TypeBase.h:8853
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1436
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:5164
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1412
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3389
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3458
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4125
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4233
QualType getBaseType() const
Definition ExprCXX.h:4207
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4217
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4198
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4243
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4237
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
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:643
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:973
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4289
QualType getElementType() const
Definition TypeBase.h:4288
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...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:272
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:822
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:833
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:829
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:825
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
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:63
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind, bool PartialOverloading=false)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition Overload.h:859
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:887
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:896
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:879
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:883
@ 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:924
@ ovl_fail_too_few_arguments
Definition Overload.h:861
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:903
@ ovl_fail_too_many_arguments
Definition Overload.h:860
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:911
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:892
@ ovl_fail_bad_deduction
Definition Overload.h:863
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:907
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:916
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:900
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:868
@ Comparison
A comparison.
Definition Sema.h:666
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1798
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1804
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:221
@ ICR_Conversion
Conversion.
Definition Overload.h:235
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:247
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:257
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:263
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:250
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:238
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:244
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:260
@ ICR_Promotion
Promotion.
Definition Overload.h:229
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:223
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:254
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:232
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:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1048
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:929
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
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
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:208
@ 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:205
@ 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:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ 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_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ 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
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:688
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:711
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:732
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:690
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:728
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:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:586
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:215
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:426
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:274
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:316
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:368
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:418
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:413
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:416
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:389
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:375
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:411
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:420
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:408
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:378
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:372
@ Success
Template argument deduction was successful.
Definition Sema.h:370
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:392
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:381
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:395
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:384
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:405
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:422
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:399
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:402
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:837
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:840
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:845
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:843
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:841
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:844
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.
Definition TypeBase.h:6019
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:447
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h:522
ConversionSet::const_iterator const_iterator
Definition Overload.h:558
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:523
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:549
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:607
QualType getFromType() const
Definition Overload.h:606
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.
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.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
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.
DeferredTemplateOverloadCandidate * Next
Definition Overload.h:1102
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
Extra information about a function prototype.
Definition TypeBase.h:5491
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5496
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1195
bool allowsReversed(OverloadedOperatorKind Op) const
Determine whether reversing parameter order is allowed for operator Op.
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD) const
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool isAcceptableCandidate(const FunctionDecl *FD) const
Definition Overload.h:1217
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1244
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1206
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1208
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1234
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:998
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:989
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1063
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1037
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1002
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:979
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:947
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:943
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:938
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1010
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:959
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:973
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1028
unsigned getNumParams() const
Definition Overload.h:1076
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1006
unsigned TookAddressOfOverload
Definition Overload.h:992
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1019
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
DeductionFailureInfo DeductionFailure
Definition Overload.h:1022
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:951
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1033
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10614
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10621
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13247
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13332
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13381
Abstract class used to diagnose incomplete types.
Definition Sema.h:8344
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
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.
DeclAccessPair FoundDecl
The declaration that was looked up, together with its access.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:477
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:489
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:511
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:502
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:497
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:516
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.