clang 23.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 // Determine whether this is considered a derived-to-base conversion.
1850 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1852
1853 return ICS;
1854 }
1855
1856 if (S.getLangOpts().HLSL) {
1857 // Handle conversion of the HLSL resource types.
1858 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1859 if (FromTy->isHLSLAttributedResourceType()) {
1860 // Attributed resource types can convert to other attributed
1861 // resource types with the same attributes and contained types,
1862 // or to __hlsl_resource_t without any attributes.
1863 bool CanConvert = false;
1864 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1865 if (ToTy->isHLSLAttributedResourceType()) {
1866 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1867 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1868 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1869 FromResType->getWrappedType()) &&
1870 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1871 FromResType->getContainedType()) &&
1872 ToResType->getAttrs() == FromResType->getAttrs())
1873 CanConvert = true;
1874 } else if (ToTy->isHLSLResourceType()) {
1875 CanConvert = true;
1876 }
1877 if (CanConvert) {
1878 ICS.setStandard();
1880 ICS.Standard.setFromType(FromType);
1881 ICS.Standard.setAllToTypes(ToType);
1882 return ICS;
1883 }
1884 }
1885 }
1886
1887 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1888 AllowExplicit, InOverloadResolution, CStyle,
1889 AllowObjCWritebackConversion,
1890 AllowObjCConversionOnExplicit);
1891}
1892
1893ImplicitConversionSequence
1895 bool SuppressUserConversions,
1896 AllowedExplicit AllowExplicit,
1897 bool InOverloadResolution,
1898 bool CStyle,
1899 bool AllowObjCWritebackConversion) {
1900 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1901 AllowExplicit, InOverloadResolution, CStyle,
1902 AllowObjCWritebackConversion,
1903 /*AllowObjCConversionOnExplicit=*/false);
1904}
1905
1907 AssignmentAction Action,
1908 bool AllowExplicit) {
1909 if (checkPlaceholderForOverload(*this, From))
1910 return ExprError();
1911
1912 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1913 bool AllowObjCWritebackConversion =
1914 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1915 Action == AssignmentAction::Sending);
1916 if (getLangOpts().ObjC)
1917 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1918 From->getType(), From);
1920 *this, From, ToType,
1921 /*SuppressUserConversions=*/false,
1922 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1923 /*InOverloadResolution=*/false,
1924 /*CStyle=*/false, AllowObjCWritebackConversion,
1925 /*AllowObjCConversionOnExplicit=*/false);
1926 return PerformImplicitConversion(From, ToType, ICS, Action);
1927}
1928
1930 QualType &ResultTy) const {
1931 bool Changed = IsFunctionConversion(FromType, ToType);
1932 if (Changed)
1933 ResultTy = ToType;
1934 return Changed;
1935}
1936
1937bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1938 if (Context.hasSameUnqualifiedType(FromType, ToType))
1939 return false;
1940
1941 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1942 // or F(t noexcept) -> F(t)
1943 // where F adds one of the following at most once:
1944 // - a pointer
1945 // - a member pointer
1946 // - a block pointer
1947 // Changes here need matching changes in FindCompositePointerType.
1948 CanQualType CanTo = Context.getCanonicalType(ToType);
1949 CanQualType CanFrom = Context.getCanonicalType(FromType);
1950 Type::TypeClass TyClass = CanTo->getTypeClass();
1951 if (TyClass != CanFrom->getTypeClass()) return false;
1952 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1953 if (TyClass == Type::Pointer) {
1954 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1955 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1956 } else if (TyClass == Type::BlockPointer) {
1957 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1958 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1959 } else if (TyClass == Type::MemberPointer) {
1960 auto ToMPT = CanTo.castAs<MemberPointerType>();
1961 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1962 // A function pointer conversion cannot change the class of the function.
1963 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1964 FromMPT->getMostRecentCXXRecordDecl()))
1965 return false;
1966 CanTo = ToMPT->getPointeeType();
1967 CanFrom = FromMPT->getPointeeType();
1968 } else {
1969 return false;
1970 }
1971
1972 TyClass = CanTo->getTypeClass();
1973 if (TyClass != CanFrom->getTypeClass()) return false;
1974 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1975 return false;
1976 }
1977
1978 const auto *FromFn = cast<FunctionType>(CanFrom);
1979 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1980
1981 const auto *ToFn = cast<FunctionType>(CanTo);
1982 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1983
1984 bool Changed = false;
1985
1986 // Drop 'noreturn' if not present in target type.
1987 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1988 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1989 Changed = true;
1990 }
1991
1992 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1993 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1994
1995 if (FromFPT && ToFPT) {
1996 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1997 QualType NewTy = Context.getFunctionType(
1998 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1999 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2000 ToFPT->hasCFIUncheckedCallee()));
2001 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2002 FromFn = FromFPT;
2003 Changed = true;
2004 }
2005 }
2006
2007 // Drop 'noexcept' if not present in target type.
2008 if (FromFPT && ToFPT) {
2009 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2010 FromFn = cast<FunctionType>(
2011 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2012 EST_None)
2013 .getTypePtr());
2014 Changed = true;
2015 }
2016
2017 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2018 // only if the ExtParameterInfo lists of the two function prototypes can be
2019 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2021 bool CanUseToFPT, CanUseFromFPT;
2022 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2023 CanUseFromFPT, NewParamInfos) &&
2024 CanUseToFPT && !CanUseFromFPT) {
2025 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2026 ExtInfo.ExtParameterInfos =
2027 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2028 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2029 FromFPT->getParamTypes(), ExtInfo);
2030 FromFn = QT->getAs<FunctionType>();
2031 Changed = true;
2032 }
2033
2034 if (Context.hasAnyFunctionEffects()) {
2035 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2036
2037 // Transparently add/drop effects; here we are concerned with
2038 // language rules/canonicalization. Adding/dropping effects is a warning.
2039 const auto FromFX = FromFPT->getFunctionEffects();
2040 const auto ToFX = ToFPT->getFunctionEffects();
2041 if (FromFX != ToFX) {
2042 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2043 ExtInfo.FunctionEffects = ToFX;
2044 QualType QT = Context.getFunctionType(
2045 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2046 FromFn = QT->getAs<FunctionType>();
2047 Changed = true;
2048 }
2049 }
2050 }
2051
2052 if (!Changed)
2053 return false;
2054
2055 assert(QualType(FromFn, 0).isCanonical());
2056 if (QualType(FromFn, 0) != CanTo) return false;
2057
2058 return true;
2059}
2060
2061/// Determine whether the conversion from FromType to ToType is a valid
2062/// floating point conversion.
2063///
2064static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2065 QualType ToType) {
2066 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2067 return false;
2068 // FIXME: disable conversions between long double, __ibm128 and __float128
2069 // if their representation is different until there is back end support
2070 // We of course allow this conversion if long double is really double.
2071
2072 // Conversions between bfloat16 and float16 are currently not supported.
2073 if ((FromType->isBFloat16Type() &&
2074 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2075 (ToType->isBFloat16Type() &&
2076 (FromType->isFloat16Type() || FromType->isHalfType())))
2077 return false;
2078
2079 // Conversions between IEEE-quad and IBM-extended semantics are not
2080 // permitted.
2081 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2082 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2083 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2084 &ToSem == &llvm::APFloat::IEEEquad()) ||
2085 (&FromSem == &llvm::APFloat::IEEEquad() &&
2086 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2087 return false;
2088 return true;
2089}
2090
2092 QualType ToType,
2094 Expr *From) {
2095 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2096 return true;
2097
2098 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2100 return true;
2101 }
2102
2103 if (IsFloatingPointConversion(S, FromType, ToType)) {
2105 return true;
2106 }
2107
2108 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2110 return true;
2111 }
2112
2113 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2115 ToType->isRealFloatingType())) {
2117 return true;
2118 }
2119
2120 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2122 return true;
2123 }
2124
2125 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2126 ToType->isIntegralType(S.Context)) {
2128 return true;
2129 }
2130
2131 return false;
2132}
2133
2134/// Determine whether the conversion from FromType to ToType is a valid
2135/// matrix conversion.
2136///
2137/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2138/// conversion.
2139static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2141 ImplicitConversionKind &ElConv, Expr *From,
2142 bool InOverloadResolution, bool CStyle) {
2143 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2144 if (!S.getLangOpts().HLSL)
2145 return false;
2146
2147 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2148 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2149
2150 // If both arguments are matrix, handle possible matrix truncation and
2151 // element conversion.
2152 if (ToMatrixType && FromMatrixType) {
2153 unsigned FromCols = FromMatrixType->getNumColumns();
2154 unsigned ToCols = ToMatrixType->getNumColumns();
2155 if (FromCols < ToCols)
2156 return false;
2157
2158 unsigned FromRows = FromMatrixType->getNumRows();
2159 unsigned ToRows = ToMatrixType->getNumRows();
2160 if (FromRows < ToRows)
2161 return false;
2162
2163 if (FromRows == ToRows && FromCols == ToCols)
2164 ElConv = ICK_Identity;
2165 else
2167
2168 QualType FromElTy = FromMatrixType->getElementType();
2169 QualType ToElTy = ToMatrixType->getElementType();
2170 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2171 return true;
2172 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2173 }
2174
2175 // Matrix splat from any arithmetic type to a matrix.
2176 if (ToMatrixType && FromType->isArithmeticType()) {
2177 ElConv = ICK_HLSL_Matrix_Splat;
2178 QualType ToElTy = ToMatrixType->getElementType();
2179 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2180 }
2181 if (FromMatrixType && !ToMatrixType) {
2183 QualType FromElTy = FromMatrixType->getElementType();
2184 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2185 return true;
2186 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2187 }
2188
2189 return false;
2190}
2191
2192/// Determine whether the conversion from FromType to ToType is a valid
2193/// vector conversion.
2194///
2195/// \param ICK Will be set to the vector conversion kind, if this is a vector
2196/// conversion.
2197static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2199 ImplicitConversionKind &ElConv, Expr *From,
2200 bool InOverloadResolution, bool CStyle) {
2201 // We need at least one of these types to be a vector type to have a vector
2202 // conversion.
2203 if (!ToType->isVectorType() && !FromType->isVectorType())
2204 return false;
2205
2206 // Identical types require no conversions.
2207 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2208 return false;
2209
2210 // HLSL allows implicit truncation of vector types.
2211 if (S.getLangOpts().HLSL) {
2212 auto *ToExtType = ToType->getAs<ExtVectorType>();
2213 auto *FromExtType = FromType->getAs<ExtVectorType>();
2214
2215 // If both arguments are vectors, handle possible vector truncation and
2216 // element conversion.
2217 if (ToExtType && FromExtType) {
2218 unsigned FromElts = FromExtType->getNumElements();
2219 unsigned ToElts = ToExtType->getNumElements();
2220 if (FromElts < ToElts)
2221 return false;
2222 if (FromElts == ToElts)
2223 ElConv = ICK_Identity;
2224 else
2226
2227 QualType FromElTy = FromExtType->getElementType();
2228 QualType ToElTy = ToExtType->getElementType();
2229 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2230 return true;
2231 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2232 }
2233 if (FromExtType && !ToExtType) {
2235 QualType FromElTy = FromExtType->getElementType();
2236 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2237 return true;
2238 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2239 }
2240 // Fallthrough for the case where ToType is a vector and FromType is not.
2241 }
2242
2243 // There are no conversions between extended vector types, only identity.
2244 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2245 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2246 // Implicit conversions require the same number of elements.
2247 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2248 return false;
2249
2250 // Permit implicit conversions from integral values to boolean vectors.
2251 if (ToType->isExtVectorBoolType() &&
2252 FromExtType->getElementType()->isIntegerType()) {
2254 return true;
2255 }
2256 // There are no other conversions between extended vector types.
2257 return false;
2258 }
2259
2260 // Vector splat from any arithmetic type to a vector.
2261 if (FromType->isArithmeticType()) {
2262 if (S.getLangOpts().HLSL) {
2263 ElConv = ICK_HLSL_Vector_Splat;
2264 QualType ToElTy = ToExtType->getElementType();
2265 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2266 From);
2267 }
2268 ICK = ICK_Vector_Splat;
2269 return true;
2270 }
2271 }
2272
2273 if (ToType->isSVESizelessBuiltinType() ||
2274 FromType->isSVESizelessBuiltinType())
2275 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2276 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2278 return true;
2279 }
2280
2281 if (ToType->isRVVSizelessBuiltinType() ||
2282 FromType->isRVVSizelessBuiltinType())
2283 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2284 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2286 return true;
2287 }
2288
2289 // We can perform the conversion between vector types in the following cases:
2290 // 1)vector types are equivalent AltiVec and GCC vector types
2291 // 2)lax vector conversions are permitted and the vector types are of the
2292 // same size
2293 // 3)the destination type does not have the ARM MVE strict-polymorphism
2294 // attribute, which inhibits lax vector conversion for overload resolution
2295 // only
2296 if (ToType->isVectorType() && FromType->isVectorType()) {
2297 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2298 (S.isLaxVectorConversion(FromType, ToType) &&
2299 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2300 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2301 S.isLaxVectorConversion(FromType, ToType) &&
2302 S.anyAltivecTypes(FromType, ToType) &&
2303 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2304 !InOverloadResolution && !CStyle) {
2305 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2306 << FromType << ToType;
2307 }
2309 return true;
2310 }
2311 }
2312
2313 return false;
2314}
2315
2316static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2317 bool InOverloadResolution,
2318 StandardConversionSequence &SCS,
2319 bool CStyle);
2320
2321static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2322 QualType ToType,
2323 bool InOverloadResolution,
2324 StandardConversionSequence &SCS,
2325 bool CStyle);
2326
2327/// IsStandardConversion - Determines whether there is a standard
2328/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2329/// expression From to the type ToType. Standard conversion sequences
2330/// only consider non-class types; for conversions that involve class
2331/// types, use TryImplicitConversion. If a conversion exists, SCS will
2332/// contain the standard conversion sequence required to perform this
2333/// conversion and this routine will return true. Otherwise, this
2334/// routine will return false and the value of SCS is unspecified.
2335static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2336 bool InOverloadResolution,
2338 bool CStyle,
2339 bool AllowObjCWritebackConversion) {
2340 QualType FromType = From->getType();
2341
2342 // Standard conversions (C++ [conv])
2344 SCS.IncompatibleObjC = false;
2345 SCS.setFromType(FromType);
2346 SCS.CopyConstructor = nullptr;
2347
2348 // There are no standard conversions for class types in C++, so
2349 // abort early. When overloading in C, however, we do permit them.
2350 if (S.getLangOpts().CPlusPlus &&
2351 (FromType->isRecordType() || ToType->isRecordType()))
2352 return false;
2353
2354 // The first conversion can be an lvalue-to-rvalue conversion,
2355 // array-to-pointer conversion, or function-to-pointer conversion
2356 // (C++ 4p1).
2357
2358 if (FromType == S.Context.OverloadTy) {
2359 DeclAccessPair AccessPair;
2360 if (FunctionDecl *Fn
2361 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2362 AccessPair)) {
2363 // We were able to resolve the address of the overloaded function,
2364 // so we can convert to the type of that function.
2365 FromType = Fn->getType();
2366 SCS.setFromType(FromType);
2367
2368 // we can sometimes resolve &foo<int> regardless of ToType, so check
2369 // if the type matches (identity) or we are converting to bool
2371 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2372 // if the function type matches except for [[noreturn]], it's ok
2373 if (!S.IsFunctionConversion(FromType,
2375 // otherwise, only a boolean conversion is standard
2376 if (!ToType->isBooleanType())
2377 return false;
2378 }
2379
2380 // Check if the "from" expression is taking the address of an overloaded
2381 // function and recompute the FromType accordingly. Take advantage of the
2382 // fact that non-static member functions *must* have such an address-of
2383 // expression.
2384 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2385 if (Method && !Method->isStatic() &&
2386 !Method->isExplicitObjectMemberFunction()) {
2387 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2388 "Non-unary operator on non-static member address");
2389 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2390 == UO_AddrOf &&
2391 "Non-address-of operator on non-static member address");
2392 FromType = S.Context.getMemberPointerType(
2393 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2394 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2395 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2396 UO_AddrOf &&
2397 "Non-address-of operator for overloaded function expression");
2398 FromType = S.Context.getPointerType(FromType);
2399 }
2400 } else {
2401 return false;
2402 }
2403 }
2404
2405 bool argIsLValue = From->isGLValue();
2406 // To handle conversion from ArrayParameterType to ConstantArrayType
2407 // this block must be above the one below because Array parameters
2408 // do not decay and when handling HLSLOutArgExprs and
2409 // the From expression is an LValue.
2410 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2411 ToType->isConstantArrayType()) {
2412 // HLSL constant array parameters do not decay, so if the argument is a
2413 // constant array and the parameter is an ArrayParameterType we have special
2414 // handling here.
2415 if (ToType->isArrayParameterType()) {
2416 FromType = S.Context.getArrayParameterType(FromType);
2417 } else if (FromType->isArrayParameterType()) {
2418 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2419 FromType = APT->getConstantArrayType(S.Context);
2420 }
2421
2423
2424 // Don't consider qualifiers, which include things like address spaces
2425 if (FromType.getCanonicalType().getUnqualifiedType() !=
2427 return false;
2428
2429 SCS.setAllToTypes(ToType);
2430 return true;
2431 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2432 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2433 // Lvalue-to-rvalue conversion (C++11 4.1):
2434 // A glvalue (3.10) of a non-function, non-array type T can
2435 // be converted to a prvalue.
2436
2438
2439 // C11 6.3.2.1p2:
2440 // ... if the lvalue has atomic type, the value has the non-atomic version
2441 // of the type of the lvalue ...
2442 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2443 FromType = Atomic->getValueType();
2444
2445 // If T is a non-class type, the type of the rvalue is the
2446 // cv-unqualified version of T. Otherwise, the type of the rvalue
2447 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2448 // just strip the qualifiers because they don't matter.
2449 FromType = FromType.getUnqualifiedType();
2450 } else if (FromType->isArrayType()) {
2451 // Array-to-pointer conversion (C++ 4.2)
2453
2454 // An lvalue or rvalue of type "array of N T" or "array of unknown
2455 // bound of T" can be converted to an rvalue of type "pointer to
2456 // T" (C++ 4.2p1).
2457 FromType = S.Context.getArrayDecayedType(FromType);
2458
2459 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2460 // This conversion is deprecated in C++03 (D.4)
2462
2463 // For the purpose of ranking in overload resolution
2464 // (13.3.3.1.1), this conversion is considered an
2465 // array-to-pointer conversion followed by a qualification
2466 // conversion (4.4). (C++ 4.2p2)
2467 SCS.Second = ICK_Identity;
2470 SCS.setAllToTypes(FromType);
2471 return true;
2472 }
2473 } else if (FromType->isFunctionType() && argIsLValue) {
2474 // Function-to-pointer conversion (C++ 4.3).
2476
2477 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2478 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2480 return false;
2481
2482 // An lvalue of function type T can be converted to an rvalue of
2483 // type "pointer to T." The result is a pointer to the
2484 // function. (C++ 4.3p1).
2485 FromType = S.Context.getPointerType(FromType);
2486 } else {
2487 // We don't require any conversions for the first step.
2488 SCS.First = ICK_Identity;
2489 }
2490 SCS.setToType(0, FromType);
2491
2492 // The second conversion can be an integral promotion, floating
2493 // point promotion, integral conversion, floating point conversion,
2494 // floating-integral conversion, pointer conversion,
2495 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2496 // For overloading in C, this can also be a "compatible-type"
2497 // conversion.
2498 bool IncompatibleObjC = false;
2500 ImplicitConversionKind DimensionICK = ICK_Identity;
2501 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2502 // The unqualified versions of the types are the same: there's no
2503 // conversion to do.
2504 SCS.Second = ICK_Identity;
2505 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2506 // Integral promotion (C++ 4.5).
2508 FromType = ToType.getUnqualifiedType();
2509 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2510 // Floating point promotion (C++ 4.6).
2512 FromType = ToType.getUnqualifiedType();
2513 } else if (S.IsComplexPromotion(FromType, ToType)) {
2514 // Complex promotion (Clang extension)
2516 FromType = ToType.getUnqualifiedType();
2517 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2518 // OverflowBehaviorType promotions
2520 FromType = ToType.getUnqualifiedType();
2521 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2522 // OverflowBehaviorType conversions
2524 FromType = ToType.getUnqualifiedType();
2525 } else if (ToType->isBooleanType() &&
2526 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2527 FromType->isBlockPointerType() ||
2528 FromType->isMemberPointerType())) {
2529 // Boolean conversions (C++ 4.12).
2531 FromType = S.Context.BoolTy;
2532 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2533 ToType->isIntegralType(S.Context)) {
2534 // Integral conversions (C++ 4.7).
2536 FromType = ToType.getUnqualifiedType();
2537 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2538 // Complex conversions (C99 6.3.1.6)
2540 FromType = ToType.getUnqualifiedType();
2541 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2542 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2543 // Complex-real conversions (C99 6.3.1.7)
2545 FromType = ToType.getUnqualifiedType();
2546 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2547 // Floating point conversions (C++ 4.8).
2549 FromType = ToType.getUnqualifiedType();
2550 } else if ((FromType->isRealFloatingType() &&
2551 ToType->isIntegralType(S.Context)) ||
2553 ToType->isRealFloatingType())) {
2554
2555 // Floating-integral conversions (C++ 4.9).
2557 FromType = ToType.getUnqualifiedType();
2558 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2560 } else if (AllowObjCWritebackConversion &&
2561 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2563 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2564 FromType, IncompatibleObjC)) {
2565 // Pointer conversions (C++ 4.10).
2567 SCS.IncompatibleObjC = IncompatibleObjC;
2568 FromType = FromType.getUnqualifiedType();
2569 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2570 InOverloadResolution, FromType)) {
2571 // Pointer to member conversions (4.11).
2573 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2574 From, InOverloadResolution, CStyle)) {
2575 SCS.Second = SecondICK;
2576 SCS.Dimension = DimensionICK;
2577 FromType = ToType.getUnqualifiedType();
2578 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2579 From, InOverloadResolution, CStyle)) {
2580 SCS.Second = SecondICK;
2581 SCS.Dimension = DimensionICK;
2582 FromType = ToType.getUnqualifiedType();
2583 } else if (!S.getLangOpts().CPlusPlus &&
2584 S.Context.typesAreCompatible(ToType, FromType)) {
2585 // Compatible conversions (Clang extension for C function overloading)
2587 FromType = ToType.getUnqualifiedType();
2589 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2591 FromType = ToType;
2592 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2593 CStyle)) {
2594 // tryAtomicConversion has updated the standard conversion sequence
2595 // appropriately.
2596 return true;
2598 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2599 return true;
2600 } else if (ToType->isEventT() &&
2602 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2604 FromType = ToType;
2605 } else if (ToType->isQueueT() &&
2607 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2609 FromType = ToType;
2610 } else if (ToType->isSamplerT() &&
2613 FromType = ToType;
2614 } else if ((ToType->isFixedPointType() &&
2615 FromType->isConvertibleToFixedPointType()) ||
2616 (FromType->isFixedPointType() &&
2617 ToType->isConvertibleToFixedPointType())) {
2619 FromType = ToType;
2620 } else {
2621 // No second conversion required.
2622 SCS.Second = ICK_Identity;
2623 }
2624 SCS.setToType(1, FromType);
2625
2626 // The third conversion can be a function pointer conversion or a
2627 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2628 bool ObjCLifetimeConversion;
2629 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2630 // Function pointer conversions (removing 'noexcept') including removal of
2631 // 'noreturn' (Clang extension).
2633 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2634 ObjCLifetimeConversion)) {
2636 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2637 FromType = ToType;
2638 } else {
2639 // No conversion required
2640 SCS.Third = ICK_Identity;
2641 }
2642
2643 // C++ [over.best.ics]p6:
2644 // [...] Any difference in top-level cv-qualification is
2645 // subsumed by the initialization itself and does not constitute
2646 // a conversion. [...]
2647 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2648 QualType CanonTo = S.Context.getCanonicalType(ToType);
2649 if (CanonFrom.getLocalUnqualifiedType()
2650 == CanonTo.getLocalUnqualifiedType() &&
2651 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2652 FromType = ToType;
2653 CanonFrom = CanonTo;
2654 }
2655
2656 SCS.setToType(2, FromType);
2657
2658 if (CanonFrom == CanonTo)
2659 return true;
2660
2661 // If we have not converted the argument type to the parameter type,
2662 // this is a bad conversion sequence, unless we're resolving an overload in C.
2663 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2664 return false;
2665
2666 ExprResult ER = ExprResult{From};
2667 AssignConvertType Conv =
2669 /*Diagnose=*/false,
2670 /*DiagnoseCFAudited=*/false,
2671 /*ConvertRHS=*/false);
2672 ImplicitConversionKind SecondConv;
2673 switch (Conv) {
2675 case AssignConvertType::
2676 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2677 SecondConv = ICK_C_Only_Conversion;
2678 break;
2679 // For our purposes, discarding qualifiers is just as bad as using an
2680 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2681 // qualifiers, as well.
2686 break;
2687 default:
2688 return false;
2689 }
2690
2691 // First can only be an lvalue conversion, so we pretend that this was the
2692 // second conversion. First should already be valid from earlier in the
2693 // function.
2694 SCS.Second = SecondConv;
2695 SCS.setToType(1, ToType);
2696
2697 // Third is Identity, because Second should rank us worse than any other
2698 // conversion. This could also be ICK_Qualification, but it's simpler to just
2699 // lump everything in with the second conversion, and we don't gain anything
2700 // from making this ICK_Qualification.
2701 SCS.Third = ICK_Identity;
2702 SCS.setToType(2, ToType);
2703 return true;
2704}
2705
2706static bool
2708 QualType &ToType,
2709 bool InOverloadResolution,
2711 bool CStyle) {
2712
2713 const RecordType *UT = ToType->getAsUnionType();
2714 if (!UT)
2715 return false;
2716 // The field to initialize within the transparent union.
2717 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2718 if (!UD->hasAttr<TransparentUnionAttr>())
2719 return false;
2720 // It's compatible if the expression matches any of the fields.
2721 for (const auto *it : UD->fields()) {
2722 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2723 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2724 ToType = it->getType();
2725 return true;
2726 }
2727 }
2728 return false;
2729}
2730
2731bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2732 const BuiltinType *To = ToType->getAs<BuiltinType>();
2733 // All integers are built-in.
2734 if (!To) {
2735 return false;
2736 }
2737
2738 // An rvalue of type char, signed char, unsigned char, short int, or
2739 // unsigned short int can be converted to an rvalue of type int if
2740 // int can represent all the values of the source type; otherwise,
2741 // the source rvalue can be converted to an rvalue of type unsigned
2742 // int (C++ 4.5p1).
2743 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2744 !FromType->isEnumeralType()) {
2745 if ( // We can promote any signed, promotable integer type to an int
2746 (FromType->isSignedIntegerType() ||
2747 // We can promote any unsigned integer type whose size is
2748 // less than int to an int.
2749 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2750 return To->getKind() == BuiltinType::Int;
2751 }
2752
2753 return To->getKind() == BuiltinType::UInt;
2754 }
2755
2756 // C++11 [conv.prom]p3:
2757 // A prvalue of an unscoped enumeration type whose underlying type is not
2758 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2759 // following types that can represent all the values of the enumeration
2760 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2761 // unsigned int, long int, unsigned long int, long long int, or unsigned
2762 // long long int. If none of the types in that list can represent all the
2763 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2764 // type can be converted to an rvalue a prvalue of the extended integer type
2765 // with lowest integer conversion rank (4.13) greater than the rank of long
2766 // long in which all the values of the enumeration can be represented. If
2767 // there are two such extended types, the signed one is chosen.
2768 // C++11 [conv.prom]p4:
2769 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2770 // can be converted to a prvalue of its underlying type. Moreover, if
2771 // integral promotion can be applied to its underlying type, a prvalue of an
2772 // unscoped enumeration type whose underlying type is fixed can also be
2773 // converted to a prvalue of the promoted underlying type.
2774 if (const auto *FromED = FromType->getAsEnumDecl()) {
2775 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2776 // provided for a scoped enumeration.
2777 if (FromED->isScoped())
2778 return false;
2779
2780 // We can perform an integral promotion to the underlying type of the enum,
2781 // even if that's not the promoted type. Note that the check for promoting
2782 // the underlying type is based on the type alone, and does not consider
2783 // the bitfield-ness of the actual source expression.
2784 if (FromED->isFixed()) {
2785 QualType Underlying = FromED->getIntegerType();
2786 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2787 IsIntegralPromotion(nullptr, Underlying, ToType);
2788 }
2789
2790 // We have already pre-calculated the promotion type, so this is trivial.
2791 if (ToType->isIntegerType() &&
2792 isCompleteType(From->getBeginLoc(), FromType))
2793 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2794
2795 // C++ [conv.prom]p5:
2796 // If the bit-field has an enumerated type, it is treated as any other
2797 // value of that type for promotion purposes.
2798 //
2799 // ... so do not fall through into the bit-field checks below in C++.
2800 if (getLangOpts().CPlusPlus)
2801 return false;
2802 }
2803
2804 // C++0x [conv.prom]p2:
2805 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2806 // to an rvalue a prvalue of the first of the following types that can
2807 // represent all the values of its underlying type: int, unsigned int,
2808 // long int, unsigned long int, long long int, or unsigned long long int.
2809 // If none of the types in that list can represent all the values of its
2810 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2811 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2812 // type.
2813 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2814 ToType->isIntegerType()) {
2815 // Determine whether the type we're converting from is signed or
2816 // unsigned.
2817 bool FromIsSigned = FromType->isSignedIntegerType();
2818 uint64_t FromSize = Context.getTypeSize(FromType);
2819
2820 // The types we'll try to promote to, in the appropriate
2821 // order. Try each of these types.
2822 QualType PromoteTypes[6] = {
2823 Context.IntTy, Context.UnsignedIntTy,
2824 Context.LongTy, Context.UnsignedLongTy ,
2825 Context.LongLongTy, Context.UnsignedLongLongTy
2826 };
2827 for (int Idx = 0; Idx < 6; ++Idx) {
2828 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2829 if (FromSize < ToSize ||
2830 (FromSize == ToSize &&
2831 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2832 // We found the type that we can promote to. If this is the
2833 // type we wanted, we have a promotion. Otherwise, no
2834 // promotion.
2835 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2836 }
2837 }
2838 }
2839
2840 // An rvalue for an integral bit-field (9.6) can be converted to an
2841 // rvalue of type int if int can represent all the values of the
2842 // bit-field; otherwise, it can be converted to unsigned int if
2843 // unsigned int can represent all the values of the bit-field. If
2844 // the bit-field is larger yet, no integral promotion applies to
2845 // it. If the bit-field has an enumerated type, it is treated as any
2846 // other value of that type for promotion purposes (C++ 4.5p3).
2847 // FIXME: We should delay checking of bit-fields until we actually perform the
2848 // conversion.
2849 //
2850 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2851 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2852 // bit-fields and those whose underlying type is larger than int) for GCC
2853 // compatibility.
2854 if (From) {
2855 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2856 std::optional<llvm::APSInt> BitWidth;
2857 if (FromType->isIntegralType(Context) &&
2858 (BitWidth =
2859 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2860 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2861 ToSize = Context.getTypeSize(ToType);
2862
2863 // Are we promoting to an int from a bitfield that fits in an int?
2864 if (*BitWidth < ToSize ||
2865 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2866 return To->getKind() == BuiltinType::Int;
2867 }
2868
2869 // Are we promoting to an unsigned int from an unsigned bitfield
2870 // that fits into an unsigned int?
2871 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2872 return To->getKind() == BuiltinType::UInt;
2873 }
2874
2875 return false;
2876 }
2877 }
2878 }
2879
2880 // An rvalue of type bool can be converted to an rvalue of type int,
2881 // with false becoming zero and true becoming one (C++ 4.5p4).
2882 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2883 return true;
2884 }
2885
2886 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2887 // integral type.
2888 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2889 ToType->isIntegerType())
2890 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2891
2892 return false;
2893}
2894
2896 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2897 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2898 /// An rvalue of type float can be converted to an rvalue of type
2899 /// double. (C++ 4.6p1).
2900 if (FromBuiltin->getKind() == BuiltinType::Float &&
2901 ToBuiltin->getKind() == BuiltinType::Double)
2902 return true;
2903
2904 // C99 6.3.1.5p1:
2905 // When a float is promoted to double or long double, or a
2906 // double is promoted to long double [...].
2907 if (!getLangOpts().CPlusPlus &&
2908 (FromBuiltin->getKind() == BuiltinType::Float ||
2909 FromBuiltin->getKind() == BuiltinType::Double) &&
2910 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2911 ToBuiltin->getKind() == BuiltinType::Float128 ||
2912 ToBuiltin->getKind() == BuiltinType::Ibm128))
2913 return true;
2914
2915 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2916 // or not native half types are enabled.
2917 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2918 (ToBuiltin->getKind() == BuiltinType::Float ||
2919 ToBuiltin->getKind() == BuiltinType::Double))
2920 return true;
2921
2922 // Half can be promoted to float.
2923 if (!getLangOpts().NativeHalfType &&
2924 FromBuiltin->getKind() == BuiltinType::Half &&
2925 ToBuiltin->getKind() == BuiltinType::Float)
2926 return true;
2927 }
2928
2929 return false;
2930}
2931
2933 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2934 if (!FromComplex)
2935 return false;
2936
2937 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2938 if (!ToComplex)
2939 return false;
2940
2941 return IsFloatingPointPromotion(FromComplex->getElementType(),
2942 ToComplex->getElementType()) ||
2943 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2944 ToComplex->getElementType());
2945}
2946
2948 if (!getLangOpts().OverflowBehaviorTypes)
2949 return false;
2950
2951 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2952 return false;
2953
2954 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2955}
2956
2958 QualType ToType) {
2959 if (!getLangOpts().OverflowBehaviorTypes)
2960 return false;
2961
2962 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2963 if (ToType->isBooleanType())
2964 return false;
2965 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2966 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2967 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2968 if (ToED->isScoped())
2969 return false;
2970 }
2971 return true;
2972 }
2973
2974 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2975 return true;
2976
2977 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2978 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2979
2980 return false;
2981}
2982
2983/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2984/// the pointer type FromPtr to a pointer to type ToPointee, with the
2985/// same type qualifiers as FromPtr has on its pointee type. ToType,
2986/// if non-empty, will be a pointer to ToType that may or may not have
2987/// the right set of qualifiers on its pointee.
2988///
2989static QualType
2991 QualType ToPointee, QualType ToType,
2992 ASTContext &Context,
2993 bool StripObjCLifetime = false) {
2994 assert((FromPtr->getTypeClass() == Type::Pointer ||
2995 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2996 "Invalid similarly-qualified pointer type");
2997
2998 /// Conversions to 'id' subsume cv-qualifier conversions.
2999 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3000 return ToType.getUnqualifiedType();
3001
3002 QualType CanonFromPointee
3003 = Context.getCanonicalType(FromPtr->getPointeeType());
3004 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3005 Qualifiers Quals = CanonFromPointee.getQualifiers();
3006
3007 if (StripObjCLifetime)
3008 Quals.removeObjCLifetime();
3009
3010 // Exact qualifier match -> return the pointer type we're converting to.
3011 if (CanonToPointee.getLocalQualifiers() == Quals) {
3012 // ToType is exactly what we need. Return it.
3013 if (!ToType.isNull())
3014 return ToType.getUnqualifiedType();
3015
3016 // Build a pointer to ToPointee. It has the right qualifiers
3017 // already.
3018 if (isa<ObjCObjectPointerType>(ToType))
3019 return Context.getObjCObjectPointerType(ToPointee);
3020 return Context.getPointerType(ToPointee);
3021 }
3022
3023 // Just build a canonical type that has the right qualifiers.
3024 QualType QualifiedCanonToPointee
3025 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3026
3027 if (isa<ObjCObjectPointerType>(ToType))
3028 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3029 return Context.getPointerType(QualifiedCanonToPointee);
3030}
3031
3033 bool InOverloadResolution,
3034 ASTContext &Context) {
3035 // Handle value-dependent integral null pointer constants correctly.
3036 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3037 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3039 return !InOverloadResolution;
3040
3041 return Expr->isNullPointerConstant(Context,
3042 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3044}
3045
3047 bool InOverloadResolution,
3048 QualType& ConvertedType,
3049 bool &IncompatibleObjC) {
3050 IncompatibleObjC = false;
3051 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3052 IncompatibleObjC))
3053 return true;
3054
3055 // Conversion from a null pointer constant to any Objective-C pointer type.
3056 if (ToType->isObjCObjectPointerType() &&
3057 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3058 ConvertedType = ToType;
3059 return true;
3060 }
3061
3062 // Blocks: Block pointers can be converted to void*.
3063 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3064 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3065 ConvertedType = ToType;
3066 return true;
3067 }
3068 // Blocks: A null pointer constant can be converted to a block
3069 // pointer type.
3070 if (ToType->isBlockPointerType() &&
3071 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3072 ConvertedType = ToType;
3073 return true;
3074 }
3075
3076 // If the left-hand-side is nullptr_t, the right side can be a null
3077 // pointer constant.
3078 if (ToType->isNullPtrType() &&
3079 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3080 ConvertedType = ToType;
3081 return true;
3082 }
3083
3084 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3085 if (!ToTypePtr)
3086 return false;
3087
3088 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3089 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3090 ConvertedType = ToType;
3091 return true;
3092 }
3093
3094 // Beyond this point, both types need to be pointers
3095 // , including objective-c pointers.
3096 QualType ToPointeeType = ToTypePtr->getPointeeType();
3097 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3098 !getLangOpts().ObjCAutoRefCount) {
3099 ConvertedType = BuildSimilarlyQualifiedPointerType(
3100 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3101 Context);
3102 return true;
3103 }
3104 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3105 if (!FromTypePtr)
3106 return false;
3107
3108 QualType FromPointeeType = FromTypePtr->getPointeeType();
3109
3110 // If the unqualified pointee types are the same, this can't be a
3111 // pointer conversion, so don't do all of the work below.
3112 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3113 return false;
3114
3115 // An rvalue of type "pointer to cv T," where T is an object type,
3116 // can be converted to an rvalue of type "pointer to cv void" (C++
3117 // 4.10p2).
3118 if (FromPointeeType->isIncompleteOrObjectType() &&
3119 ToPointeeType->isVoidType()) {
3120 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3121 ToPointeeType,
3122 ToType, Context,
3123 /*StripObjCLifetime=*/true);
3124 return true;
3125 }
3126
3127 // MSVC allows implicit function to void* type conversion.
3128 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3129 ToPointeeType->isVoidType()) {
3130 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3131 ToPointeeType,
3132 ToType, Context);
3133 return true;
3134 }
3135
3136 // When we're overloading in C, we allow a special kind of pointer
3137 // conversion for compatible-but-not-identical pointee types.
3138 if (!getLangOpts().CPlusPlus &&
3139 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3140 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3141 ToPointeeType,
3142 ToType, Context);
3143 return true;
3144 }
3145
3146 // C++ [conv.ptr]p3:
3147 //
3148 // An rvalue of type "pointer to cv D," where D is a class type,
3149 // can be converted to an rvalue of type "pointer to cv B," where
3150 // B is a base class (clause 10) of D. If B is an inaccessible
3151 // (clause 11) or ambiguous (10.2) base class of D, a program that
3152 // necessitates this conversion is ill-formed. The result of the
3153 // conversion is a pointer to the base class sub-object of the
3154 // derived class object. The null pointer value is converted to
3155 // the null pointer value of the destination type.
3156 //
3157 // Note that we do not check for ambiguity or inaccessibility
3158 // here. That is handled by CheckPointerConversion.
3159 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3160 ToPointeeType->isRecordType() &&
3161 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3162 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3164 ToPointeeType,
3165 ToType, Context);
3166 return true;
3167 }
3168
3169 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3170 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3171 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3172 ToPointeeType,
3173 ToType, Context);
3174 return true;
3175 }
3176
3177 return false;
3178}
3179
3180/// Adopt the given qualifiers for the given type.
3182 Qualifiers TQs = T.getQualifiers();
3183
3184 // Check whether qualifiers already match.
3185 if (TQs == Qs)
3186 return T;
3187
3188 if (Qs.compatiblyIncludes(TQs, Context))
3189 return Context.getQualifiedType(T, Qs);
3190
3191 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3192}
3193
3195 QualType& ConvertedType,
3196 bool &IncompatibleObjC) {
3197 if (!getLangOpts().ObjC)
3198 return false;
3199
3200 // The set of qualifiers on the type we're converting from.
3201 Qualifiers FromQualifiers = FromType.getQualifiers();
3202
3203 // First, we handle all conversions on ObjC object pointer types.
3204 const ObjCObjectPointerType* ToObjCPtr =
3205 ToType->getAs<ObjCObjectPointerType>();
3206 const ObjCObjectPointerType *FromObjCPtr =
3207 FromType->getAs<ObjCObjectPointerType>();
3208
3209 if (ToObjCPtr && FromObjCPtr) {
3210 // If the pointee types are the same (ignoring qualifications),
3211 // then this is not a pointer conversion.
3212 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3213 FromObjCPtr->getPointeeType()))
3214 return false;
3215
3216 // Conversion between Objective-C pointers.
3217 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3218 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3219 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3220 if (getLangOpts().CPlusPlus && LHS && RHS &&
3222 FromObjCPtr->getPointeeType(), getASTContext()))
3223 return false;
3224 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3225 ToObjCPtr->getPointeeType(),
3226 ToType, Context);
3227 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3228 return true;
3229 }
3230
3231 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3232 // Okay: this is some kind of implicit downcast of Objective-C
3233 // interfaces, which is permitted. However, we're going to
3234 // complain about it.
3235 IncompatibleObjC = true;
3236 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3237 ToObjCPtr->getPointeeType(),
3238 ToType, Context);
3239 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3240 return true;
3241 }
3242 }
3243 // Beyond this point, both types need to be C pointers or block pointers.
3244 QualType ToPointeeType;
3245 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3246 ToPointeeType = ToCPtr->getPointeeType();
3247 else if (const BlockPointerType *ToBlockPtr =
3248 ToType->getAs<BlockPointerType>()) {
3249 // Objective C++: We're able to convert from a pointer to any object
3250 // to a block pointer type.
3251 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3252 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3253 return true;
3254 }
3255 ToPointeeType = ToBlockPtr->getPointeeType();
3256 }
3257 else if (FromType->getAs<BlockPointerType>() &&
3258 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3259 // Objective C++: We're able to convert from a block pointer type to a
3260 // pointer to any object.
3261 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3262 return true;
3263 }
3264 else
3265 return false;
3266
3267 QualType FromPointeeType;
3268 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3269 FromPointeeType = FromCPtr->getPointeeType();
3270 else if (const BlockPointerType *FromBlockPtr =
3271 FromType->getAs<BlockPointerType>())
3272 FromPointeeType = FromBlockPtr->getPointeeType();
3273 else
3274 return false;
3275
3276 // If we have pointers to pointers, recursively check whether this
3277 // is an Objective-C conversion.
3278 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3279 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3280 IncompatibleObjC)) {
3281 // We always complain about this conversion.
3282 IncompatibleObjC = true;
3283 ConvertedType = Context.getPointerType(ConvertedType);
3284 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3285 return true;
3286 }
3287 // Allow conversion of pointee being objective-c pointer to another one;
3288 // as in I* to id.
3289 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3290 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3291 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3292 IncompatibleObjC)) {
3293
3294 ConvertedType = Context.getPointerType(ConvertedType);
3295 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3296 return true;
3297 }
3298
3299 // If we have pointers to functions or blocks, check whether the only
3300 // differences in the argument and result types are in Objective-C
3301 // pointer conversions. If so, we permit the conversion (but
3302 // complain about it).
3303 const FunctionProtoType *FromFunctionType
3304 = FromPointeeType->getAs<FunctionProtoType>();
3305 const FunctionProtoType *ToFunctionType
3306 = ToPointeeType->getAs<FunctionProtoType>();
3307 if (FromFunctionType && ToFunctionType) {
3308 // If the function types are exactly the same, this isn't an
3309 // Objective-C pointer conversion.
3310 if (Context.getCanonicalType(FromPointeeType)
3311 == Context.getCanonicalType(ToPointeeType))
3312 return false;
3313
3314 // Perform the quick checks that will tell us whether these
3315 // function types are obviously different.
3316 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3317 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3318 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3319 return false;
3320
3321 bool HasObjCConversion = false;
3322 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3323 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3324 // Okay, the types match exactly. Nothing to do.
3325 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3326 ToFunctionType->getReturnType(),
3327 ConvertedType, IncompatibleObjC)) {
3328 // Okay, we have an Objective-C pointer conversion.
3329 HasObjCConversion = true;
3330 } else {
3331 // Function types are too different. Abort.
3332 return false;
3333 }
3334
3335 // Check argument types.
3336 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3337 ArgIdx != NumArgs; ++ArgIdx) {
3338 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3339 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3340 if (Context.getCanonicalType(FromArgType)
3341 == Context.getCanonicalType(ToArgType)) {
3342 // Okay, the types match exactly. Nothing to do.
3343 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3344 ConvertedType, IncompatibleObjC)) {
3345 // Okay, we have an Objective-C pointer conversion.
3346 HasObjCConversion = true;
3347 } else {
3348 // Argument types are too different. Abort.
3349 return false;
3350 }
3351 }
3352
3353 if (HasObjCConversion) {
3354 // We had an Objective-C conversion. Allow this pointer
3355 // conversion, but complain about it.
3356 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3357 IncompatibleObjC = true;
3358 return true;
3359 }
3360 }
3361
3362 return false;
3363}
3364
3366 QualType& ConvertedType) {
3367 QualType ToPointeeType;
3368 if (const BlockPointerType *ToBlockPtr =
3369 ToType->getAs<BlockPointerType>())
3370 ToPointeeType = ToBlockPtr->getPointeeType();
3371 else
3372 return false;
3373
3374 QualType FromPointeeType;
3375 if (const BlockPointerType *FromBlockPtr =
3376 FromType->getAs<BlockPointerType>())
3377 FromPointeeType = FromBlockPtr->getPointeeType();
3378 else
3379 return false;
3380 // We have pointer to blocks, check whether the only
3381 // differences in the argument and result types are in Objective-C
3382 // pointer conversions. If so, we permit the conversion.
3383
3384 const FunctionProtoType *FromFunctionType
3385 = FromPointeeType->getAs<FunctionProtoType>();
3386 const FunctionProtoType *ToFunctionType
3387 = ToPointeeType->getAs<FunctionProtoType>();
3388
3389 if (!FromFunctionType || !ToFunctionType)
3390 return false;
3391
3392 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3393 return true;
3394
3395 // Perform the quick checks that will tell us whether these
3396 // function types are obviously different.
3397 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3398 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3399 return false;
3400
3401 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3402 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3403 if (FromEInfo != ToEInfo)
3404 return false;
3405
3406 bool IncompatibleObjC = false;
3407 if (Context.hasSameType(FromFunctionType->getReturnType(),
3408 ToFunctionType->getReturnType())) {
3409 // Okay, the types match exactly. Nothing to do.
3410 } else {
3411 QualType RHS = FromFunctionType->getReturnType();
3412 QualType LHS = ToFunctionType->getReturnType();
3413 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3414 !RHS.hasQualifiers() && LHS.hasQualifiers())
3415 LHS = LHS.getUnqualifiedType();
3416
3417 if (Context.hasSameType(RHS,LHS)) {
3418 // OK exact match.
3419 } else if (isObjCPointerConversion(RHS, LHS,
3420 ConvertedType, IncompatibleObjC)) {
3421 if (IncompatibleObjC)
3422 return false;
3423 // Okay, we have an Objective-C pointer conversion.
3424 }
3425 else
3426 return false;
3427 }
3428
3429 // Check argument types.
3430 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3431 ArgIdx != NumArgs; ++ArgIdx) {
3432 IncompatibleObjC = false;
3433 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3434 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3435 if (Context.hasSameType(FromArgType, ToArgType)) {
3436 // Okay, the types match exactly. Nothing to do.
3437 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3438 ConvertedType, IncompatibleObjC)) {
3439 if (IncompatibleObjC)
3440 return false;
3441 // Okay, we have an Objective-C pointer conversion.
3442 } else
3443 // Argument types are too different. Abort.
3444 return false;
3445 }
3446
3448 bool CanUseToFPT, CanUseFromFPT;
3449 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3450 CanUseToFPT, CanUseFromFPT,
3451 NewParamInfos))
3452 return false;
3453
3454 ConvertedType = ToType;
3455 return true;
3456}
3457
3458enum {
3466};
3467
3468/// Attempts to get the FunctionProtoType from a Type. Handles
3469/// MemberFunctionPointers properly.
3471 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3472 return FPT;
3473
3474 if (auto *MPT = FromType->getAs<MemberPointerType>())
3475 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3476
3477 return nullptr;
3478}
3479
3481 QualType FromType, QualType ToType) {
3482 // If either type is not valid, include no extra info.
3483 if (FromType.isNull() || ToType.isNull()) {
3484 PDiag << ft_default;
3485 return;
3486 }
3487
3488 // Get the function type from the pointers.
3489 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3490 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3491 *ToMember = ToType->castAs<MemberPointerType>();
3492 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3493 ToMember->getMostRecentCXXRecordDecl())) {
3495 if (ToMember->isSugared())
3496 PDiag << Context.getCanonicalTagType(
3497 ToMember->getMostRecentCXXRecordDecl());
3498 else
3499 PDiag << ToMember->getQualifier();
3500 if (FromMember->isSugared())
3501 PDiag << Context.getCanonicalTagType(
3502 FromMember->getMostRecentCXXRecordDecl());
3503 else
3504 PDiag << FromMember->getQualifier();
3505 return;
3506 }
3507 FromType = FromMember->getPointeeType();
3508 ToType = ToMember->getPointeeType();
3509 }
3510
3511 if (FromType->isPointerType())
3512 FromType = FromType->getPointeeType();
3513 if (ToType->isPointerType())
3514 ToType = ToType->getPointeeType();
3515
3516 // Remove references.
3517 FromType = FromType.getNonReferenceType();
3518 ToType = ToType.getNonReferenceType();
3519
3520 // Don't print extra info for non-specialized template functions.
3521 if (FromType->isInstantiationDependentType() &&
3522 !FromType->getAs<TemplateSpecializationType>()) {
3523 PDiag << ft_default;
3524 return;
3525 }
3526
3527 // No extra info for same types.
3528 if (Context.hasSameType(FromType, ToType)) {
3529 PDiag << ft_default;
3530 return;
3531 }
3532
3533 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3534 *ToFunction = tryGetFunctionProtoType(ToType);
3535
3536 // Both types need to be function types.
3537 if (!FromFunction || !ToFunction) {
3538 PDiag << ft_default;
3539 return;
3540 }
3541
3542 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3543 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3544 << FromFunction->getNumParams();
3545 return;
3546 }
3547
3548 // Handle different parameter types.
3549 unsigned ArgPos;
3550 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3551 PDiag << ft_parameter_mismatch << ArgPos + 1
3552 << ToFunction->getParamType(ArgPos)
3553 << FromFunction->getParamType(ArgPos);
3554 return;
3555 }
3556
3557 // Handle different return type.
3558 if (!Context.hasSameType(FromFunction->getReturnType(),
3559 ToFunction->getReturnType())) {
3560 PDiag << ft_return_type << ToFunction->getReturnType()
3561 << FromFunction->getReturnType();
3562 return;
3563 }
3564
3565 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3566 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3567 << FromFunction->getMethodQuals();
3568 return;
3569 }
3570
3571 // Handle exception specification differences on canonical type (in C++17
3572 // onwards).
3574 ->isNothrow() !=
3575 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3576 ->isNothrow()) {
3577 PDiag << ft_noexcept;
3578 return;
3579 }
3580
3581 // Unable to find a difference, so add no extra info.
3582 PDiag << ft_default;
3583}
3584
3586 ArrayRef<QualType> New, unsigned *ArgPos,
3587 bool Reversed) {
3588 assert(llvm::size(Old) == llvm::size(New) &&
3589 "Can't compare parameters of functions with different number of "
3590 "parameters!");
3591
3592 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3593 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3594 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3595
3596 // Ignore address spaces in pointee type. This is to disallow overloading
3597 // on __ptr32/__ptr64 address spaces.
3598 QualType OldType =
3599 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3600 QualType NewType =
3601 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3602
3603 if (!Context.hasSameType(OldType, NewType)) {
3604 if (ArgPos)
3605 *ArgPos = Idx;
3606 return false;
3607 }
3608 }
3609 return true;
3610}
3611
3613 const FunctionProtoType *NewType,
3614 unsigned *ArgPos, bool Reversed) {
3615 return FunctionParamTypesAreEqual(OldType->param_types(),
3616 NewType->param_types(), ArgPos, Reversed);
3617}
3618
3620 const FunctionDecl *NewFunction,
3621 unsigned *ArgPos,
3622 bool Reversed) {
3623
3624 if (OldFunction->getNumNonObjectParams() !=
3625 NewFunction->getNumNonObjectParams())
3626 return false;
3627
3628 unsigned OldIgnore =
3630 unsigned NewIgnore =
3632
3633 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3634 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3635
3636 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3637 NewPT->param_types().slice(NewIgnore),
3638 ArgPos, Reversed);
3639}
3640
3642 CastKind &Kind,
3643 CXXCastPath& BasePath,
3644 bool IgnoreBaseAccess,
3645 bool Diagnose) {
3646 QualType FromType = From->getType();
3647 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3648
3649 Kind = CK_BitCast;
3650
3651 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3654 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3655 DiagRuntimeBehavior(From->getExprLoc(), From,
3656 PDiag(diag::warn_impcast_bool_to_null_pointer)
3657 << ToType << From->getSourceRange());
3658 else if (!isUnevaluatedContext())
3659 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3660 << ToType << From->getSourceRange();
3661 }
3662 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3663 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3664 QualType FromPointeeType = FromPtrType->getPointeeType(),
3665 ToPointeeType = ToPtrType->getPointeeType();
3666
3667 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3668 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3669 // We must have a derived-to-base conversion. Check an
3670 // ambiguous or inaccessible conversion.
3671 unsigned InaccessibleID = 0;
3672 unsigned AmbiguousID = 0;
3673 if (Diagnose) {
3674 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3675 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3676 }
3678 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3679 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3680 &BasePath, IgnoreBaseAccess))
3681 return true;
3682
3683 // The conversion was successful.
3684 Kind = CK_DerivedToBase;
3685 }
3686
3687 if (Diagnose && !IsCStyleOrFunctionalCast &&
3688 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3689 assert(getLangOpts().MSVCCompat &&
3690 "this should only be possible with MSVCCompat!");
3691 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3692 << From->getSourceRange();
3693 }
3694 }
3695 } else if (const ObjCObjectPointerType *ToPtrType =
3696 ToType->getAs<ObjCObjectPointerType>()) {
3697 if (const ObjCObjectPointerType *FromPtrType =
3698 FromType->getAs<ObjCObjectPointerType>()) {
3699 // Objective-C++ conversions are always okay.
3700 // FIXME: We should have a different class of conversions for the
3701 // Objective-C++ implicit conversions.
3702 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3703 return false;
3704 } else if (FromType->isBlockPointerType()) {
3705 Kind = CK_BlockPointerToObjCPointerCast;
3706 } else {
3707 Kind = CK_CPointerToObjCPointerCast;
3708 }
3709 } else if (ToType->isBlockPointerType()) {
3710 if (!FromType->isBlockPointerType())
3711 Kind = CK_AnyPointerToBlockPointerCast;
3712 }
3713
3714 // We shouldn't fall into this case unless it's valid for other
3715 // reasons.
3717 Kind = CK_NullToPointer;
3718
3719 return false;
3720}
3721
3723 QualType ToType,
3724 bool InOverloadResolution,
3725 QualType &ConvertedType) {
3726 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3727 if (!ToTypePtr)
3728 return false;
3729
3730 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3732 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3734 ConvertedType = ToType;
3735 return true;
3736 }
3737
3738 // Otherwise, both types have to be member pointers.
3739 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3740 if (!FromTypePtr)
3741 return false;
3742
3743 // A pointer to member of B can be converted to a pointer to member of D,
3744 // where D is derived from B (C++ 4.11p2).
3745 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3746 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3747
3748 if (!declaresSameEntity(FromClass, ToClass) &&
3749 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3750 ConvertedType = Context.getMemberPointerType(
3751 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3752 return true;
3753 }
3754
3755 return false;
3756}
3757
3759 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3760 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3761 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3762 // Lock down the inheritance model right now in MS ABI, whether or not the
3763 // pointee types are the same.
3764 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3765 (void)isCompleteType(CheckLoc, FromType);
3766 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3767 }
3768
3769 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3770 if (!FromPtrType) {
3771 // This must be a null pointer to member pointer conversion
3772 Kind = CK_NullToMemberPointer;
3774 }
3775
3776 // T == T, modulo cv
3778 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3779 ToPtrType->getPointeeType()))
3781
3782 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3783 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3784
3785 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3786 const CXXRecordDecl *Cls) {
3787 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3788 PD << Qual;
3789 else
3790 PD << Context.getCanonicalTagType(Cls);
3791 };
3792 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3793 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3794 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3795 return PD;
3796 };
3797
3798 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3800 std::swap(Base, Derived);
3801
3802 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3803 /*DetectVirtual=*/true);
3804 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3806
3807 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3808 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3809 PD << int(Direction);
3810 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3811 Diag(CheckLoc, PD);
3813 }
3814
3815 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3816 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3817 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3818 Diag(CheckLoc, PD);
3820 }
3821
3822 // Must be a base to derived member conversion.
3823 BuildBasePathArray(Paths, BasePath);
3825 ? CK_DerivedToBaseMemberPointer
3826 : CK_BaseToDerivedMemberPointer;
3827
3828 if (!IgnoreBaseAccess)
3829 switch (CheckBaseClassAccess(
3830 CheckLoc, Base, Derived, Paths.front(),
3832 ? diag::err_upcast_to_inaccessible_base
3833 : diag::err_downcast_from_inaccessible_base,
3834 [&](PartialDiagnostic &PD) {
3835 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3836 DerivedQual = ToPtrType->getQualifier();
3837 if (Direction == MemberPointerConversionDirection::Upcast)
3838 std::swap(BaseQual, DerivedQual);
3839 DiagCls(PD, DerivedQual, Derived);
3840 DiagCls(PD, BaseQual, Base);
3841 })) {
3843 case Sema::AR_delayed:
3844 case Sema::AR_dependent:
3845 // Optimistically assume that the delayed and dependent cases
3846 // will work out.
3847 break;
3848
3851 }
3852
3854}
3855
3856/// Determine whether the lifetime conversion between the two given
3857/// qualifiers sets is nontrivial.
3859 Qualifiers ToQuals) {
3860 // Converting anything to const __unsafe_unretained is trivial.
3861 if (ToQuals.hasConst() &&
3863 return false;
3864
3865 return true;
3866}
3867
3868/// Perform a single iteration of the loop for checking if a qualification
3869/// conversion is valid.
3870///
3871/// Specifically, check whether any change between the qualifiers of \p
3872/// FromType and \p ToType is permissible, given knowledge about whether every
3873/// outer layer is const-qualified.
3875 bool CStyle, bool IsTopLevel,
3876 bool &PreviousToQualsIncludeConst,
3877 bool &ObjCLifetimeConversion,
3878 const ASTContext &Ctx) {
3879 Qualifiers FromQuals = FromType.getQualifiers();
3880 Qualifiers ToQuals = ToType.getQualifiers();
3881
3882 // Ignore __unaligned qualifier.
3883 FromQuals.removeUnaligned();
3884
3885 // Objective-C ARC:
3886 // Check Objective-C lifetime conversions.
3887 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3888 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3889 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3890 ObjCLifetimeConversion = true;
3891 FromQuals.removeObjCLifetime();
3892 ToQuals.removeObjCLifetime();
3893 } else {
3894 // Qualification conversions cannot cast between different
3895 // Objective-C lifetime qualifiers.
3896 return false;
3897 }
3898 }
3899
3900 // Allow addition/removal of GC attributes but not changing GC attributes.
3901 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3902 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3903 FromQuals.removeObjCGCAttr();
3904 ToQuals.removeObjCGCAttr();
3905 }
3906
3907 // __ptrauth qualifiers must match exactly.
3908 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3909 return false;
3910
3911 // -- for every j > 0, if const is in cv 1,j then const is in cv
3912 // 2,j, and similarly for volatile.
3913 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3914 return false;
3915
3916 // If address spaces mismatch:
3917 // - in top level it is only valid to convert to addr space that is a
3918 // superset in all cases apart from C-style casts where we allow
3919 // conversions between overlapping address spaces.
3920 // - in non-top levels it is not a valid conversion.
3921 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3922 (!IsTopLevel ||
3923 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3924 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3925 return false;
3926
3927 // -- if the cv 1,j and cv 2,j are different, then const is in
3928 // every cv for 0 < k < j.
3929 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3930 !PreviousToQualsIncludeConst)
3931 return false;
3932
3933 // The following wording is from C++20, where the result of the conversion
3934 // is T3, not T2.
3935 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3936 // "array of unknown bound of"
3937 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3938 return false;
3939
3940 // -- if the resulting P3,i is different from P1,i [...], then const is
3941 // added to every cv 3_k for 0 < k < i.
3942 if (!CStyle && FromType->isConstantArrayType() &&
3943 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3944 return false;
3945
3946 // Keep track of whether all prior cv-qualifiers in the "to" type
3947 // include const.
3948 PreviousToQualsIncludeConst =
3949 PreviousToQualsIncludeConst && ToQuals.hasConst();
3950 return true;
3951}
3952
3953bool
3955 bool CStyle, bool &ObjCLifetimeConversion) {
3956 FromType = Context.getCanonicalType(FromType);
3957 ToType = Context.getCanonicalType(ToType);
3958 ObjCLifetimeConversion = false;
3959
3960 // If FromType and ToType are the same type, this is not a
3961 // qualification conversion.
3962 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3963 return false;
3964
3965 // (C++ 4.4p4):
3966 // A conversion can add cv-qualifiers at levels other than the first
3967 // in multi-level pointers, subject to the following rules: [...]
3968 bool PreviousToQualsIncludeConst = true;
3969 bool UnwrappedAnyPointer = false;
3970 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3971 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3972 !UnwrappedAnyPointer,
3973 PreviousToQualsIncludeConst,
3974 ObjCLifetimeConversion, getASTContext()))
3975 return false;
3976 UnwrappedAnyPointer = true;
3977 }
3978
3979 // We are left with FromType and ToType being the pointee types
3980 // after unwrapping the original FromType and ToType the same number
3981 // of times. If we unwrapped any pointers, and if FromType and
3982 // ToType have the same unqualified type (since we checked
3983 // qualifiers above), then this is a qualification conversion.
3984 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3985}
3986
3987/// - Determine whether this is a conversion from a scalar type to an
3988/// atomic type.
3989///
3990/// If successful, updates \c SCS's second and third steps in the conversion
3991/// sequence to finish the conversion.
3992static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3993 bool InOverloadResolution,
3995 bool CStyle) {
3996 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3997 if (!ToAtomic)
3998 return false;
3999
4001 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4002 InOverloadResolution, InnerSCS,
4003 CStyle, /*AllowObjCWritebackConversion=*/false))
4004 return false;
4005
4006 SCS.Second = InnerSCS.Second;
4007 SCS.setToType(1, InnerSCS.getToType(1));
4008 SCS.Third = InnerSCS.Third;
4011 SCS.setToType(2, InnerSCS.getToType(2));
4012 return true;
4013}
4014
4016 QualType ToType,
4017 bool InOverloadResolution,
4019 bool CStyle) {
4020 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4021 if (!ToOBT)
4022 return false;
4023
4024 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4025 QualType FromType = From->getType();
4026 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4027 return false;
4028
4030 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4031 InOverloadResolution, InnerSCS, CStyle,
4032 /*AllowObjCWritebackConversion=*/false))
4033 return false;
4034
4035 SCS.Second = InnerSCS.Second;
4036 SCS.setToType(1, InnerSCS.getToType(1));
4037 SCS.Third = InnerSCS.Third;
4040 SCS.setToType(2, InnerSCS.getToType(2));
4041 return true;
4042}
4043
4046 QualType Type) {
4047 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4048 if (CtorType->getNumParams() > 0) {
4049 QualType FirstArg = CtorType->getParamType(0);
4050 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4051 return true;
4052 }
4053 return false;
4054}
4055
4056static OverloadingResult
4058 CXXRecordDecl *To,
4060 OverloadCandidateSet &CandidateSet,
4061 bool AllowExplicit) {
4063 for (auto *D : S.LookupConstructors(To)) {
4064 auto Info = getConstructorInfo(D);
4065 if (!Info)
4066 continue;
4067
4068 bool Usable = !Info.Constructor->isInvalidDecl() &&
4069 S.isInitListConstructor(Info.Constructor);
4070 if (Usable) {
4071 bool SuppressUserConversions = false;
4072 if (Info.ConstructorTmpl)
4073 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4074 /*ExplicitArgs*/ nullptr, From,
4075 CandidateSet, SuppressUserConversions,
4076 /*PartialOverloading*/ false,
4077 AllowExplicit);
4078 else
4079 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4080 CandidateSet, SuppressUserConversions,
4081 /*PartialOverloading*/ false, AllowExplicit);
4082 }
4083 }
4084
4085 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4086
4088 switch (auto Result =
4089 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4090 case OR_Deleted:
4091 case OR_Success: {
4092 // Record the standard conversion we used and the conversion function.
4094 QualType ThisType = Constructor->getFunctionObjectParameterType();
4095 // Initializer lists don't have conversions as such.
4097 User.HadMultipleCandidates = HadMultipleCandidates;
4099 User.FoundConversionFunction = Best->FoundDecl;
4101 User.After.setFromType(ThisType);
4102 User.After.setAllToTypes(ToType);
4103 return Result;
4104 }
4105
4107 return OR_No_Viable_Function;
4108 case OR_Ambiguous:
4109 return OR_Ambiguous;
4110 }
4111
4112 llvm_unreachable("Invalid OverloadResult!");
4113}
4114
4115/// Determines whether there is a user-defined conversion sequence
4116/// (C++ [over.ics.user]) that converts expression From to the type
4117/// ToType. If such a conversion exists, User will contain the
4118/// user-defined conversion sequence that performs such a conversion
4119/// and this routine will return true. Otherwise, this routine returns
4120/// false and User is unspecified.
4121///
4122/// \param AllowExplicit true if the conversion should consider C++0x
4123/// "explicit" conversion functions as well as non-explicit conversion
4124/// functions (C++0x [class.conv.fct]p2).
4125///
4126/// \param AllowObjCConversionOnExplicit true if the conversion should
4127/// allow an extra Objective-C pointer conversion on uses of explicit
4128/// constructors. Requires \c AllowExplicit to also be set.
4129static OverloadingResult
4132 OverloadCandidateSet &CandidateSet,
4133 AllowedExplicit AllowExplicit,
4134 bool AllowObjCConversionOnExplicit) {
4135 assert(AllowExplicit != AllowedExplicit::None ||
4136 !AllowObjCConversionOnExplicit);
4138
4139 // Whether we will only visit constructors.
4140 bool ConstructorsOnly = false;
4141
4142 // If the type we are conversion to is a class type, enumerate its
4143 // constructors.
4144 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4145 // C++ [over.match.ctor]p1:
4146 // When objects of class type are direct-initialized (8.5), or
4147 // copy-initialized from an expression of the same or a
4148 // derived class type (8.5), overload resolution selects the
4149 // constructor. [...] For copy-initialization, the candidate
4150 // functions are all the converting constructors (12.3.1) of
4151 // that class. The argument list is the expression-list within
4152 // the parentheses of the initializer.
4153 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4154 (From->getType()->isRecordType() &&
4155 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4156 ConstructorsOnly = true;
4157
4158 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4159 // We're not going to find any constructors.
4160 } else if (auto *ToRecordDecl =
4161 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4162 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4163
4164 Expr **Args = &From;
4165 unsigned NumArgs = 1;
4166 bool ListInitializing = false;
4167 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4168 // But first, see if there is an init-list-constructor that will work.
4170 S, From, ToType, ToRecordDecl, User, CandidateSet,
4171 AllowExplicit == AllowedExplicit::All);
4173 return Result;
4174 // Never mind.
4175 CandidateSet.clear(
4177
4178 // If we're list-initializing, we pass the individual elements as
4179 // arguments, not the entire list.
4180 Args = InitList->getInits();
4181 NumArgs = InitList->getNumInits();
4182 ListInitializing = true;
4183 }
4184
4185 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4186 auto Info = getConstructorInfo(D);
4187 if (!Info)
4188 continue;
4189
4190 bool Usable = !Info.Constructor->isInvalidDecl();
4191 if (!ListInitializing)
4192 Usable = Usable && Info.Constructor->isConvertingConstructor(
4193 /*AllowExplicit*/ true);
4194 if (Usable) {
4195 bool SuppressUserConversions = !ConstructorsOnly;
4196 // C++20 [over.best.ics.general]/4.5:
4197 // if the target is the first parameter of a constructor [of class
4198 // X] and the constructor [...] is a candidate by [...] the second
4199 // phase of [over.match.list] when the initializer list has exactly
4200 // one element that is itself an initializer list, [...] and the
4201 // conversion is to X or reference to cv X, user-defined conversion
4202 // sequences are not considered.
4203 if (SuppressUserConversions && ListInitializing) {
4204 SuppressUserConversions =
4205 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4206 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4207 ToType);
4208 }
4209 if (Info.ConstructorTmpl)
4211 Info.ConstructorTmpl, Info.FoundDecl,
4212 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4213 CandidateSet, SuppressUserConversions,
4214 /*PartialOverloading*/ false,
4215 AllowExplicit == AllowedExplicit::All);
4216 else
4217 // Allow one user-defined conversion when user specifies a
4218 // From->ToType conversion via an static cast (c-style, etc).
4219 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4220 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4221 SuppressUserConversions,
4222 /*PartialOverloading*/ false,
4223 AllowExplicit == AllowedExplicit::All);
4224 }
4225 }
4226 }
4227 }
4228
4229 // Enumerate conversion functions, if we're allowed to.
4230 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4231 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4232 // No conversion functions from incomplete types.
4233 } else if (const RecordType *FromRecordType =
4234 From->getType()->getAsCanonical<RecordType>()) {
4235 if (auto *FromRecordDecl =
4236 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4237 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4238 // Add all of the conversion functions as candidates.
4239 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4240 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4241 DeclAccessPair FoundDecl = I.getPair();
4242 NamedDecl *D = FoundDecl.getDecl();
4243 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4244 if (isa<UsingShadowDecl>(D))
4245 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4246
4247 CXXConversionDecl *Conv;
4248 FunctionTemplateDecl *ConvTemplate;
4249 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4250 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4251 else
4252 Conv = cast<CXXConversionDecl>(D);
4253
4254 if (ConvTemplate)
4256 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4257 CandidateSet, AllowObjCConversionOnExplicit,
4258 AllowExplicit != AllowedExplicit::None);
4259 else
4260 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4261 CandidateSet, AllowObjCConversionOnExplicit,
4262 AllowExplicit != AllowedExplicit::None);
4263 }
4264 }
4265 }
4266
4267 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4268
4270 switch (auto Result =
4271 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4272 case OR_Success:
4273 case OR_Deleted:
4274 // Record the standard conversion we used and the conversion function.
4276 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4277 // C++ [over.ics.user]p1:
4278 // If the user-defined conversion is specified by a
4279 // constructor (12.3.1), the initial standard conversion
4280 // sequence converts the source type to the type required by
4281 // the argument of the constructor.
4282 //
4283 if (isa<InitListExpr>(From)) {
4284 // Initializer lists don't have conversions as such.
4286 User.Before.FromBracedInitList = true;
4287 } else {
4288 if (Best->Conversions[0].isEllipsis())
4289 User.EllipsisConversion = true;
4290 else {
4291 User.Before = Best->Conversions[0].Standard;
4292 User.EllipsisConversion = false;
4293 }
4294 }
4295 User.HadMultipleCandidates = HadMultipleCandidates;
4297 User.FoundConversionFunction = Best->FoundDecl;
4299 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4300 User.After.setAllToTypes(ToType);
4301 return Result;
4302 }
4303 if (CXXConversionDecl *Conversion
4304 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4305
4306 assert(Best->HasFinalConversion);
4307
4308 // C++ [over.ics.user]p1:
4309 //
4310 // [...] If the user-defined conversion is specified by a
4311 // conversion function (12.3.2), the initial standard
4312 // conversion sequence converts the source type to the
4313 // implicit object parameter of the conversion function.
4314 User.Before = Best->Conversions[0].Standard;
4315 User.HadMultipleCandidates = HadMultipleCandidates;
4316 User.ConversionFunction = Conversion;
4317 User.FoundConversionFunction = Best->FoundDecl;
4318 User.EllipsisConversion = false;
4319
4320 // C++ [over.ics.user]p2:
4321 // The second standard conversion sequence converts the
4322 // result of the user-defined conversion to the target type
4323 // for the sequence. Since an implicit conversion sequence
4324 // is an initialization, the special rules for
4325 // initialization by user-defined conversion apply when
4326 // selecting the best user-defined conversion for a
4327 // user-defined conversion sequence (see 13.3.3 and
4328 // 13.3.3.1).
4329 User.After = Best->FinalConversion;
4330 return Result;
4331 }
4332 llvm_unreachable("Not a constructor or conversion function?");
4333
4335 return OR_No_Viable_Function;
4336
4337 case OR_Ambiguous:
4338 return OR_Ambiguous;
4339 }
4340
4341 llvm_unreachable("Invalid OverloadResult!");
4342}
4343
4344bool
4347 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4349 OverloadingResult OvResult =
4350 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4351 CandidateSet, AllowedExplicit::None, false);
4352
4353 if (!(OvResult == OR_Ambiguous ||
4354 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4355 return false;
4356
4357 auto Cands = CandidateSet.CompleteCandidates(
4358 *this,
4360 From);
4361 if (OvResult == OR_Ambiguous)
4362 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4363 << From->getType() << ToType << From->getSourceRange();
4364 else { // OR_No_Viable_Function && !CandidateSet.empty()
4365 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4366 diag::err_typecheck_nonviable_condition_incomplete,
4367 From->getType(), From->getSourceRange()))
4368 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4369 << false << From->getType() << From->getSourceRange() << ToType;
4370 }
4371
4372 CandidateSet.NoteCandidates(
4373 *this, From, Cands);
4374 return true;
4375}
4376
4377// Helper for compareConversionFunctions that gets the FunctionType that the
4378// conversion-operator return value 'points' to, or nullptr.
4379static const FunctionType *
4381 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4382 const PointerType *RetPtrTy =
4383 ConvFuncTy->getReturnType()->getAs<PointerType>();
4384
4385 if (!RetPtrTy)
4386 return nullptr;
4387
4388 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4389}
4390
4391/// Compare the user-defined conversion functions or constructors
4392/// of two user-defined conversion sequences to determine whether any ordering
4393/// is possible.
4396 FunctionDecl *Function2) {
4397 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4398 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4399 if (!Conv1 || !Conv2)
4401
4402 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4404
4405 // Objective-C++:
4406 // If both conversion functions are implicitly-declared conversions from
4407 // a lambda closure type to a function pointer and a block pointer,
4408 // respectively, always prefer the conversion to a function pointer,
4409 // because the function pointer is more lightweight and is more likely
4410 // to keep code working.
4411 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4412 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4413 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4414 if (Block1 != Block2)
4415 return Block1 ? ImplicitConversionSequence::Worse
4417 }
4418
4419 // In order to support multiple calling conventions for the lambda conversion
4420 // operator (such as when the free and member function calling convention is
4421 // different), prefer the 'free' mechanism, followed by the calling-convention
4422 // of operator(). The latter is in place to support the MSVC-like solution of
4423 // defining ALL of the possible conversions in regards to calling-convention.
4424 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4425 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4426
4427 if (Conv1FuncRet && Conv2FuncRet &&
4428 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4429 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4430 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4431
4432 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4433 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4434
4435 CallingConv CallOpCC =
4436 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4438 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4440 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4441
4442 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4443 for (CallingConv CC : PrefOrder) {
4444 if (Conv1CC == CC)
4446 if (Conv2CC == CC)
4448 }
4449 }
4450
4452}
4453
4460
4461/// CompareImplicitConversionSequences - Compare two implicit
4462/// conversion sequences to determine whether one is better than the
4463/// other or if they are indistinguishable (C++ 13.3.3.2).
4466 const ImplicitConversionSequence& ICS1,
4467 const ImplicitConversionSequence& ICS2)
4468{
4469 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4470 // conversion sequences (as defined in 13.3.3.1)
4471 // -- a standard conversion sequence (13.3.3.1.1) is a better
4472 // conversion sequence than a user-defined conversion sequence or
4473 // an ellipsis conversion sequence, and
4474 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4475 // conversion sequence than an ellipsis conversion sequence
4476 // (13.3.3.1.3).
4477 //
4478 // C++0x [over.best.ics]p10:
4479 // For the purpose of ranking implicit conversion sequences as
4480 // described in 13.3.3.2, the ambiguous conversion sequence is
4481 // treated as a user-defined sequence that is indistinguishable
4482 // from any other user-defined conversion sequence.
4483
4484 // String literal to 'char *' conversion has been deprecated in C++03. It has
4485 // been removed from C++11. We still accept this conversion, if it happens at
4486 // the best viable function. Otherwise, this conversion is considered worse
4487 // than ellipsis conversion. Consider this as an extension; this is not in the
4488 // standard. For example:
4489 //
4490 // int &f(...); // #1
4491 // void f(char*); // #2
4492 // void g() { int &r = f("foo"); }
4493 //
4494 // In C++03, we pick #2 as the best viable function.
4495 // In C++11, we pick #1 as the best viable function, because ellipsis
4496 // conversion is better than string-literal to char* conversion (since there
4497 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4498 // convert arguments, #2 would be the best viable function in C++11.
4499 // If the best viable function has this conversion, a warning will be issued
4500 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4501
4502 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4505 // Ill-formedness must not differ
4506 ICS1.isBad() == ICS2.isBad())
4510
4511 if (ICS1.getKindRank() < ICS2.getKindRank())
4513 if (ICS2.getKindRank() < ICS1.getKindRank())
4515
4516 // The following checks require both conversion sequences to be of
4517 // the same kind.
4518 if (ICS1.getKind() != ICS2.getKind())
4520
4523
4524 // Two implicit conversion sequences of the same form are
4525 // indistinguishable conversion sequences unless one of the
4526 // following rules apply: (C++ 13.3.3.2p3):
4527
4528 // List-initialization sequence L1 is a better conversion sequence than
4529 // list-initialization sequence L2 if:
4530 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4531 // if not that,
4532 // — L1 and L2 convert to arrays of the same element type, and either the
4533 // number of elements n_1 initialized by L1 is less than the number of
4534 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4535 // an array of unknown bound and L1 does not,
4536 // even if one of the other rules in this paragraph would otherwise apply.
4537 if (!ICS1.isBad()) {
4538 bool StdInit1 = false, StdInit2 = false;
4541 nullptr);
4544 nullptr);
4545 if (StdInit1 != StdInit2)
4546 return StdInit1 ? ImplicitConversionSequence::Better
4548
4551 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4553 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4555 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4556 CAT2->getElementType())) {
4557 // Both to arrays of the same element type
4558 if (CAT1->getSize() != CAT2->getSize())
4559 // Different sized, the smaller wins
4560 return CAT1->getSize().ult(CAT2->getSize())
4565 // One is incomplete, it loses
4569 }
4570 }
4571 }
4572
4573 if (ICS1.isStandard())
4574 // Standard conversion sequence S1 is a better conversion sequence than
4575 // standard conversion sequence S2 if [...]
4577 ICS1.Standard, ICS2.Standard);
4578 else if (ICS1.isUserDefined()) {
4579 // With lazy template loading, it is possible to find non-canonical
4580 // FunctionDecls, depending on when redecl chains are completed. Make sure
4581 // to compare the canonical decls of conversion functions. This avoids
4582 // ambiguity problems for templated conversion operators.
4583 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4584 if (ConvFunc1)
4585 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4586 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4587 if (ConvFunc2)
4588 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4589 // User-defined conversion sequence U1 is a better conversion
4590 // sequence than another user-defined conversion sequence U2 if
4591 // they contain the same user-defined conversion function or
4592 // constructor and if the second standard conversion sequence of
4593 // U1 is better than the second standard conversion sequence of
4594 // U2 (C++ 13.3.3.2p3).
4595 if (ConvFunc1 == ConvFunc2)
4597 ICS1.UserDefined.After,
4598 ICS2.UserDefined.After);
4599 else
4603 }
4604
4605 return Result;
4606}
4607
4608// Per 13.3.3.2p3, compare the given standard conversion sequences to
4609// determine if one is a proper subset of the other.
4612 const StandardConversionSequence& SCS1,
4613 const StandardConversionSequence& SCS2) {
4616
4617 // the identity conversion sequence is considered to be a subsequence of
4618 // any non-identity conversion sequence
4619 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4621 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4623
4624 if (SCS1.Second != SCS2.Second) {
4625 if (SCS1.Second == ICK_Identity)
4627 else if (SCS2.Second == ICK_Identity)
4629 else
4631 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4633
4634 if (SCS1.Third == SCS2.Third) {
4635 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4637 }
4638
4639 if (SCS1.Third == ICK_Identity)
4643
4644 if (SCS2.Third == ICK_Identity)
4648
4650}
4651
4652/// Determine whether one of the given reference bindings is better
4653/// than the other based on what kind of bindings they are.
4654static bool
4656 const StandardConversionSequence &SCS2) {
4657 // C++0x [over.ics.rank]p3b4:
4658 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4659 // implicit object parameter of a non-static member function declared
4660 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4661 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4662 // lvalue reference to a function lvalue and S2 binds an rvalue
4663 // reference*.
4664 //
4665 // FIXME: Rvalue references. We're going rogue with the above edits,
4666 // because the semantics in the current C++0x working paper (N3225 at the
4667 // time of this writing) break the standard definition of std::forward
4668 // and std::reference_wrapper when dealing with references to functions.
4669 // Proposed wording changes submitted to CWG for consideration.
4672 return false;
4673
4674 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4675 SCS2.IsLvalueReference) ||
4678}
4679
4685
4686/// Returns kind of fixed enum promotion the \a SCS uses.
4687static FixedEnumPromotion
4689
4690 if (SCS.Second != ICK_Integral_Promotion)
4692
4693 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4694 if (!Enum)
4696
4697 if (!Enum->isFixed())
4699
4700 QualType UnderlyingType = Enum->getIntegerType();
4701 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4703
4705}
4706
4707/// CompareStandardConversionSequences - Compare two standard
4708/// conversion sequences to determine whether one is better than the
4709/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4712 const StandardConversionSequence& SCS1,
4713 const StandardConversionSequence& SCS2)
4714{
4715 // Standard conversion sequence S1 is a better conversion sequence
4716 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4717
4718 // -- S1 is a proper subsequence of S2 (comparing the conversion
4719 // sequences in the canonical form defined by 13.3.3.1.1,
4720 // excluding any Lvalue Transformation; the identity conversion
4721 // sequence is considered to be a subsequence of any
4722 // non-identity conversion sequence) or, if not that,
4725 return CK;
4726
4727 // -- the rank of S1 is better than the rank of S2 (by the rules
4728 // defined below), or, if not that,
4729 ImplicitConversionRank Rank1 = SCS1.getRank();
4730 ImplicitConversionRank Rank2 = SCS2.getRank();
4731 if (Rank1 < Rank2)
4733 else if (Rank2 < Rank1)
4735
4736 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4737 // are indistinguishable unless one of the following rules
4738 // applies:
4739
4740 // A conversion that is not a conversion of a pointer, or
4741 // pointer to member, to bool is better than another conversion
4742 // that is such a conversion.
4744 return SCS2.isPointerConversionToBool()
4747
4748 // C++14 [over.ics.rank]p4b2:
4749 // This is retroactively applied to C++11 by CWG 1601.
4750 //
4751 // A conversion that promotes an enumeration whose underlying type is fixed
4752 // to its underlying type is better than one that promotes to the promoted
4753 // underlying type, if the two are different.
4756 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4757 FEP1 != FEP2)
4761
4762 // C++ [over.ics.rank]p4b2:
4763 //
4764 // If class B is derived directly or indirectly from class A,
4765 // conversion of B* to A* is better than conversion of B* to
4766 // void*, and conversion of A* to void* is better than conversion
4767 // of B* to void*.
4768 bool SCS1ConvertsToVoid
4770 bool SCS2ConvertsToVoid
4772 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4773 // Exactly one of the conversion sequences is a conversion to
4774 // a void pointer; it's the worse conversion.
4775 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4777 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4778 // Neither conversion sequence converts to a void pointer; compare
4779 // their derived-to-base conversions.
4781 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4782 return DerivedCK;
4783 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4784 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4785 // Both conversion sequences are conversions to void
4786 // pointers. Compare the source types to determine if there's an
4787 // inheritance relationship in their sources.
4788 QualType FromType1 = SCS1.getFromType();
4789 QualType FromType2 = SCS2.getFromType();
4790
4791 // Adjust the types we're converting from via the array-to-pointer
4792 // conversion, if we need to.
4793 if (SCS1.First == ICK_Array_To_Pointer)
4794 FromType1 = S.Context.getArrayDecayedType(FromType1);
4795 if (SCS2.First == ICK_Array_To_Pointer)
4796 FromType2 = S.Context.getArrayDecayedType(FromType2);
4797
4798 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4799 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4800
4801 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4803 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4805
4806 // Objective-C++: If one interface is more specific than the
4807 // other, it is the better one.
4808 const ObjCObjectPointerType* FromObjCPtr1
4809 = FromType1->getAs<ObjCObjectPointerType>();
4810 const ObjCObjectPointerType* FromObjCPtr2
4811 = FromType2->getAs<ObjCObjectPointerType>();
4812 if (FromObjCPtr1 && FromObjCPtr2) {
4813 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4814 FromObjCPtr2);
4815 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4816 FromObjCPtr1);
4817 if (AssignLeft != AssignRight) {
4818 return AssignLeft? ImplicitConversionSequence::Better
4820 }
4821 }
4822 }
4823
4824 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4825 // Check for a better reference binding based on the kind of bindings.
4826 if (isBetterReferenceBindingKind(SCS1, SCS2))
4828 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4830 }
4831
4832 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4833 // bullet 3).
4835 = CompareQualificationConversions(S, SCS1, SCS2))
4836 return QualCK;
4837
4840 return ObtCK;
4841
4842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4843 // C++ [over.ics.rank]p3b4:
4844 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4845 // which the references refer are the same type except for
4846 // top-level cv-qualifiers, and the type to which the reference
4847 // initialized by S2 refers is more cv-qualified than the type
4848 // to which the reference initialized by S1 refers.
4849 QualType T1 = SCS1.getToType(2);
4850 QualType T2 = SCS2.getToType(2);
4851 T1 = S.Context.getCanonicalType(T1);
4852 T2 = S.Context.getCanonicalType(T2);
4853 Qualifiers T1Quals, T2Quals;
4854 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4855 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4856 if (UnqualT1 == UnqualT2) {
4857 // Objective-C++ ARC: If the references refer to objects with different
4858 // lifetimes, prefer bindings that don't change lifetime.
4864 }
4865
4866 // If the type is an array type, promote the element qualifiers to the
4867 // type for comparison.
4868 if (isa<ArrayType>(T1) && T1Quals)
4869 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4870 if (isa<ArrayType>(T2) && T2Quals)
4871 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4872 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4874 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4876 }
4877 }
4878
4879 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4880 // floating-to-integral conversion if the integral conversion
4881 // is between types of the same size.
4882 // For example:
4883 // void f(float);
4884 // void f(int);
4885 // int main {
4886 // long a;
4887 // f(a);
4888 // }
4889 // Here, MSVC will call f(int) instead of generating a compile error
4890 // as clang will do in standard mode.
4891 if (S.getLangOpts().MSVCCompat &&
4894 SCS2.Second == ICK_Floating_Integral &&
4895 S.Context.getTypeSize(SCS1.getFromType()) ==
4896 S.Context.getTypeSize(SCS1.getToType(2)))
4898
4899 // Prefer a compatible vector conversion over a lax vector conversion
4900 // For example:
4901 //
4902 // typedef float __v4sf __attribute__((__vector_size__(16)));
4903 // void f(vector float);
4904 // void f(vector signed int);
4905 // int main() {
4906 // __v4sf a;
4907 // f(a);
4908 // }
4909 // Here, we'd like to choose f(vector float) and not
4910 // report an ambiguous call error
4911 if (SCS1.Second == ICK_Vector_Conversion &&
4912 SCS2.Second == ICK_Vector_Conversion) {
4913 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4914 SCS1.getFromType(), SCS1.getToType(2));
4915 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4916 SCS2.getFromType(), SCS2.getToType(2));
4917
4918 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4919 return SCS1IsCompatibleVectorConversion
4922 }
4923
4924 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4926 bool SCS1IsCompatibleSVEVectorConversion =
4927 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4928 bool SCS2IsCompatibleSVEVectorConversion =
4929 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4930
4931 if (SCS1IsCompatibleSVEVectorConversion !=
4932 SCS2IsCompatibleSVEVectorConversion)
4933 return SCS1IsCompatibleSVEVectorConversion
4936 }
4937
4938 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4940 bool SCS1IsCompatibleRVVVectorConversion =
4942 bool SCS2IsCompatibleRVVVectorConversion =
4944
4945 if (SCS1IsCompatibleRVVVectorConversion !=
4946 SCS2IsCompatibleRVVVectorConversion)
4947 return SCS1IsCompatibleRVVVectorConversion
4950 }
4952}
4953
4954/// CompareOverflowBehaviorConversions - Compares two standard conversion
4955/// sequences to determine whether they can be ranked based on their
4956/// OverflowBehaviorType's underlying type.
4972
4973/// CompareQualificationConversions - Compares two standard conversion
4974/// sequences to determine whether they can be ranked based on their
4975/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4978 const StandardConversionSequence& SCS1,
4979 const StandardConversionSequence& SCS2) {
4980 // C++ [over.ics.rank]p3:
4981 // -- S1 and S2 differ only in their qualification conversion and
4982 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4983 // [C++98]
4984 // [...] and the cv-qualification signature of type T1 is a proper subset
4985 // of the cv-qualification signature of type T2, and S1 is not the
4986 // deprecated string literal array-to-pointer conversion (4.2).
4987 // [C++2a]
4988 // [...] where T1 can be converted to T2 by a qualification conversion.
4989 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4990 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4992
4993 // FIXME: the example in the standard doesn't use a qualification
4994 // conversion (!)
4995 QualType T1 = SCS1.getToType(2);
4996 QualType T2 = SCS2.getToType(2);
4997 T1 = S.Context.getCanonicalType(T1);
4998 T2 = S.Context.getCanonicalType(T2);
4999 assert(!T1->isReferenceType() && !T2->isReferenceType());
5000 Qualifiers T1Quals, T2Quals;
5001 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5002 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5003
5004 // If the types are the same, we won't learn anything by unwrapping
5005 // them.
5006 if (UnqualT1 == UnqualT2)
5008
5009 // Don't ever prefer a standard conversion sequence that uses the deprecated
5010 // string literal array to pointer conversion.
5011 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5012 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5013
5014 // Objective-C++ ARC:
5015 // Prefer qualification conversions not involving a change in lifetime
5016 // to qualification conversions that do change lifetime.
5019 CanPick1 = false;
5022 CanPick2 = false;
5023
5024 bool ObjCLifetimeConversion;
5025 if (CanPick1 &&
5026 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5027 CanPick1 = false;
5028 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5029 // directions, so we can't short-cut this second check in general.
5030 if (CanPick2 &&
5031 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5032 CanPick2 = false;
5033
5034 if (CanPick1 != CanPick2)
5035 return CanPick1 ? ImplicitConversionSequence::Better
5038}
5039
5040/// CompareDerivedToBaseConversions - Compares two standard conversion
5041/// sequences to determine whether they can be ranked based on their
5042/// various kinds of derived-to-base conversions (C++
5043/// [over.ics.rank]p4b3). As part of these checks, we also look at
5044/// conversions between Objective-C interface types.
5047 const StandardConversionSequence& SCS1,
5048 const StandardConversionSequence& SCS2) {
5049 QualType FromType1 = SCS1.getFromType();
5050 QualType ToType1 = SCS1.getToType(1);
5051 QualType FromType2 = SCS2.getFromType();
5052 QualType ToType2 = SCS2.getToType(1);
5053
5054 // Adjust the types we're converting from via the array-to-pointer
5055 // conversion, if we need to.
5056 if (SCS1.First == ICK_Array_To_Pointer)
5057 FromType1 = S.Context.getArrayDecayedType(FromType1);
5058 if (SCS2.First == ICK_Array_To_Pointer)
5059 FromType2 = S.Context.getArrayDecayedType(FromType2);
5060
5061 // Canonicalize all of the types.
5062 FromType1 = S.Context.getCanonicalType(FromType1);
5063 ToType1 = S.Context.getCanonicalType(ToType1);
5064 FromType2 = S.Context.getCanonicalType(FromType2);
5065 ToType2 = S.Context.getCanonicalType(ToType2);
5066
5067 // C++ [over.ics.rank]p4b3:
5068 //
5069 // If class B is derived directly or indirectly from class A and
5070 // class C is derived directly or indirectly from B,
5071 //
5072 // Compare based on pointer conversions.
5073 if (SCS1.Second == ICK_Pointer_Conversion &&
5075 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5076 FromType1->isPointerType() && FromType2->isPointerType() &&
5077 ToType1->isPointerType() && ToType2->isPointerType()) {
5078 QualType FromPointee1 =
5080 QualType ToPointee1 =
5082 QualType FromPointee2 =
5084 QualType ToPointee2 =
5086
5087 // -- conversion of C* to B* is better than conversion of C* to A*,
5088 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5089 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5091 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5093 }
5094
5095 // -- conversion of B* to A* is better than conversion of C* to A*,
5096 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5097 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5099 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5101 }
5102 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5104 const ObjCObjectPointerType *FromPtr1
5105 = FromType1->getAs<ObjCObjectPointerType>();
5106 const ObjCObjectPointerType *FromPtr2
5107 = FromType2->getAs<ObjCObjectPointerType>();
5108 const ObjCObjectPointerType *ToPtr1
5109 = ToType1->getAs<ObjCObjectPointerType>();
5110 const ObjCObjectPointerType *ToPtr2
5111 = ToType2->getAs<ObjCObjectPointerType>();
5112
5113 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5114 // Apply the same conversion ranking rules for Objective-C pointer types
5115 // that we do for C++ pointers to class types. However, we employ the
5116 // Objective-C pseudo-subtyping relationship used for assignment of
5117 // Objective-C pointer types.
5118 bool FromAssignLeft
5119 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5120 bool FromAssignRight
5121 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5122 bool ToAssignLeft
5123 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5124 bool ToAssignRight
5125 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5126
5127 // A conversion to an a non-id object pointer type or qualified 'id'
5128 // type is better than a conversion to 'id'.
5129 if (ToPtr1->isObjCIdType() &&
5130 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5132 if (ToPtr2->isObjCIdType() &&
5133 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5135
5136 // A conversion to a non-id object pointer type is better than a
5137 // conversion to a qualified 'id' type
5138 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5140 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5142
5143 // A conversion to an a non-Class object pointer type or qualified 'Class'
5144 // type is better than a conversion to 'Class'.
5145 if (ToPtr1->isObjCClassType() &&
5146 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5148 if (ToPtr2->isObjCClassType() &&
5149 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5151
5152 // A conversion to a non-Class object pointer type is better than a
5153 // conversion to a qualified 'Class' type.
5154 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5156 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5158
5159 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5160 if (S.Context.hasSameType(FromType1, FromType2) &&
5161 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5162 (ToAssignLeft != ToAssignRight)) {
5163 if (FromPtr1->isSpecialized()) {
5164 // "conversion of B<A> * to B * is better than conversion of B * to
5165 // C *.
5166 bool IsFirstSame =
5167 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5168 bool IsSecondSame =
5169 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5170 if (IsFirstSame) {
5171 if (!IsSecondSame)
5173 } else if (IsSecondSame)
5175 }
5176 return ToAssignLeft? ImplicitConversionSequence::Worse
5178 }
5179
5180 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5181 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5182 (FromAssignLeft != FromAssignRight))
5183 return FromAssignLeft? ImplicitConversionSequence::Better
5185 }
5186 }
5187
5188 // Ranking of member-pointer types.
5189 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5190 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5191 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5192 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5193 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5194 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5195 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5196 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5197 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5198 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5199 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5200 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5201 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5202 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5204 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5206 }
5207 // conversion of B::* to C::* is better than conversion of A::* to C::*
5208 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5209 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5211 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5213 }
5214 }
5215
5216 if (SCS1.Second == ICK_Derived_To_Base) {
5217 // -- conversion of C to B is better than conversion of C to A,
5218 // -- binding of an expression of type C to a reference of type
5219 // B& is better than binding an expression of type C to a
5220 // reference of type A&,
5221 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5222 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5223 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5225 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5227 }
5228
5229 // -- conversion of B to A is better than conversion of C to A.
5230 // -- binding of an expression of type B to a reference of type
5231 // A& is better than binding an expression of type C to a
5232 // reference of type A&,
5233 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5234 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5235 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5237 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5239 }
5240 }
5241
5243}
5244
5246 if (!T.getQualifiers().hasUnaligned())
5247 return T;
5248
5249 Qualifiers Q;
5250 T = Ctx.getUnqualifiedArrayType(T, Q);
5251 Q.removeUnaligned();
5252 return Ctx.getQualifiedType(T, Q);
5253}
5254
5257 QualType OrigT1, QualType OrigT2,
5258 ReferenceConversions *ConvOut) {
5259 assert(!OrigT1->isReferenceType() &&
5260 "T1 must be the pointee type of the reference type");
5261 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5262
5263 QualType T1 = Context.getCanonicalType(OrigT1);
5264 QualType T2 = Context.getCanonicalType(OrigT2);
5265 Qualifiers T1Quals, T2Quals;
5266 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5267 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5268
5269 ReferenceConversions ConvTmp;
5270 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5271 Conv = ReferenceConversions();
5272
5273 // C++2a [dcl.init.ref]p4:
5274 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5275 // reference-related to "cv2 T2" if T1 is similar to T2, or
5276 // T1 is a base class of T2.
5277 // "cv1 T1" is reference-compatible with "cv2 T2" if
5278 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5279 // "pointer to cv1 T1" via a standard conversion sequence.
5280
5281 // Check for standard conversions we can apply to pointers: derived-to-base
5282 // conversions, ObjC pointer conversions, and function pointer conversions.
5283 // (Qualification conversions are checked last.)
5284 if (UnqualT1 == UnqualT2) {
5285 // Nothing to do.
5286 } else if (isCompleteType(Loc, OrigT2) &&
5287 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5288 Conv |= ReferenceConversions::DerivedToBase;
5289 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5290 UnqualT2->isObjCObjectOrInterfaceType() &&
5291 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5292 Conv |= ReferenceConversions::ObjC;
5293 else if (UnqualT2->isFunctionType() &&
5294 IsFunctionConversion(UnqualT2, UnqualT1)) {
5295 Conv |= ReferenceConversions::Function;
5296 // No need to check qualifiers; function types don't have them.
5297 return Ref_Compatible;
5298 }
5299 bool ConvertedReferent = Conv != 0;
5300
5301 // We can have a qualification conversion. Compute whether the types are
5302 // similar at the same time.
5303 bool PreviousToQualsIncludeConst = true;
5304 bool TopLevel = true;
5305 do {
5306 if (T1 == T2)
5307 break;
5308
5309 // We will need a qualification conversion.
5310 Conv |= ReferenceConversions::Qualification;
5311
5312 // Track whether we performed a qualification conversion anywhere other
5313 // than the top level. This matters for ranking reference bindings in
5314 // overload resolution.
5315 if (!TopLevel)
5316 Conv |= ReferenceConversions::NestedQualification;
5317
5318 // MS compiler ignores __unaligned qualifier for references; do the same.
5319 T1 = withoutUnaligned(Context, T1);
5320 T2 = withoutUnaligned(Context, T2);
5321
5322 // If we find a qualifier mismatch, the types are not reference-compatible,
5323 // but are still be reference-related if they're similar.
5324 bool ObjCLifetimeConversion = false;
5325 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5326 PreviousToQualsIncludeConst,
5327 ObjCLifetimeConversion, getASTContext()))
5328 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5329 ? Ref_Related
5331
5332 // FIXME: Should we track this for any level other than the first?
5333 if (ObjCLifetimeConversion)
5334 Conv |= ReferenceConversions::ObjCLifetime;
5335
5336 TopLevel = false;
5337 } while (Context.UnwrapSimilarTypes(T1, T2));
5338
5339 // At this point, if the types are reference-related, we must either have the
5340 // same inner type (ignoring qualifiers), or must have already worked out how
5341 // to convert the referent.
5342 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5345}
5346
5347/// Look for a user-defined conversion to a value reference-compatible
5348/// with DeclType. Return true if something definite is found.
5349static bool
5351 QualType DeclType, SourceLocation DeclLoc,
5352 Expr *Init, QualType T2, bool AllowRvalues,
5353 bool AllowExplicit) {
5354 assert(T2->isRecordType() && "Can only find conversions of record types.");
5355 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5356 OverloadCandidateSet CandidateSet(
5358 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5359 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5360 NamedDecl *D = *I;
5362 if (isa<UsingShadowDecl>(D))
5363 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5364
5365 FunctionTemplateDecl *ConvTemplate
5366 = dyn_cast<FunctionTemplateDecl>(D);
5367 CXXConversionDecl *Conv;
5368 if (ConvTemplate)
5369 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5370 else
5371 Conv = cast<CXXConversionDecl>(D);
5372
5373 if (AllowRvalues) {
5374 // If we are initializing an rvalue reference, don't permit conversion
5375 // functions that return lvalues.
5376 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5377 const ReferenceType *RefType
5379 if (RefType && !RefType->getPointeeType()->isFunctionType())
5380 continue;
5381 }
5382
5383 if (!ConvTemplate &&
5385 DeclLoc,
5386 Conv->getConversionType()
5391 continue;
5392 } else {
5393 // If the conversion function doesn't return a reference type,
5394 // it can't be considered for this conversion. An rvalue reference
5395 // is only acceptable if its referencee is a function type.
5396
5397 const ReferenceType *RefType =
5399 if (!RefType ||
5400 (!RefType->isLValueReferenceType() &&
5401 !RefType->getPointeeType()->isFunctionType()))
5402 continue;
5403 }
5404
5405 if (ConvTemplate)
5407 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5408 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5409 else
5411 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5412 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5413 }
5414
5415 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5416
5418 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5419 case OR_Success:
5420
5421 assert(Best->HasFinalConversion);
5422
5423 // C++ [over.ics.ref]p1:
5424 //
5425 // [...] If the parameter binds directly to the result of
5426 // applying a conversion function to the argument
5427 // expression, the implicit conversion sequence is a
5428 // user-defined conversion sequence (13.3.3.1.2), with the
5429 // second standard conversion sequence either an identity
5430 // conversion or, if the conversion function returns an
5431 // entity of a type that is a derived class of the parameter
5432 // type, a derived-to-base Conversion.
5433 if (!Best->FinalConversion.DirectBinding)
5434 return false;
5435
5436 ICS.setUserDefined();
5437 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5438 ICS.UserDefined.After = Best->FinalConversion;
5439 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5440 ICS.UserDefined.ConversionFunction = Best->Function;
5441 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5442 ICS.UserDefined.EllipsisConversion = false;
5443 assert(ICS.UserDefined.After.ReferenceBinding &&
5445 "Expected a direct reference binding!");
5446 return true;
5447
5448 case OR_Ambiguous:
5449 ICS.setAmbiguous();
5450 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5451 Cand != CandidateSet.end(); ++Cand)
5452 if (Cand->Best)
5453 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5454 return true;
5455
5457 case OR_Deleted:
5458 // There was no suitable conversion, or we found a deleted
5459 // conversion; continue with other checks.
5460 return false;
5461 }
5462
5463 llvm_unreachable("Invalid OverloadResult!");
5464}
5465
5466/// Compute an implicit conversion sequence for reference
5467/// initialization.
5468static ImplicitConversionSequence
5470 SourceLocation DeclLoc,
5471 bool SuppressUserConversions,
5472 bool AllowExplicit) {
5473 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5474
5475 // Most paths end in a failed conversion.
5478
5479 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5480 QualType T2 = Init->getType();
5481
5482 // If the initializer is the address of an overloaded function, try
5483 // to resolve the overloaded function. If all goes well, T2 is the
5484 // type of the resulting function.
5485 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5488 false, Found))
5489 T2 = Fn->getType();
5490 }
5491
5492 // Compute some basic properties of the types and the initializer.
5493 bool isRValRef = DeclType->isRValueReferenceType();
5494 Expr::Classification InitCategory = Init->Classify(S.Context);
5495
5497 Sema::ReferenceCompareResult RefRelationship =
5498 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5499
5500 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5501 ICS.setStandard();
5503 // FIXME: A reference binding can be a function conversion too. We should
5504 // consider that when ordering reference-to-function bindings.
5505 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5507 : (RefConv & Sema::ReferenceConversions::ObjC)
5509 : ICK_Identity;
5511 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5512 // a reference binding that performs a non-top-level qualification
5513 // conversion as a qualification conversion, not as an identity conversion.
5514 ICS.Standard.Third = (RefConv &
5515 Sema::ReferenceConversions::NestedQualification)
5517 : ICK_Identity;
5518 ICS.Standard.setFromType(T2);
5519 ICS.Standard.setToType(0, T2);
5520 ICS.Standard.setToType(1, T1);
5521 ICS.Standard.setToType(2, T1);
5522 ICS.Standard.ReferenceBinding = true;
5523 ICS.Standard.DirectBinding = BindsDirectly;
5524 ICS.Standard.IsLvalueReference = !isRValRef;
5526 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5529 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5530 ICS.Standard.FromBracedInitList = false;
5531 ICS.Standard.CopyConstructor = nullptr;
5533 };
5534
5535 // C++0x [dcl.init.ref]p5:
5536 // A reference to type "cv1 T1" is initialized by an expression
5537 // of type "cv2 T2" as follows:
5538
5539 // -- If reference is an lvalue reference and the initializer expression
5540 if (!isRValRef) {
5541 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5542 // reference-compatible with "cv2 T2," or
5543 //
5544 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5545 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5546 // C++ [over.ics.ref]p1:
5547 // When a parameter of reference type binds directly (8.5.3)
5548 // to an argument expression, the implicit conversion sequence
5549 // is the identity conversion, unless the argument expression
5550 // has a type that is a derived class of the parameter type,
5551 // in which case the implicit conversion sequence is a
5552 // derived-to-base Conversion (13.3.3.1).
5553 SetAsReferenceBinding(/*BindsDirectly=*/true);
5554
5555 // Nothing more to do: the inaccessibility/ambiguity check for
5556 // derived-to-base conversions is suppressed when we're
5557 // computing the implicit conversion sequence (C++
5558 // [over.best.ics]p2).
5559 return ICS;
5560 }
5561
5562 // -- has a class type (i.e., T2 is a class type), where T1 is
5563 // not reference-related to T2, and can be implicitly
5564 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5565 // is reference-compatible with "cv3 T3" 92) (this
5566 // conversion is selected by enumerating the applicable
5567 // conversion functions (13.3.1.6) and choosing the best
5568 // one through overload resolution (13.3)),
5569 if (!SuppressUserConversions && T2->isRecordType() &&
5570 S.isCompleteType(DeclLoc, T2) &&
5571 RefRelationship == Sema::Ref_Incompatible) {
5572 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5573 Init, T2, /*AllowRvalues=*/false,
5574 AllowExplicit))
5575 return ICS;
5576 }
5577 }
5578
5579 // -- Otherwise, the reference shall be an lvalue reference to a
5580 // non-volatile const type (i.e., cv1 shall be const), or the reference
5581 // shall be an rvalue reference.
5582 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5583 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5585 return ICS;
5586 }
5587
5588 // -- If the initializer expression
5589 //
5590 // -- is an xvalue, class prvalue, array prvalue or function
5591 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5592 if (RefRelationship == Sema::Ref_Compatible &&
5593 (InitCategory.isXValue() ||
5594 (InitCategory.isPRValue() &&
5595 (T2->isRecordType() || T2->isArrayType())) ||
5596 (InitCategory.isLValue() && T2->isFunctionType()))) {
5597 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5598 // binding unless we're binding to a class prvalue.
5599 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5600 // allow the use of rvalue references in C++98/03 for the benefit of
5601 // standard library implementors; therefore, we need the xvalue check here.
5602 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5603 !(InitCategory.isPRValue() || T2->isRecordType()));
5604 return ICS;
5605 }
5606
5607 // -- has a class type (i.e., T2 is a class type), where T1 is not
5608 // reference-related to T2, and can be implicitly converted to
5609 // an xvalue, class prvalue, or function lvalue of type
5610 // "cv3 T3", where "cv1 T1" is reference-compatible with
5611 // "cv3 T3",
5612 //
5613 // then the reference is bound to the value of the initializer
5614 // expression in the first case and to the result of the conversion
5615 // in the second case (or, in either case, to an appropriate base
5616 // class subobject).
5617 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5618 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5619 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5620 Init, T2, /*AllowRvalues=*/true,
5621 AllowExplicit)) {
5622 // In the second case, if the reference is an rvalue reference
5623 // and the second standard conversion sequence of the
5624 // user-defined conversion sequence includes an lvalue-to-rvalue
5625 // conversion, the program is ill-formed.
5626 if (ICS.isUserDefined() && isRValRef &&
5629
5630 return ICS;
5631 }
5632
5633 // A temporary of function type cannot be created; don't even try.
5634 if (T1->isFunctionType())
5635 return ICS;
5636
5637 // -- Otherwise, a temporary of type "cv1 T1" is created and
5638 // initialized from the initializer expression using the
5639 // rules for a non-reference copy initialization (8.5). The
5640 // reference is then bound to the temporary. If T1 is
5641 // reference-related to T2, cv1 must be the same
5642 // cv-qualification as, or greater cv-qualification than,
5643 // cv2; otherwise, the program is ill-formed.
5644 if (RefRelationship == Sema::Ref_Related) {
5645 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5646 // we would be reference-compatible or reference-compatible with
5647 // added qualification. But that wasn't the case, so the reference
5648 // initialization fails.
5649 //
5650 // Note that we only want to check address spaces and cvr-qualifiers here.
5651 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5652 Qualifiers T1Quals = T1.getQualifiers();
5653 Qualifiers T2Quals = T2.getQualifiers();
5654 T1Quals.removeObjCGCAttr();
5655 T1Quals.removeObjCLifetime();
5656 T2Quals.removeObjCGCAttr();
5657 T2Quals.removeObjCLifetime();
5658 // MS compiler ignores __unaligned qualifier for references; do the same.
5659 T1Quals.removeUnaligned();
5660 T2Quals.removeUnaligned();
5661 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5662 return ICS;
5663 }
5664
5665 // If at least one of the types is a class type, the types are not
5666 // related, and we aren't allowed any user conversions, the
5667 // reference binding fails. This case is important for breaking
5668 // recursion, since TryImplicitConversion below will attempt to
5669 // create a temporary through the use of a copy constructor.
5670 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5671 (T1->isRecordType() || T2->isRecordType()))
5672 return ICS;
5673
5674 // If T1 is reference-related to T2 and the reference is an rvalue
5675 // reference, the initializer expression shall not be an lvalue.
5676 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5677 Init->Classify(S.Context).isLValue()) {
5679 return ICS;
5680 }
5681
5682 // C++ [over.ics.ref]p2:
5683 // When a parameter of reference type is not bound directly to
5684 // an argument expression, the conversion sequence is the one
5685 // required to convert the argument expression to the
5686 // underlying type of the reference according to
5687 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5688 // to copy-initializing a temporary of the underlying type with
5689 // the argument expression. Any difference in top-level
5690 // cv-qualification is subsumed by the initialization itself
5691 // and does not constitute a conversion.
5692 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5693 AllowedExplicit::None,
5694 /*InOverloadResolution=*/false,
5695 /*CStyle=*/false,
5696 /*AllowObjCWritebackConversion=*/false,
5697 /*AllowObjCConversionOnExplicit=*/false);
5698
5699 // Of course, that's still a reference binding.
5700 if (ICS.isStandard()) {
5701 ICS.Standard.ReferenceBinding = true;
5702 ICS.Standard.IsLvalueReference = !isRValRef;
5703 ICS.Standard.BindsToFunctionLvalue = false;
5704 ICS.Standard.BindsToRvalue = true;
5707 } else if (ICS.isUserDefined()) {
5708 const ReferenceType *LValRefType =
5711
5712 // C++ [over.ics.ref]p3:
5713 // Except for an implicit object parameter, for which see 13.3.1, a
5714 // standard conversion sequence cannot be formed if it requires [...]
5715 // binding an rvalue reference to an lvalue other than a function
5716 // lvalue.
5717 // Note that the function case is not possible here.
5718 if (isRValRef && LValRefType) {
5720 return ICS;
5721 }
5722
5724 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5726 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5730 }
5731
5732 return ICS;
5733}
5734
5735static ImplicitConversionSequence
5736TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5737 bool SuppressUserConversions,
5738 bool InOverloadResolution,
5739 bool AllowObjCWritebackConversion,
5740 bool AllowExplicit = false);
5741
5742/// TryListConversion - Try to copy-initialize a value of type ToType from the
5743/// initializer list From.
5744static ImplicitConversionSequence
5746 bool SuppressUserConversions,
5747 bool InOverloadResolution,
5748 bool AllowObjCWritebackConversion) {
5749 // C++11 [over.ics.list]p1:
5750 // When an argument is an initializer list, it is not an expression and
5751 // special rules apply for converting it to a parameter type.
5752
5754 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5755
5756 // We need a complete type for what follows. With one C++20 exception,
5757 // incomplete types can never be initialized from init lists.
5758 QualType InitTy = ToType;
5759 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5760 if (AT && S.getLangOpts().CPlusPlus20)
5761 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5762 // C++20 allows list initialization of an incomplete array type.
5763 InitTy = IAT->getElementType();
5764 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5765 return Result;
5766
5767 // C++20 [over.ics.list]/2:
5768 // If the initializer list is a designated-initializer-list, a conversion
5769 // is only possible if the parameter has an aggregate type
5770 //
5771 // FIXME: The exception for reference initialization here is not part of the
5772 // language rules, but follow other compilers in adding it as a tentative DR
5773 // resolution.
5774 bool IsDesignatedInit = From->hasDesignatedInit();
5775 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5776 IsDesignatedInit)
5777 return Result;
5778
5779 // Per DR1467 and DR2137:
5780 // If the parameter type is an aggregate class X and the initializer list
5781 // has a single element of type cv U, where U is X or a class derived from
5782 // X, the implicit conversion sequence is the one required to convert the
5783 // element to the parameter type.
5784 //
5785 // Otherwise, if the parameter type is a character array [... ]
5786 // and the initializer list has a single element that is an
5787 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5788 // implicit conversion sequence is the identity conversion.
5789 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5790 if (ToType->isRecordType() && ToType->isAggregateType()) {
5791 QualType InitType = From->getInit(0)->getType();
5792 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5793 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5794 return TryCopyInitialization(S, From->getInit(0), ToType,
5795 SuppressUserConversions,
5796 InOverloadResolution,
5797 AllowObjCWritebackConversion);
5798 }
5799
5800 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5801 InitializedEntity Entity =
5803 /*Consumed=*/false);
5804 if (S.CanPerformCopyInitialization(Entity, From)) {
5805 Result.setStandard();
5806 Result.Standard.setAsIdentityConversion();
5807 Result.Standard.setFromType(ToType);
5808 Result.Standard.setAllToTypes(ToType);
5809 return Result;
5810 }
5811 }
5812 }
5813
5814 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5815 // C++11 [over.ics.list]p2:
5816 // If the parameter type is std::initializer_list<X> or "array of X" and
5817 // all the elements can be implicitly converted to X, the implicit
5818 // conversion sequence is the worst conversion necessary to convert an
5819 // element of the list to X.
5820 //
5821 // C++14 [over.ics.list]p3:
5822 // Otherwise, if the parameter type is "array of N X", if the initializer
5823 // list has exactly N elements or if it has fewer than N elements and X is
5824 // default-constructible, and if all the elements of the initializer list
5825 // can be implicitly converted to X, the implicit conversion sequence is
5826 // the worst conversion necessary to convert an element of the list to X.
5827 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5828 unsigned e = From->getNumInits();
5831 QualType());
5832 QualType ContTy = ToType;
5833 bool IsUnbounded = false;
5834 if (AT) {
5835 InitTy = AT->getElementType();
5836 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5837 if (CT->getSize().ult(e)) {
5838 // Too many inits, fatally bad
5840 ToType);
5841 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5842 return Result;
5843 }
5844 if (CT->getSize().ugt(e)) {
5845 // Need an init from empty {}, is there one?
5846 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5847 From->getEndLoc());
5848 EmptyList.setType(S.Context.VoidTy);
5849 DfltElt = TryListConversion(
5850 S, &EmptyList, InitTy, SuppressUserConversions,
5851 InOverloadResolution, AllowObjCWritebackConversion);
5852 if (DfltElt.isBad()) {
5853 // No {} init, fatally bad
5855 ToType);
5856 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5857 return Result;
5858 }
5859 }
5860 } else {
5861 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5862 IsUnbounded = true;
5863 if (!e) {
5864 // Cannot convert to zero-sized.
5866 ToType);
5867 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5868 return Result;
5869 }
5870 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5871 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5873 }
5874 }
5875
5876 Result.setStandard();
5877 Result.Standard.setAsIdentityConversion();
5878 Result.Standard.setFromType(InitTy);
5879 Result.Standard.setAllToTypes(InitTy);
5880 for (unsigned i = 0; i < e; ++i) {
5881 Expr *Init = From->getInit(i);
5883 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5884 AllowObjCWritebackConversion);
5885
5886 // Keep the worse conversion seen so far.
5887 // FIXME: Sequences are not totally ordered, so 'worse' can be
5888 // ambiguous. CWG has been informed.
5890 Result) ==
5892 Result = ICS;
5893 // Bail as soon as we find something unconvertible.
5894 if (Result.isBad()) {
5895 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5896 return Result;
5897 }
5898 }
5899 }
5900
5901 // If we needed any implicit {} initialization, compare that now.
5902 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5903 // has been informed that this might not be the best thing.
5904 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5905 S, From->getEndLoc(), DfltElt, Result) ==
5907 Result = DfltElt;
5908 // Record the type being initialized so that we may compare sequences
5909 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5910 return Result;
5911 }
5912
5913 // C++14 [over.ics.list]p4:
5914 // C++11 [over.ics.list]p3:
5915 // Otherwise, if the parameter is a non-aggregate class X and overload
5916 // resolution chooses a single best constructor [...] the implicit
5917 // conversion sequence is a user-defined conversion sequence. If multiple
5918 // constructors are viable but none is better than the others, the
5919 // implicit conversion sequence is a user-defined conversion sequence.
5920 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5921 // This function can deal with initializer lists.
5922 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5923 AllowedExplicit::None,
5924 InOverloadResolution, /*CStyle=*/false,
5925 AllowObjCWritebackConversion,
5926 /*AllowObjCConversionOnExplicit=*/false);
5927 }
5928
5929 // C++14 [over.ics.list]p5:
5930 // C++11 [over.ics.list]p4:
5931 // Otherwise, if the parameter has an aggregate type which can be
5932 // initialized from the initializer list [...] the implicit conversion
5933 // sequence is a user-defined conversion sequence.
5934 if (ToType->isAggregateType()) {
5935 // Type is an aggregate, argument is an init list. At this point it comes
5936 // down to checking whether the initialization works.
5937 // FIXME: Find out whether this parameter is consumed or not.
5938 InitializedEntity Entity =
5940 /*Consumed=*/false);
5942 From)) {
5943 Result.setUserDefined();
5944 Result.UserDefined.Before.setAsIdentityConversion();
5945 // Initializer lists don't have a type.
5946 Result.UserDefined.Before.setFromType(QualType());
5947 Result.UserDefined.Before.setAllToTypes(QualType());
5948
5949 Result.UserDefined.After.setAsIdentityConversion();
5950 Result.UserDefined.After.setFromType(ToType);
5951 Result.UserDefined.After.setAllToTypes(ToType);
5952 Result.UserDefined.ConversionFunction = nullptr;
5953 }
5954 return Result;
5955 }
5956
5957 // C++14 [over.ics.list]p6:
5958 // C++11 [over.ics.list]p5:
5959 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5960 if (ToType->isReferenceType()) {
5961 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5962 // mention initializer lists in any way. So we go by what list-
5963 // initialization would do and try to extrapolate from that.
5964
5965 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5966
5967 // If the initializer list has a single element that is reference-related
5968 // to the parameter type, we initialize the reference from that.
5969 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5970 Expr *Init = From->getInit(0);
5971
5972 QualType T2 = Init->getType();
5973
5974 // If the initializer is the address of an overloaded function, try
5975 // to resolve the overloaded function. If all goes well, T2 is the
5976 // type of the resulting function.
5977 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5980 Init, ToType, false, Found))
5981 T2 = Fn->getType();
5982 }
5983
5984 // Compute some basic properties of the types and the initializer.
5985 Sema::ReferenceCompareResult RefRelationship =
5986 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5987
5988 if (RefRelationship >= Sema::Ref_Related) {
5989 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5990 SuppressUserConversions,
5991 /*AllowExplicit=*/false);
5992 }
5993 }
5994
5995 // Otherwise, we bind the reference to a temporary created from the
5996 // initializer list.
5997 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5998 InOverloadResolution,
5999 AllowObjCWritebackConversion);
6000 if (Result.isFailure())
6001 return Result;
6002 assert(!Result.isEllipsis() &&
6003 "Sub-initialization cannot result in ellipsis conversion.");
6004
6005 // Can we even bind to a temporary?
6006 if (ToType->isRValueReferenceType() ||
6007 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6008 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6009 Result.UserDefined.After;
6010 SCS.ReferenceBinding = true;
6012 SCS.BindsToRvalue = true;
6013 SCS.BindsToFunctionLvalue = false;
6016 SCS.FromBracedInitList = false;
6017
6018 } else
6020 From, ToType);
6021 return Result;
6022 }
6023
6024 // C++14 [over.ics.list]p7:
6025 // C++11 [over.ics.list]p6:
6026 // Otherwise, if the parameter type is not a class:
6027 if (!ToType->isRecordType()) {
6028 // - if the initializer list has one element that is not itself an
6029 // initializer list, the implicit conversion sequence is the one
6030 // required to convert the element to the parameter type.
6031 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6032 // single integer.
6033 unsigned NumInits = From->getNumInits();
6034 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6035 !isa<EmbedExpr>(From->getInit(0))) {
6037 S, From->getInit(0), ToType, SuppressUserConversions,
6038 InOverloadResolution, AllowObjCWritebackConversion);
6039 if (Result.isStandard())
6040 Result.Standard.FromBracedInitList = true;
6041 }
6042 // - if the initializer list has no elements, the implicit conversion
6043 // sequence is the identity conversion.
6044 else if (NumInits == 0) {
6045 Result.setStandard();
6046 Result.Standard.setAsIdentityConversion();
6047 Result.Standard.setFromType(ToType);
6048 Result.Standard.setAllToTypes(ToType);
6049 }
6050 return Result;
6051 }
6052
6053 // C++14 [over.ics.list]p8:
6054 // C++11 [over.ics.list]p7:
6055 // In all cases other than those enumerated above, no conversion is possible
6056 return Result;
6057}
6058
6059/// TryCopyInitialization - Try to copy-initialize a value of type
6060/// ToType from the expression From. Return the implicit conversion
6061/// sequence required to pass this argument, which may be a bad
6062/// conversion sequence (meaning that the argument cannot be passed to
6063/// a parameter of this type). If @p SuppressUserConversions, then we
6064/// do not permit any user-defined conversion sequences.
6065static ImplicitConversionSequence
6067 bool SuppressUserConversions,
6068 bool InOverloadResolution,
6069 bool AllowObjCWritebackConversion,
6070 bool AllowExplicit) {
6071 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6072 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6073 InOverloadResolution,AllowObjCWritebackConversion);
6074
6075 if (ToType->isReferenceType())
6076 return TryReferenceInit(S, From, ToType,
6077 /*FIXME:*/ From->getBeginLoc(),
6078 SuppressUserConversions, AllowExplicit);
6079
6080 return TryImplicitConversion(S, From, ToType,
6081 SuppressUserConversions,
6082 AllowedExplicit::None,
6083 InOverloadResolution,
6084 /*CStyle=*/false,
6085 AllowObjCWritebackConversion,
6086 /*AllowObjCConversionOnExplicit=*/false);
6087}
6088
6089static bool TryCopyInitialization(const CanQualType FromQTy,
6090 const CanQualType ToQTy,
6091 Sema &S,
6092 SourceLocation Loc,
6093 ExprValueKind FromVK) {
6094 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6096 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6097
6098 return !ICS.isBad();
6099}
6100
6101/// TryObjectArgumentInitialization - Try to initialize the object
6102/// parameter of the given member function (@c Method) from the
6103/// expression @p From.
6105 Sema &S, SourceLocation Loc, QualType FromType,
6106 Expr::Classification FromClassification, CXXMethodDecl *Method,
6107 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6108 QualType ExplicitParameterType = QualType(),
6109 bool SuppressUserConversion = false) {
6110
6111 // We need to have an object of class type.
6112 if (const auto *PT = FromType->getAs<PointerType>()) {
6113 FromType = PT->getPointeeType();
6114
6115 // When we had a pointer, it's implicitly dereferenced, so we
6116 // better have an lvalue.
6117 assert(FromClassification.isLValue());
6118 }
6119
6120 auto ValueKindFromClassification = [](Expr::Classification C) {
6121 if (C.isPRValue())
6122 return clang::VK_PRValue;
6123 if (C.isXValue())
6124 return VK_XValue;
6125 return clang::VK_LValue;
6126 };
6127
6128 if (Method->isExplicitObjectMemberFunction()) {
6129 if (ExplicitParameterType.isNull())
6130 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6131 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6132 ValueKindFromClassification(FromClassification));
6134 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6135 /*InOverloadResolution=*/true, false);
6136 if (ICS.isBad())
6137 ICS.Bad.FromExpr = nullptr;
6138 return ICS;
6139 }
6140
6141 assert(FromType->isRecordType());
6142
6143 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6144 // C++98 [class.dtor]p2:
6145 // A destructor can be invoked for a const, volatile or const volatile
6146 // object.
6147 // C++98 [over.match.funcs]p4:
6148 // For static member functions, the implicit object parameter is considered
6149 // to match any object (since if the function is selected, the object is
6150 // discarded).
6151 Qualifiers Quals = Method->getMethodQualifiers();
6152 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6153 Quals.addConst();
6154 Quals.addVolatile();
6155 }
6156
6157 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6158
6159 // Set up the conversion sequence as a "bad" conversion, to allow us
6160 // to exit early.
6162
6163 // C++0x [over.match.funcs]p4:
6164 // For non-static member functions, the type of the implicit object
6165 // parameter is
6166 //
6167 // - "lvalue reference to cv X" for functions declared without a
6168 // ref-qualifier or with the & ref-qualifier
6169 // - "rvalue reference to cv X" for functions declared with the &&
6170 // ref-qualifier
6171 //
6172 // where X is the class of which the function is a member and cv is the
6173 // cv-qualification on the member function declaration.
6174 //
6175 // However, when finding an implicit conversion sequence for the argument, we
6176 // are not allowed to perform user-defined conversions
6177 // (C++ [over.match.funcs]p5). We perform a simplified version of
6178 // reference binding here, that allows class rvalues to bind to
6179 // non-constant references.
6180
6181 // First check the qualifiers.
6182 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6183 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6184 if (ImplicitParamType.getCVRQualifiers() !=
6185 FromTypeCanon.getLocalCVRQualifiers() &&
6186 !ImplicitParamType.isAtLeastAsQualifiedAs(
6187 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6189 FromType, ImplicitParamType);
6190 return ICS;
6191 }
6192
6193 if (FromTypeCanon.hasAddressSpace()) {
6194 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6195 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6196 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6197 S.getASTContext())) {
6199 FromType, ImplicitParamType);
6200 return ICS;
6201 }
6202 }
6203
6204 // Check that we have either the same type or a derived type. It
6205 // affects the conversion rank.
6206 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6207 ImplicitConversionKind SecondKind;
6208 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6209 SecondKind = ICK_Identity;
6210 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6211 SecondKind = ICK_Derived_To_Base;
6212 } else if (!Method->isExplicitObjectMemberFunction()) {
6214 FromType, ImplicitParamType);
6215 return ICS;
6216 }
6217
6218 // Check the ref-qualifier.
6219 switch (Method->getRefQualifier()) {
6220 case RQ_None:
6221 // Do nothing; we don't care about lvalueness or rvalueness.
6222 break;
6223
6224 case RQ_LValue:
6225 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6226 // non-const lvalue reference cannot bind to an rvalue
6228 ImplicitParamType);
6229 return ICS;
6230 }
6231 break;
6232
6233 case RQ_RValue:
6234 if (!FromClassification.isRValue()) {
6235 // rvalue reference cannot bind to an lvalue
6237 ImplicitParamType);
6238 return ICS;
6239 }
6240 break;
6241 }
6242
6243 // Success. Mark this as a reference binding.
6244 ICS.setStandard();
6246 ICS.Standard.Second = SecondKind;
6247 ICS.Standard.setFromType(FromType);
6248 ICS.Standard.setAllToTypes(ImplicitParamType);
6249 ICS.Standard.ReferenceBinding = true;
6250 ICS.Standard.DirectBinding = true;
6251 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6252 ICS.Standard.BindsToFunctionLvalue = false;
6253 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6254 ICS.Standard.FromBracedInitList = false;
6256 = (Method->getRefQualifier() == RQ_None);
6257 return ICS;
6258}
6259
6260/// PerformObjectArgumentInitialization - Perform initialization of
6261/// the implicit object parameter for the given Method with the given
6262/// expression.
6264 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6266 QualType FromRecordType, DestType;
6267 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6268
6269 Expr::Classification FromClassification;
6270 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6271 FromRecordType = PT->getPointeeType();
6272 DestType = Method->getThisType();
6273 FromClassification = Expr::Classification::makeSimpleLValue();
6274 } else {
6275 FromRecordType = From->getType();
6276 DestType = ImplicitParamRecordType;
6277 FromClassification = From->Classify(Context);
6278
6279 // CWG2813 [expr.call]p6:
6280 // If the function is an implicit object member function, the object
6281 // expression of the class member access shall be a glvalue [...]
6282 if (From->isPRValue()) {
6283 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6284 Method->getRefQualifier() !=
6286 }
6287 }
6288
6289 // Note that we always use the true parent context when performing
6290 // the actual argument initialization.
6292 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6293 Method->getParent());
6294 if (ICS.isBad()) {
6295 switch (ICS.Bad.Kind) {
6297 Qualifiers FromQs = FromRecordType.getQualifiers();
6298 Qualifiers ToQs = DestType.getQualifiers();
6299 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6300 if (CVR) {
6301 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6302 << Method->getDeclName() << FromRecordType << (CVR - 1)
6303 << From->getSourceRange();
6304 Diag(Method->getLocation(), diag::note_previous_decl)
6305 << Method->getDeclName();
6306 return ExprError();
6307 }
6308 break;
6309 }
6310
6313 bool IsRValueQualified =
6314 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6315 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6316 << Method->getDeclName() << FromClassification.isRValue()
6317 << IsRValueQualified;
6318 Diag(Method->getLocation(), diag::note_previous_decl)
6319 << Method->getDeclName();
6320 return ExprError();
6321 }
6322
6325 break;
6326
6329 llvm_unreachable("Lists are not objects");
6330 }
6331
6332 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6333 << ImplicitParamRecordType << FromRecordType
6334 << From->getSourceRange();
6335 }
6336
6337 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6338 ExprResult FromRes =
6339 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6340 if (FromRes.isInvalid())
6341 return ExprError();
6342 From = FromRes.get();
6343 }
6344
6345 if (!Context.hasSameType(From->getType(), DestType)) {
6346 CastKind CK;
6347 QualType PteeTy = DestType->getPointeeType();
6348 LangAS DestAS =
6349 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6350 if (FromRecordType.getAddressSpace() != DestAS)
6351 CK = CK_AddressSpaceConversion;
6352 else
6353 CK = CK_NoOp;
6354 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6355 }
6356 return From;
6357}
6358
6359/// TryContextuallyConvertToBool - Attempt to contextually convert the
6360/// expression From to bool (C++0x [conv]p3).
6363 // C++ [dcl.init]/17.8:
6364 // - Otherwise, if the initialization is direct-initialization, the source
6365 // type is std::nullptr_t, and the destination type is bool, the initial
6366 // value of the object being initialized is false.
6367 if (From->getType()->isNullPtrType())
6369 S.Context.BoolTy,
6370 From->isGLValue());
6371
6372 // All other direct-initialization of bool is equivalent to an implicit
6373 // conversion to bool in which explicit conversions are permitted.
6374 return TryImplicitConversion(S, From, S.Context.BoolTy,
6375 /*SuppressUserConversions=*/false,
6376 AllowedExplicit::Conversions,
6377 /*InOverloadResolution=*/false,
6378 /*CStyle=*/false,
6379 /*AllowObjCWritebackConversion=*/false,
6380 /*AllowObjCConversionOnExplicit=*/false);
6381}
6382
6384 if (checkPlaceholderForOverload(*this, From))
6385 return ExprError();
6386 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6387 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6388
6390 if (!ICS.isBad())
6391 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6394 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6395 << From->getType() << From->getSourceRange();
6396 return ExprError();
6397}
6398
6399/// Check that the specified conversion is permitted in a converted constant
6400/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6401/// is acceptable.
6404 // Since we know that the target type is an integral or unscoped enumeration
6405 // type, most conversion kinds are impossible. All possible First and Third
6406 // conversions are fine.
6407 switch (SCS.Second) {
6408 case ICK_Identity:
6410 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6412 return true;
6413
6415 // Conversion from an integral or unscoped enumeration type to bool is
6416 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6417 // conversion, so we allow it in a converted constant expression.
6418 //
6419 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6420 // a lot of popular code. We should at least add a warning for this
6421 // (non-conforming) extension.
6423 SCS.getToType(2)->isBooleanType();
6424
6426 case ICK_Pointer_Member:
6427 // C++1z: null pointer conversions and null member pointer conversions are
6428 // only permitted if the source type is std::nullptr_t.
6429 return SCS.getFromType()->isNullPtrType();
6430
6443 case ICK_Vector_Splat:
6444 case ICK_Complex_Real:
6454 return false;
6455
6460 llvm_unreachable("found a first conversion kind in Second");
6461
6463 case ICK_Qualification:
6464 llvm_unreachable("found a third conversion kind in Second");
6465
6467 break;
6468 }
6469
6470 llvm_unreachable("unknown conversion kind");
6471}
6472
6473/// BuildConvertedConstantExpression - Check that the expression From is a
6474/// converted constant expression of type T, perform the conversion but
6475/// does not evaluate the expression
6477 QualType T, CCEKind CCE,
6478 NamedDecl *Dest,
6479 APValue &PreNarrowingValue) {
6480 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6482 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6483 "converted constant expression outside C++11 or TTP matching");
6484
6485 if (checkPlaceholderForOverload(S, From))
6486 return ExprError();
6487
6488 if (From->containsErrors()) {
6489 // The expression already has errors, so the correct cast kind can't be
6490 // determined. Use RecoveryExpr to keep the expected type T and mark the
6491 // result as invalid, preventing further cascading errors.
6492 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6493 T);
6494 }
6495
6496 // C++1z [expr.const]p3:
6497 // A converted constant expression of type T is an expression,
6498 // implicitly converted to type T, where the converted
6499 // expression is a constant expression and the implicit conversion
6500 // sequence contains only [... list of conversions ...].
6502 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6504 : TryCopyInitialization(S, From, T,
6505 /*SuppressUserConversions=*/false,
6506 /*InOverloadResolution=*/false,
6507 /*AllowObjCWritebackConversion=*/false,
6508 /*AllowExplicit=*/false);
6509 StandardConversionSequence *SCS = nullptr;
6510 switch (ICS.getKind()) {
6512 SCS = &ICS.Standard;
6513 break;
6515 if (T->isRecordType())
6516 SCS = &ICS.UserDefined.Before;
6517 else
6518 SCS = &ICS.UserDefined.After;
6519 break;
6523 return S.Diag(From->getBeginLoc(),
6524 diag::err_typecheck_converted_constant_expression)
6525 << From->getType() << From->getSourceRange() << T;
6526 return ExprError();
6527
6530 llvm_unreachable("bad conversion in converted constant expression");
6531 }
6532
6533 // Check that we would only use permitted conversions.
6534 if (!CheckConvertedConstantConversions(S, *SCS)) {
6535 return S.Diag(From->getBeginLoc(),
6536 diag::err_typecheck_converted_constant_expression_disallowed)
6537 << From->getType() << From->getSourceRange() << T;
6538 }
6539 // [...] and where the reference binding (if any) binds directly.
6540 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6541 return S.Diag(From->getBeginLoc(),
6542 diag::err_typecheck_converted_constant_expression_indirect)
6543 << From->getType() << From->getSourceRange() << T;
6544 }
6545 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6546 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6547 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6548 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6549 // case explicitly.
6550 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6551 return S.Diag(From->getBeginLoc(),
6552 diag::err_reference_bind_to_bitfield_in_cce)
6553 << From->getSourceRange();
6554 }
6555
6556 // Usually we can simply apply the ImplicitConversionSequence we formed
6557 // earlier, but that's not guaranteed to work when initializing an object of
6558 // class type.
6560 bool IsTemplateArgument =
6562 if (T->isRecordType()) {
6563 assert(IsTemplateArgument &&
6564 "unexpected class type converted constant expr");
6568 SourceLocation(), From);
6569 } else {
6570 Result =
6572 }
6573 if (Result.isInvalid())
6574 return Result;
6575
6576 // C++2a [intro.execution]p5:
6577 // A full-expression is [...] a constant-expression [...]
6578 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6579 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6580 IsTemplateArgument);
6581 if (Result.isInvalid())
6582 return Result;
6583
6584 // Check for a narrowing implicit conversion.
6585 bool ReturnPreNarrowingValue = false;
6586 QualType PreNarrowingType;
6587 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6588 PreNarrowingType)) {
6590 // Implicit conversion to a narrower type, and the value is not a constant
6591 // expression. We'll diagnose this in a moment.
6592 case NK_Not_Narrowing:
6593 break;
6594
6596 if (CCE == CCEKind::ArrayBound &&
6597 PreNarrowingType->isIntegralOrEnumerationType() &&
6598 PreNarrowingValue.isInt()) {
6599 // Don't diagnose array bound narrowing here; we produce more precise
6600 // errors by allowing the un-narrowed value through.
6601 ReturnPreNarrowingValue = true;
6602 break;
6603 }
6604 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6605 << CCE << /*Constant*/ 1
6606 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6607 // If this is an SFINAE Context, treat the result as invalid so it stops
6608 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6609 // FIXME: Should do this whenever the above diagnostic is an error, but
6610 // without further changes this would degrade some other diagnostics.
6611 if (S.isSFINAEContext())
6612 return ExprError();
6613 break;
6614
6616 // Implicit conversion to a narrower type, but the expression is
6617 // value-dependent so we can't tell whether it's actually narrowing.
6618 // For matching the parameters of a TTP, the conversion is ill-formed
6619 // if it may narrow.
6620 if (CCE != CCEKind::TempArgStrict)
6621 break;
6622 [[fallthrough]];
6623 case NK_Type_Narrowing:
6624 // FIXME: It would be better to diagnose that the expression is not a
6625 // constant expression.
6626 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6627 << CCE << /*Constant*/ 0 << From->getType() << T;
6628 if (S.isSFINAEContext())
6629 return ExprError();
6630 break;
6631 }
6632 if (!ReturnPreNarrowingValue)
6633 PreNarrowingValue = {};
6634
6635 return Result;
6636}
6637
6638/// CheckConvertedConstantExpression - Check that the expression From is a
6639/// converted constant expression of type T, perform the conversion and produce
6640/// the converted expression, per C++11 [expr.const]p3.
6643 CCEKind CCE, bool RequireInt,
6644 NamedDecl *Dest) {
6645
6646 APValue PreNarrowingValue;
6647 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6648 PreNarrowingValue);
6649 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6650 Value = APValue();
6651 return Result;
6652 }
6653 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6654 RequireInt, PreNarrowingValue);
6655}
6656
6658 CCEKind CCE,
6659 NamedDecl *Dest) {
6660 APValue PreNarrowingValue;
6661 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6662 PreNarrowingValue);
6663}
6664
6666 APValue &Value, CCEKind CCE,
6667 NamedDecl *Dest) {
6668 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6669 Dest);
6670}
6671
6673 llvm::APSInt &Value,
6674 CCEKind CCE) {
6675 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6676
6677 APValue V;
6678 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6679 /*Dest=*/nullptr);
6680 if (!R.isInvalid() && !R.get()->isValueDependent())
6681 Value = V.getInt();
6682 return R;
6683}
6684
6687 CCEKind CCE, bool RequireInt,
6688 const APValue &PreNarrowingValue) {
6689
6690 ExprResult Result = E;
6691 // Check the expression is a constant expression.
6693 Expr::EvalResult Eval;
6694 Eval.Diag = &Notes;
6695
6696 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6697
6698 ConstantExprKind Kind;
6699 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6700 Kind = ConstantExprKind::ClassTemplateArgument;
6701 else if (CCE == CCEKind::TemplateArg)
6702 Kind = ConstantExprKind::NonClassTemplateArgument;
6703 else
6704 Kind = ConstantExprKind::Normal;
6705
6706 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6707 (RequireInt && !Eval.Val.isInt())) {
6708 // The expression can't be folded, so we can't keep it at this position in
6709 // the AST.
6710 Result = ExprError();
6711 } else {
6712 Value = Eval.Val;
6713
6714 if (Notes.empty()) {
6715 // It's a constant expression.
6716 Expr *E = Result.get();
6717 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6718 // We expect a ConstantExpr to have a value associated with it
6719 // by this point.
6720 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6721 "ConstantExpr has no value associated with it");
6722 (void)CE;
6723 } else {
6725 }
6726 if (!PreNarrowingValue.isAbsent())
6727 Value = std::move(PreNarrowingValue);
6728 return E;
6729 }
6730 }
6731
6732 // It's not a constant expression. Produce an appropriate diagnostic.
6733 if (Notes.size() == 1 &&
6734 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6735 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6736 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6737 diag::note_constexpr_invalid_template_arg) {
6738 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6739 for (unsigned I = 0; I < Notes.size(); ++I)
6740 Diag(Notes[I].first, Notes[I].second);
6741 } else {
6742 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6743 << CCE << E->getSourceRange();
6744 for (unsigned I = 0; I < Notes.size(); ++I)
6745 Diag(Notes[I].first, Notes[I].second);
6746 }
6747 return ExprError();
6748}
6749
6750/// dropPointerConversions - If the given standard conversion sequence
6751/// involves any pointer conversions, remove them. This may change
6752/// the result type of the conversion sequence.
6754 if (SCS.Second == ICK_Pointer_Conversion) {
6755 SCS.Second = ICK_Identity;
6756 SCS.Dimension = ICK_Identity;
6757 SCS.Third = ICK_Identity;
6758 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6759 }
6760}
6761
6762/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6763/// convert the expression From to an Objective-C pointer type.
6764static ImplicitConversionSequence
6766 // Do an implicit conversion to 'id'.
6769 = TryImplicitConversion(S, From, Ty,
6770 // FIXME: Are these flags correct?
6771 /*SuppressUserConversions=*/false,
6772 AllowedExplicit::Conversions,
6773 /*InOverloadResolution=*/false,
6774 /*CStyle=*/false,
6775 /*AllowObjCWritebackConversion=*/false,
6776 /*AllowObjCConversionOnExplicit=*/true);
6777
6778 // Strip off any final conversions to 'id'.
6779 switch (ICS.getKind()) {
6784 break;
6785
6788 break;
6789
6792 break;
6793 }
6794
6795 return ICS;
6796}
6797
6799 if (checkPlaceholderForOverload(*this, From))
6800 return ExprError();
6801
6802 QualType Ty = Context.getObjCIdType();
6805 if (!ICS.isBad())
6806 return PerformImplicitConversion(From, Ty, ICS,
6808 return ExprResult();
6809}
6810
6811static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6812 const Expr *Base = nullptr;
6813 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6814 "expected a member expression");
6815
6816 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6817 M && !M->isImplicitAccess())
6818 Base = M->getBase();
6819 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6820 M && !M->isImplicitAccess())
6821 Base = M->getBase();
6822
6823 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6824
6825 if (T->isPointerType())
6826 T = T->getPointeeType();
6827
6828 return T;
6829}
6830
6832 const FunctionDecl *Fun) {
6833 QualType ObjType = Obj->getType();
6834 if (ObjType->isPointerType()) {
6835 ObjType = ObjType->getPointeeType();
6836 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6838 /*CanOverflow=*/false, FPOptionsOverride());
6839 }
6840 return Obj;
6841}
6842
6850
6852 Expr *Object, MultiExprArg &Args,
6853 SmallVectorImpl<Expr *> &NewArgs) {
6854 assert(Method->isExplicitObjectMemberFunction() &&
6855 "Method is not an explicit member function");
6856 assert(NewArgs.empty() && "NewArgs should be empty");
6857
6858 NewArgs.reserve(Args.size() + 1);
6859 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6860 NewArgs.push_back(This);
6861 NewArgs.append(Args.begin(), Args.end());
6862 Args = NewArgs;
6864 Method, Object->getBeginLoc());
6865}
6866
6867/// Determine whether the provided type is an integral type, or an enumeration
6868/// type of a permitted flavor.
6870 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6871 : T->isIntegralOrUnscopedEnumerationType();
6872}
6873
6874static ExprResult
6877 QualType T, UnresolvedSetImpl &ViableConversions) {
6878
6879 if (Converter.Suppress)
6880 return ExprError();
6881
6882 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6883 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6884 CXXConversionDecl *Conv =
6885 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6887 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6888 }
6889 return From;
6890}
6891
6892static bool
6895 QualType T, bool HadMultipleCandidates,
6896 UnresolvedSetImpl &ExplicitConversions) {
6897 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6898 DeclAccessPair Found = ExplicitConversions[0];
6899 CXXConversionDecl *Conversion =
6900 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6901
6902 // The user probably meant to invoke the given explicit
6903 // conversion; use it.
6904 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6905 std::string TypeStr;
6906 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6907
6908 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6910 "static_cast<" + TypeStr + ">(")
6912 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6913 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6914
6915 // If we aren't in a SFINAE context, build a call to the
6916 // explicit conversion function.
6917 if (SemaRef.isSFINAEContext())
6918 return true;
6919
6920 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6921 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6922 HadMultipleCandidates);
6923 if (Result.isInvalid())
6924 return true;
6925
6926 // Replace the conversion with a RecoveryExpr, so we don't try to
6927 // instantiate it later, but can further diagnose here.
6928 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6929 From, Result.get()->getType());
6930 if (Result.isInvalid())
6931 return true;
6932 From = Result.get();
6933 }
6934 return false;
6935}
6936
6937static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6939 QualType T, bool HadMultipleCandidates,
6941 CXXConversionDecl *Conversion =
6942 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6943 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6944
6945 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6946 if (!Converter.SuppressConversion) {
6947 if (SemaRef.isSFINAEContext())
6948 return true;
6949
6950 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6951 << From->getSourceRange();
6952 }
6953
6954 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6955 HadMultipleCandidates);
6956 if (Result.isInvalid())
6957 return true;
6958 // Record usage of conversion in an implicit cast.
6959 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6960 CK_UserDefinedConversion, Result.get(),
6961 nullptr, Result.get()->getValueKind(),
6962 SemaRef.CurFPFeatureOverrides());
6963 return false;
6964}
6965
6967 Sema &SemaRef, SourceLocation Loc, Expr *From,
6969 if (!Converter.match(From->getType()) && !Converter.Suppress)
6970 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6971 << From->getSourceRange();
6972
6973 return SemaRef.DefaultLvalueConversion(From);
6974}
6975
6976static void
6978 UnresolvedSetImpl &ViableConversions,
6979 OverloadCandidateSet &CandidateSet) {
6980 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6981 NamedDecl *D = FoundDecl.getDecl();
6982 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6983 if (isa<UsingShadowDecl>(D))
6984 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6985
6986 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6988 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6989 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6990 continue;
6991 }
6993 SemaRef.AddConversionCandidate(
6994 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6995 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6996 }
6997}
6998
6999/// Attempt to convert the given expression to a type which is accepted
7000/// by the given converter.
7001///
7002/// This routine will attempt to convert an expression of class type to a
7003/// type accepted by the specified converter. In C++11 and before, the class
7004/// must have a single non-explicit conversion function converting to a matching
7005/// type. In C++1y, there can be multiple such conversion functions, but only
7006/// one target type.
7007///
7008/// \param Loc The source location of the construct that requires the
7009/// conversion.
7010///
7011/// \param From The expression we're converting from.
7012///
7013/// \param Converter Used to control and diagnose the conversion process.
7014///
7015/// \returns The expression, converted to an integral or enumeration type if
7016/// successful.
7018 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7019 // We can't perform any more checking for type-dependent expressions.
7020 if (From->isTypeDependent())
7021 return From;
7022
7023 // Process placeholders immediately.
7024 if (From->hasPlaceholderType()) {
7025 ExprResult result = CheckPlaceholderExpr(From);
7026 if (result.isInvalid())
7027 return result;
7028 From = result.get();
7029 }
7030
7031 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7032 ExprResult Converted = DefaultLvalueConversion(From);
7033 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7034 // If the expression already has a matching type, we're golden.
7035 if (Converter.match(T))
7036 return Converted;
7037
7038 // FIXME: Check for missing '()' if T is a function type?
7039
7040 // We can only perform contextual implicit conversions on objects of class
7041 // type.
7042 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7043 if (!RecordTy || !getLangOpts().CPlusPlus) {
7044 if (!Converter.Suppress)
7045 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7046 return From;
7047 }
7048
7049 // We must have a complete class type.
7050 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7051 ContextualImplicitConverter &Converter;
7052 Expr *From;
7053
7054 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7055 : Converter(Converter), From(From) {}
7056
7057 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7058 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7059 }
7060 } IncompleteDiagnoser(Converter, From);
7061
7062 if (Converter.Suppress ? !isCompleteType(Loc, T)
7063 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7064 return From;
7065
7066 // Look for a conversion to an integral or enumeration type.
7068 ViableConversions; // These are *potentially* viable in C++1y.
7069 UnresolvedSet<4> ExplicitConversions;
7070 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7071 ->getDefinitionOrSelf()
7072 ->getVisibleConversionFunctions();
7073
7074 bool HadMultipleCandidates =
7075 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7076
7077 // To check that there is only one target type, in C++1y:
7078 QualType ToType;
7079 bool HasUniqueTargetType = true;
7080
7081 // Collect explicit or viable (potentially in C++1y) conversions.
7082 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7083 NamedDecl *D = (*I)->getUnderlyingDecl();
7084 CXXConversionDecl *Conversion;
7085 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7086 if (ConvTemplate) {
7088 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7089 else
7090 continue; // C++11 does not consider conversion operator templates(?).
7091 } else
7092 Conversion = cast<CXXConversionDecl>(D);
7093
7094 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7095 "Conversion operator templates are considered potentially "
7096 "viable in C++1y");
7097
7098 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7099 if (Converter.match(CurToType) || ConvTemplate) {
7100
7101 if (Conversion->isExplicit()) {
7102 // FIXME: For C++1y, do we need this restriction?
7103 // cf. diagnoseNoViableConversion()
7104 if (!ConvTemplate)
7105 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7106 } else {
7107 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7108 if (ToType.isNull())
7109 ToType = CurToType.getUnqualifiedType();
7110 else if (HasUniqueTargetType &&
7111 (CurToType.getUnqualifiedType() != ToType))
7112 HasUniqueTargetType = false;
7113 }
7114 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7115 }
7116 }
7117 }
7118
7119 if (getLangOpts().CPlusPlus14) {
7120 // C++1y [conv]p6:
7121 // ... An expression e of class type E appearing in such a context
7122 // is said to be contextually implicitly converted to a specified
7123 // type T and is well-formed if and only if e can be implicitly
7124 // converted to a type T that is determined as follows: E is searched
7125 // for conversion functions whose return type is cv T or reference to
7126 // cv T such that T is allowed by the context. There shall be
7127 // exactly one such T.
7128
7129 // If no unique T is found:
7130 if (ToType.isNull()) {
7131 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7132 HadMultipleCandidates,
7133 ExplicitConversions))
7134 return ExprError();
7135 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7136 }
7137
7138 // If more than one unique Ts are found:
7139 if (!HasUniqueTargetType)
7140 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7141 ViableConversions);
7142
7143 // If one unique T is found:
7144 // First, build a candidate set from the previously recorded
7145 // potentially viable conversions.
7147 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7148 CandidateSet);
7149
7150 // Then, perform overload resolution over the candidate set.
7152 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7153 case OR_Success: {
7154 // Apply this conversion.
7156 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7157 if (recordConversion(*this, Loc, From, Converter, T,
7158 HadMultipleCandidates, Found))
7159 return ExprError();
7160 break;
7161 }
7162 case OR_Ambiguous:
7163 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7164 ViableConversions);
7166 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7167 HadMultipleCandidates,
7168 ExplicitConversions))
7169 return ExprError();
7170 [[fallthrough]];
7171 case OR_Deleted:
7172 // We'll complain below about a non-integral condition type.
7173 break;
7174 }
7175 } else {
7176 switch (ViableConversions.size()) {
7177 case 0: {
7178 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7179 HadMultipleCandidates,
7180 ExplicitConversions))
7181 return ExprError();
7182
7183 // We'll complain below about a non-integral condition type.
7184 break;
7185 }
7186 case 1: {
7187 // Apply this conversion.
7188 DeclAccessPair Found = ViableConversions[0];
7189 if (recordConversion(*this, Loc, From, Converter, T,
7190 HadMultipleCandidates, Found))
7191 return ExprError();
7192 break;
7193 }
7194 default:
7195 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7196 ViableConversions);
7197 }
7198 }
7199
7200 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7201}
7202
7203/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7204/// an acceptable non-member overloaded operator for a call whose
7205/// arguments have types T1 (and, if non-empty, T2). This routine
7206/// implements the check in C++ [over.match.oper]p3b2 concerning
7207/// enumeration types.
7209 FunctionDecl *Fn,
7210 ArrayRef<Expr *> Args) {
7211 QualType T1 = Args[0]->getType();
7212 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7213
7214 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7215 return true;
7216
7217 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7218 return true;
7219
7220 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7221 if (Proto->getNumParams() < 1)
7222 return false;
7223
7224 if (T1->isEnumeralType()) {
7225 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7226 if (Context.hasSameUnqualifiedType(T1, ArgType))
7227 return true;
7228 }
7229
7230 if (Proto->getNumParams() < 2)
7231 return false;
7232
7233 if (!T2.isNull() && T2->isEnumeralType()) {
7234 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7235 if (Context.hasSameUnqualifiedType(T2, ArgType))
7236 return true;
7237 }
7238
7239 return false;
7240}
7241
7244 return false;
7245
7246 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7247 return FD->isTargetMultiVersion();
7248
7249 if (!FD->isMultiVersion())
7250 return false;
7251
7252 // Among multiple target versions consider either the default,
7253 // or the first non-default in the absence of default version.
7254 unsigned SeenAt = 0;
7255 unsigned I = 0;
7256 bool HasDefault = false;
7258 FD, [&](const FunctionDecl *CurFD) {
7259 if (FD == CurFD)
7260 SeenAt = I;
7261 else if (CurFD->isTargetMultiVersionDefault())
7262 HasDefault = true;
7263 ++I;
7264 });
7265 return HasDefault || SeenAt != 0;
7266}
7267
7270 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7271 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7272 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7273 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7274 bool StrictPackMatch) {
7275 const FunctionProtoType *Proto
7276 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7277 assert(Proto && "Functions without a prototype cannot be overloaded");
7278 assert(!Function->getDescribedFunctionTemplate() &&
7279 "Use AddTemplateOverloadCandidate for function templates");
7280
7281 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7283 // If we get here, it's because we're calling a member function
7284 // that is named without a member access expression (e.g.,
7285 // "this->f") that was either written explicitly or created
7286 // implicitly. This can happen with a qualified call to a member
7287 // function, e.g., X::f(). We use an empty type for the implied
7288 // object argument (C++ [over.call.func]p3), and the acting context
7289 // is irrelevant.
7290 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7292 CandidateSet, SuppressUserConversions,
7293 PartialOverloading, EarlyConversions, PO,
7294 StrictPackMatch);
7295 return;
7296 }
7297 // We treat a constructor like a non-member function, since its object
7298 // argument doesn't participate in overload resolution.
7299 }
7300
7301 if (!CandidateSet.isNewCandidate(Function, PO))
7302 return;
7303
7304 // C++11 [class.copy]p11: [DR1402]
7305 // A defaulted move constructor that is defined as deleted is ignored by
7306 // overload resolution.
7307 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7308 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7309 Constructor->isMoveConstructor())
7310 return;
7311
7312 // Overload resolution is always an unevaluated context.
7315
7316 // C++ [over.match.oper]p3:
7317 // if no operand has a class type, only those non-member functions in the
7318 // lookup set that have a first parameter of type T1 or "reference to
7319 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7320 // is a right operand) a second parameter of type T2 or "reference to
7321 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7322 // candidate functions.
7323 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7325 return;
7326
7327 // Add this candidate
7328 OverloadCandidate &Candidate =
7329 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7330 Candidate.FoundDecl = FoundDecl;
7331 Candidate.Function = Function;
7332 Candidate.Viable = true;
7333 Candidate.RewriteKind =
7334 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7335 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7336 Candidate.ExplicitCallArguments = Args.size();
7337 Candidate.StrictPackMatch = StrictPackMatch;
7338
7339 // Explicit functions are not actually candidates at all if we're not
7340 // allowing them in this context, but keep them around so we can point
7341 // to them in diagnostics.
7342 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7343 Candidate.Viable = false;
7344 Candidate.FailureKind = ovl_fail_explicit;
7345 return;
7346 }
7347
7348 // Functions with internal linkage are only viable in the same module unit.
7349 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7350 /// FIXME: Currently, the semantics of linkage in clang is slightly
7351 /// different from the semantics in C++ spec. In C++ spec, only names
7352 /// have linkage. So that all entities of the same should share one
7353 /// linkage. But in clang, different entities of the same could have
7354 /// different linkage.
7355 const NamedDecl *ND = Function;
7356 bool IsImplicitlyInstantiated = false;
7357 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7358 ND = SpecInfo->getTemplate();
7359 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7361 }
7362
7363 /// Don't remove inline functions with internal linkage from the overload
7364 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7365 /// However:
7366 /// - Inline functions with internal linkage are a common pattern in
7367 /// headers to avoid ODR issues.
7368 /// - The global module is meant to be a transition mechanism for C and C++
7369 /// headers, and the current rules as written work against that goal.
7370 const bool IsInlineFunctionInGMF =
7371 Function->isFromGlobalModule() &&
7372 (IsImplicitlyInstantiated || Function->isInlined());
7373
7374 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7375 Candidate.Viable = false;
7377 return;
7378 }
7379 }
7380
7382 Candidate.Viable = false;
7384 return;
7385 }
7386
7387 if (Constructor) {
7388 // C++ [class.copy]p3:
7389 // A member function template is never instantiated to perform the copy
7390 // of a class object to an object of its class type.
7391 CanQualType ClassType =
7392 Context.getCanonicalTagType(Constructor->getParent());
7393 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7394 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7395 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7396 ClassType))) {
7397 Candidate.Viable = false;
7399 return;
7400 }
7401
7402 // C++ [over.match.funcs]p8: (proposed DR resolution)
7403 // A constructor inherited from class type C that has a first parameter
7404 // of type "reference to P" (including such a constructor instantiated
7405 // from a template) is excluded from the set of candidate functions when
7406 // constructing an object of type cv D if the argument list has exactly
7407 // one argument and D is reference-related to P and P is reference-related
7408 // to C.
7409 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7410 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7411 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7412 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7413 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7414 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7415 SourceLocation Loc = Args.front()->getExprLoc();
7416 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7417 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7418 Candidate.Viable = false;
7420 return;
7421 }
7422 }
7423
7424 // Check that the constructor is capable of constructing an object in the
7425 // destination address space.
7427 Constructor->getMethodQualifiers().getAddressSpace(),
7428 CandidateSet.getDestAS(), getASTContext())) {
7429 Candidate.Viable = false;
7431 }
7432 }
7433
7434 unsigned NumParams = Proto->getNumParams();
7435
7436 // (C++ 13.3.2p2): A candidate function having fewer than m
7437 // parameters is viable only if it has an ellipsis in its parameter
7438 // list (8.3.5).
7439 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7440 !Proto->isVariadic() &&
7441 shouldEnforceArgLimit(PartialOverloading, Function)) {
7442 Candidate.Viable = false;
7444 return;
7445 }
7446
7447 // (C++ 13.3.2p2): A candidate function having more than m parameters
7448 // is viable only if the (m+1)st parameter has a default argument
7449 // (8.3.6). For the purposes of overload resolution, the
7450 // parameter list is truncated on the right, so that there are
7451 // exactly m parameters.
7452 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7453 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7454 !PartialOverloading) {
7455 // Not enough arguments.
7456 Candidate.Viable = false;
7458 return;
7459 }
7460
7461 // (CUDA B.1): Check for invalid calls between targets.
7462 if (getLangOpts().CUDA) {
7463 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7464 // Skip the check for callers that are implicit members, because in this
7465 // case we may not yet know what the member's target is; the target is
7466 // inferred for the member automatically, based on the bases and fields of
7467 // the class.
7468 if (!(Caller && Caller->isImplicit()) &&
7469 !CUDA().IsAllowedCall(Caller, Function)) {
7470 Candidate.Viable = false;
7471 Candidate.FailureKind = ovl_fail_bad_target;
7472 return;
7473 }
7474 }
7475
7476 if (Function->getTrailingRequiresClause()) {
7477 ConstraintSatisfaction Satisfaction;
7478 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7479 /*ForOverloadResolution*/ true) ||
7480 !Satisfaction.IsSatisfied) {
7481 Candidate.Viable = false;
7483 return;
7484 }
7485 }
7486
7487 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7488 // Determine the implicit conversion sequences for each of the
7489 // arguments.
7490 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7491 unsigned ConvIdx =
7492 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7493 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7494 // We already formed a conversion sequence for this parameter during
7495 // template argument deduction.
7496 } else if (ArgIdx < NumParams) {
7497 // (C++ 13.3.2p3): for F to be a viable function, there shall
7498 // exist for each argument an implicit conversion sequence
7499 // (13.3.3.1) that converts that argument to the corresponding
7500 // parameter of F.
7501 QualType ParamType = Proto->getParamType(ArgIdx);
7502 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7503 if (ParamABI == ParameterABI::HLSLOut ||
7504 ParamABI == ParameterABI::HLSLInOut) {
7505 ParamType = ParamType.getNonReferenceType();
7506 if (ParamABI == ParameterABI::HLSLInOut &&
7507 Args[ArgIdx]->getType().getAddressSpace() ==
7509 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7510 }
7511 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7512 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7513 /*InOverloadResolution=*/true,
7514 /*AllowObjCWritebackConversion=*/
7515 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7516 if (Candidate.Conversions[ConvIdx].isBad()) {
7517 Candidate.Viable = false;
7519 return;
7520 }
7521 } else {
7522 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7523 // argument for which there is no corresponding parameter is
7524 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7525 Candidate.Conversions[ConvIdx].setEllipsis();
7526 }
7527 }
7528
7529 if (EnableIfAttr *FailedAttr =
7530 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7531 Candidate.Viable = false;
7532 Candidate.FailureKind = ovl_fail_enable_if;
7533 Candidate.DeductionFailure.Data = FailedAttr;
7534 return;
7535 }
7536}
7537
7541 if (Methods.size() <= 1)
7542 return nullptr;
7543
7544 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7545 bool Match = true;
7546 ObjCMethodDecl *Method = Methods[b];
7547 unsigned NumNamedArgs = Sel.getNumArgs();
7548 // Method might have more arguments than selector indicates. This is due
7549 // to addition of c-style arguments in method.
7550 if (Method->param_size() > NumNamedArgs)
7551 NumNamedArgs = Method->param_size();
7552 if (Args.size() < NumNamedArgs)
7553 continue;
7554
7555 for (unsigned i = 0; i < NumNamedArgs; i++) {
7556 // We can't do any type-checking on a type-dependent argument.
7557 if (Args[i]->isTypeDependent()) {
7558 Match = false;
7559 break;
7560 }
7561
7562 ParmVarDecl *param = Method->parameters()[i];
7563 Expr *argExpr = Args[i];
7564 assert(argExpr && "SelectBestMethod(): missing expression");
7565
7566 // Strip the unbridged-cast placeholder expression off unless it's
7567 // a consumed argument.
7568 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7569 !param->hasAttr<CFConsumedAttr>())
7570 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7571
7572 // If the parameter is __unknown_anytype, move on to the next method.
7573 if (param->getType() == Context.UnknownAnyTy) {
7574 Match = false;
7575 break;
7576 }
7577
7578 ImplicitConversionSequence ConversionState
7579 = TryCopyInitialization(*this, argExpr, param->getType(),
7580 /*SuppressUserConversions*/false,
7581 /*InOverloadResolution=*/true,
7582 /*AllowObjCWritebackConversion=*/
7583 getLangOpts().ObjCAutoRefCount,
7584 /*AllowExplicit*/false);
7585 // This function looks for a reasonably-exact match, so we consider
7586 // incompatible pointer conversions to be a failure here.
7587 if (ConversionState.isBad() ||
7588 (ConversionState.isStandard() &&
7589 ConversionState.Standard.Second ==
7591 Match = false;
7592 break;
7593 }
7594 }
7595 // Promote additional arguments to variadic methods.
7596 if (Match && Method->isVariadic()) {
7597 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7598 if (Args[i]->isTypeDependent()) {
7599 Match = false;
7600 break;
7601 }
7603 Args[i], VariadicCallType::Method, nullptr);
7604 if (Arg.isInvalid()) {
7605 Match = false;
7606 break;
7607 }
7608 }
7609 } else {
7610 // Check for extra arguments to non-variadic methods.
7611 if (Args.size() != NumNamedArgs)
7612 Match = false;
7613 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7614 // Special case when selectors have no argument. In this case, select
7615 // one with the most general result type of 'id'.
7616 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7617 QualType ReturnT = Methods[b]->getReturnType();
7618 if (ReturnT->isObjCIdType())
7619 return Methods[b];
7620 }
7621 }
7622 }
7623
7624 if (Match)
7625 return Method;
7626 }
7627 return nullptr;
7628}
7629
7631 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7632 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7633 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7634 if (ThisArg) {
7635 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7636 assert(!isa<CXXConstructorDecl>(Method) &&
7637 "Shouldn't have `this` for ctors!");
7638 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7640 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7641 if (R.isInvalid())
7642 return false;
7643 ConvertedThis = R.get();
7644 } else {
7645 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7646 (void)MD;
7647 assert((MissingImplicitThis || MD->isStatic() ||
7649 "Expected `this` for non-ctor instance methods");
7650 }
7651 ConvertedThis = nullptr;
7652 }
7653
7654 // Ignore any variadic arguments. Converting them is pointless, since the
7655 // user can't refer to them in the function condition.
7656 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7657
7658 // Convert the arguments.
7659 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7660 ExprResult R;
7662 S.Context, Function->getParamDecl(I)),
7663 SourceLocation(), Args[I]);
7664
7665 if (R.isInvalid())
7666 return false;
7667
7668 ConvertedArgs.push_back(R.get());
7669 }
7670
7671 if (Trap.hasErrorOccurred())
7672 return false;
7673
7674 // Push default arguments if needed.
7675 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7676 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7677 ParmVarDecl *P = Function->getParamDecl(i);
7678 if (!P->hasDefaultArg())
7679 return false;
7680 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7681 if (R.isInvalid())
7682 return false;
7683 ConvertedArgs.push_back(R.get());
7684 }
7685
7686 if (Trap.hasErrorOccurred())
7687 return false;
7688 }
7689 return true;
7690}
7691
7693 SourceLocation CallLoc,
7694 ArrayRef<Expr *> Args,
7695 bool MissingImplicitThis) {
7696 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7697 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7698 return nullptr;
7699
7700 SFINAETrap Trap(*this);
7701 // Perform the access checking immediately so any access diagnostics are
7702 // caught by the SFINAE trap.
7703 llvm::scope_exit UndelayDiags(
7704 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7705 DelayedDiagnostics.popUndelayed(CurrentState);
7706 });
7707 SmallVector<Expr *, 16> ConvertedArgs;
7708 // FIXME: We should look into making enable_if late-parsed.
7709 Expr *DiscardedThis;
7711 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7712 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7713 return *EnableIfAttrs.begin();
7714
7715 for (auto *EIA : EnableIfAttrs) {
7717 // FIXME: This doesn't consider value-dependent cases, because doing so is
7718 // very difficult. Ideally, we should handle them more gracefully.
7719 if (EIA->getCond()->isValueDependent() ||
7720 !EIA->getCond()->EvaluateWithSubstitution(
7721 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7722 return EIA;
7723
7724 if (!Result.isInt() || !Result.getInt().getBoolValue())
7725 return EIA;
7726 }
7727 return nullptr;
7728}
7729
7730template <typename CheckFn>
7732 bool ArgDependent, SourceLocation Loc,
7733 CheckFn &&IsSuccessful) {
7735 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7736 if (ArgDependent == DIA->getArgDependent())
7737 Attrs.push_back(DIA);
7738 }
7739
7740 // Common case: No diagnose_if attributes, so we can quit early.
7741 if (Attrs.empty())
7742 return false;
7743
7744 auto WarningBegin = std::stable_partition(
7745 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7746 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7747 DIA->getWarningGroup().empty();
7748 });
7749
7750 // Note that diagnose_if attributes are late-parsed, so they appear in the
7751 // correct order (unlike enable_if attributes).
7752 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7753 IsSuccessful);
7754 if (ErrAttr != WarningBegin) {
7755 const DiagnoseIfAttr *DIA = *ErrAttr;
7756 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7757 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7758 << DIA->getParent() << DIA->getCond()->getSourceRange();
7759 return true;
7760 }
7761
7762 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7763 switch (Sev) {
7764 case DiagnoseIfAttr::DS_warning:
7766 case DiagnoseIfAttr::DS_error:
7767 return diag::Severity::Error;
7768 }
7769 llvm_unreachable("Fully covered switch above!");
7770 };
7771
7772 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7773 if (IsSuccessful(DIA)) {
7774 if (DIA->getWarningGroup().empty() &&
7775 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7776 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7777 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7778 << DIA->getParent() << DIA->getCond()->getSourceRange();
7779 } else {
7780 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7781 DIA->getWarningGroup());
7782 assert(DiagGroup);
7783 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7784 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7785 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7786 S.Diag(Loc, DiagID) << DIA->getMessage();
7787 }
7788 }
7789
7790 return false;
7791}
7792
7794 const Expr *ThisArg,
7796 SourceLocation Loc) {
7798 *this, Function, /*ArgDependent=*/true, Loc,
7799 [&](const DiagnoseIfAttr *DIA) {
7801 // It's sane to use the same Args for any redecl of this function, since
7802 // EvaluateWithSubstitution only cares about the position of each
7803 // argument in the arg list, not the ParmVarDecl* it maps to.
7804 if (!DIA->getCond()->EvaluateWithSubstitution(
7805 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7806 return false;
7807 return Result.isInt() && Result.getInt().getBoolValue();
7808 });
7809}
7810
7812 SourceLocation Loc) {
7814 *this, ND, /*ArgDependent=*/false, Loc,
7815 [&](const DiagnoseIfAttr *DIA) {
7816 bool Result;
7817 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7818 Result;
7819 });
7820}
7821
7823 ArrayRef<Expr *> Args,
7824 OverloadCandidateSet &CandidateSet,
7825 TemplateArgumentListInfo *ExplicitTemplateArgs,
7826 bool SuppressUserConversions,
7827 bool PartialOverloading,
7828 bool FirstArgumentIsBase) {
7829 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7830 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7831 ArrayRef<Expr *> FunctionArgs = Args;
7832
7833 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7834 FunctionDecl *FD =
7835 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7836
7837 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7838 QualType ObjectType;
7839 Expr::Classification ObjectClassification;
7840 if (Args.size() > 0) {
7841 if (Expr *E = Args[0]) {
7842 // Use the explicit base to restrict the lookup:
7843 ObjectType = E->getType();
7844 // Pointers in the object arguments are implicitly dereferenced, so we
7845 // always classify them as l-values.
7846 if (!ObjectType.isNull() && ObjectType->isPointerType())
7847 ObjectClassification = Expr::Classification::makeSimpleLValue();
7848 else
7849 ObjectClassification = E->Classify(Context);
7850 } // .. else there is an implicit base.
7851 FunctionArgs = Args.slice(1);
7852 }
7853 if (FunTmpl) {
7855 FunTmpl, F.getPair(),
7857 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7858 FunctionArgs, CandidateSet, SuppressUserConversions,
7859 PartialOverloading);
7860 } else {
7861 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7862 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7863 ObjectClassification, FunctionArgs, CandidateSet,
7864 SuppressUserConversions, PartialOverloading);
7865 }
7866 } else {
7867 // This branch handles both standalone functions and static methods.
7868
7869 // Slice the first argument (which is the base) when we access
7870 // static method as non-static.
7871 if (Args.size() > 0 &&
7872 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7873 !isa<CXXConstructorDecl>(FD)))) {
7874 assert(cast<CXXMethodDecl>(FD)->isStatic());
7875 FunctionArgs = Args.slice(1);
7876 }
7877 if (FunTmpl) {
7878 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7879 ExplicitTemplateArgs, FunctionArgs,
7880 CandidateSet, SuppressUserConversions,
7881 PartialOverloading);
7882 } else {
7883 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7884 SuppressUserConversions, PartialOverloading);
7885 }
7886 }
7887 }
7888}
7889
7891 Expr::Classification ObjectClassification,
7892 ArrayRef<Expr *> Args,
7893 OverloadCandidateSet &CandidateSet,
7894 bool SuppressUserConversions,
7896 NamedDecl *Decl = FoundDecl.getDecl();
7898
7900 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7901
7902 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7903 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7904 "Expected a member function template");
7905 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7906 /*ExplicitArgs*/ nullptr, ObjectType,
7907 ObjectClassification, Args, CandidateSet,
7908 SuppressUserConversions, false, PO);
7909 } else {
7910 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7911 ObjectType, ObjectClassification, Args, CandidateSet,
7912 SuppressUserConversions, false, {}, PO);
7913 }
7914}
7915
7918 CXXRecordDecl *ActingContext, QualType ObjectType,
7919 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7920 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7921 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7922 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7923 const FunctionProtoType *Proto
7924 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7925 assert(Proto && "Methods without a prototype cannot be overloaded");
7927 "Use AddOverloadCandidate for constructors");
7928
7929 if (!CandidateSet.isNewCandidate(Method, PO))
7930 return;
7931
7932 // C++11 [class.copy]p23: [DR1402]
7933 // A defaulted move assignment operator that is defined as deleted is
7934 // ignored by overload resolution.
7935 if (Method->isDefaulted() && Method->isDeleted() &&
7936 Method->isMoveAssignmentOperator())
7937 return;
7938
7939 // Overload resolution is always an unevaluated context.
7942
7943 bool IgnoreExplicitObject =
7944 (Method->isExplicitObjectMemberFunction() &&
7945 CandidateSet.getKind() ==
7947 bool ImplicitObjectMethodTreatedAsStatic =
7948 CandidateSet.getKind() ==
7950 Method->isImplicitObjectMemberFunction();
7951
7952 unsigned ExplicitOffset =
7953 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7954
7955 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7956 int(ImplicitObjectMethodTreatedAsStatic);
7957
7958 unsigned ExtraArgs =
7960 ? 0
7961 : 1;
7962
7963 // Add this candidate
7964 OverloadCandidate &Candidate =
7965 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7966 Candidate.FoundDecl = FoundDecl;
7967 Candidate.Function = Method;
7968 Candidate.RewriteKind =
7969 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7970 Candidate.TookAddressOfOverload =
7972 Candidate.ExplicitCallArguments = Args.size();
7973 Candidate.StrictPackMatch = StrictPackMatch;
7974
7975 // (C++ 13.3.2p2): A candidate function having fewer than m
7976 // parameters is viable only if it has an ellipsis in its parameter
7977 // list (8.3.5).
7978 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7979 !Proto->isVariadic() &&
7980 shouldEnforceArgLimit(PartialOverloading, Method)) {
7981 Candidate.Viable = false;
7983 return;
7984 }
7985
7986 // (C++ 13.3.2p2): A candidate function having more than m parameters
7987 // is viable only if the (m+1)st parameter has a default argument
7988 // (8.3.6). For the purposes of overload resolution, the
7989 // parameter list is truncated on the right, so that there are
7990 // exactly m parameters.
7991 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7992 ExplicitOffset +
7993 int(ImplicitObjectMethodTreatedAsStatic);
7994
7995 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7996 // Not enough arguments.
7997 Candidate.Viable = false;
7999 return;
8000 }
8001
8002 Candidate.Viable = true;
8003
8004 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8005 if (!IgnoreExplicitObject) {
8006 if (ObjectType.isNull())
8007 Candidate.IgnoreObjectArgument = true;
8008 else if (Method->isStatic()) {
8009 // [over.best.ics.general]p8
8010 // When the parameter is the implicit object parameter of a static member
8011 // function, the implicit conversion sequence is a standard conversion
8012 // sequence that is neither better nor worse than any other standard
8013 // conversion sequence.
8014 //
8015 // This is a rule that was introduced in C++23 to support static lambdas.
8016 // We apply it retroactively because we want to support static lambdas as
8017 // an extension and it doesn't hurt previous code.
8018 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8019 } else {
8020 // Determine the implicit conversion sequence for the object
8021 // parameter.
8022 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8023 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8024 Method, ActingContext, /*InOverloadResolution=*/true);
8025 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8026 Candidate.Viable = false;
8028 return;
8029 }
8030 }
8031 }
8032
8033 // (CUDA B.1): Check for invalid calls between targets.
8034 if (getLangOpts().CUDA)
8035 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8036 Method)) {
8037 Candidate.Viable = false;
8038 Candidate.FailureKind = ovl_fail_bad_target;
8039 return;
8040 }
8041
8042 if (Method->getTrailingRequiresClause()) {
8043 ConstraintSatisfaction Satisfaction;
8044 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8045 /*ForOverloadResolution*/ true) ||
8046 !Satisfaction.IsSatisfied) {
8047 Candidate.Viable = false;
8049 return;
8050 }
8051 }
8052
8053 // Determine the implicit conversion sequences for each of the
8054 // arguments.
8055 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8056 unsigned ConvIdx =
8057 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8058 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8059 // We already formed a conversion sequence for this parameter during
8060 // template argument deduction.
8061 } else if (ArgIdx < NumParams) {
8062 // (C++ 13.3.2p3): for F to be a viable function, there shall
8063 // exist for each argument an implicit conversion sequence
8064 // (13.3.3.1) that converts that argument to the corresponding
8065 // parameter of F.
8066 QualType ParamType;
8067 if (ImplicitObjectMethodTreatedAsStatic) {
8068 ParamType = ArgIdx == 0
8069 ? Method->getFunctionObjectParameterReferenceType()
8070 : Proto->getParamType(ArgIdx - 1);
8071 } else {
8072 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8073 }
8074 Candidate.Conversions[ConvIdx]
8075 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8076 SuppressUserConversions,
8077 /*InOverloadResolution=*/true,
8078 /*AllowObjCWritebackConversion=*/
8079 getLangOpts().ObjCAutoRefCount);
8080 if (Candidate.Conversions[ConvIdx].isBad()) {
8081 Candidate.Viable = false;
8083 return;
8084 }
8085 } else {
8086 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8087 // argument for which there is no corresponding parameter is
8088 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8089 Candidate.Conversions[ConvIdx].setEllipsis();
8090 }
8091 }
8092
8093 if (EnableIfAttr *FailedAttr =
8094 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8095 Candidate.Viable = false;
8096 Candidate.FailureKind = ovl_fail_enable_if;
8097 Candidate.DeductionFailure.Data = FailedAttr;
8098 return;
8099 }
8100
8102 Candidate.Viable = false;
8104 }
8105}
8106
8108 Sema &S, OverloadCandidateSet &CandidateSet,
8109 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8110 CXXRecordDecl *ActingContext,
8111 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8112 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8113 bool SuppressUserConversions, bool PartialOverloading,
8115
8116 // C++ [over.match.funcs]p7:
8117 // In each case where a candidate is a function template, candidate
8118 // function template specializations are generated using template argument
8119 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8120 // candidate functions in the usual way.113) A given name can refer to one
8121 // or more function templates and also to a set of overloaded non-template
8122 // functions. In such a case, the candidate functions generated from each
8123 // function template are combined with the set of non-template candidate
8124 // functions.
8125 TemplateDeductionInfo Info(CandidateSet.getLocation());
8126 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8127 FunctionDecl *Specialization = nullptr;
8128 ConversionSequenceList Conversions;
8130 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8131 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8132 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8133 CandidateSet.getKind() ==
8135 [&](ArrayRef<QualType> ParamTypes,
8136 bool OnlyInitializeNonUserDefinedConversions) {
8137 return S.CheckNonDependentConversions(
8138 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8139 Sema::CheckNonDependentConversionsFlag(
8140 SuppressUserConversions,
8141 OnlyInitializeNonUserDefinedConversions),
8142 ActingContext, ObjectType, ObjectClassification, PO);
8143 });
8145 OverloadCandidate &Candidate =
8146 CandidateSet.addCandidate(Conversions.size(), Conversions);
8147 Candidate.FoundDecl = FoundDecl;
8148 Candidate.Function = Method;
8149 Candidate.Viable = false;
8150 Candidate.RewriteKind =
8151 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8152 Candidate.IsSurrogate = false;
8153 Candidate.TookAddressOfOverload =
8154 CandidateSet.getKind() ==
8156
8157 Candidate.IgnoreObjectArgument =
8158 Method->isStatic() ||
8159 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8160 Candidate.ExplicitCallArguments = Args.size();
8163 else {
8165 Candidate.DeductionFailure =
8167 }
8168 return;
8169 }
8170
8171 // Add the function template specialization produced by template argument
8172 // deduction as a candidate.
8173 assert(Specialization && "Missing member function template specialization?");
8175 "Specialization is not a member function?");
8177 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8178 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8179 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8180}
8181
8183 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8184 CXXRecordDecl *ActingContext,
8185 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8186 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8187 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8188 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8189 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8190 return;
8191
8192 if (ExplicitTemplateArgs ||
8195 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8196 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8197 SuppressUserConversions, PartialOverloading, PO);
8198 return;
8199 }
8200
8202 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8203 Args, SuppressUserConversions, PartialOverloading, PO);
8204}
8205
8206/// Determine whether a given function template has a simple explicit specifier
8207/// or a non-value-dependent explicit-specification that evaluates to true.
8211
8216
8218 Sema &S, OverloadCandidateSet &CandidateSet,
8220 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8221 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8223 bool AggregateCandidateDeduction) {
8224
8225 // If the function template has a non-dependent explicit specification,
8226 // exclude it now if appropriate; we are not permitted to perform deduction
8227 // and substitution in this case.
8228 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8229 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8230 Candidate.FoundDecl = FoundDecl;
8231 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8232 Candidate.Viable = false;
8233 Candidate.FailureKind = ovl_fail_explicit;
8234 return;
8235 }
8236
8237 // C++ [over.match.funcs]p7:
8238 // In each case where a candidate is a function template, candidate
8239 // function template specializations are generated using template argument
8240 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8241 // candidate functions in the usual way.113) A given name can refer to one
8242 // or more function templates and also to a set of overloaded non-template
8243 // functions. In such a case, the candidate functions generated from each
8244 // function template are combined with the set of non-template candidate
8245 // functions.
8246 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8247 FunctionTemplate->getTemplateDepth());
8248 FunctionDecl *Specialization = nullptr;
8249 ConversionSequenceList Conversions;
8251 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8252 PartialOverloading, AggregateCandidateDeduction,
8253 /*PartialOrdering=*/false,
8254 /*ObjectType=*/QualType(),
8255 /*ObjectClassification=*/Expr::Classification(),
8256 CandidateSet.getKind() ==
8258 [&](ArrayRef<QualType> ParamTypes,
8259 bool OnlyInitializeNonUserDefinedConversions) {
8260 return S.CheckNonDependentConversions(
8261 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8262 Sema::CheckNonDependentConversionsFlag(
8263 SuppressUserConversions,
8264 OnlyInitializeNonUserDefinedConversions),
8265 nullptr, QualType(), {}, PO);
8266 });
8268 OverloadCandidate &Candidate =
8269 CandidateSet.addCandidate(Conversions.size(), Conversions);
8270 Candidate.FoundDecl = FoundDecl;
8271 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8272 Candidate.Viable = false;
8273 Candidate.RewriteKind =
8274 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8275 Candidate.IsSurrogate = false;
8276 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8277 // Ignore the object argument if there is one, since we don't have an object
8278 // type.
8279 Candidate.TookAddressOfOverload =
8280 CandidateSet.getKind() ==
8282
8283 Candidate.IgnoreObjectArgument =
8284 isa<CXXMethodDecl>(Candidate.Function) &&
8285 !cast<CXXMethodDecl>(Candidate.Function)
8286 ->isExplicitObjectMemberFunction() &&
8288
8289 Candidate.ExplicitCallArguments = Args.size();
8292 else {
8294 Candidate.DeductionFailure =
8296 }
8297 return;
8298 }
8299
8300 // Add the function template specialization produced by template argument
8301 // deduction as a candidate.
8302 assert(Specialization && "Missing function template specialization?");
8304 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8305 PartialOverloading, AllowExplicit,
8306 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8307 Info.AggregateDeductionCandidateHasMismatchedArity,
8308 Info.hasStrictPackMatch());
8309}
8310
8313 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8314 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8315 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8316 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8317 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8318 return;
8319
8320 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8321
8322 if (ExplicitTemplateArgs ||
8324 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8325 DependentExplicitSpecifier)) {
8326
8328 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8329 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8330 IsADLCandidate, PO, AggregateCandidateDeduction);
8331
8332 if (DependentExplicitSpecifier)
8334 return;
8335 }
8336
8337 CandidateSet.AddDeferredTemplateCandidate(
8338 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8339 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8340 AggregateCandidateDeduction);
8341}
8342
8345 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8347 CheckNonDependentConversionsFlag UserConversionFlag,
8348 CXXRecordDecl *ActingContext, QualType ObjectType,
8349 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8350 // FIXME: The cases in which we allow explicit conversions for constructor
8351 // arguments never consider calling a constructor template. It's not clear
8352 // that is correct.
8353 const bool AllowExplicit = false;
8354
8355 bool ForOverloadSetAddressResolution =
8357 auto *FD = FunctionTemplate->getTemplatedDecl();
8358 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8359 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8361 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8362
8363 if (Conversions.empty())
8364 Conversions =
8365 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8366
8367 // Overload resolution is always an unevaluated context.
8370
8371 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8372 // require that, but this check should never result in a hard error, and
8373 // overload resolution is permitted to sidestep instantiations.
8374 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8375 !ObjectType.isNull()) {
8376 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8377 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8378 !ParamTypes[0]->isDependentType()) {
8380 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8381 Method, ActingContext, /*InOverloadResolution=*/true,
8382 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8383 : QualType());
8384 if (Conversions[ConvIdx].isBad())
8385 return true;
8386 }
8387 }
8388
8389 // A speculative workaround for self-dependent constraint bugs that manifest
8390 // after CWG2369.
8391 // FIXME: Add references to the standard once P3606 is adopted.
8392 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8393 QualType ArgType) {
8394 ParamType = ParamType.getNonReferenceType();
8395 ArgType = ArgType.getNonReferenceType();
8396 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8397 if (PointerConv) {
8398 ParamType = ParamType->getPointeeType();
8399 ArgType = ArgType->getPointeeType();
8400 }
8401
8402 if (auto *RD = ParamType->getAsCXXRecordDecl();
8403 RD && RD->hasDefinition() &&
8404 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8405 auto Info = getConstructorInfo(ND);
8406 if (!Info)
8407 return false;
8408 CXXConstructorDecl *Ctor = Info.Constructor;
8409 /// isConvertingConstructor takes copy/move constructors into
8410 /// account!
8411 return !Ctor->isCopyOrMoveConstructor() &&
8413 /*AllowExplicit=*/true);
8414 }))
8415 return true;
8416 if (auto *RD = ArgType->getAsCXXRecordDecl();
8417 RD && RD->hasDefinition() &&
8418 !RD->getVisibleConversionFunctions().empty())
8419 return true;
8420
8421 return false;
8422 };
8423
8424 unsigned Offset =
8425 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8426 : 0;
8427
8428 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8429 I != N; ++I) {
8430 QualType ParamType = ParamTypes[I + Offset];
8431 if (!ParamType->isDependentType()) {
8432 unsigned ConvIdx;
8434 ConvIdx = Args.size() - 1 - I;
8435 assert(Args.size() + ThisConversions == 2 &&
8436 "number of args (including 'this') must be exactly 2 for "
8437 "reversed order");
8438 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8439 // would also be 0. 'this' got ConvIdx = 1 previously.
8440 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8441 } else {
8442 // For members, 'this' got ConvIdx = 0 previously.
8443 ConvIdx = ThisConversions + I;
8444 }
8445 if (Conversions[ConvIdx].isInitialized())
8446 continue;
8447 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8448 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8449 continue;
8451 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8452 /*InOverloadResolution=*/true,
8453 /*AllowObjCWritebackConversion=*/
8454 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8455 if (Conversions[ConvIdx].isBad())
8456 return true;
8457 }
8458 }
8459
8460 return false;
8461}
8462
8463/// Determine whether this is an allowable conversion from the result
8464/// of an explicit conversion operator to the expected type, per C++
8465/// [over.match.conv]p1 and [over.match.ref]p1.
8466///
8467/// \param ConvType The return type of the conversion function.
8468///
8469/// \param ToType The type we are converting to.
8470///
8471/// \param AllowObjCPointerConversion Allow a conversion from one
8472/// Objective-C pointer to another.
8473///
8474/// \returns true if the conversion is allowable, false otherwise.
8476 QualType ConvType, QualType ToType,
8477 bool AllowObjCPointerConversion) {
8478 QualType ToNonRefType = ToType.getNonReferenceType();
8479
8480 // Easy case: the types are the same.
8481 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8482 return true;
8483
8484 // Allow qualification conversions.
8485 bool ObjCLifetimeConversion;
8486 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8487 ObjCLifetimeConversion))
8488 return true;
8489
8490 // If we're not allowed to consider Objective-C pointer conversions,
8491 // we're done.
8492 if (!AllowObjCPointerConversion)
8493 return false;
8494
8495 // Is this an Objective-C pointer conversion?
8496 bool IncompatibleObjC = false;
8497 QualType ConvertedType;
8498 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8499 IncompatibleObjC);
8500}
8501
8503 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8504 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8505 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8506 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8507 assert(!Conversion->getDescribedFunctionTemplate() &&
8508 "Conversion function templates use AddTemplateConversionCandidate");
8509 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8510 if (!CandidateSet.isNewCandidate(Conversion))
8511 return;
8512
8513 // If the conversion function has an undeduced return type, trigger its
8514 // deduction now.
8515 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8516 if (DeduceReturnType(Conversion, From->getExprLoc()))
8517 return;
8518 ConvType = Conversion->getConversionType().getNonReferenceType();
8519 }
8520
8521 // If we don't allow any conversion of the result type, ignore conversion
8522 // functions that don't convert to exactly (possibly cv-qualified) T.
8523 if (!AllowResultConversion &&
8524 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8525 return;
8526
8527 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8528 // operator is only a candidate if its return type is the target type or
8529 // can be converted to the target type with a qualification conversion.
8530 //
8531 // FIXME: Include such functions in the candidate list and explain why we
8532 // can't select them.
8533 if (Conversion->isExplicit() &&
8534 !isAllowableExplicitConversion(*this, ConvType, ToType,
8535 AllowObjCConversionOnExplicit))
8536 return;
8537
8538 // Overload resolution is always an unevaluated context.
8541
8542 // Add this candidate
8543 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8544 Candidate.FoundDecl = FoundDecl;
8545 Candidate.Function = Conversion;
8547 Candidate.FinalConversion.setFromType(ConvType);
8548 Candidate.FinalConversion.setAllToTypes(ToType);
8549 Candidate.HasFinalConversion = true;
8550 Candidate.Viable = true;
8551 Candidate.ExplicitCallArguments = 1;
8552 Candidate.StrictPackMatch = StrictPackMatch;
8553
8554 // Explicit functions are not actually candidates at all if we're not
8555 // allowing them in this context, but keep them around so we can point
8556 // to them in diagnostics.
8557 if (!AllowExplicit && Conversion->isExplicit()) {
8558 Candidate.Viable = false;
8559 Candidate.FailureKind = ovl_fail_explicit;
8560 return;
8561 }
8562
8563 // C++ [over.match.funcs]p4:
8564 // For conversion functions, the function is considered to be a member of
8565 // the class of the implicit implied object argument for the purpose of
8566 // defining the type of the implicit object parameter.
8567 //
8568 // Determine the implicit conversion sequence for the implicit
8569 // object parameter.
8570 QualType ObjectType = From->getType();
8571 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8572 ObjectType = FromPtrType->getPointeeType();
8573 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8574 // C++23 [over.best.ics.general]
8575 // However, if the target is [...]
8576 // - the object parameter of a user-defined conversion function
8577 // [...] user-defined conversion sequences are not considered.
8579 *this, CandidateSet.getLocation(), From->getType(),
8580 From->Classify(Context), Conversion, ConversionContext,
8581 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8582 /*SuppressUserConversion*/ true);
8583
8584 if (Candidate.Conversions[0].isBad()) {
8585 Candidate.Viable = false;
8587 return;
8588 }
8589
8590 if (Conversion->getTrailingRequiresClause()) {
8591 ConstraintSatisfaction Satisfaction;
8592 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8593 !Satisfaction.IsSatisfied) {
8594 Candidate.Viable = false;
8596 return;
8597 }
8598 }
8599
8600 // We won't go through a user-defined type conversion function to convert a
8601 // derived to base as such conversions are given Conversion Rank. They only
8602 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8603 QualType FromCanon
8604 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8605 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8606 if (FromCanon == ToCanon ||
8607 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8608 Candidate.Viable = false;
8610 return;
8611 }
8612
8613 // To determine what the conversion from the result of calling the
8614 // conversion function to the type we're eventually trying to
8615 // convert to (ToType), we need to synthesize a call to the
8616 // conversion function and attempt copy initialization from it. This
8617 // makes sure that we get the right semantics with respect to
8618 // lvalues/rvalues and the type. Fortunately, we can allocate this
8619 // call on the stack and we don't need its arguments to be
8620 // well-formed.
8621 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8622 VK_LValue, From->getBeginLoc());
8624 Context.getPointerType(Conversion->getType()),
8625 CK_FunctionToPointerDecay, &ConversionRef,
8627
8628 QualType ConversionType = Conversion->getConversionType();
8629 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8630 Candidate.Viable = false;
8632 return;
8633 }
8634
8635 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8636
8637 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8638
8639 // Introduce a temporary expression with the right type and value category
8640 // that we can use for deduction purposes.
8641 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8642
8644 TryCopyInitialization(*this, &FakeCall, ToType,
8645 /*SuppressUserConversions=*/true,
8646 /*InOverloadResolution=*/false,
8647 /*AllowObjCWritebackConversion=*/false);
8648
8649 switch (ICS.getKind()) {
8651 Candidate.FinalConversion = ICS.Standard;
8652 Candidate.HasFinalConversion = true;
8653
8654 // C++ [over.ics.user]p3:
8655 // If the user-defined conversion is specified by a specialization of a
8656 // conversion function template, the second standard conversion sequence
8657 // shall have exact match rank.
8658 if (Conversion->getPrimaryTemplate() &&
8660 Candidate.Viable = false;
8662 return;
8663 }
8664
8665 // C++0x [dcl.init.ref]p5:
8666 // In the second case, if the reference is an rvalue reference and
8667 // the second standard conversion sequence of the user-defined
8668 // conversion sequence includes an lvalue-to-rvalue conversion, the
8669 // program is ill-formed.
8670 if (ToType->isRValueReferenceType() &&
8672 Candidate.Viable = false;
8674 return;
8675 }
8676 break;
8677
8679 Candidate.Viable = false;
8681 return;
8682
8683 default:
8684 llvm_unreachable(
8685 "Can only end up with a standard conversion sequence or failure");
8686 }
8687
8688 if (EnableIfAttr *FailedAttr =
8689 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8690 Candidate.Viable = false;
8691 Candidate.FailureKind = ovl_fail_enable_if;
8692 Candidate.DeductionFailure.Data = FailedAttr;
8693 return;
8694 }
8695
8696 if (isNonViableMultiVersionOverload(Conversion)) {
8697 Candidate.Viable = false;
8699 }
8700}
8701
8703 Sema &S, OverloadCandidateSet &CandidateSet,
8705 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8706 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8707 bool AllowResultConversion) {
8708
8709 // If the function template has a non-dependent explicit specification,
8710 // exclude it now if appropriate; we are not permitted to perform deduction
8711 // and substitution in this case.
8712 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8713 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8714 Candidate.FoundDecl = FoundDecl;
8715 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8716 Candidate.Viable = false;
8717 Candidate.FailureKind = ovl_fail_explicit;
8718 return;
8719 }
8720
8721 QualType ObjectType = From->getType();
8722 Expr::Classification ObjectClassification = From->Classify(S.Context);
8723
8724 TemplateDeductionInfo Info(CandidateSet.getLocation());
8727 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8728 Specialization, Info);
8730 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8731 Candidate.FoundDecl = FoundDecl;
8732 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8733 Candidate.Viable = false;
8735 Candidate.ExplicitCallArguments = 1;
8736 Candidate.DeductionFailure =
8738 return;
8739 }
8740
8741 // Add the conversion function template specialization produced by
8742 // template argument deduction as a candidate.
8743 assert(Specialization && "Missing function template specialization?");
8744 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8745 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8746 AllowExplicit, AllowResultConversion,
8747 Info.hasStrictPackMatch());
8748}
8749
8752 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8753 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8754 bool AllowExplicit, bool AllowResultConversion) {
8755 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8756 "Only conversion function templates permitted here");
8757
8758 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8759 return;
8760
8762 CandidateSet.getKind() ==
8766 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8767 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8768 AllowResultConversion);
8769
8771 return;
8772 }
8773
8775 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8776 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8777}
8778
8780 DeclAccessPair FoundDecl,
8781 CXXRecordDecl *ActingContext,
8782 const FunctionProtoType *Proto,
8783 Expr *Object,
8784 ArrayRef<Expr *> Args,
8785 OverloadCandidateSet& CandidateSet) {
8786 if (!CandidateSet.isNewCandidate(Conversion))
8787 return;
8788
8789 // Overload resolution is always an unevaluated context.
8792
8793 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8794 Candidate.FoundDecl = FoundDecl;
8795 Candidate.Function = nullptr;
8796 Candidate.Surrogate = Conversion;
8797 Candidate.IsSurrogate = true;
8798 Candidate.Viable = true;
8799 Candidate.ExplicitCallArguments = Args.size();
8800
8801 // Determine the implicit conversion sequence for the implicit
8802 // object parameter.
8803 ImplicitConversionSequence ObjectInit;
8804 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8805 ObjectInit = TryCopyInitialization(*this, Object,
8806 Conversion->getParamDecl(0)->getType(),
8807 /*SuppressUserConversions=*/false,
8808 /*InOverloadResolution=*/true, false);
8809 } else {
8811 *this, CandidateSet.getLocation(), Object->getType(),
8812 Object->Classify(Context), Conversion, ActingContext);
8813 }
8814
8815 if (ObjectInit.isBad()) {
8816 Candidate.Viable = false;
8818 Candidate.Conversions[0] = ObjectInit;
8819 return;
8820 }
8821
8822 // The first conversion is actually a user-defined conversion whose
8823 // first conversion is ObjectInit's standard conversion (which is
8824 // effectively a reference binding). Record it as such.
8825 Candidate.Conversions[0].setUserDefined();
8826 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8827 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8828 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8829 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8830 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8831 Candidate.Conversions[0].UserDefined.After
8832 = Candidate.Conversions[0].UserDefined.Before;
8833 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8834
8835 // Find the
8836 unsigned NumParams = Proto->getNumParams();
8837
8838 // (C++ 13.3.2p2): A candidate function having fewer than m
8839 // parameters is viable only if it has an ellipsis in its parameter
8840 // list (8.3.5).
8841 if (Args.size() > NumParams && !Proto->isVariadic()) {
8842 Candidate.Viable = false;
8844 return;
8845 }
8846
8847 // Function types don't have any default arguments, so just check if
8848 // we have enough arguments.
8849 if (Args.size() < NumParams) {
8850 // Not enough arguments.
8851 Candidate.Viable = false;
8853 return;
8854 }
8855
8856 // Determine the implicit conversion sequences for each of the
8857 // arguments.
8858 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8859 if (ArgIdx < NumParams) {
8860 // (C++ 13.3.2p3): for F to be a viable function, there shall
8861 // exist for each argument an implicit conversion sequence
8862 // (13.3.3.1) that converts that argument to the corresponding
8863 // parameter of F.
8864 QualType ParamType = Proto->getParamType(ArgIdx);
8865 Candidate.Conversions[ArgIdx + 1]
8866 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8867 /*SuppressUserConversions=*/false,
8868 /*InOverloadResolution=*/false,
8869 /*AllowObjCWritebackConversion=*/
8870 getLangOpts().ObjCAutoRefCount);
8871 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8872 Candidate.Viable = false;
8874 return;
8875 }
8876 } else {
8877 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8878 // argument for which there is no corresponding parameter is
8879 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8880 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8881 }
8882 }
8883
8884 if (Conversion->getTrailingRequiresClause()) {
8885 ConstraintSatisfaction Satisfaction;
8886 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8887 /*ForOverloadResolution*/ true) ||
8888 !Satisfaction.IsSatisfied) {
8889 Candidate.Viable = false;
8891 return;
8892 }
8893 }
8894
8895 if (EnableIfAttr *FailedAttr =
8896 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8897 Candidate.Viable = false;
8898 Candidate.FailureKind = ovl_fail_enable_if;
8899 Candidate.DeductionFailure.Data = FailedAttr;
8900 return;
8901 }
8902}
8903
8905 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8906 OverloadCandidateSet &CandidateSet,
8907 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8908 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8909 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8910 ArrayRef<Expr *> FunctionArgs = Args;
8911
8912 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8913 FunctionDecl *FD =
8914 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8915
8916 // Don't consider rewritten functions if we're not rewriting.
8917 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8918 continue;
8919
8920 assert(!isa<CXXMethodDecl>(FD) &&
8921 "unqualified operator lookup found a member function");
8922
8923 if (FunTmpl) {
8924 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8925 FunctionArgs, CandidateSet);
8926 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8927
8928 // As template candidates are not deduced immediately,
8929 // persist the array in the overload set.
8931 FunctionArgs[1], FunctionArgs[0]);
8932 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8933 Reversed, CandidateSet, false, false, true,
8934 ADLCallKind::NotADL,
8936 }
8937 } else {
8938 if (ExplicitTemplateArgs)
8939 continue;
8940 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8941 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8942 AddOverloadCandidate(FD, F.getPair(),
8943 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8944 false, false, true, false, ADLCallKind::NotADL, {},
8946 }
8947 }
8948}
8949
8951 SourceLocation OpLoc,
8952 ArrayRef<Expr *> Args,
8953 OverloadCandidateSet &CandidateSet,
8955 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8956
8957 // C++ [over.match.oper]p3:
8958 // For a unary operator @ with an operand of a type whose
8959 // cv-unqualified version is T1, and for a binary operator @ with
8960 // a left operand of a type whose cv-unqualified version is T1 and
8961 // a right operand of a type whose cv-unqualified version is T2,
8962 // three sets of candidate functions, designated member
8963 // candidates, non-member candidates and built-in candidates, are
8964 // constructed as follows:
8965 QualType T1 = Args[0]->getType();
8966
8967 // -- If T1 is a complete class type or a class currently being
8968 // defined, the set of member candidates is the result of the
8969 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8970 // the set of member candidates is empty.
8971 if (T1->isRecordType()) {
8972 bool IsComplete = isCompleteType(OpLoc, T1);
8973 auto *T1RD = T1->getAsCXXRecordDecl();
8974 // Complete the type if it can be completed.
8975 // If the type is neither complete nor being defined, bail out now.
8976 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8977 return;
8978
8979 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8980 LookupQualifiedName(Operators, T1RD);
8981 Operators.suppressAccessDiagnostics();
8982
8983 for (LookupResult::iterator Oper = Operators.begin(),
8984 OperEnd = Operators.end();
8985 Oper != OperEnd; ++Oper) {
8986 if (Oper->getAsFunction() &&
8988 !CandidateSet.getRewriteInfo().shouldAddReversed(
8989 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8990 continue;
8991 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8992 Args[0]->Classify(Context), Args.slice(1),
8993 CandidateSet, /*SuppressUserConversion=*/false, PO);
8994 }
8995 }
8996}
8997
8999 OverloadCandidateSet& CandidateSet,
9000 bool IsAssignmentOperator,
9001 unsigned NumContextualBoolArguments) {
9002 // Overload resolution is always an unevaluated context.
9005
9006 // Add this candidate
9007 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9008 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9009 Candidate.Function = nullptr;
9010 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9011
9012 // Determine the implicit conversion sequences for each of the
9013 // arguments.
9014 Candidate.Viable = true;
9015 Candidate.ExplicitCallArguments = Args.size();
9016 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9017 // C++ [over.match.oper]p4:
9018 // For the built-in assignment operators, conversions of the
9019 // left operand are restricted as follows:
9020 // -- no temporaries are introduced to hold the left operand, and
9021 // -- no user-defined conversions are applied to the left
9022 // operand to achieve a type match with the left-most
9023 // parameter of a built-in candidate.
9024 //
9025 // We block these conversions by turning off user-defined
9026 // conversions, since that is the only way that initialization of
9027 // a reference to a non-class type can occur from something that
9028 // is not of the same type.
9029 if (ArgIdx < NumContextualBoolArguments) {
9030 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9031 "Contextual conversion to bool requires bool type");
9032 Candidate.Conversions[ArgIdx]
9033 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9034 } else {
9035 Candidate.Conversions[ArgIdx]
9036 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9037 ArgIdx == 0 && IsAssignmentOperator,
9038 /*InOverloadResolution=*/false,
9039 /*AllowObjCWritebackConversion=*/
9040 getLangOpts().ObjCAutoRefCount);
9041 }
9042 if (Candidate.Conversions[ArgIdx].isBad()) {
9043 Candidate.Viable = false;
9045 break;
9046 }
9047 }
9048}
9049
9050namespace {
9051
9052/// BuiltinCandidateTypeSet - A set of types that will be used for the
9053/// candidate operator functions for built-in operators (C++
9054/// [over.built]). The types are separated into pointer types and
9055/// enumeration types.
9056class BuiltinCandidateTypeSet {
9057 /// TypeSet - A set of types.
9058 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9059
9060 /// PointerTypes - The set of pointer types that will be used in the
9061 /// built-in candidates.
9062 TypeSet PointerTypes;
9063
9064 /// MemberPointerTypes - The set of member pointer types that will be
9065 /// used in the built-in candidates.
9066 TypeSet MemberPointerTypes;
9067
9068 /// EnumerationTypes - The set of enumeration types that will be
9069 /// used in the built-in candidates.
9070 TypeSet EnumerationTypes;
9071
9072 /// The set of vector types that will be used in the built-in
9073 /// candidates.
9074 TypeSet VectorTypes;
9075
9076 /// The set of matrix types that will be used in the built-in
9077 /// candidates.
9078 TypeSet MatrixTypes;
9079
9080 /// The set of _BitInt types that will be used in the built-in candidates.
9081 TypeSet BitIntTypes;
9082
9083 /// A flag indicating non-record types are viable candidates
9084 bool HasNonRecordTypes;
9085
9086 /// A flag indicating whether either arithmetic or enumeration types
9087 /// were present in the candidate set.
9088 bool HasArithmeticOrEnumeralTypes;
9089
9090 /// A flag indicating whether the nullptr type was present in the
9091 /// candidate set.
9092 bool HasNullPtrType;
9093
9094 /// Sema - The semantic analysis instance where we are building the
9095 /// candidate type set.
9096 Sema &SemaRef;
9097
9098 /// Context - The AST context in which we will build the type sets.
9099 ASTContext &Context;
9100
9101 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9102 const Qualifiers &VisibleQuals);
9103 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9104
9105public:
9106 /// iterator - Iterates through the types that are part of the set.
9107 typedef TypeSet::iterator iterator;
9108
9109 BuiltinCandidateTypeSet(Sema &SemaRef)
9110 : HasNonRecordTypes(false),
9111 HasArithmeticOrEnumeralTypes(false),
9112 HasNullPtrType(false),
9113 SemaRef(SemaRef),
9114 Context(SemaRef.Context) { }
9115
9116 void AddTypesConvertedFrom(QualType Ty,
9117 SourceLocation Loc,
9118 bool AllowUserConversions,
9119 bool AllowExplicitConversions,
9120 const Qualifiers &VisibleTypeConversionsQuals);
9121
9122 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9123 llvm::iterator_range<iterator> member_pointer_types() {
9124 return MemberPointerTypes;
9125 }
9126 llvm::iterator_range<iterator> enumeration_types() {
9127 return EnumerationTypes;
9128 }
9129 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9130 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9131 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9132
9133 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9134 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9135 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9136 bool hasNullPtrType() const { return HasNullPtrType; }
9137};
9138
9139} // end anonymous namespace
9140
9141/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9142/// the set of pointer types along with any more-qualified variants of
9143/// that type. For example, if @p Ty is "int const *", this routine
9144/// will add "int const *", "int const volatile *", "int const
9145/// restrict *", and "int const volatile restrict *" to the set of
9146/// pointer types. Returns true if the add of @p Ty itself succeeded,
9147/// false otherwise.
9148///
9149/// FIXME: what to do about extended qualifiers?
9150bool
9151BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9152 const Qualifiers &VisibleQuals) {
9153
9154 // Insert this type.
9155 if (!PointerTypes.insert(Ty))
9156 return false;
9157
9158 QualType PointeeTy;
9159 const PointerType *PointerTy = Ty->getAs<PointerType>();
9160 bool buildObjCPtr = false;
9161 if (!PointerTy) {
9162 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9163 PointeeTy = PTy->getPointeeType();
9164 buildObjCPtr = true;
9165 } else {
9166 PointeeTy = PointerTy->getPointeeType();
9167 }
9168
9169 // Don't add qualified variants of arrays. For one, they're not allowed
9170 // (the qualifier would sink to the element type), and for another, the
9171 // only overload situation where it matters is subscript or pointer +- int,
9172 // and those shouldn't have qualifier variants anyway.
9173 if (PointeeTy->isArrayType())
9174 return true;
9175
9176 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9177 bool hasVolatile = VisibleQuals.hasVolatile();
9178 bool hasRestrict = VisibleQuals.hasRestrict();
9179
9180 // Iterate through all strict supersets of BaseCVR.
9181 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9182 if ((CVR | BaseCVR) != CVR) continue;
9183 // Skip over volatile if no volatile found anywhere in the types.
9184 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9185
9186 // Skip over restrict if no restrict found anywhere in the types, or if
9187 // the type cannot be restrict-qualified.
9188 if ((CVR & Qualifiers::Restrict) &&
9189 (!hasRestrict ||
9190 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9191 continue;
9192
9193 // Build qualified pointee type.
9194 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9195
9196 // Build qualified pointer type.
9197 QualType QPointerTy;
9198 if (!buildObjCPtr)
9199 QPointerTy = Context.getPointerType(QPointeeTy);
9200 else
9201 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9202
9203 // Insert qualified pointer type.
9204 PointerTypes.insert(QPointerTy);
9205 }
9206
9207 return true;
9208}
9209
9210/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9211/// to the set of pointer types along with any more-qualified variants of
9212/// that type. For example, if @p Ty is "int const *", this routine
9213/// will add "int const *", "int const volatile *", "int const
9214/// restrict *", and "int const volatile restrict *" to the set of
9215/// pointer types. Returns true if the add of @p Ty itself succeeded,
9216/// false otherwise.
9217///
9218/// FIXME: what to do about extended qualifiers?
9219bool
9220BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9221 QualType Ty) {
9222 // Insert this type.
9223 if (!MemberPointerTypes.insert(Ty))
9224 return false;
9225
9226 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9227 assert(PointerTy && "type was not a member pointer type!");
9228
9229 QualType PointeeTy = PointerTy->getPointeeType();
9230 // Don't add qualified variants of arrays. For one, they're not allowed
9231 // (the qualifier would sink to the element type), and for another, the
9232 // only overload situation where it matters is subscript or pointer +- int,
9233 // and those shouldn't have qualifier variants anyway.
9234 if (PointeeTy->isArrayType())
9235 return true;
9236 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9237
9238 // Iterate through all strict supersets of the pointee type's CVR
9239 // qualifiers.
9240 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9241 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9242 if ((CVR | BaseCVR) != CVR) continue;
9243
9244 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9245 MemberPointerTypes.insert(Context.getMemberPointerType(
9246 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9247 }
9248
9249 return true;
9250}
9251
9252/// AddTypesConvertedFrom - Add each of the types to which the type @p
9253/// Ty can be implicit converted to the given set of @p Types. We're
9254/// primarily interested in pointer types and enumeration types. We also
9255/// take member pointer types, for the conditional operator.
9256/// AllowUserConversions is true if we should look at the conversion
9257/// functions of a class type, and AllowExplicitConversions if we
9258/// should also include the explicit conversion functions of a class
9259/// type.
9260void
9261BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9262 SourceLocation Loc,
9263 bool AllowUserConversions,
9264 bool AllowExplicitConversions,
9265 const Qualifiers &VisibleQuals) {
9266 // Only deal with canonical types.
9267 Ty = Context.getCanonicalType(Ty);
9268
9269 // Look through reference types; they aren't part of the type of an
9270 // expression for the purposes of conversions.
9271 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9272 Ty = RefTy->getPointeeType();
9273
9274 // If we're dealing with an array type, decay to the pointer.
9275 if (Ty->isArrayType())
9276 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9277
9278 // Otherwise, we don't care about qualifiers on the type.
9279 Ty = Ty.getLocalUnqualifiedType();
9280
9281 // Flag if we ever add a non-record type.
9282 bool TyIsRec = Ty->isRecordType();
9283 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9284
9285 // Flag if we encounter an arithmetic type.
9286 HasArithmeticOrEnumeralTypes =
9287 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9288
9289 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9290 PointerTypes.insert(Ty);
9291 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9292 // Insert our type, and its more-qualified variants, into the set
9293 // of types.
9294 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9295 return;
9296 } else if (Ty->isMemberPointerType()) {
9297 // Member pointers are far easier, since the pointee can't be converted.
9298 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9299 return;
9300 } else if (Ty->isEnumeralType()) {
9301 HasArithmeticOrEnumeralTypes = true;
9302 EnumerationTypes.insert(Ty);
9303 } else if (Ty->isBitIntType()) {
9304 HasArithmeticOrEnumeralTypes = true;
9305 BitIntTypes.insert(Ty);
9306 } else if (Ty->isVectorType()) {
9307 // We treat vector types as arithmetic types in many contexts as an
9308 // extension.
9309 HasArithmeticOrEnumeralTypes = true;
9310 VectorTypes.insert(Ty);
9311 } else if (Ty->isMatrixType()) {
9312 // Similar to vector types, we treat vector types as arithmetic types in
9313 // many contexts as an extension.
9314 HasArithmeticOrEnumeralTypes = true;
9315 MatrixTypes.insert(Ty);
9316 } else if (Ty->isNullPtrType()) {
9317 HasNullPtrType = true;
9318 } else if (AllowUserConversions && TyIsRec) {
9319 // No conversion functions in incomplete types.
9320 if (!SemaRef.isCompleteType(Loc, Ty))
9321 return;
9322
9323 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9324 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9325 if (isa<UsingShadowDecl>(D))
9326 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9327
9328 // Skip conversion function templates; they don't tell us anything
9329 // about which builtin types we can convert to.
9331 continue;
9332
9333 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9334 if (AllowExplicitConversions || !Conv->isExplicit()) {
9335 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9336 VisibleQuals);
9337 }
9338 }
9339 }
9340}
9341/// Helper function for adjusting address spaces for the pointer or reference
9342/// operands of builtin operators depending on the argument.
9347
9348/// Helper function for AddBuiltinOperatorCandidates() that adds
9349/// the volatile- and non-volatile-qualified assignment operators for the
9350/// given type to the candidate set.
9352 QualType T,
9353 ArrayRef<Expr *> Args,
9354 OverloadCandidateSet &CandidateSet) {
9355 QualType ParamTypes[2];
9356
9357 // T& operator=(T&, T)
9358 ParamTypes[0] = S.Context.getLValueReferenceType(
9360 ParamTypes[1] = T;
9361 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9362 /*IsAssignmentOperator=*/true);
9363
9365 // volatile T& operator=(volatile T&, T)
9366 ParamTypes[0] = S.Context.getLValueReferenceType(
9368 Args[0]));
9369 ParamTypes[1] = T;
9370 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9371 /*IsAssignmentOperator=*/true);
9372 }
9373}
9374
9375/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9376/// if any, found in visible type conversion functions found in ArgExpr's type.
9377static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9378 Qualifiers VRQuals;
9379 CXXRecordDecl *ClassDecl;
9380 if (const MemberPointerType *RHSMPType =
9381 ArgExpr->getType()->getAs<MemberPointerType>())
9382 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9383 else
9384 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9385 if (!ClassDecl) {
9386 // Just to be safe, assume the worst case.
9387 VRQuals.addVolatile();
9388 VRQuals.addRestrict();
9389 return VRQuals;
9390 }
9391 if (!ClassDecl->hasDefinition())
9392 return VRQuals;
9393
9394 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9395 if (isa<UsingShadowDecl>(D))
9396 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9397 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9398 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9399 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9400 CanTy = ResTypeRef->getPointeeType();
9401 // Need to go down the pointer/mempointer chain and add qualifiers
9402 // as see them.
9403 bool done = false;
9404 while (!done) {
9405 if (CanTy.isRestrictQualified())
9406 VRQuals.addRestrict();
9407 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9408 CanTy = ResTypePtr->getPointeeType();
9409 else if (const MemberPointerType *ResTypeMPtr =
9410 CanTy->getAs<MemberPointerType>())
9411 CanTy = ResTypeMPtr->getPointeeType();
9412 else
9413 done = true;
9414 if (CanTy.isVolatileQualified())
9415 VRQuals.addVolatile();
9416 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9417 return VRQuals;
9418 }
9419 }
9420 }
9421 return VRQuals;
9422}
9423
9424// Note: We're currently only handling qualifiers that are meaningful for the
9425// LHS of compound assignment overloading.
9427 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9428 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9429 // _Atomic
9430 if (Available.hasAtomic()) {
9431 Available.removeAtomic();
9432 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9433 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9434 return;
9435 }
9436
9437 // volatile
9438 if (Available.hasVolatile()) {
9439 Available.removeVolatile();
9440 assert(!Applied.hasVolatile());
9441 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9442 Callback);
9443 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9444 return;
9445 }
9446
9447 Callback(Applied);
9448}
9449
9451 QualifiersAndAtomic Quals,
9452 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9454 Callback);
9455}
9456
9458 QualifiersAndAtomic Quals,
9459 Sema &S) {
9460 if (Quals.hasAtomic())
9462 if (Quals.hasVolatile())
9465}
9466
9467namespace {
9468
9469/// Helper class to manage the addition of builtin operator overload
9470/// candidates. It provides shared state and utility methods used throughout
9471/// the process, as well as a helper method to add each group of builtin
9472/// operator overloads from the standard to a candidate set.
9473class BuiltinOperatorOverloadBuilder {
9474 // Common instance state available to all overload candidate addition methods.
9475 Sema &S;
9476 ArrayRef<Expr *> Args;
9477 QualifiersAndAtomic VisibleTypeConversionsQuals;
9478 bool HasArithmeticOrEnumeralCandidateType;
9479 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9480 OverloadCandidateSet &CandidateSet;
9481
9482 static constexpr int ArithmeticTypesCap = 26;
9483 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9484
9485 // Define some indices used to iterate over the arithmetic types in
9486 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9487 // types are that preserved by promotion (C++ [over.built]p2).
9488 unsigned FirstIntegralType,
9489 LastIntegralType;
9490 unsigned FirstPromotedIntegralType,
9491 LastPromotedIntegralType;
9492 unsigned FirstPromotedArithmeticType,
9493 LastPromotedArithmeticType;
9494 unsigned NumArithmeticTypes;
9495
9496 void InitArithmeticTypes() {
9497 // Start of promoted types.
9498 FirstPromotedArithmeticType = 0;
9499 ArithmeticTypes.push_back(S.Context.FloatTy);
9500 ArithmeticTypes.push_back(S.Context.DoubleTy);
9501 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9503 ArithmeticTypes.push_back(S.Context.Float128Ty);
9505 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9506
9507 // Start of integral types.
9508 FirstIntegralType = ArithmeticTypes.size();
9509 FirstPromotedIntegralType = ArithmeticTypes.size();
9510 ArithmeticTypes.push_back(S.Context.IntTy);
9511 ArithmeticTypes.push_back(S.Context.LongTy);
9512 ArithmeticTypes.push_back(S.Context.LongLongTy);
9516 ArithmeticTypes.push_back(S.Context.Int128Ty);
9517 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9518 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9519 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9523 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9524
9525 /// We add candidates for the unique, unqualified _BitInt types present in
9526 /// the candidate type set. The candidate set already handled ensuring the
9527 /// type is unqualified and canonical, but because we're adding from N
9528 /// different sets, we need to do some extra work to unique things. Insert
9529 /// the candidates into a unique set, then move from that set into the list
9530 /// of arithmetic types.
9531 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9532 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9533 for (QualType BitTy : Candidate.bitint_types())
9534 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9535 }
9536 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9537 LastPromotedIntegralType = ArithmeticTypes.size();
9538 LastPromotedArithmeticType = ArithmeticTypes.size();
9539 // End of promoted types.
9540
9541 ArithmeticTypes.push_back(S.Context.BoolTy);
9542 ArithmeticTypes.push_back(S.Context.CharTy);
9543 ArithmeticTypes.push_back(S.Context.WCharTy);
9544 if (S.Context.getLangOpts().Char8)
9545 ArithmeticTypes.push_back(S.Context.Char8Ty);
9546 ArithmeticTypes.push_back(S.Context.Char16Ty);
9547 ArithmeticTypes.push_back(S.Context.Char32Ty);
9548 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9549 ArithmeticTypes.push_back(S.Context.ShortTy);
9550 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9551 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9552 LastIntegralType = ArithmeticTypes.size();
9553 NumArithmeticTypes = ArithmeticTypes.size();
9554 // End of integral types.
9555 // FIXME: What about complex? What about half?
9556
9557 // We don't know for sure how many bit-precise candidates were involved, so
9558 // we subtract those from the total when testing whether we're under the
9559 // cap or not.
9560 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9561 ArithmeticTypesCap &&
9562 "Enough inline storage for all arithmetic types.");
9563 }
9564
9565 /// Helper method to factor out the common pattern of adding overloads
9566 /// for '++' and '--' builtin operators.
9567 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9568 bool HasVolatile,
9569 bool HasRestrict) {
9570 QualType ParamTypes[2] = {
9571 S.Context.getLValueReferenceType(CandidateTy),
9572 S.Context.IntTy
9573 };
9574
9575 // Non-volatile version.
9576 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9577
9578 // Use a heuristic to reduce number of builtin candidates in the set:
9579 // add volatile version only if there are conversions to a volatile type.
9580 if (HasVolatile) {
9581 ParamTypes[0] =
9583 S.Context.getVolatileType(CandidateTy));
9584 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9585 }
9586
9587 // Add restrict version only if there are conversions to a restrict type
9588 // and our candidate type is a non-restrict-qualified pointer.
9589 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9590 !CandidateTy.isRestrictQualified()) {
9591 ParamTypes[0]
9594 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9595
9596 if (HasVolatile) {
9597 ParamTypes[0]
9599 S.Context.getCVRQualifiedType(CandidateTy,
9602 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9603 }
9604 }
9605
9606 }
9607
9608 /// Helper to add an overload candidate for a binary builtin with types \p L
9609 /// and \p R.
9610 void AddCandidate(QualType L, QualType R) {
9611 QualType LandR[2] = {L, R};
9612 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9613 }
9614
9615public:
9616 BuiltinOperatorOverloadBuilder(
9617 Sema &S, ArrayRef<Expr *> Args,
9618 QualifiersAndAtomic VisibleTypeConversionsQuals,
9619 bool HasArithmeticOrEnumeralCandidateType,
9620 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9621 OverloadCandidateSet &CandidateSet)
9622 : S(S), Args(Args),
9623 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9624 HasArithmeticOrEnumeralCandidateType(
9625 HasArithmeticOrEnumeralCandidateType),
9626 CandidateTypes(CandidateTypes),
9627 CandidateSet(CandidateSet) {
9628
9629 InitArithmeticTypes();
9630 }
9631
9632 // Increment is deprecated for bool since C++17.
9633 //
9634 // C++ [over.built]p3:
9635 //
9636 // For every pair (T, VQ), where T is an arithmetic type other
9637 // than bool, and VQ is either volatile or empty, there exist
9638 // candidate operator functions of the form
9639 //
9640 // VQ T& operator++(VQ T&);
9641 // T operator++(VQ T&, int);
9642 //
9643 // C++ [over.built]p4:
9644 //
9645 // For every pair (T, VQ), where T is an arithmetic type other
9646 // than bool, and VQ is either volatile or empty, there exist
9647 // candidate operator functions of the form
9648 //
9649 // VQ T& operator--(VQ T&);
9650 // T operator--(VQ T&, int);
9651 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9652 if (!HasArithmeticOrEnumeralCandidateType)
9653 return;
9654
9655 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9656 const auto TypeOfT = ArithmeticTypes[Arith];
9657 if (TypeOfT == S.Context.BoolTy) {
9658 if (Op == OO_MinusMinus)
9659 continue;
9660 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9661 continue;
9662 }
9663 addPlusPlusMinusMinusStyleOverloads(
9664 TypeOfT,
9665 VisibleTypeConversionsQuals.hasVolatile(),
9666 VisibleTypeConversionsQuals.hasRestrict());
9667 }
9668 }
9669
9670 // C++ [over.built]p5:
9671 //
9672 // For every pair (T, VQ), where T is a cv-qualified or
9673 // cv-unqualified object type, and VQ is either volatile or
9674 // empty, there exist candidate operator functions of the form
9675 //
9676 // T*VQ& operator++(T*VQ&);
9677 // T*VQ& operator--(T*VQ&);
9678 // T* operator++(T*VQ&, int);
9679 // T* operator--(T*VQ&, int);
9680 void addPlusPlusMinusMinusPointerOverloads() {
9681 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9682 // Skip pointer types that aren't pointers to object types.
9683 if (!PtrTy->getPointeeType()->isObjectType())
9684 continue;
9685
9686 addPlusPlusMinusMinusStyleOverloads(
9687 PtrTy,
9688 (!PtrTy.isVolatileQualified() &&
9689 VisibleTypeConversionsQuals.hasVolatile()),
9690 (!PtrTy.isRestrictQualified() &&
9691 VisibleTypeConversionsQuals.hasRestrict()));
9692 }
9693 }
9694
9695 // C++ [over.built]p6:
9696 // For every cv-qualified or cv-unqualified object type T, there
9697 // exist candidate operator functions of the form
9698 //
9699 // T& operator*(T*);
9700 //
9701 // C++ [over.built]p7:
9702 // For every function type T that does not have cv-qualifiers or a
9703 // ref-qualifier, there exist candidate operator functions of the form
9704 // T& operator*(T*);
9705 void addUnaryStarPointerOverloads() {
9706 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9707 QualType PointeeTy = ParamTy->getPointeeType();
9708 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9709 continue;
9710
9711 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9712 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9713 continue;
9714
9715 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9716 }
9717 }
9718
9719 // C++ [over.built]p9:
9720 // For every promoted arithmetic type T, there exist candidate
9721 // operator functions of the form
9722 //
9723 // T operator+(T);
9724 // T operator-(T);
9725 void addUnaryPlusOrMinusArithmeticOverloads() {
9726 if (!HasArithmeticOrEnumeralCandidateType)
9727 return;
9728
9729 for (unsigned Arith = FirstPromotedArithmeticType;
9730 Arith < LastPromotedArithmeticType; ++Arith) {
9731 QualType ArithTy = ArithmeticTypes[Arith];
9732 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9733 }
9734
9735 // Extension: We also add these operators for vector types.
9736 for (QualType VecTy : CandidateTypes[0].vector_types())
9737 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9738 }
9739
9740 // C++ [over.built]p8:
9741 // For every type T, there exist candidate operator functions of
9742 // the form
9743 //
9744 // T* operator+(T*);
9745 void addUnaryPlusPointerOverloads() {
9746 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9747 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9748 }
9749
9750 // C++ [over.built]p10:
9751 // For every promoted integral type T, there exist candidate
9752 // operator functions of the form
9753 //
9754 // T operator~(T);
9755 void addUnaryTildePromotedIntegralOverloads() {
9756 if (!HasArithmeticOrEnumeralCandidateType)
9757 return;
9758
9759 for (unsigned Int = FirstPromotedIntegralType;
9760 Int < LastPromotedIntegralType; ++Int) {
9761 QualType IntTy = ArithmeticTypes[Int];
9762 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9763 }
9764
9765 // Extension: We also add this operator for vector types.
9766 for (QualType VecTy : CandidateTypes[0].vector_types())
9767 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9768 }
9769
9770 // C++ [over.match.oper]p16:
9771 // For every pointer to member type T or type std::nullptr_t, there
9772 // exist candidate operator functions of the form
9773 //
9774 // bool operator==(T,T);
9775 // bool operator!=(T,T);
9776 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9777 /// Set of (canonical) types that we've already handled.
9778 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9779
9780 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9781 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9782 // Don't add the same builtin candidate twice.
9783 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9784 continue;
9785
9786 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9787 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9788 }
9789
9790 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9792 if (AddedTypes.insert(NullPtrTy).second) {
9793 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9794 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9795 }
9796 }
9797 }
9798 }
9799
9800 // C++ [over.built]p15:
9801 //
9802 // For every T, where T is an enumeration type or a pointer type,
9803 // there exist candidate operator functions of the form
9804 //
9805 // bool operator<(T, T);
9806 // bool operator>(T, T);
9807 // bool operator<=(T, T);
9808 // bool operator>=(T, T);
9809 // bool operator==(T, T);
9810 // bool operator!=(T, T);
9811 // R operator<=>(T, T)
9812 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9813 // C++ [over.match.oper]p3:
9814 // [...]the built-in candidates include all of the candidate operator
9815 // functions defined in 13.6 that, compared to the given operator, [...]
9816 // do not have the same parameter-type-list as any non-template non-member
9817 // candidate.
9818 //
9819 // Note that in practice, this only affects enumeration types because there
9820 // aren't any built-in candidates of record type, and a user-defined operator
9821 // must have an operand of record or enumeration type. Also, the only other
9822 // overloaded operator with enumeration arguments, operator=,
9823 // cannot be overloaded for enumeration types, so this is the only place
9824 // where we must suppress candidates like this.
9825 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9826 UserDefinedBinaryOperators;
9827
9828 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9829 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9830 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9831 CEnd = CandidateSet.end();
9832 C != CEnd; ++C) {
9833 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9834 continue;
9835
9836 if (C->Function->isFunctionTemplateSpecialization())
9837 continue;
9838
9839 // We interpret "same parameter-type-list" as applying to the
9840 // "synthesized candidate, with the order of the two parameters
9841 // reversed", not to the original function.
9842 bool Reversed = C->isReversed();
9843 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9844 ->getType()
9845 .getUnqualifiedType();
9846 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9847 ->getType()
9848 .getUnqualifiedType();
9849
9850 // Skip if either parameter isn't of enumeral type.
9851 if (!FirstParamType->isEnumeralType() ||
9852 !SecondParamType->isEnumeralType())
9853 continue;
9854
9855 // Add this operator to the set of known user-defined operators.
9856 UserDefinedBinaryOperators.insert(
9857 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9858 S.Context.getCanonicalType(SecondParamType)));
9859 }
9860 }
9861 }
9862
9863 /// Set of (canonical) types that we've already handled.
9864 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9865
9866 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9867 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9868 // Don't add the same builtin candidate twice.
9869 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9870 continue;
9871 if (IsSpaceship && PtrTy->isFunctionPointerType())
9872 continue;
9873
9874 QualType ParamTypes[2] = {PtrTy, PtrTy};
9875 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9876 }
9877 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9878 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9879
9880 // Don't add the same builtin candidate twice, or if a user defined
9881 // candidate exists.
9882 if (!AddedTypes.insert(CanonType).second ||
9883 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9884 CanonType)))
9885 continue;
9886 QualType ParamTypes[2] = {EnumTy, EnumTy};
9887 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9888 }
9889 }
9890 }
9891
9892 // C++ [over.built]p13:
9893 //
9894 // For every cv-qualified or cv-unqualified object type T
9895 // there exist candidate operator functions of the form
9896 //
9897 // T* operator+(T*, ptrdiff_t);
9898 // T& operator[](T*, ptrdiff_t); [BELOW]
9899 // T* operator-(T*, ptrdiff_t);
9900 // T* operator+(ptrdiff_t, T*);
9901 // T& operator[](ptrdiff_t, T*); [BELOW]
9902 //
9903 // C++ [over.built]p14:
9904 //
9905 // For every T, where T is a pointer to object type, there
9906 // exist candidate operator functions of the form
9907 //
9908 // ptrdiff_t operator-(T, T);
9909 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9910 /// Set of (canonical) types that we've already handled.
9911 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9912
9913 for (int Arg = 0; Arg < 2; ++Arg) {
9914 QualType AsymmetricParamTypes[2] = {
9917 };
9918 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9919 QualType PointeeTy = PtrTy->getPointeeType();
9920 if (!PointeeTy->isObjectType())
9921 continue;
9922
9923 AsymmetricParamTypes[Arg] = PtrTy;
9924 if (Arg == 0 || Op == OO_Plus) {
9925 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9926 // T* operator+(ptrdiff_t, T*);
9927 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9928 }
9929 if (Op == OO_Minus) {
9930 // ptrdiff_t operator-(T, T);
9931 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9932 continue;
9933
9934 QualType ParamTypes[2] = {PtrTy, PtrTy};
9935 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9936 }
9937 }
9938 }
9939 }
9940
9941 // C++ [over.built]p12:
9942 //
9943 // For every pair of promoted arithmetic types L and R, there
9944 // exist candidate operator functions of the form
9945 //
9946 // LR operator*(L, R);
9947 // LR operator/(L, R);
9948 // LR operator+(L, R);
9949 // LR operator-(L, R);
9950 // bool operator<(L, R);
9951 // bool operator>(L, R);
9952 // bool operator<=(L, R);
9953 // bool operator>=(L, R);
9954 // bool operator==(L, R);
9955 // bool operator!=(L, R);
9956 //
9957 // where LR is the result of the usual arithmetic conversions
9958 // between types L and R.
9959 //
9960 // C++ [over.built]p24:
9961 //
9962 // For every pair of promoted arithmetic types L and R, there exist
9963 // candidate operator functions of the form
9964 //
9965 // LR operator?(bool, L, R);
9966 //
9967 // where LR is the result of the usual arithmetic conversions
9968 // between types L and R.
9969 // Our candidates ignore the first parameter.
9970 void addGenericBinaryArithmeticOverloads() {
9971 if (!HasArithmeticOrEnumeralCandidateType)
9972 return;
9973
9974 for (unsigned Left = FirstPromotedArithmeticType;
9975 Left < LastPromotedArithmeticType; ++Left) {
9976 for (unsigned Right = FirstPromotedArithmeticType;
9977 Right < LastPromotedArithmeticType; ++Right) {
9978 QualType LandR[2] = { ArithmeticTypes[Left],
9979 ArithmeticTypes[Right] };
9980 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9981 }
9982 }
9983
9984 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9985 // conditional operator for vector types.
9986 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9987 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9988 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9989 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9990 }
9991 }
9992
9993 /// Add binary operator overloads for each candidate matrix type M1, M2:
9994 /// * (M1, M1) -> M1
9995 /// * (M1, M1.getElementType()) -> M1
9996 /// * (M2.getElementType(), M2) -> M2
9997 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9998 void addMatrixBinaryArithmeticOverloads() {
9999 if (!HasArithmeticOrEnumeralCandidateType)
10000 return;
10001
10002 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10003 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10004 AddCandidate(M1, M1);
10005 }
10006
10007 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10008 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10009 if (!CandidateTypes[0].containsMatrixType(M2))
10010 AddCandidate(M2, M2);
10011 }
10012 }
10013
10014 // C++2a [over.built]p14:
10015 //
10016 // For every integral type T there exists a candidate operator function
10017 // of the form
10018 //
10019 // std::strong_ordering operator<=>(T, T)
10020 //
10021 // C++2a [over.built]p15:
10022 //
10023 // For every pair of floating-point types L and R, there exists a candidate
10024 // operator function of the form
10025 //
10026 // std::partial_ordering operator<=>(L, R);
10027 //
10028 // FIXME: The current specification for integral types doesn't play nice with
10029 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10030 // comparisons. Under the current spec this can lead to ambiguity during
10031 // overload resolution. For example:
10032 //
10033 // enum A : int {a};
10034 // auto x = (a <=> (long)42);
10035 //
10036 // error: call is ambiguous for arguments 'A' and 'long'.
10037 // note: candidate operator<=>(int, int)
10038 // note: candidate operator<=>(long, long)
10039 //
10040 // To avoid this error, this function deviates from the specification and adds
10041 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10042 // arithmetic types (the same as the generic relational overloads).
10043 //
10044 // For now this function acts as a placeholder.
10045 void addThreeWayArithmeticOverloads() {
10046 addGenericBinaryArithmeticOverloads();
10047 }
10048
10049 // C++ [over.built]p17:
10050 //
10051 // For every pair of promoted integral types L and R, there
10052 // exist candidate operator functions of the form
10053 //
10054 // LR operator%(L, R);
10055 // LR operator&(L, R);
10056 // LR operator^(L, R);
10057 // LR operator|(L, R);
10058 // L operator<<(L, R);
10059 // L operator>>(L, R);
10060 //
10061 // where LR is the result of the usual arithmetic conversions
10062 // between types L and R.
10063 void addBinaryBitwiseArithmeticOverloads() {
10064 if (!HasArithmeticOrEnumeralCandidateType)
10065 return;
10066
10067 for (unsigned Left = FirstPromotedIntegralType;
10068 Left < LastPromotedIntegralType; ++Left) {
10069 for (unsigned Right = FirstPromotedIntegralType;
10070 Right < LastPromotedIntegralType; ++Right) {
10071 QualType LandR[2] = { ArithmeticTypes[Left],
10072 ArithmeticTypes[Right] };
10073 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10074 }
10075 }
10076 }
10077
10078 // C++ [over.built]p20:
10079 //
10080 // For every pair (T, VQ), where T is an enumeration or
10081 // pointer to member type and VQ is either volatile or
10082 // empty, there exist candidate operator functions of the form
10083 //
10084 // VQ T& operator=(VQ T&, T);
10085 void addAssignmentMemberPointerOrEnumeralOverloads() {
10086 /// Set of (canonical) types that we've already handled.
10087 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10088
10089 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10090 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10091 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10092 continue;
10093
10094 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10095 }
10096
10097 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10098 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10099 continue;
10100
10101 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10102 }
10103 }
10104 }
10105
10106 // C++ [over.built]p19:
10107 //
10108 // For every pair (T, VQ), where T is any type and VQ is either
10109 // volatile or empty, there exist candidate operator functions
10110 // of the form
10111 //
10112 // T*VQ& operator=(T*VQ&, T*);
10113 //
10114 // C++ [over.built]p21:
10115 //
10116 // For every pair (T, VQ), where T is a cv-qualified or
10117 // cv-unqualified object type and VQ is either volatile or
10118 // empty, there exist candidate operator functions of the form
10119 //
10120 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10121 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10122 void addAssignmentPointerOverloads(bool isEqualOp) {
10123 /// Set of (canonical) types that we've already handled.
10124 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10125
10126 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10127 // If this is operator=, keep track of the builtin candidates we added.
10128 if (isEqualOp)
10129 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10130 else if (!PtrTy->getPointeeType()->isObjectType())
10131 continue;
10132
10133 // non-volatile version
10134 QualType ParamTypes[2] = {
10136 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10137 };
10138 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10139 /*IsAssignmentOperator=*/ isEqualOp);
10140
10141 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10142 VisibleTypeConversionsQuals.hasVolatile();
10143 if (NeedVolatile) {
10144 // volatile version
10145 ParamTypes[0] =
10147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10148 /*IsAssignmentOperator=*/isEqualOp);
10149 }
10150
10151 if (!PtrTy.isRestrictQualified() &&
10152 VisibleTypeConversionsQuals.hasRestrict()) {
10153 // restrict version
10154 ParamTypes[0] =
10156 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10157 /*IsAssignmentOperator=*/isEqualOp);
10158
10159 if (NeedVolatile) {
10160 // volatile restrict version
10161 ParamTypes[0] =
10164 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10165 /*IsAssignmentOperator=*/isEqualOp);
10166 }
10167 }
10168 }
10169
10170 if (isEqualOp) {
10171 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10172 // Make sure we don't add the same candidate twice.
10173 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10174 continue;
10175
10176 QualType ParamTypes[2] = {
10178 PtrTy,
10179 };
10180
10181 // non-volatile version
10182 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10183 /*IsAssignmentOperator=*/true);
10184
10185 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10186 VisibleTypeConversionsQuals.hasVolatile();
10187 if (NeedVolatile) {
10188 // volatile version
10189 ParamTypes[0] = S.Context.getLValueReferenceType(
10190 S.Context.getVolatileType(PtrTy));
10191 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10192 /*IsAssignmentOperator=*/true);
10193 }
10194
10195 if (!PtrTy.isRestrictQualified() &&
10196 VisibleTypeConversionsQuals.hasRestrict()) {
10197 // restrict version
10198 ParamTypes[0] = S.Context.getLValueReferenceType(
10199 S.Context.getRestrictType(PtrTy));
10200 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10201 /*IsAssignmentOperator=*/true);
10202
10203 if (NeedVolatile) {
10204 // volatile restrict version
10205 ParamTypes[0] =
10208 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10209 /*IsAssignmentOperator=*/true);
10210 }
10211 }
10212 }
10213 }
10214 }
10215
10216 // C++ [over.built]p18:
10217 //
10218 // For every triple (L, VQ, R), where L is an arithmetic type,
10219 // VQ is either volatile or empty, and R is a promoted
10220 // arithmetic type, there exist candidate operator functions of
10221 // the form
10222 //
10223 // VQ L& operator=(VQ L&, R);
10224 // VQ L& operator*=(VQ L&, R);
10225 // VQ L& operator/=(VQ L&, R);
10226 // VQ L& operator+=(VQ L&, R);
10227 // VQ L& operator-=(VQ L&, R);
10228 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10229 if (!HasArithmeticOrEnumeralCandidateType)
10230 return;
10231
10232 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10233 for (unsigned Right = FirstPromotedArithmeticType;
10234 Right < LastPromotedArithmeticType; ++Right) {
10235 QualType ParamTypes[2];
10236 ParamTypes[1] = ArithmeticTypes[Right];
10238 S, ArithmeticTypes[Left], Args[0]);
10239
10241 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10242 ParamTypes[0] =
10243 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10244 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10245 /*IsAssignmentOperator=*/isEqualOp);
10246 });
10247 }
10248 }
10249
10250 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10251 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10252 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10253 QualType ParamTypes[2];
10254 ParamTypes[1] = Vec2Ty;
10255 // Add this built-in operator as a candidate (VQ is empty).
10256 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10257 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10258 /*IsAssignmentOperator=*/isEqualOp);
10259
10260 // Add this built-in operator as a candidate (VQ is 'volatile').
10261 if (VisibleTypeConversionsQuals.hasVolatile()) {
10262 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10263 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10264 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10265 /*IsAssignmentOperator=*/isEqualOp);
10266 }
10267 }
10268 }
10269
10270 // C++ [over.built]p22:
10271 //
10272 // For every triple (L, VQ, R), where L is an integral type, VQ
10273 // is either volatile or empty, and R is a promoted integral
10274 // type, there exist candidate operator functions of the form
10275 //
10276 // VQ L& operator%=(VQ L&, R);
10277 // VQ L& operator<<=(VQ L&, R);
10278 // VQ L& operator>>=(VQ L&, R);
10279 // VQ L& operator&=(VQ L&, R);
10280 // VQ L& operator^=(VQ L&, R);
10281 // VQ L& operator|=(VQ L&, R);
10282 void addAssignmentIntegralOverloads() {
10283 if (!HasArithmeticOrEnumeralCandidateType)
10284 return;
10285
10286 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10287 for (unsigned Right = FirstPromotedIntegralType;
10288 Right < LastPromotedIntegralType; ++Right) {
10289 QualType ParamTypes[2];
10290 ParamTypes[1] = ArithmeticTypes[Right];
10292 S, ArithmeticTypes[Left], Args[0]);
10293
10295 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10296 ParamTypes[0] =
10297 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10298 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10299 });
10300 }
10301 }
10302 }
10303
10304 // C++ [over.operator]p23:
10305 //
10306 // There also exist candidate operator functions of the form
10307 //
10308 // bool operator!(bool);
10309 // bool operator&&(bool, bool);
10310 // bool operator||(bool, bool);
10311 void addExclaimOverload() {
10312 QualType ParamTy = S.Context.BoolTy;
10313 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10314 /*IsAssignmentOperator=*/false,
10315 /*NumContextualBoolArguments=*/1);
10316 }
10317 void addAmpAmpOrPipePipeOverload() {
10318 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10319 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10320 /*IsAssignmentOperator=*/false,
10321 /*NumContextualBoolArguments=*/2);
10322 }
10323
10324 // C++ [over.built]p13:
10325 //
10326 // For every cv-qualified or cv-unqualified object type T there
10327 // exist candidate operator functions of the form
10328 //
10329 // T* operator+(T*, ptrdiff_t); [ABOVE]
10330 // T& operator[](T*, ptrdiff_t);
10331 // T* operator-(T*, ptrdiff_t); [ABOVE]
10332 // T* operator+(ptrdiff_t, T*); [ABOVE]
10333 // T& operator[](ptrdiff_t, T*);
10334 void addSubscriptOverloads() {
10335 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10336 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10337 QualType PointeeType = PtrTy->getPointeeType();
10338 if (!PointeeType->isObjectType())
10339 continue;
10340
10341 // T& operator[](T*, ptrdiff_t)
10342 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10343 }
10344
10345 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10346 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10347 QualType PointeeType = PtrTy->getPointeeType();
10348 if (!PointeeType->isObjectType())
10349 continue;
10350
10351 // T& operator[](ptrdiff_t, T*)
10352 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10353 }
10354 }
10355
10356 // C++ [over.built]p11:
10357 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10358 // C1 is the same type as C2 or is a derived class of C2, T is an object
10359 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10360 // there exist candidate operator functions of the form
10361 //
10362 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10363 //
10364 // where CV12 is the union of CV1 and CV2.
10365 void addArrowStarOverloads() {
10366 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10367 QualType C1Ty = PtrTy;
10368 QualType C1;
10369 QualifierCollector Q1;
10370 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10371 if (!isa<RecordType>(C1))
10372 continue;
10373 // heuristic to reduce number of builtin candidates in the set.
10374 // Add volatile/restrict version only if there are conversions to a
10375 // volatile/restrict type.
10376 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10377 continue;
10378 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10379 continue;
10380 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10381 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10382 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10383 *D2 = mptr->getMostRecentCXXRecordDecl();
10384 if (!declaresSameEntity(D1, D2) &&
10385 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10386 break;
10387 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10388 // build CV12 T&
10389 QualType T = mptr->getPointeeType();
10390 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10392 continue;
10393 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10395 continue;
10396 T = Q1.apply(S.Context, T);
10397 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10398 }
10399 }
10400 }
10401
10402 // Note that we don't consider the first argument, since it has been
10403 // contextually converted to bool long ago. The candidates below are
10404 // therefore added as binary.
10405 //
10406 // C++ [over.built]p25:
10407 // For every type T, where T is a pointer, pointer-to-member, or scoped
10408 // enumeration type, there exist candidate operator functions of the form
10409 //
10410 // T operator?(bool, T, T);
10411 //
10412 void addConditionalOperatorOverloads() {
10413 /// Set of (canonical) types that we've already handled.
10414 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10415
10416 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10417 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10418 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10419 continue;
10420
10421 QualType ParamTypes[2] = {PtrTy, PtrTy};
10422 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10423 }
10424
10425 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10426 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10427 continue;
10428
10429 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10430 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10431 }
10432
10433 if (S.getLangOpts().CPlusPlus11) {
10434 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10435 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10436 continue;
10437
10438 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10439 continue;
10440
10441 QualType ParamTypes[2] = {EnumTy, EnumTy};
10442 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10443 }
10444 }
10445 }
10446 }
10447};
10448
10449} // end anonymous namespace
10450
10452 SourceLocation OpLoc,
10453 ArrayRef<Expr *> Args,
10454 OverloadCandidateSet &CandidateSet) {
10455 // Find all of the types that the arguments can convert to, but only
10456 // if the operator we're looking at has built-in operator candidates
10457 // that make use of these types. Also record whether we encounter non-record
10458 // candidate types or either arithmetic or enumeral candidate types.
10459 QualifiersAndAtomic VisibleTypeConversionsQuals;
10460 VisibleTypeConversionsQuals.addConst();
10461 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10462 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10463 if (Args[ArgIdx]->getType()->isAtomicType())
10464 VisibleTypeConversionsQuals.addAtomic();
10465 }
10466
10467 bool HasNonRecordCandidateType = false;
10468 bool HasArithmeticOrEnumeralCandidateType = false;
10470 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10471 CandidateTypes.emplace_back(*this);
10472 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10473 OpLoc,
10474 true,
10475 (Op == OO_Exclaim ||
10476 Op == OO_AmpAmp ||
10477 Op == OO_PipePipe),
10478 VisibleTypeConversionsQuals);
10479 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10480 CandidateTypes[ArgIdx].hasNonRecordTypes();
10481 HasArithmeticOrEnumeralCandidateType =
10482 HasArithmeticOrEnumeralCandidateType ||
10483 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10484 }
10485
10486 // Exit early when no non-record types have been added to the candidate set
10487 // for any of the arguments to the operator.
10488 //
10489 // We can't exit early for !, ||, or &&, since there we have always have
10490 // 'bool' overloads.
10491 if (!HasNonRecordCandidateType &&
10492 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10493 return;
10494
10495 // Setup an object to manage the common state for building overloads.
10496 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10497 VisibleTypeConversionsQuals,
10498 HasArithmeticOrEnumeralCandidateType,
10499 CandidateTypes, CandidateSet);
10500
10501 // Dispatch over the operation to add in only those overloads which apply.
10502 switch (Op) {
10503 case OO_None:
10505 llvm_unreachable("Expected an overloaded operator");
10506
10507 case OO_New:
10508 case OO_Delete:
10509 case OO_Array_New:
10510 case OO_Array_Delete:
10511 case OO_Call:
10512 llvm_unreachable(
10513 "Special operators don't use AddBuiltinOperatorCandidates");
10514
10515 case OO_Comma:
10516 case OO_Arrow:
10517 case OO_Coawait:
10518 // C++ [over.match.oper]p3:
10519 // -- For the operator ',', the unary operator '&', the
10520 // operator '->', or the operator 'co_await', the
10521 // built-in candidates set is empty.
10522 break;
10523
10524 case OO_Plus: // '+' is either unary or binary
10525 if (Args.size() == 1)
10526 OpBuilder.addUnaryPlusPointerOverloads();
10527 [[fallthrough]];
10528
10529 case OO_Minus: // '-' is either unary or binary
10530 if (Args.size() == 1) {
10531 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10532 } else {
10533 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10534 OpBuilder.addGenericBinaryArithmeticOverloads();
10535 OpBuilder.addMatrixBinaryArithmeticOverloads();
10536 }
10537 break;
10538
10539 case OO_Star: // '*' is either unary or binary
10540 if (Args.size() == 1)
10541 OpBuilder.addUnaryStarPointerOverloads();
10542 else {
10543 OpBuilder.addGenericBinaryArithmeticOverloads();
10544 OpBuilder.addMatrixBinaryArithmeticOverloads();
10545 }
10546 break;
10547
10548 case OO_Slash:
10549 OpBuilder.addGenericBinaryArithmeticOverloads();
10550 break;
10551
10552 case OO_PlusPlus:
10553 case OO_MinusMinus:
10554 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10555 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10556 break;
10557
10558 case OO_EqualEqual:
10559 case OO_ExclaimEqual:
10560 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10561 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10562 OpBuilder.addGenericBinaryArithmeticOverloads();
10563 break;
10564
10565 case OO_Less:
10566 case OO_Greater:
10567 case OO_LessEqual:
10568 case OO_GreaterEqual:
10569 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10570 OpBuilder.addGenericBinaryArithmeticOverloads();
10571 break;
10572
10573 case OO_Spaceship:
10574 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10575 OpBuilder.addThreeWayArithmeticOverloads();
10576 break;
10577
10578 case OO_Percent:
10579 case OO_Caret:
10580 case OO_Pipe:
10581 case OO_LessLess:
10582 case OO_GreaterGreater:
10583 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10584 break;
10585
10586 case OO_Amp: // '&' is either unary or binary
10587 if (Args.size() == 1)
10588 // C++ [over.match.oper]p3:
10589 // -- For the operator ',', the unary operator '&', or the
10590 // operator '->', the built-in candidates set is empty.
10591 break;
10592
10593 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10594 break;
10595
10596 case OO_Tilde:
10597 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10598 break;
10599
10600 case OO_Equal:
10601 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10602 [[fallthrough]];
10603
10604 case OO_PlusEqual:
10605 case OO_MinusEqual:
10606 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10607 [[fallthrough]];
10608
10609 case OO_StarEqual:
10610 case OO_SlashEqual:
10611 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10612 break;
10613
10614 case OO_PercentEqual:
10615 case OO_LessLessEqual:
10616 case OO_GreaterGreaterEqual:
10617 case OO_AmpEqual:
10618 case OO_CaretEqual:
10619 case OO_PipeEqual:
10620 OpBuilder.addAssignmentIntegralOverloads();
10621 break;
10622
10623 case OO_Exclaim:
10624 OpBuilder.addExclaimOverload();
10625 break;
10626
10627 case OO_AmpAmp:
10628 case OO_PipePipe:
10629 OpBuilder.addAmpAmpOrPipePipeOverload();
10630 break;
10631
10632 case OO_Subscript:
10633 if (Args.size() == 2)
10634 OpBuilder.addSubscriptOverloads();
10635 break;
10636
10637 case OO_ArrowStar:
10638 OpBuilder.addArrowStarOverloads();
10639 break;
10640
10641 case OO_Conditional:
10642 OpBuilder.addConditionalOperatorOverloads();
10643 OpBuilder.addGenericBinaryArithmeticOverloads();
10644 break;
10645 }
10646}
10647
10648void
10650 SourceLocation Loc,
10651 ArrayRef<Expr *> Args,
10652 TemplateArgumentListInfo *ExplicitTemplateArgs,
10653 OverloadCandidateSet& CandidateSet,
10654 bool PartialOverloading) {
10655 ADLResult Fns;
10656
10657 // FIXME: This approach for uniquing ADL results (and removing
10658 // redundant candidates from the set) relies on pointer-equality,
10659 // which means we need to key off the canonical decl. However,
10660 // always going back to the canonical decl might not get us the
10661 // right set of default arguments. What default arguments are
10662 // we supposed to consider on ADL candidates, anyway?
10663
10664 // FIXME: Pass in the explicit template arguments?
10665 ArgumentDependentLookup(Name, Loc, Args, Fns);
10666
10667 ArrayRef<Expr *> ReversedArgs;
10668
10669 // Erase all of the candidates we already knew about.
10670 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10671 CandEnd = CandidateSet.end();
10672 Cand != CandEnd; ++Cand)
10673 if (Cand->Function) {
10674 FunctionDecl *Fn = Cand->Function;
10675 Fns.erase(Fn);
10676 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10677 Fns.erase(FunTmpl);
10678 }
10679
10680 // For each of the ADL candidates we found, add it to the overload
10681 // set.
10682 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10684
10685 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10686 if (ExplicitTemplateArgs)
10687 continue;
10688
10690 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10691 PartialOverloading, /*AllowExplicit=*/true,
10692 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10693 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10695 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10696 /*SuppressUserConversions=*/false, PartialOverloading,
10697 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10698 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10699 }
10700 } else {
10701 auto *FTD = cast<FunctionTemplateDecl>(*I);
10703 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10704 /*SuppressUserConversions=*/false, PartialOverloading,
10705 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10706 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10707 *this, Args, FTD->getTemplatedDecl())) {
10708
10709 // As template candidates are not deduced immediately,
10710 // persist the array in the overload set.
10711 if (ReversedArgs.empty())
10712 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10713
10715 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10716 /*SuppressUserConversions=*/false, PartialOverloading,
10717 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10719 }
10720 }
10721 }
10722}
10723
10724namespace {
10725enum class Comparison { Equal, Better, Worse };
10726}
10727
10728/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10729/// overload resolution.
10730///
10731/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10732/// Cand1's first N enable_if attributes have precisely the same conditions as
10733/// Cand2's first N enable_if attributes (where N = the number of enable_if
10734/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10735///
10736/// Note that you can have a pair of candidates such that Cand1's enable_if
10737/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10738/// worse than Cand1's.
10739static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10740 const FunctionDecl *Cand2) {
10741 // Common case: One (or both) decls don't have enable_if attrs.
10742 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10743 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10744 if (!Cand1Attr || !Cand2Attr) {
10745 if (Cand1Attr == Cand2Attr)
10746 return Comparison::Equal;
10747 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10748 }
10749
10750 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10751 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10752
10753 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10754 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10755 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10756 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10757
10758 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10759 // has fewer enable_if attributes than Cand2, and vice versa.
10760 if (!Cand1A)
10761 return Comparison::Worse;
10762 if (!Cand2A)
10763 return Comparison::Better;
10764
10765 Cand1ID.clear();
10766 Cand2ID.clear();
10767
10768 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10769 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10770 if (Cand1ID != Cand2ID)
10771 return Comparison::Worse;
10772 }
10773
10774 return Comparison::Equal;
10775}
10776
10777static Comparison
10779 const OverloadCandidate &Cand2) {
10780 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10781 !Cand2.Function->isMultiVersion())
10782 return Comparison::Equal;
10783
10784 // If both are invalid, they are equal. If one of them is invalid, the other
10785 // is better.
10786 if (Cand1.Function->isInvalidDecl()) {
10787 if (Cand2.Function->isInvalidDecl())
10788 return Comparison::Equal;
10789 return Comparison::Worse;
10790 }
10791 if (Cand2.Function->isInvalidDecl())
10792 return Comparison::Better;
10793
10794 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10795 // cpu_dispatch, else arbitrarily based on the identifiers.
10796 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10797 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10798 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10799 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10800
10801 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10802 return Comparison::Equal;
10803
10804 if (Cand1CPUDisp && !Cand2CPUDisp)
10805 return Comparison::Better;
10806 if (Cand2CPUDisp && !Cand1CPUDisp)
10807 return Comparison::Worse;
10808
10809 if (Cand1CPUSpec && Cand2CPUSpec) {
10810 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10811 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10812 ? Comparison::Better
10813 : Comparison::Worse;
10814
10815 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10816 FirstDiff = std::mismatch(
10817 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10818 Cand2CPUSpec->cpus_begin(),
10819 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10820 return LHS->getName() == RHS->getName();
10821 });
10822
10823 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10824 "Two different cpu-specific versions should not have the same "
10825 "identifier list, otherwise they'd be the same decl!");
10826 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10827 ? Comparison::Better
10828 : Comparison::Worse;
10829 }
10830 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10831}
10832
10833/// Compute the type of the implicit object parameter for the given function,
10834/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10835/// null QualType if there is a 'matches anything' implicit object parameter.
10836static std::optional<QualType>
10839 return std::nullopt;
10840
10841 auto *M = cast<CXXMethodDecl>(F);
10842 // Static member functions' object parameters match all types.
10843 if (M->isStatic())
10844 return QualType();
10845 return M->getFunctionObjectParameterReferenceType();
10846}
10847
10848// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10849// represent the same entity.
10850static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10851 const FunctionDecl *F2) {
10852 if (declaresSameEntity(F1, F2))
10853 return true;
10854 auto PT1 = F1->getPrimaryTemplate();
10855 auto PT2 = F2->getPrimaryTemplate();
10856 if (PT1 && PT2) {
10857 if (declaresSameEntity(PT1, PT2) ||
10858 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10859 PT2->getInstantiatedFromMemberTemplate()))
10860 return true;
10861 }
10862 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10863 // different functions with same params). Consider removing this (as no test
10864 // fail w/o it).
10865 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10866 if (First) {
10867 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10868 return *T;
10869 }
10870 assert(I < F->getNumParams());
10871 return F->getParamDecl(I++)->getType();
10872 };
10873
10874 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10875 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10876
10877 if (F1NumParams != F2NumParams)
10878 return false;
10879
10880 unsigned I1 = 0, I2 = 0;
10881 for (unsigned I = 0; I != F1NumParams; ++I) {
10882 QualType T1 = NextParam(F1, I1, I == 0);
10883 QualType T2 = NextParam(F2, I2, I == 0);
10884 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10885 if (!Context.hasSameUnqualifiedType(T1, T2))
10886 return false;
10887 }
10888 return true;
10889}
10890
10891/// We're allowed to use constraints partial ordering only if the candidates
10892/// have the same parameter types:
10893/// [over.match.best.general]p2.6
10894/// F1 and F2 are non-template functions with the same
10895/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10897 FunctionDecl *Fn2,
10898 bool IsFn1Reversed,
10899 bool IsFn2Reversed) {
10900 assert(Fn1 && Fn2);
10901 if (Fn1->isVariadic() != Fn2->isVariadic())
10902 return false;
10903
10904 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10905 IsFn1Reversed ^ IsFn2Reversed))
10906 return false;
10907
10908 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10909 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10910 if (Mem1 && Mem2) {
10911 // if they are member functions, both are direct members of the same class,
10912 // and
10913 if (Mem1->getParent() != Mem2->getParent())
10914 return false;
10915 // if both are non-static member functions, they have the same types for
10916 // their object parameters
10917 if (Mem1->isInstance() && Mem2->isInstance() &&
10919 Mem1->getFunctionObjectParameterReferenceType(),
10920 Mem1->getFunctionObjectParameterReferenceType()))
10921 return false;
10922 }
10923 return true;
10924}
10925
10926static FunctionDecl *
10928 bool IsFn1Reversed, bool IsFn2Reversed) {
10929 if (!Fn1 || !Fn2)
10930 return nullptr;
10931
10932 // C++ [temp.constr.order]:
10933 // A non-template function F1 is more partial-ordering-constrained than a
10934 // non-template function F2 if:
10935 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10936 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10937
10938 if (Cand1IsSpecialization || Cand2IsSpecialization)
10939 return nullptr;
10940
10941 // - they have the same non-object-parameter-type-lists, and [...]
10942 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10943 IsFn2Reversed))
10944 return nullptr;
10945
10946 // - the declaration of F1 is more constrained than the declaration of F2.
10947 return S.getMoreConstrainedFunction(Fn1, Fn2);
10948}
10949
10950/// isBetterOverloadCandidate - Determines whether the first overload
10951/// candidate is a better candidate than the second (C++ 13.3.3p1).
10953 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10955 bool PartialOverloading) {
10956 // Define viable functions to be better candidates than non-viable
10957 // functions.
10958 if (!Cand2.Viable)
10959 return Cand1.Viable;
10960 else if (!Cand1.Viable)
10961 return false;
10962
10963 // [CUDA] A function with 'never' preference is marked not viable, therefore
10964 // is never shown up here. The worst preference shown up here is 'wrong side',
10965 // e.g. an H function called by a HD function in device compilation. This is
10966 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10967 // function which is called only by an H function. A deferred diagnostic will
10968 // be triggered if it is emitted. However a wrong-sided function is still
10969 // a viable candidate here.
10970 //
10971 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10972 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10973 // can be emitted, Cand1 is not better than Cand2. This rule should have
10974 // precedence over other rules.
10975 //
10976 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10977 // other rules should be used to determine which is better. This is because
10978 // host/device based overloading resolution is mostly for determining
10979 // viability of a function. If two functions are both viable, other factors
10980 // should take precedence in preference, e.g. the standard-defined preferences
10981 // like argument conversion ranks or enable_if partial-ordering. The
10982 // preference for pass-object-size parameters is probably most similar to a
10983 // type-based-overloading decision and so should take priority.
10984 //
10985 // If other rules cannot determine which is better, CUDA preference will be
10986 // used again to determine which is better.
10987 //
10988 // TODO: Currently IdentifyPreference does not return correct values
10989 // for functions called in global variable initializers due to missing
10990 // correct context about device/host. Therefore we can only enforce this
10991 // rule when there is a caller. We should enforce this rule for functions
10992 // in global variable initializers once proper context is added.
10993 //
10994 // TODO: We can only enable the hostness based overloading resolution when
10995 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10996 // overloading resolution diagnostics.
10997 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10998 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10999 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11000 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11001 bool IsCand1ImplicitHD =
11003 bool IsCand2ImplicitHD =
11005 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11006 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11007 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11008 // The implicit HD function may be a function in a system header which
11009 // is forced by pragma. In device compilation, if we prefer HD candidates
11010 // over wrong-sided candidates, overloading resolution may change, which
11011 // may result in non-deferrable diagnostics. As a workaround, we let
11012 // implicit HD candidates take equal preference as wrong-sided candidates.
11013 // This will preserve the overloading resolution.
11014 // TODO: We still need special handling of implicit HD functions since
11015 // they may incur other diagnostics to be deferred. We should make all
11016 // host/device related diagnostics deferrable and remove special handling
11017 // of implicit HD functions.
11018 auto EmitThreshold =
11019 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11020 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11023 auto Cand1Emittable = P1 > EmitThreshold;
11024 auto Cand2Emittable = P2 > EmitThreshold;
11025 if (Cand1Emittable && !Cand2Emittable)
11026 return true;
11027 if (!Cand1Emittable && Cand2Emittable)
11028 return false;
11029 }
11030 }
11031
11032 // C++ [over.match.best]p1: (Changed in C++23)
11033 //
11034 // -- if F is a static member function, ICS1(F) is defined such
11035 // that ICS1(F) is neither better nor worse than ICS1(G) for
11036 // any function G, and, symmetrically, ICS1(G) is neither
11037 // better nor worse than ICS1(F).
11038 unsigned StartArg = 0;
11039 if (!Cand1.TookAddressOfOverload &&
11041 StartArg = 1;
11042
11043 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11044 // We don't allow incompatible pointer conversions in C++.
11045 if (!S.getLangOpts().CPlusPlus)
11046 return ICS.isStandard() &&
11047 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11048
11049 // The only ill-formed conversion we allow in C++ is the string literal to
11050 // char* conversion, which is only considered ill-formed after C++11.
11051 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11053 };
11054
11055 // Define functions that don't require ill-formed conversions for a given
11056 // argument to be better candidates than functions that do.
11057 unsigned NumArgs = Cand1.Conversions.size();
11058 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11059 bool HasBetterConversion = false;
11060 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11061 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11062 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11063 if (Cand1Bad != Cand2Bad) {
11064 if (Cand1Bad)
11065 return false;
11066 HasBetterConversion = true;
11067 }
11068 }
11069
11070 if (HasBetterConversion)
11071 return true;
11072
11073 // C++ [over.match.best]p1:
11074 // A viable function F1 is defined to be a better function than another
11075 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11076 // conversion sequence than ICSi(F2), and then...
11077 bool HasWorseConversion = false;
11078 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11080 Cand1.Conversions[ArgIdx],
11081 Cand2.Conversions[ArgIdx])) {
11083 // Cand1 has a better conversion sequence.
11084 HasBetterConversion = true;
11085 break;
11086
11088 if (Cand1.Function && Cand2.Function &&
11089 Cand1.isReversed() != Cand2.isReversed() &&
11090 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11091 // Work around large-scale breakage caused by considering reversed
11092 // forms of operator== in C++20:
11093 //
11094 // When comparing a function against a reversed function, if we have a
11095 // better conversion for one argument and a worse conversion for the
11096 // other, the implicit conversion sequences are treated as being equally
11097 // good.
11098 //
11099 // This prevents a comparison function from being considered ambiguous
11100 // with a reversed form that is written in the same way.
11101 //
11102 // We diagnose this as an extension from CreateOverloadedBinOp.
11103 HasWorseConversion = true;
11104 break;
11105 }
11106
11107 // Cand1 can't be better than Cand2.
11108 return false;
11109
11111 // Do nothing.
11112 break;
11113 }
11114 }
11115
11116 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11117 // ICSj(F2), or, if not that,
11118 if (HasBetterConversion && !HasWorseConversion)
11119 return true;
11120
11121 // -- the context is an initialization by user-defined conversion
11122 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11123 // from the return type of F1 to the destination type (i.e.,
11124 // the type of the entity being initialized) is a better
11125 // conversion sequence than the standard conversion sequence
11126 // from the return type of F2 to the destination type.
11128 Cand1.Function && Cand2.Function &&
11131
11132 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11133 // First check whether we prefer one of the conversion functions over the
11134 // other. This only distinguishes the results in non-standard, extension
11135 // cases such as the conversion from a lambda closure type to a function
11136 // pointer or block.
11141 Cand1.FinalConversion,
11142 Cand2.FinalConversion);
11143
11146
11147 // FIXME: Compare kind of reference binding if conversion functions
11148 // convert to a reference type used in direct reference binding, per
11149 // C++14 [over.match.best]p1 section 2 bullet 3.
11150 }
11151
11152 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11153 // as combined with the resolution to CWG issue 243.
11154 //
11155 // When the context is initialization by constructor ([over.match.ctor] or
11156 // either phase of [over.match.list]), a constructor is preferred over
11157 // a conversion function.
11158 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11159 Cand1.Function && Cand2.Function &&
11162 return isa<CXXConstructorDecl>(Cand1.Function);
11163
11164 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11165 return Cand2.StrictPackMatch;
11166
11167 // -- F1 is a non-template function and F2 is a function template
11168 // specialization, or, if not that,
11169 bool Cand1IsSpecialization = Cand1.Function &&
11171 bool Cand2IsSpecialization = Cand2.Function &&
11173 if (Cand1IsSpecialization != Cand2IsSpecialization)
11174 return Cand2IsSpecialization;
11175
11176 // -- F1 and F2 are function template specializations, and the function
11177 // template for F1 is more specialized than the template for F2
11178 // according to the partial ordering rules described in 14.5.5.2, or,
11179 // if not that,
11180 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11181 const auto *Obj1Context =
11182 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11183 const auto *Obj2Context =
11184 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11185 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11187 Cand2.Function->getPrimaryTemplate(), Loc,
11189 : TPOC_Call,
11191 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11192 : QualType{},
11193 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11194 : QualType{},
11195 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11196 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11197 }
11198 }
11199
11200 // -— F1 and F2 are non-template functions and F1 is more
11201 // partial-ordering-constrained than F2 [...],
11203 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11204 Cand2.isReversed());
11205 F && F == Cand1.Function)
11206 return true;
11207
11208 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11209 // class B of D, and for all arguments the corresponding parameters of
11210 // F1 and F2 have the same type.
11211 // FIXME: Implement the "all parameters have the same type" check.
11212 bool Cand1IsInherited =
11213 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11214 bool Cand2IsInherited =
11215 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11216 if (Cand1IsInherited != Cand2IsInherited)
11217 return Cand2IsInherited;
11218 else if (Cand1IsInherited) {
11219 assert(Cand2IsInherited);
11220 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11221 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11222 if (Cand1Class->isDerivedFrom(Cand2Class))
11223 return true;
11224 if (Cand2Class->isDerivedFrom(Cand1Class))
11225 return false;
11226 // Inherited from sibling base classes: still ambiguous.
11227 }
11228
11229 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11230 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11231 // with reversed order of parameters and F1 is not
11232 //
11233 // We rank reversed + different operator as worse than just reversed, but
11234 // that comparison can never happen, because we only consider reversing for
11235 // the maximally-rewritten operator (== or <=>).
11236 if (Cand1.RewriteKind != Cand2.RewriteKind)
11237 return Cand1.RewriteKind < Cand2.RewriteKind;
11238
11239 // Check C++17 tie-breakers for deduction guides.
11240 {
11241 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11242 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11243 if (Guide1 && Guide2) {
11244 // -- F1 is generated from a deduction-guide and F2 is not
11245 if (Guide1->isImplicit() != Guide2->isImplicit())
11246 return Guide2->isImplicit();
11247
11248 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11249 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11250 return true;
11251 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11252 return false;
11253
11254 // --F1 is generated from a non-template constructor and F2 is generated
11255 // from a constructor template
11256 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11257 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11258 if (Constructor1 && Constructor2) {
11259 bool isC1Templated = Constructor1->getTemplatedKind() !=
11261 bool isC2Templated = Constructor2->getTemplatedKind() !=
11263 if (isC1Templated != isC2Templated)
11264 return isC2Templated;
11265 }
11266 }
11267 }
11268
11269 // Check for enable_if value-based overload resolution.
11270 if (Cand1.Function && Cand2.Function) {
11272 if (Cmp != Comparison::Equal)
11273 return Cmp == Comparison::Better;
11274 }
11275
11276 bool HasPS1 = Cand1.Function != nullptr &&
11278 bool HasPS2 = Cand2.Function != nullptr &&
11280 if (HasPS1 != HasPS2 && HasPS1)
11281 return true;
11282
11283 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11284 if (MV == Comparison::Better)
11285 return true;
11286 if (MV == Comparison::Worse)
11287 return false;
11288
11289 // If other rules cannot determine which is better, CUDA preference is used
11290 // to determine which is better.
11291 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11292 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11293 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11294 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11295 }
11296
11297 // General member function overloading is handled above, so this only handles
11298 // constructors with address spaces.
11299 // This only handles address spaces since C++ has no other
11300 // qualifier that can be used with constructors.
11301 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11302 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11303 if (CD1 && CD2) {
11304 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11305 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11306 if (AS1 != AS2) {
11308 return true;
11310 return false;
11311 }
11312 }
11313
11314 return false;
11315}
11316
11317/// Determine whether two declarations are "equivalent" for the purposes of
11318/// name lookup and overload resolution. This applies when the same internal/no
11319/// linkage entity is defined by two modules (probably by textually including
11320/// the same header). In such a case, we don't consider the declarations to
11321/// declare the same entity, but we also don't want lookups with both
11322/// declarations visible to be ambiguous in some cases (this happens when using
11323/// a modularized libstdc++).
11325 const NamedDecl *B) {
11326 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11327 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11328 if (!VA || !VB)
11329 return false;
11330
11331 // The declarations must be declaring the same name as an internal linkage
11332 // entity in different modules.
11333 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11334 VB->getDeclContext()->getRedeclContext()) ||
11335 getOwningModule(VA) == getOwningModule(VB) ||
11336 VA->isExternallyVisible() || VB->isExternallyVisible())
11337 return false;
11338
11339 // Check that the declarations appear to be equivalent.
11340 //
11341 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11342 // For constants and functions, we should check the initializer or body is
11343 // the same. For non-constant variables, we shouldn't allow it at all.
11344 if (Context.hasSameType(VA->getType(), VB->getType()))
11345 return true;
11346
11347 // Enum constants within unnamed enumerations will have different types, but
11348 // may still be similar enough to be interchangeable for our purposes.
11349 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11350 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11351 // Only handle anonymous enums. If the enumerations were named and
11352 // equivalent, they would have been merged to the same type.
11353 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11354 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11355 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11356 !Context.hasSameType(EnumA->getIntegerType(),
11357 EnumB->getIntegerType()))
11358 return false;
11359 // Allow this only if the value is the same for both enumerators.
11360 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11361 }
11362 }
11363
11364 // Nothing else is sufficiently similar.
11365 return false;
11366}
11367
11370 assert(D && "Unknown declaration");
11371 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11372
11373 Module *M = getOwningModule(D);
11374 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11375 << !M << (M ? M->getFullModuleName() : "");
11376
11377 for (auto *E : Equiv) {
11378 Module *M = getOwningModule(E);
11379 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11380 << !M << (M ? M->getFullModuleName() : "");
11381 }
11382}
11383
11386 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11388 static_cast<CNSInfo *>(DeductionFailure.Data)
11389 ->Satisfaction.ContainsErrors;
11390}
11391
11394 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11395 bool PartialOverloading, bool AllowExplicit,
11397 bool AggregateCandidateDeduction) {
11398
11399 auto *C =
11400 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11401
11404 /*AllowObjCConversionOnExplicit=*/false,
11405 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11406 PartialOverloading, AggregateCandidateDeduction},
11408 FoundDecl,
11409 Args,
11410 IsADLCandidate,
11411 PO};
11412
11413 HasDeferredTemplateConstructors |=
11414 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11415}
11416
11418 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11419 CXXRecordDecl *ActingContext, QualType ObjectType,
11420 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11421 bool SuppressUserConversions, bool PartialOverloading,
11423
11424 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11425
11426 auto *C =
11427 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11428
11431 /*AllowObjCConversionOnExplicit=*/false,
11432 /*AllowResultConversion=*/false,
11433 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11434 /*AggregateCandidateDeduction=*/false},
11435 MethodTmpl,
11436 FoundDecl,
11437 Args,
11438 ActingContext,
11439 ObjectClassification,
11440 ObjectType,
11441 PO};
11442}
11443
11446 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11447 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11448 bool AllowResultConversion) {
11449
11450 auto *C =
11451 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11452
11455 AllowObjCConversionOnExplicit, AllowResultConversion,
11456 /*AllowExplicit=*/false,
11457 /*SuppressUserConversions=*/false,
11458 /*PartialOverloading*/ false,
11459 /*AggregateCandidateDeduction=*/false},
11461 FoundDecl,
11462 ActingContext,
11463 From,
11464 ToType};
11465}
11466
11467static void
11470
11472 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11473 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11474 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11475}
11476
11477static void
11481 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11482 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11483 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11484 C.AggregateCandidateDeduction);
11485}
11486
11487static void
11491 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11492 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11493 C.AllowResultConversion);
11494}
11495
11497 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11498 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11499 while (Cand) {
11500 switch (Cand->Kind) {
11503 S, *this,
11504 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11505 break;
11508 S, *this,
11509 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11510 break;
11513 S, *this,
11514 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11515 break;
11516 }
11517 Cand = Cand->Next;
11518 }
11519 FirstDeferredCandidate = nullptr;
11520 DeferredCandidatesCount = 0;
11521}
11522
11524OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11525 Best->Best = true;
11526 if (Best->Function && Best->Function->isDeleted())
11527 return OR_Deleted;
11528 return OR_Success;
11529}
11530
11531void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11533 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11534 // are accepted by both clang and NVCC. However, during a particular
11535 // compilation mode only one call variant is viable. We need to
11536 // exclude non-viable overload candidates from consideration based
11537 // only on their host/device attributes. Specifically, if one
11538 // candidate call is WrongSide and the other is SameSide, we ignore
11539 // the WrongSide candidate.
11540 // We only need to remove wrong-sided candidates here if
11541 // -fgpu-exclude-wrong-side-overloads is off. When
11542 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11543 // uniformly in isBetterOverloadCandidate.
11544 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11545 return;
11546 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11547
11548 bool ContainsSameSideCandidate =
11549 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11550 // Check viable function only.
11551 return Cand->Viable && Cand->Function &&
11552 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11554 });
11555
11556 if (!ContainsSameSideCandidate)
11557 return;
11558
11559 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11560 // Check viable function only to avoid unnecessary data copying/moving.
11561 return Cand->Viable && Cand->Function &&
11562 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11564 };
11565 llvm::erase_if(Candidates, IsWrongSideCandidate);
11566}
11567
11568/// Computes the best viable function (C++ 13.3.3)
11569/// within an overload candidate set.
11570///
11571/// \param Loc The location of the function name (or operator symbol) for
11572/// which overload resolution occurs.
11573///
11574/// \param Best If overload resolution was successful or found a deleted
11575/// function, \p Best points to the candidate function found.
11576///
11577/// \returns The result of overload resolution.
11579 SourceLocation Loc,
11580 iterator &Best) {
11581
11583 DeferredCandidatesCount == 0) &&
11584 "Unexpected deferred template candidates");
11585
11586 bool TwoPhaseResolution =
11587 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11588
11589 if (TwoPhaseResolution) {
11590 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11591 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11592 if (!(HasDeferredTemplateConstructors &&
11593 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11594 return Res;
11595 }
11596 }
11597
11599 return BestViableFunctionImpl(S, Loc, Best);
11600}
11601
11602OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11604
11606 Candidates.reserve(this->Candidates.size());
11607 std::transform(this->Candidates.begin(), this->Candidates.end(),
11608 std::back_inserter(Candidates),
11609 [](OverloadCandidate &Cand) { return &Cand; });
11610
11611 if (S.getLangOpts().CUDA)
11612 CudaExcludeWrongSideCandidates(S, Candidates);
11613
11614 Best = end();
11615 for (auto *Cand : Candidates) {
11616 Cand->Best = false;
11617 if (Cand->Viable) {
11618 if (Best == end() ||
11619 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11620 Best = Cand;
11621 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11622 // This candidate has constraint that we were unable to evaluate because
11623 // it referenced an expression that contained an error. Rather than fall
11624 // back onto a potentially unintended candidate (made worse by
11625 // subsuming constraints), treat this as 'no viable candidate'.
11626 Best = end();
11627 return OR_No_Viable_Function;
11628 }
11629 }
11630
11631 // If we didn't find any viable functions, abort.
11632 if (Best == end())
11633 return OR_No_Viable_Function;
11634
11635 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11636 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11637 PendingBest.push_back(&*Best);
11638 Best->Best = true;
11639
11640 // Make sure that this function is better than every other viable
11641 // function. If not, we have an ambiguity.
11642 while (!PendingBest.empty()) {
11643 auto *Curr = PendingBest.pop_back_val();
11644 for (auto *Cand : Candidates) {
11645 if (Cand->Viable && !Cand->Best &&
11646 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11647 PendingBest.push_back(Cand);
11648 Cand->Best = true;
11649
11651 Curr->Function))
11652 EquivalentCands.push_back(Cand->Function);
11653 else
11654 Best = end();
11655 }
11656 }
11657 }
11658
11659 if (Best == end())
11660 return OR_Ambiguous;
11661
11662 OverloadingResult R = ResultForBestCandidate(Best);
11663
11664 if (!EquivalentCands.empty())
11666 EquivalentCands);
11667 return R;
11668}
11669
11670namespace {
11671
11672enum OverloadCandidateKind {
11673 oc_function,
11674 oc_method,
11675 oc_reversed_binary_operator,
11676 oc_constructor,
11677 oc_implicit_default_constructor,
11678 oc_implicit_copy_constructor,
11679 oc_implicit_move_constructor,
11680 oc_implicit_copy_assignment,
11681 oc_implicit_move_assignment,
11682 oc_implicit_equality_comparison,
11683 oc_inherited_constructor
11684};
11685
11686enum OverloadCandidateSelect {
11687 ocs_non_template,
11688 ocs_template,
11689 ocs_described_template,
11690};
11691
11692static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11693ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11694 const FunctionDecl *Fn,
11696 std::string &Description) {
11697
11698 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11699 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11700 isTemplate = true;
11701 Description = S.getTemplateArgumentBindingsText(
11702 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11703 }
11704
11705 OverloadCandidateSelect Select = [&]() {
11706 if (!Description.empty())
11707 return ocs_described_template;
11708 return isTemplate ? ocs_template : ocs_non_template;
11709 }();
11710
11711 OverloadCandidateKind Kind = [&]() {
11712 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11713 return oc_implicit_equality_comparison;
11714
11715 if (CRK & CRK_Reversed)
11716 return oc_reversed_binary_operator;
11717
11718 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11719 if (!Ctor->isImplicit()) {
11721 return oc_inherited_constructor;
11722 else
11723 return oc_constructor;
11724 }
11725
11726 if (Ctor->isDefaultConstructor())
11727 return oc_implicit_default_constructor;
11728
11729 if (Ctor->isMoveConstructor())
11730 return oc_implicit_move_constructor;
11731
11732 assert(Ctor->isCopyConstructor() &&
11733 "unexpected sort of implicit constructor");
11734 return oc_implicit_copy_constructor;
11735 }
11736
11737 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11738 // This actually gets spelled 'candidate function' for now, but
11739 // it doesn't hurt to split it out.
11740 if (!Meth->isImplicit())
11741 return oc_method;
11742
11743 if (Meth->isMoveAssignmentOperator())
11744 return oc_implicit_move_assignment;
11745
11746 if (Meth->isCopyAssignmentOperator())
11747 return oc_implicit_copy_assignment;
11748
11749 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11750 return oc_method;
11751 }
11752
11753 return oc_function;
11754 }();
11755
11756 return std::make_pair(Kind, Select);
11757}
11758
11759void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11760 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11761 // set.
11762 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11763 S.Diag(FoundDecl->getLocation(),
11764 diag::note_ovl_candidate_inherited_constructor)
11765 << Shadow->getNominatedBaseClass();
11766}
11767
11768} // end anonymous namespace
11769
11771 const FunctionDecl *FD) {
11772 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11773 bool AlwaysTrue;
11774 if (EnableIf->getCond()->isValueDependent() ||
11775 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11776 return false;
11777 if (!AlwaysTrue)
11778 return false;
11779 }
11780 return true;
11781}
11782
11783/// Returns true if we can take the address of the function.
11784///
11785/// \param Complain - If true, we'll emit a diagnostic
11786/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11787/// we in overload resolution?
11788/// \param Loc - The location of the statement we're complaining about. Ignored
11789/// if we're not complaining, or if we're in overload resolution.
11791 bool Complain,
11792 bool InOverloadResolution,
11793 SourceLocation Loc) {
11794 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11795 if (Complain) {
11796 if (InOverloadResolution)
11797 S.Diag(FD->getBeginLoc(),
11798 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11799 else
11800 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11801 }
11802 return false;
11803 }
11804
11805 if (FD->getTrailingRequiresClause()) {
11806 ConstraintSatisfaction Satisfaction;
11807 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11808 return false;
11809 if (!Satisfaction.IsSatisfied) {
11810 if (Complain) {
11811 if (InOverloadResolution) {
11812 SmallString<128> TemplateArgString;
11813 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11814 TemplateArgString += " ";
11815 TemplateArgString += S.getTemplateArgumentBindingsText(
11816 FunTmpl->getTemplateParameters(),
11818 }
11819
11820 S.Diag(FD->getBeginLoc(),
11821 diag::note_ovl_candidate_unsatisfied_constraints)
11822 << TemplateArgString;
11823 } else
11824 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11825 << FD;
11826 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11827 }
11828 return false;
11829 }
11830 }
11831
11832 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11833 return P->hasAttr<PassObjectSizeAttr>();
11834 });
11835 if (I == FD->param_end())
11836 return true;
11837
11838 if (Complain) {
11839 // Add one to ParamNo because it's user-facing
11840 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11841 if (InOverloadResolution)
11842 S.Diag(FD->getLocation(),
11843 diag::note_ovl_candidate_has_pass_object_size_params)
11844 << ParamNo;
11845 else
11846 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11847 << FD << ParamNo;
11848 }
11849 return false;
11850}
11851
11853 const FunctionDecl *FD) {
11854 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11855 /*InOverloadResolution=*/true,
11856 /*Loc=*/SourceLocation());
11857}
11858
11860 bool Complain,
11861 SourceLocation Loc) {
11862 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11863 /*InOverloadResolution=*/false,
11864 Loc);
11865}
11866
11867// Don't print candidates other than the one that matches the calling
11868// convention of the call operator, since that is guaranteed to exist.
11870 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11871
11872 if (!ConvD)
11873 return false;
11874 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11875 if (!RD->isLambda())
11876 return false;
11877
11878 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11879 CallingConv CallOpCC =
11880 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11881 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11882 CallingConv ConvToCC =
11883 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11884
11885 return ConvToCC != CallOpCC;
11886}
11887
11888// Notes the location of an overload candidate.
11890 OverloadCandidateRewriteKind RewriteKind,
11891 QualType DestType, bool TakingAddress) {
11892 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11893 return;
11894 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11895 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11896 return;
11897 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11898 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11899 return;
11901 return;
11902
11903 std::string FnDesc;
11904 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11905 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11906 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11907 << (unsigned)KSPair.first << (unsigned)KSPair.second
11908 << Fn << FnDesc;
11909
11910 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11911 Diag(Fn->getLocation(), PD);
11912 MaybeEmitInheritedConstructorNote(*this, Found);
11913}
11914
11915static void
11917 // Perhaps the ambiguity was caused by two atomic constraints that are
11918 // 'identical' but not equivalent:
11919 //
11920 // void foo() requires (sizeof(T) > 4) { } // #1
11921 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11922 //
11923 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11924 // #2 to subsume #1, but these constraint are not considered equivalent
11925 // according to the subsumption rules because they are not the same
11926 // source-level construct. This behavior is quite confusing and we should try
11927 // to help the user figure out what happened.
11928
11929 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11930 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11931 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11932 if (!I->Function)
11933 continue;
11935 if (auto *Template = I->Function->getPrimaryTemplate())
11936 Template->getAssociatedConstraints(AC);
11937 else
11938 I->Function->getAssociatedConstraints(AC);
11939 if (AC.empty())
11940 continue;
11941 if (FirstCand == nullptr) {
11942 FirstCand = I->Function;
11943 FirstAC = AC;
11944 } else if (SecondCand == nullptr) {
11945 SecondCand = I->Function;
11946 SecondAC = AC;
11947 } else {
11948 // We have more than one pair of constrained functions - this check is
11949 // expensive and we'd rather not try to diagnose it.
11950 return;
11951 }
11952 }
11953 if (!SecondCand)
11954 return;
11955 // The diagnostic can only happen if there are associated constraints on
11956 // both sides (there needs to be some identical atomic constraint).
11957 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11958 SecondCand, SecondAC))
11959 // Just show the user one diagnostic, they'll probably figure it out
11960 // from here.
11961 return;
11962}
11963
11964// Notes the location of all overload candidates designated through
11965// OverloadedExpr
11966void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11967 bool TakingAddress) {
11968 assert(OverloadedExpr->getType() == Context.OverloadTy);
11969
11970 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11971 OverloadExpr *OvlExpr = Ovl.Expression;
11972
11973 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11974 IEnd = OvlExpr->decls_end();
11975 I != IEnd; ++I) {
11976 if (FunctionTemplateDecl *FunTmpl =
11977 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11978 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11979 TakingAddress);
11980 } else if (FunctionDecl *Fun
11981 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11982 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11983 }
11984 }
11985}
11986
11987/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11988/// "lead" diagnostic; it will be given two arguments, the source and
11989/// target types of the conversion.
11991 Sema &S,
11992 SourceLocation CaretLoc,
11993 const PartialDiagnostic &PDiag) const {
11994 S.Diag(CaretLoc, PDiag)
11995 << Ambiguous.getFromType() << Ambiguous.getToType();
11996 unsigned CandsShown = 0;
11998 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11999 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12000 break;
12001 ++CandsShown;
12002 S.NoteOverloadCandidate(I->first, I->second);
12003 }
12004 S.Diags.overloadCandidatesShown(CandsShown);
12005 if (I != E)
12006 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12007}
12008
12010 unsigned I, bool TakingCandidateAddress) {
12011 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12012 assert(Conv.isBad());
12013 assert(Cand->Function && "for now, candidate must be a function");
12014 FunctionDecl *Fn = Cand->Function;
12015
12016 // There's a conversion slot for the object argument if this is a
12017 // non-constructor method. Note that 'I' corresponds the
12018 // conversion-slot index.
12019 bool isObjectArgument = false;
12020 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12022 if (I == 0)
12023 isObjectArgument = true;
12024 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12025 I--;
12026 }
12027
12028 std::string FnDesc;
12029 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12030 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12031 FnDesc);
12032
12033 Expr *FromExpr = Conv.Bad.FromExpr;
12034 QualType FromTy = Conv.Bad.getFromType();
12035 QualType ToTy = Conv.Bad.getToType();
12036 SourceRange ToParamRange;
12037
12038 // FIXME: In presence of parameter packs we can't determine parameter range
12039 // reliably, as we don't have access to instantiation.
12040 bool HasParamPack =
12041 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12042 return Parm->isParameterPack();
12043 });
12044 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12045 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12046
12047 if (FromTy == S.Context.OverloadTy) {
12048 assert(FromExpr && "overload set argument came from implicit argument?");
12049 Expr *E = FromExpr->IgnoreParens();
12050 if (isa<UnaryOperator>(E))
12051 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12052 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12053
12054 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12055 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12056 << ToParamRange << ToTy << Name << I + 1;
12057 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12058 return;
12059 }
12060
12061 // Do some hand-waving analysis to see if the non-viability is due
12062 // to a qualifier mismatch.
12063 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12064 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12065 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12066 CToTy = RT->getPointeeType();
12067 else {
12068 // TODO: detect and diagnose the full richness of const mismatches.
12069 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12070 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12071 CFromTy = FromPT->getPointeeType();
12072 CToTy = ToPT->getPointeeType();
12073 }
12074 }
12075
12076 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12077 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12078 Qualifiers FromQs = CFromTy.getQualifiers();
12079 Qualifiers ToQs = CToTy.getQualifiers();
12080
12081 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12082 if (isObjectArgument)
12083 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12084 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12085 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12086 else
12087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12088 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12089 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12090 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12091 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12092 return;
12093 }
12094
12095 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12097 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12098 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12099 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12100 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12101 return;
12102 }
12103
12104 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12106 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12107 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12108 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12109 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12110 return;
12111 }
12112
12113 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12114 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12115 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12116 << FromTy << !!FromQs.getPointerAuth()
12117 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12118 << ToQs.getPointerAuth().getAsString() << I + 1
12119 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12120 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12121 return;
12122 }
12123
12124 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12125 assert(CVR && "expected qualifiers mismatch");
12126
12127 if (isObjectArgument) {
12128 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12129 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12130 << FromTy << (CVR - 1);
12131 } else {
12132 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12133 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12134 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12135 }
12136 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12137 return;
12138 }
12139
12142 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12143 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12144 << (unsigned)isObjectArgument << I + 1
12146 << ToParamRange;
12147 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12148 return;
12149 }
12150
12151 // Special diagnostic for failure to convert an initializer list, since
12152 // telling the user that it has type void is not useful.
12153 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12155 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12156 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12159 ? 2
12160 : 0);
12161 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12162 return;
12163 }
12164
12165 // Diagnose references or pointers to incomplete types differently,
12166 // since it's far from impossible that the incompleteness triggered
12167 // the failure.
12168 QualType TempFromTy = FromTy.getNonReferenceType();
12169 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12170 TempFromTy = PTy->getPointeeType();
12171 if (TempFromTy->isIncompleteType()) {
12172 // Emit the generic diagnostic and, optionally, add the hints to it.
12173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12174 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12175 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12176 << (unsigned)(Cand->Fix.Kind);
12177
12178 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12179 return;
12180 }
12181
12182 // Diagnose base -> derived pointer conversions.
12183 unsigned BaseToDerivedConversion = 0;
12184 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12185 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12186 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12187 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12188 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12189 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12190 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12191 FromPtrTy->getPointeeType()))
12192 BaseToDerivedConversion = 1;
12193 }
12194 } else if (const ObjCObjectPointerType *FromPtrTy
12195 = FromTy->getAs<ObjCObjectPointerType>()) {
12196 if (const ObjCObjectPointerType *ToPtrTy
12197 = ToTy->getAs<ObjCObjectPointerType>())
12198 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12199 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12200 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12201 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12202 FromIface->isSuperClassOf(ToIface))
12203 BaseToDerivedConversion = 2;
12204 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12205 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12206 S.getASTContext()) &&
12207 !FromTy->isIncompleteType() &&
12208 !ToRefTy->getPointeeType()->isIncompleteType() &&
12209 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12210 BaseToDerivedConversion = 3;
12211 }
12212 }
12213
12214 if (BaseToDerivedConversion) {
12215 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12216 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12217 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12218 << I + 1;
12219 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12220 return;
12221 }
12222
12223 if (isa<ObjCObjectPointerType>(CFromTy) &&
12224 isa<PointerType>(CToTy)) {
12225 Qualifiers FromQs = CFromTy.getQualifiers();
12226 Qualifiers ToQs = CToTy.getQualifiers();
12227 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12229 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12230 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12231 << I + 1;
12232 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12233 return;
12234 }
12235 }
12236
12237 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12238 return;
12239
12240 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12241 // although this is almost always an error and we advise against it.
12242 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12243 ToTy == S.Context.getLogicalOperationType()) {
12244 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12245 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12246 << Conv.Bad.FromExpr << ToTy;
12247 return;
12248 }
12249
12250 // Emit the generic diagnostic and, optionally, add the hints to it.
12251 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12252 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12253 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12254 << (unsigned)(Cand->Fix.Kind);
12255
12256 // Check that location of Fn is not in system header.
12257 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12258 // If we can fix the conversion, suggest the FixIts.
12259 for (const FixItHint &HI : Cand->Fix.Hints)
12260 FDiag << HI;
12261 }
12262
12263 S.Diag(Fn->getLocation(), FDiag);
12264
12265 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12266}
12267
12268/// Additional arity mismatch diagnosis specific to a function overload
12269/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12270/// over a candidate in any candidate set.
12272 unsigned NumArgs, bool IsAddressOf = false) {
12273 assert(Cand->Function && "Candidate is required to be a function.");
12274 FunctionDecl *Fn = Cand->Function;
12275 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12276 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12277
12278 // With invalid overloaded operators, it's possible that we think we
12279 // have an arity mismatch when in fact it looks like we have the
12280 // right number of arguments, because only overloaded operators have
12281 // the weird behavior of overloading member and non-member functions.
12282 // Just don't report anything.
12283 if (Fn->isInvalidDecl() &&
12284 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12285 return true;
12286
12287 if (NumArgs < MinParams) {
12288 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12290 Cand->DeductionFailure.getResult() ==
12292 } else {
12293 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12295 Cand->DeductionFailure.getResult() ==
12297 }
12298
12299 return false;
12300}
12301
12302/// General arity mismatch diagnosis over a candidate in a candidate set.
12304 unsigned NumFormalArgs,
12305 bool IsAddressOf = false) {
12306 assert(isa<FunctionDecl>(D) &&
12307 "The templated declaration should at least be a function"
12308 " when diagnosing bad template argument deduction due to too many"
12309 " or too few arguments");
12310
12312
12313 // TODO: treat calls to a missing default constructor as a special case
12314 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12315 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12316 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12317
12318 // at least / at most / exactly
12319 bool HasExplicitObjectParam =
12320 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12321
12322 unsigned ParamCount =
12323 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12324 unsigned mode, modeCount;
12325
12326 if (NumFormalArgs < MinParams) {
12327 if (MinParams != ParamCount || FnTy->isVariadic() ||
12328 FnTy->isTemplateVariadic())
12329 mode = 0; // "at least"
12330 else
12331 mode = 2; // "exactly"
12332 modeCount = MinParams;
12333 } else {
12334 if (MinParams != ParamCount)
12335 mode = 1; // "at most"
12336 else
12337 mode = 2; // "exactly"
12338 modeCount = ParamCount;
12339 }
12340
12341 std::string Description;
12342 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12343 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12344
12345 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12346 if (modeCount == 1 && !IsAddressOf &&
12347 FirstNonObjectParamIdx < Fn->getNumParams() &&
12348 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12349 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12350 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12351 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12352 << NumFormalArgs << HasExplicitObjectParam
12353 << Fn->getParametersSourceRange();
12354 else
12355 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12356 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12357 << Description << mode << modeCount << NumFormalArgs
12358 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12359
12360 MaybeEmitInheritedConstructorNote(S, Found);
12361}
12362
12363/// Arity mismatch diagnosis specific to a function overload candidate.
12365 unsigned NumFormalArgs) {
12366 assert(Cand->Function && "Candidate must be a function");
12367 FunctionDecl *Fn = Cand->Function;
12368 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12369 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12370 Cand->TookAddressOfOverload);
12371}
12372
12374 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12375 return TD;
12376 llvm_unreachable("Unsupported: Getting the described template declaration"
12377 " for bad deduction diagnosis");
12378}
12379
12380/// Diagnose a failed template-argument deduction.
12381static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12382 DeductionFailureInfo &DeductionFailure,
12383 unsigned NumArgs,
12384 bool TakingCandidateAddress) {
12385 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12386 NamedDecl *ParamD;
12387 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12388 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12389 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12390 switch (DeductionFailure.getResult()) {
12392 llvm_unreachable(
12393 "TemplateDeductionResult::Success while diagnosing bad deduction");
12395 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12396 "while diagnosing bad deduction");
12399 return;
12400
12402 assert(ParamD && "no parameter found for incomplete deduction result");
12403 S.Diag(Templated->getLocation(),
12404 diag::note_ovl_candidate_incomplete_deduction)
12405 << ParamD->getDeclName();
12406 MaybeEmitInheritedConstructorNote(S, Found);
12407 return;
12408 }
12409
12411 assert(ParamD && "no parameter found for incomplete deduction result");
12412 S.Diag(Templated->getLocation(),
12413 diag::note_ovl_candidate_incomplete_deduction_pack)
12414 << ParamD->getDeclName()
12415 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12416 << *DeductionFailure.getFirstArg();
12417 MaybeEmitInheritedConstructorNote(S, Found);
12418 return;
12419 }
12420
12422 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12424
12425 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12426
12427 // Param will have been canonicalized, but it should just be a
12428 // qualified version of ParamD, so move the qualifiers to that.
12430 Qs.strip(Param);
12431 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12432 assert(S.Context.hasSameType(Param, NonCanonParam));
12433
12434 // Arg has also been canonicalized, but there's nothing we can do
12435 // about that. It also doesn't matter as much, because it won't
12436 // have any template parameters in it (because deduction isn't
12437 // done on dependent types).
12438 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12439
12440 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12441 << ParamD->getDeclName() << Arg << NonCanonParam;
12442 MaybeEmitInheritedConstructorNote(S, Found);
12443 return;
12444 }
12445
12447 assert(ParamD && "no parameter found for inconsistent deduction result");
12448 int which = 0;
12449 if (isa<TemplateTypeParmDecl>(ParamD))
12450 which = 0;
12451 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12452 // Deduction might have failed because we deduced arguments of two
12453 // different types for a non-type template parameter.
12454 // FIXME: Use a different TDK value for this.
12455 QualType T1 =
12456 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12457 QualType T2 =
12458 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12459 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12460 S.Diag(Templated->getLocation(),
12461 diag::note_ovl_candidate_inconsistent_deduction_types)
12462 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12463 << *DeductionFailure.getSecondArg() << T2;
12464 MaybeEmitInheritedConstructorNote(S, Found);
12465 return;
12466 }
12467
12468 which = 1;
12469 } else {
12470 which = 2;
12471 }
12472
12473 // Tweak the diagnostic if the problem is that we deduced packs of
12474 // different arities. We'll print the actual packs anyway in case that
12475 // includes additional useful information.
12476 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12477 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12478 DeductionFailure.getFirstArg()->pack_size() !=
12479 DeductionFailure.getSecondArg()->pack_size()) {
12480 which = 3;
12481 }
12482
12483 S.Diag(Templated->getLocation(),
12484 diag::note_ovl_candidate_inconsistent_deduction)
12485 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12486 << *DeductionFailure.getSecondArg();
12487 MaybeEmitInheritedConstructorNote(S, Found);
12488 return;
12489 }
12490
12492 assert(ParamD && "no parameter found for invalid explicit arguments");
12493
12494 auto Diag = S.Diag(Templated->getLocation(),
12495 diag::note_ovl_candidate_explicit_arg_mismatch);
12496 if (ParamD->getDeclName())
12497 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12498 else
12499 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12500 << (getDepthAndIndex(ParamD).second + 1);
12501 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12502 SmallString<128> DiagContent;
12503 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12504 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12505 } else {
12506 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12507 }
12508
12509 MaybeEmitInheritedConstructorNote(S, Found);
12510 return;
12511 }
12513 // Format the template argument list into the argument string.
12514 SmallString<128> TemplateArgString;
12515 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12516 TemplateArgString = " ";
12517 TemplateArgString += S.getTemplateArgumentBindingsText(
12518 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12519 if (TemplateArgString.size() == 1)
12520 TemplateArgString.clear();
12521 S.Diag(Templated->getLocation(),
12522 diag::note_ovl_candidate_unsatisfied_constraints)
12523 << TemplateArgString;
12524
12526 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12527 return;
12528 }
12531 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12532 return;
12533
12535 S.Diag(Templated->getLocation(),
12536 diag::note_ovl_candidate_instantiation_depth);
12537 MaybeEmitInheritedConstructorNote(S, Found);
12538 return;
12539
12541 // Format the template argument list into the argument string.
12542 SmallString<128> TemplateArgString;
12543 if (TemplateArgumentList *Args =
12544 DeductionFailure.getTemplateArgumentList()) {
12545 TemplateArgString = " ";
12546 TemplateArgString += S.getTemplateArgumentBindingsText(
12547 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12548 if (TemplateArgString.size() == 1)
12549 TemplateArgString.clear();
12550 }
12551
12552 // If this candidate was disabled by enable_if, say so.
12553 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12554 if (PDiag && PDiag->second.getDiagID() ==
12555 diag::err_typename_nested_not_found_enable_if) {
12556 // FIXME: Use the source range of the condition, and the fully-qualified
12557 // name of the enable_if template. These are both present in PDiag.
12558 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12559 << "'enable_if'" << TemplateArgString;
12560 return;
12561 }
12562
12563 // We found a specific requirement that disabled the enable_if.
12564 if (PDiag && PDiag->second.getDiagID() ==
12565 diag::err_typename_nested_not_found_requirement) {
12566 S.Diag(Templated->getLocation(),
12567 diag::note_ovl_candidate_disabled_by_requirement)
12568 << PDiag->second.getStringArg(0) << TemplateArgString;
12569 return;
12570 }
12571
12572 // Format the SFINAE diagnostic into the argument string.
12573 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12574 // formatted message in another diagnostic.
12575 SmallString<128> SFINAEArgString;
12576 SourceRange R;
12577 if (PDiag) {
12578 SFINAEArgString = ": ";
12579 R = SourceRange(PDiag->first, PDiag->first);
12580 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12581 }
12582
12583 S.Diag(Templated->getLocation(),
12584 diag::note_ovl_candidate_substitution_failure)
12585 << TemplateArgString << SFINAEArgString << R;
12586 MaybeEmitInheritedConstructorNote(S, Found);
12587 return;
12588 }
12589
12592 // Format the template argument list into the argument string.
12593 SmallString<128> TemplateArgString;
12594 if (TemplateArgumentList *Args =
12595 DeductionFailure.getTemplateArgumentList()) {
12596 TemplateArgString = " ";
12597 TemplateArgString += S.getTemplateArgumentBindingsText(
12598 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12599 if (TemplateArgString.size() == 1)
12600 TemplateArgString.clear();
12601 }
12602
12603 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12604 << (*DeductionFailure.getCallArgIndex() + 1)
12605 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12606 << TemplateArgString
12607 << (DeductionFailure.getResult() ==
12609 break;
12610 }
12611
12613 // FIXME: Provide a source location to indicate what we couldn't match.
12614 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12615 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12616 if (FirstTA.getKind() == TemplateArgument::Template &&
12617 SecondTA.getKind() == TemplateArgument::Template) {
12618 TemplateName FirstTN = FirstTA.getAsTemplate();
12619 TemplateName SecondTN = SecondTA.getAsTemplate();
12620 if (FirstTN.getKind() == TemplateName::Template &&
12621 SecondTN.getKind() == TemplateName::Template) {
12622 if (FirstTN.getAsTemplateDecl()->getName() ==
12623 SecondTN.getAsTemplateDecl()->getName()) {
12624 // FIXME: This fixes a bad diagnostic where both templates are named
12625 // the same. This particular case is a bit difficult since:
12626 // 1) It is passed as a string to the diagnostic printer.
12627 // 2) The diagnostic printer only attempts to find a better
12628 // name for types, not decls.
12629 // Ideally, this should folded into the diagnostic printer.
12630 S.Diag(Templated->getLocation(),
12631 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12632 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12633 return;
12634 }
12635 }
12636 }
12637
12638 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12640 return;
12641
12642 // FIXME: For generic lambda parameters, check if the function is a lambda
12643 // call operator, and if so, emit a prettier and more informative
12644 // diagnostic that mentions 'auto' and lambda in addition to
12645 // (or instead of?) the canonical template type parameters.
12646 S.Diag(Templated->getLocation(),
12647 diag::note_ovl_candidate_non_deduced_mismatch)
12648 << FirstTA << SecondTA;
12649 return;
12650 }
12651 // TODO: diagnose these individually, then kill off
12652 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12654 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12655 MaybeEmitInheritedConstructorNote(S, Found);
12656 return;
12658 S.Diag(Templated->getLocation(),
12659 diag::note_cuda_ovl_candidate_target_mismatch);
12660 return;
12661 }
12662}
12663
12664/// Diagnose a failed template-argument deduction, for function calls.
12666 unsigned NumArgs,
12667 bool TakingCandidateAddress) {
12668 assert(Cand->Function && "Candidate must be a function");
12669 FunctionDecl *Fn = Cand->Function;
12673 if (CheckArityMismatch(S, Cand, NumArgs))
12674 return;
12675 }
12676 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12677 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12678}
12679
12680/// CUDA: diagnose an invalid call across targets.
12682 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12683 assert(Cand->Function && "Candidate must be a Function.");
12684 FunctionDecl *Callee = Cand->Function;
12685
12686 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12687 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12688
12689 std::string FnDesc;
12690 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12691 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12692 Cand->getRewriteKind(), FnDesc);
12693
12694 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12695 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12696 << FnDesc /* Ignored */
12697 << CalleeTarget << CallerTarget;
12698
12699 // This could be an implicit constructor for which we could not infer the
12700 // target due to a collsion. Diagnose that case.
12701 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12702 if (Meth != nullptr && Meth->isImplicit()) {
12703 CXXRecordDecl *ParentClass = Meth->getParent();
12705
12706 switch (FnKindPair.first) {
12707 default:
12708 return;
12709 case oc_implicit_default_constructor:
12711 break;
12712 case oc_implicit_copy_constructor:
12714 break;
12715 case oc_implicit_move_constructor:
12717 break;
12718 case oc_implicit_copy_assignment:
12720 break;
12721 case oc_implicit_move_assignment:
12723 break;
12724 };
12725
12726 bool ConstRHS = false;
12727 if (Meth->getNumParams()) {
12728 if (const ReferenceType *RT =
12729 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12730 ConstRHS = RT->getPointeeType().isConstQualified();
12731 }
12732 }
12733
12734 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12735 /* ConstRHS */ ConstRHS,
12736 /* Diagnose */ true);
12737 }
12738}
12739
12741 assert(Cand->Function && "Candidate must be a function");
12742 FunctionDecl *Callee = Cand->Function;
12743 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12744
12745 S.Diag(Callee->getLocation(),
12746 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12747 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12748}
12749
12751 assert(Cand->Function && "Candidate must be a function");
12752 FunctionDecl *Fn = Cand->Function;
12754 assert(ES.isExplicit() && "not an explicit candidate");
12755
12756 unsigned Kind;
12757 switch (Fn->getDeclKind()) {
12758 case Decl::Kind::CXXConstructor:
12759 Kind = 0;
12760 break;
12761 case Decl::Kind::CXXConversion:
12762 Kind = 1;
12763 break;
12764 case Decl::Kind::CXXDeductionGuide:
12765 Kind = Fn->isImplicit() ? 0 : 2;
12766 break;
12767 default:
12768 llvm_unreachable("invalid Decl");
12769 }
12770
12771 // Note the location of the first (in-class) declaration; a redeclaration
12772 // (particularly an out-of-class definition) will typically lack the
12773 // 'explicit' specifier.
12774 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12775 FunctionDecl *First = Fn->getFirstDecl();
12776 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12777 First = Pattern->getFirstDecl();
12778
12779 S.Diag(First->getLocation(),
12780 diag::note_ovl_candidate_explicit)
12781 << Kind << (ES.getExpr() ? 1 : 0)
12782 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12783}
12784
12786 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12787 if (!DG)
12788 return;
12789 TemplateDecl *OriginTemplate =
12791 // We want to always print synthesized deduction guides for type aliases.
12792 // They would retain the explicit bit of the corresponding constructor.
12793 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12794 return;
12795 std::string FunctionProto;
12796 llvm::raw_string_ostream OS(FunctionProto);
12797 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12798 if (!Template) {
12799 // This also could be an instantiation. Find out the primary template.
12800 FunctionDecl *Pattern =
12801 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12802 if (!Pattern) {
12803 // The implicit deduction guide is built on an explicit non-template
12804 // deduction guide. Currently, this might be the case only for type
12805 // aliases.
12806 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12807 // gets merged.
12808 assert(OriginTemplate->isTypeAlias() &&
12809 "Non-template implicit deduction guides are only possible for "
12810 "type aliases");
12811 DG->print(OS);
12812 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12813 << FunctionProto;
12814 return;
12815 }
12817 assert(Template && "Cannot find the associated function template of "
12818 "CXXDeductionGuideDecl?");
12819 }
12820 Template->print(OS);
12821 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12822 << FunctionProto;
12823}
12824
12825/// Generates a 'note' diagnostic for an overload candidate. We've
12826/// already generated a primary error at the call site.
12827///
12828/// It really does need to be a single diagnostic with its caret
12829/// pointed at the candidate declaration. Yes, this creates some
12830/// major challenges of technical writing. Yes, this makes pointing
12831/// out problems with specific arguments quite awkward. It's still
12832/// better than generating twenty screens of text for every failed
12833/// overload.
12834///
12835/// It would be great to be able to express per-candidate problems
12836/// more richly for those diagnostic clients that cared, but we'd
12837/// still have to be just as careful with the default diagnostics.
12838/// \param CtorDestAS Addr space of object being constructed (for ctor
12839/// candidates only).
12841 unsigned NumArgs,
12842 bool TakingCandidateAddress,
12843 LangAS CtorDestAS = LangAS::Default) {
12844 assert(Cand->Function && "Candidate must be a function");
12845 FunctionDecl *Fn = Cand->Function;
12847 return;
12848
12849 // There is no physical candidate declaration to point to for OpenCL builtins.
12850 // Except for failed conversions, the notes are identical for each candidate,
12851 // so do not generate such notes.
12852 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12854 return;
12855
12856 // Skip implicit member functions when trying to resolve
12857 // the address of a an overload set for a function pointer.
12858 if (Cand->TookAddressOfOverload &&
12859 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12860 return;
12861
12862 // Note deleted candidates, but only if they're viable.
12863 if (Cand->Viable) {
12864 if (Fn->isDeleted()) {
12865 std::string FnDesc;
12866 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12867 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12868 Cand->getRewriteKind(), FnDesc);
12869
12870 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12871 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12872 << (Fn->isDeleted()
12873 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12874 : 0);
12875 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12876 return;
12877 }
12878
12879 // We don't really have anything else to say about viable candidates.
12880 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12881 return;
12882 }
12883
12884 // If this is a synthesized deduction guide we're deducing against, add a note
12885 // for it. These deduction guides are not explicitly spelled in the source
12886 // code, so simply printing a deduction failure note mentioning synthesized
12887 // template parameters or pointing to the header of the surrounding RecordDecl
12888 // would be confusing.
12889 //
12890 // We prefer adding such notes at the end of the deduction failure because
12891 // duplicate code snippets appearing in the diagnostic would likely become
12892 // noisy.
12893 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12894
12895 switch (Cand->FailureKind) {
12898 return DiagnoseArityMismatch(S, Cand, NumArgs);
12899
12901 return DiagnoseBadDeduction(S, Cand, NumArgs,
12902 TakingCandidateAddress);
12903
12905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12906 << (Fn->getPrimaryTemplate() ? 1 : 0);
12907 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12908 return;
12909 }
12910
12912 Qualifiers QualsForPrinting;
12913 QualsForPrinting.setAddressSpace(CtorDestAS);
12914 S.Diag(Fn->getLocation(),
12915 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12916 << QualsForPrinting;
12917 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12918 return;
12919 }
12920
12924 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12925
12927 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12928 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12929 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12930 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12931
12932 // FIXME: this currently happens when we're called from SemaInit
12933 // when user-conversion overload fails. Figure out how to handle
12934 // those conditions and diagnose them well.
12935 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12936 }
12937
12939 return DiagnoseBadTarget(S, Cand);
12940
12941 case ovl_fail_enable_if:
12942 return DiagnoseFailedEnableIfAttr(S, Cand);
12943
12944 case ovl_fail_explicit:
12945 return DiagnoseFailedExplicitSpec(S, Cand);
12946
12948 // It's generally not interesting to note copy/move constructors here.
12949 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12950 return;
12951 S.Diag(Fn->getLocation(),
12952 diag::note_ovl_candidate_inherited_constructor_slice)
12953 << (Fn->getPrimaryTemplate() ? 1 : 0)
12954 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12955 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12956 return;
12957
12959 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12960 (void)Available;
12961 assert(!Available);
12962 break;
12963 }
12965 // Do nothing, these should simply be ignored.
12966 break;
12967
12969 std::string FnDesc;
12970 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12971 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12972 Cand->getRewriteKind(), FnDesc);
12973
12974 S.Diag(Fn->getLocation(),
12975 diag::note_ovl_candidate_constraints_not_satisfied)
12976 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12977 << FnDesc /* Ignored */;
12978 ConstraintSatisfaction Satisfaction;
12979 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12980 /*ForOverloadResolution=*/true))
12981 break;
12982 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12983 }
12984 }
12985}
12986
12989 return;
12990
12991 // Desugar the type of the surrogate down to a function type,
12992 // retaining as many typedefs as possible while still showing
12993 // the function type (and, therefore, its parameter types).
12994 QualType FnType = Cand->Surrogate->getConversionType();
12995 bool isLValueReference = false;
12996 bool isRValueReference = false;
12997 bool isPointer = false;
12998 if (const LValueReferenceType *FnTypeRef =
12999 FnType->getAs<LValueReferenceType>()) {
13000 FnType = FnTypeRef->getPointeeType();
13001 isLValueReference = true;
13002 } else if (const RValueReferenceType *FnTypeRef =
13003 FnType->getAs<RValueReferenceType>()) {
13004 FnType = FnTypeRef->getPointeeType();
13005 isRValueReference = true;
13006 }
13007 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13008 FnType = FnTypePtr->getPointeeType();
13009 isPointer = true;
13010 }
13011 // Desugar down to a function type.
13012 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13013 // Reconstruct the pointer/reference as appropriate.
13014 if (isPointer) FnType = S.Context.getPointerType(FnType);
13015 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13016 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13017
13018 if (!Cand->Viable &&
13020 S.Diag(Cand->Surrogate->getLocation(),
13021 diag::note_ovl_surrogate_constraints_not_satisfied)
13022 << Cand->Surrogate;
13023 ConstraintSatisfaction Satisfaction;
13024 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13025 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13026 } else {
13027 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13028 << FnType;
13029 }
13030}
13031
13032static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13033 SourceLocation OpLoc,
13034 OverloadCandidate *Cand) {
13035 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13036 std::string TypeStr("operator");
13037 TypeStr += Opc;
13038 TypeStr += "(";
13039 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13040 if (Cand->Conversions.size() == 1) {
13041 TypeStr += ")";
13042 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13043 } else {
13044 TypeStr += ", ";
13045 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13046 TypeStr += ")";
13047 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13048 }
13049}
13050
13052 OverloadCandidate *Cand) {
13053 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13054 if (ICS.isBad()) break; // all meaningless after first invalid
13055 if (!ICS.isAmbiguous()) continue;
13056
13058 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13059 }
13060}
13061
13063 if (Cand->Function)
13064 return Cand->Function->getLocation();
13065 if (Cand->IsSurrogate)
13066 return Cand->Surrogate->getLocation();
13067 return SourceLocation();
13068}
13069
13070static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13071 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13075 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13076
13080 return 1;
13081
13084 return 2;
13085
13093 return 3;
13094
13096 return 4;
13097
13099 return 5;
13100
13103 return 6;
13104 }
13105 llvm_unreachable("Unhandled deduction result");
13106}
13107
13108namespace {
13109
13110struct CompareOverloadCandidatesForDisplay {
13111 Sema &S;
13112 SourceLocation Loc;
13113 size_t NumArgs;
13115
13116 CompareOverloadCandidatesForDisplay(
13117 Sema &S, SourceLocation Loc, size_t NArgs,
13119 : S(S), NumArgs(NArgs), CSK(CSK) {}
13120
13121 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13122 // If there are too many or too few arguments, that's the high-order bit we
13123 // want to sort by, even if the immediate failure kind was something else.
13124 if (C->FailureKind == ovl_fail_too_many_arguments ||
13125 C->FailureKind == ovl_fail_too_few_arguments)
13126 return static_cast<OverloadFailureKind>(C->FailureKind);
13127
13128 if (C->Function) {
13129 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13131 if (NumArgs < C->Function->getMinRequiredArguments())
13133 }
13134
13135 return static_cast<OverloadFailureKind>(C->FailureKind);
13136 }
13137
13138 bool operator()(const OverloadCandidate *L,
13139 const OverloadCandidate *R) {
13140 // Fast-path this check.
13141 if (L == R) return false;
13142
13143 // Order first by viability.
13144 if (L->Viable) {
13145 if (!R->Viable) return true;
13146
13147 if (int Ord = CompareConversions(*L, *R))
13148 return Ord < 0;
13149 // Use other tie breakers.
13150 } else if (R->Viable)
13151 return false;
13152
13153 assert(L->Viable == R->Viable);
13154
13155 // Criteria by which we can sort non-viable candidates:
13156 if (!L->Viable) {
13157 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13158 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13159
13160 // 1. Arity mismatches come after other candidates.
13161 if (LFailureKind == ovl_fail_too_many_arguments ||
13162 LFailureKind == ovl_fail_too_few_arguments) {
13163 if (RFailureKind == ovl_fail_too_many_arguments ||
13164 RFailureKind == ovl_fail_too_few_arguments) {
13165 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13166 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13167 if (LDist == RDist) {
13168 if (LFailureKind == RFailureKind)
13169 // Sort non-surrogates before surrogates.
13170 return !L->IsSurrogate && R->IsSurrogate;
13171 // Sort candidates requiring fewer parameters than there were
13172 // arguments given after candidates requiring more parameters
13173 // than there were arguments given.
13174 return LFailureKind == ovl_fail_too_many_arguments;
13175 }
13176 return LDist < RDist;
13177 }
13178 return false;
13179 }
13180 if (RFailureKind == ovl_fail_too_many_arguments ||
13181 RFailureKind == ovl_fail_too_few_arguments)
13182 return true;
13183
13184 // 2. Bad conversions come first and are ordered by the number
13185 // of bad conversions and quality of good conversions.
13186 if (LFailureKind == ovl_fail_bad_conversion) {
13187 if (RFailureKind != ovl_fail_bad_conversion)
13188 return true;
13189
13190 // The conversion that can be fixed with a smaller number of changes,
13191 // comes first.
13192 unsigned numLFixes = L->Fix.NumConversionsFixed;
13193 unsigned numRFixes = R->Fix.NumConversionsFixed;
13194 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13195 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13196 if (numLFixes != numRFixes) {
13197 return numLFixes < numRFixes;
13198 }
13199
13200 // If there's any ordering between the defined conversions...
13201 if (int Ord = CompareConversions(*L, *R))
13202 return Ord < 0;
13203 } else if (RFailureKind == ovl_fail_bad_conversion)
13204 return false;
13205
13206 if (LFailureKind == ovl_fail_bad_deduction) {
13207 if (RFailureKind != ovl_fail_bad_deduction)
13208 return true;
13209
13210 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13211 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13212 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13213 if (LRank != RRank)
13214 return LRank < RRank;
13215 }
13216 } else if (RFailureKind == ovl_fail_bad_deduction)
13217 return false;
13218
13219 // TODO: others?
13220 }
13221
13222 // Sort everything else by location.
13223 SourceLocation LLoc = GetLocationForCandidate(L);
13224 SourceLocation RLoc = GetLocationForCandidate(R);
13225
13226 // Put candidates without locations (e.g. builtins) at the end.
13227 if (LLoc.isValid() && RLoc.isValid())
13228 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13229 if (LLoc.isValid() && !RLoc.isValid())
13230 return true;
13231 if (RLoc.isValid() && !LLoc.isValid())
13232 return false;
13233 assert(!LLoc.isValid() && !RLoc.isValid());
13234 // For builtins and other functions without locations, fallback to the order
13235 // in which they were added into the candidate set.
13236 return L < R;
13237 }
13238
13239private:
13240 struct ConversionSignals {
13241 unsigned KindRank = 0;
13243
13244 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13245 ConversionSignals Sig;
13246 Sig.KindRank = Seq.getKindRank();
13247 if (Seq.isStandard())
13248 Sig.Rank = Seq.Standard.getRank();
13249 else if (Seq.isUserDefined())
13250 Sig.Rank = Seq.UserDefined.After.getRank();
13251 // We intend StaticObjectArgumentConversion to compare the same as
13252 // StandardConversion with ICR_ExactMatch rank.
13253 return Sig;
13254 }
13255
13256 static ConversionSignals ForObjectArgument() {
13257 // We intend StaticObjectArgumentConversion to compare the same as
13258 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13259 return {};
13260 }
13261 };
13262
13263 // Returns -1 if conversions in L are considered better.
13264 // 0 if they are considered indistinguishable.
13265 // 1 if conversions in R are better.
13266 int CompareConversions(const OverloadCandidate &L,
13267 const OverloadCandidate &R) {
13268 // We cannot use `isBetterOverloadCandidate` because it is defined
13269 // according to the C++ standard and provides a partial order, but we need
13270 // a total order as this function is used in sort.
13271 assert(L.Conversions.size() == R.Conversions.size());
13272 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13273 auto LS = L.IgnoreObjectArgument && I == 0
13274 ? ConversionSignals::ForObjectArgument()
13275 : ConversionSignals::ForSequence(L.Conversions[I]);
13276 auto RS = R.IgnoreObjectArgument
13277 ? ConversionSignals::ForObjectArgument()
13278 : ConversionSignals::ForSequence(R.Conversions[I]);
13279 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13280 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13281 ? -1
13282 : 1;
13283 }
13284 // FIXME: find a way to compare templates for being more or less
13285 // specialized that provides a strict weak ordering.
13286 return 0;
13287 }
13288};
13289}
13290
13291/// CompleteNonViableCandidate - Normally, overload resolution only
13292/// computes up to the first bad conversion. Produces the FixIt set if
13293/// possible.
13294static void
13296 ArrayRef<Expr *> Args,
13298 assert(!Cand->Viable);
13299
13300 // Don't do anything on failures other than bad conversion.
13302 return;
13303
13304 // We only want the FixIts if all the arguments can be corrected.
13305 bool Unfixable = false;
13306 // Use a implicit copy initialization to check conversion fixes.
13308
13309 // Attempt to fix the bad conversion.
13310 unsigned ConvCount = Cand->Conversions.size();
13311 for (unsigned ConvIdx =
13312 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13313 : 0);
13314 /**/; ++ConvIdx) {
13315 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13316 if (Cand->Conversions[ConvIdx].isInitialized() &&
13317 Cand->Conversions[ConvIdx].isBad()) {
13318 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13319 break;
13320 }
13321 }
13322
13323 // FIXME: this should probably be preserved from the overload
13324 // operation somehow.
13325 bool SuppressUserConversions = false;
13326
13327 unsigned ConvIdx = 0;
13328 unsigned ArgIdx = 0;
13329 ArrayRef<QualType> ParamTypes;
13330 bool Reversed = Cand->isReversed();
13331
13332 if (Cand->IsSurrogate) {
13333 QualType ConvType
13335 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13336 ConvType = ConvPtrType->getPointeeType();
13337 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13338 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13339 ConvIdx = 1;
13340 } else if (Cand->Function) {
13341 ParamTypes =
13342 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13343 if (isa<CXXMethodDecl>(Cand->Function) &&
13346 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13347 ConvIdx = 1;
13349 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13351 OO_Subscript)
13352 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13353 ArgIdx = 1;
13354 }
13355 } else {
13356 // Builtin operator.
13357 assert(ConvCount <= 3);
13358 ParamTypes = Cand->BuiltinParamTypes;
13359 }
13360
13361 // Fill in the rest of the conversions.
13362 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13363 ConvIdx != ConvCount && ArgIdx < Args.size();
13364 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13365 if (Cand->Conversions[ConvIdx].isInitialized()) {
13366 // We've already checked this conversion.
13367 } else if (ParamIdx < ParamTypes.size()) {
13368 if (ParamTypes[ParamIdx]->isDependentType())
13369 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13370 Args[ArgIdx]->getType());
13371 else {
13372 Cand->Conversions[ConvIdx] =
13373 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13374 SuppressUserConversions,
13375 /*InOverloadResolution=*/true,
13376 /*AllowObjCWritebackConversion=*/
13377 S.getLangOpts().ObjCAutoRefCount);
13378 // Store the FixIt in the candidate if it exists.
13379 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13380 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13381 }
13382 } else
13383 Cand->Conversions[ConvIdx].setEllipsis();
13384 }
13385}
13386
13389 SourceLocation OpLoc,
13390 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13391
13393
13394 // Sort the candidates by viability and position. Sorting directly would
13395 // be prohibitive, so we make a set of pointers and sort those.
13397 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13398 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13399 Cand != LastCand; ++Cand) {
13400 if (!Filter(*Cand))
13401 continue;
13402 switch (OCD) {
13403 case OCD_AllCandidates:
13404 if (!Cand->Viable) {
13405 if (!Cand->Function && !Cand->IsSurrogate) {
13406 // This a non-viable builtin candidate. We do not, in general,
13407 // want to list every possible builtin candidate.
13408 continue;
13409 }
13410 CompleteNonViableCandidate(S, Cand, Args, Kind);
13411 }
13412 break;
13413
13415 if (!Cand->Viable)
13416 continue;
13417 break;
13418
13420 if (!Cand->Best)
13421 continue;
13422 break;
13423 }
13424
13425 Cands.push_back(Cand);
13426 }
13427
13428 llvm::stable_sort(
13429 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13430
13431 return Cands;
13432}
13433
13435 SourceLocation OpLoc) {
13436 bool DeferHint = false;
13437 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13438 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13439 // host device candidates.
13440 auto WrongSidedCands =
13441 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13442 return (Cand.Viable == false &&
13444 (Cand.Function &&
13445 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13446 Cand.Function->template hasAttr<CUDADeviceAttr>());
13447 });
13448 DeferHint = !WrongSidedCands.empty();
13449 }
13450 return DeferHint;
13451}
13452
13453/// When overload resolution fails, prints diagnostic messages containing the
13454/// candidates in the candidate set.
13457 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13458 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13459
13460 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13461
13462 {
13463 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13464 S.Diag(PD.first, PD.second);
13465 }
13466
13467 // In WebAssembly we don't want to emit further diagnostics if a table is
13468 // passed as an argument to a function.
13469 bool NoteCands = true;
13470 for (const Expr *Arg : Args) {
13471 if (Arg->getType()->isWebAssemblyTableType())
13472 NoteCands = false;
13473 }
13474
13475 if (NoteCands)
13476 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13477
13478 if (OCD == OCD_AmbiguousCandidates)
13480 {Candidates.begin(), Candidates.end()});
13481}
13482
13485 StringRef Opc, SourceLocation OpLoc) {
13486 bool ReportedAmbiguousConversions = false;
13487
13488 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13489 unsigned CandsShown = 0;
13490 auto I = Cands.begin(), E = Cands.end();
13491 for (; I != E; ++I) {
13492 OverloadCandidate *Cand = *I;
13493
13494 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13495 ShowOverloads == Ovl_Best) {
13496 break;
13497 }
13498 ++CandsShown;
13499
13500 if (Cand->Function)
13501 NoteFunctionCandidate(S, Cand, Args.size(),
13502 Kind == CSK_AddressOfOverloadSet, DestAS);
13503 else if (Cand->IsSurrogate)
13504 NoteSurrogateCandidate(S, Cand);
13505 else {
13506 assert(Cand->Viable &&
13507 "Non-viable built-in candidates are not added to Cands.");
13508 // Generally we only see ambiguities including viable builtin
13509 // operators if overload resolution got screwed up by an
13510 // ambiguous user-defined conversion.
13511 //
13512 // FIXME: It's quite possible for different conversions to see
13513 // different ambiguities, though.
13514 if (!ReportedAmbiguousConversions) {
13515 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13516 ReportedAmbiguousConversions = true;
13517 }
13518
13519 // If this is a viable builtin, print it.
13520 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13521 }
13522 }
13523
13524 // Inform S.Diags that we've shown an overload set with N elements. This may
13525 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13526 S.Diags.overloadCandidatesShown(CandsShown);
13527
13528 if (I != E) {
13529 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13530 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13531 }
13532}
13533
13534static SourceLocation
13536 return Cand->Specialization ? Cand->Specialization->getLocation()
13537 : SourceLocation();
13538}
13539
13540namespace {
13541struct CompareTemplateSpecCandidatesForDisplay {
13542 Sema &S;
13543 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13544
13545 bool operator()(const TemplateSpecCandidate *L,
13546 const TemplateSpecCandidate *R) {
13547 // Fast-path this check.
13548 if (L == R)
13549 return false;
13550
13551 // Assuming that both candidates are not matches...
13552
13553 // Sort by the ranking of deduction failures.
13554 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13556 RankDeductionFailure(R->DeductionFailure);
13557
13558 // Sort everything else by location.
13559 SourceLocation LLoc = GetLocationForCandidate(L);
13560 SourceLocation RLoc = GetLocationForCandidate(R);
13561
13562 // Put candidates without locations (e.g. builtins) at the end.
13563 if (LLoc.isInvalid())
13564 return false;
13565 if (RLoc.isInvalid())
13566 return true;
13567
13568 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13569 }
13570};
13571}
13572
13573/// Diagnose a template argument deduction failure.
13574/// We are treating these failures as overload failures due to bad
13575/// deductions.
13577 bool ForTakingAddress) {
13579 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13580}
13581
13582void TemplateSpecCandidateSet::destroyCandidates() {
13583 for (iterator i = begin(), e = end(); i != e; ++i) {
13584 i->DeductionFailure.Destroy();
13585 }
13586}
13587
13589 destroyCandidates();
13590 Candidates.clear();
13591}
13592
13593/// NoteCandidates - When no template specialization match is found, prints
13594/// diagnostic messages containing the non-matching specializations that form
13595/// the candidate set.
13596/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13597/// OCD == OCD_AllCandidates and Cand->Viable == false.
13599 // Sort the candidates by position (assuming no candidate is a match).
13600 // Sorting directly would be prohibitive, so we make a set of pointers
13601 // and sort those.
13603 Cands.reserve(size());
13604 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13605 if (Cand->Specialization)
13606 Cands.push_back(Cand);
13607 // Otherwise, this is a non-matching builtin candidate. We do not,
13608 // in general, want to list every possible builtin candidate.
13609 }
13610
13611 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13612
13613 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13614 // for generalization purposes (?).
13615 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13616
13618 unsigned CandsShown = 0;
13619 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13620 TemplateSpecCandidate *Cand = *I;
13621
13622 // Set an arbitrary limit on the number of candidates we'll spam
13623 // the user with. FIXME: This limit should depend on details of the
13624 // candidate list.
13625 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13626 break;
13627 ++CandsShown;
13628
13629 assert(Cand->Specialization &&
13630 "Non-matching built-in candidates are not added to Cands.");
13631 Cand->NoteDeductionFailure(S, ForTakingAddress);
13632 }
13633
13634 if (I != E)
13635 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13636}
13637
13638// [PossiblyAFunctionType] --> [Return]
13639// NonFunctionType --> NonFunctionType
13640// R (A) --> R(A)
13641// R (*)(A) --> R (A)
13642// R (&)(A) --> R (A)
13643// R (S::*)(A) --> R (A)
13645 QualType Ret = PossiblyAFunctionType;
13646 if (const PointerType *ToTypePtr =
13647 PossiblyAFunctionType->getAs<PointerType>())
13648 Ret = ToTypePtr->getPointeeType();
13649 else if (const ReferenceType *ToTypeRef =
13650 PossiblyAFunctionType->getAs<ReferenceType>())
13651 Ret = ToTypeRef->getPointeeType();
13652 else if (const MemberPointerType *MemTypePtr =
13653 PossiblyAFunctionType->getAs<MemberPointerType>())
13654 Ret = MemTypePtr->getPointeeType();
13655 Ret =
13656 Context.getCanonicalType(Ret).getUnqualifiedType();
13657 return Ret;
13658}
13659
13661 bool Complain = true) {
13662 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13663 S.DeduceReturnType(FD, Loc, Complain))
13664 return true;
13665
13666 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13667 if (S.getLangOpts().CPlusPlus17 &&
13668 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13669 !S.ResolveExceptionSpec(Loc, FPT))
13670 return true;
13671
13672 return false;
13673}
13674
13675namespace {
13676// A helper class to help with address of function resolution
13677// - allows us to avoid passing around all those ugly parameters
13678class AddressOfFunctionResolver {
13679 Sema& S;
13680 Expr* SourceExpr;
13681 const QualType& TargetType;
13682 QualType TargetFunctionType; // Extracted function type from target type
13683
13684 bool Complain;
13685 //DeclAccessPair& ResultFunctionAccessPair;
13686 ASTContext& Context;
13687
13688 bool TargetTypeIsNonStaticMemberFunction;
13689 bool FoundNonTemplateFunction;
13690 bool StaticMemberFunctionFromBoundPointer;
13691 bool HasComplained;
13692
13693 OverloadExpr::FindResult OvlExprInfo;
13694 OverloadExpr *OvlExpr;
13695 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13696 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13697 TemplateSpecCandidateSet FailedCandidates;
13698
13699public:
13700 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13701 const QualType &TargetType, bool Complain)
13702 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13703 Complain(Complain), Context(S.getASTContext()),
13704 TargetTypeIsNonStaticMemberFunction(
13705 !!TargetType->getAs<MemberPointerType>()),
13706 FoundNonTemplateFunction(false),
13707 StaticMemberFunctionFromBoundPointer(false),
13708 HasComplained(false),
13709 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13710 OvlExpr(OvlExprInfo.Expression),
13711 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13712 ExtractUnqualifiedFunctionTypeFromTargetType();
13713
13714 if (TargetFunctionType->isFunctionType()) {
13715 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13716 if (!UME->isImplicitAccess() &&
13718 StaticMemberFunctionFromBoundPointer = true;
13719 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13720 DeclAccessPair dap;
13721 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13722 OvlExpr, false, &dap)) {
13723 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13724 if (!Method->isStatic()) {
13725 // If the target type is a non-function type and the function found
13726 // is a non-static member function, pretend as if that was the
13727 // target, it's the only possible type to end up with.
13728 TargetTypeIsNonStaticMemberFunction = true;
13729
13730 // And skip adding the function if its not in the proper form.
13731 // We'll diagnose this due to an empty set of functions.
13732 if (!OvlExprInfo.HasFormOfMemberPointer)
13733 return;
13734 }
13735
13736 Matches.push_back(std::make_pair(dap, Fn));
13737 }
13738 return;
13739 }
13740
13741 if (OvlExpr->hasExplicitTemplateArgs())
13742 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13743
13744 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13745 // C++ [over.over]p4:
13746 // If more than one function is selected, [...]
13747 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13748 if (FoundNonTemplateFunction) {
13749 EliminateAllTemplateMatches();
13750 EliminateLessPartialOrderingConstrainedMatches();
13751 } else
13752 EliminateAllExceptMostSpecializedTemplate();
13753 }
13754 }
13755
13756 if (S.getLangOpts().CUDA && Matches.size() > 1)
13757 EliminateSuboptimalCudaMatches();
13758 }
13759
13760 bool hasComplained() const { return HasComplained; }
13761
13762private:
13763 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13764 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13765 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13766 }
13767
13768 /// \return true if A is considered a better overload candidate for the
13769 /// desired type than B.
13770 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13771 // If A doesn't have exactly the correct type, we don't want to classify it
13772 // as "better" than anything else. This way, the user is required to
13773 // disambiguate for us if there are multiple candidates and no exact match.
13774 return candidateHasExactlyCorrectType(A) &&
13775 (!candidateHasExactlyCorrectType(B) ||
13776 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13777 }
13778
13779 /// \return true if we were able to eliminate all but one overload candidate,
13780 /// false otherwise.
13781 bool eliminiateSuboptimalOverloadCandidates() {
13782 // Same algorithm as overload resolution -- one pass to pick the "best",
13783 // another pass to be sure that nothing is better than the best.
13784 auto Best = Matches.begin();
13785 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13786 if (isBetterCandidate(I->second, Best->second))
13787 Best = I;
13788
13789 const FunctionDecl *BestFn = Best->second;
13790 auto IsBestOrInferiorToBest = [this, BestFn](
13791 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13792 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13793 };
13794
13795 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13796 // option, so we can potentially give the user a better error
13797 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13798 return false;
13799 Matches[0] = *Best;
13800 Matches.resize(1);
13801 return true;
13802 }
13803
13804 bool isTargetTypeAFunction() const {
13805 return TargetFunctionType->isFunctionType();
13806 }
13807
13808 // [ToType] [Return]
13809
13810 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13811 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13812 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13813 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13814 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13815 }
13816
13817 // return true if any matching specializations were found
13818 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13819 const DeclAccessPair& CurAccessFunPair) {
13820 if (CXXMethodDecl *Method
13821 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13822 // Skip non-static function templates when converting to pointer, and
13823 // static when converting to member pointer.
13824 bool CanConvertToFunctionPointer =
13825 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13826 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13827 return false;
13828 }
13829 else if (TargetTypeIsNonStaticMemberFunction)
13830 return false;
13831
13832 // C++ [over.over]p2:
13833 // If the name is a function template, template argument deduction is
13834 // done (14.8.2.2), and if the argument deduction succeeds, the
13835 // resulting template argument list is used to generate a single
13836 // function template specialization, which is added to the set of
13837 // overloaded functions considered.
13838 FunctionDecl *Specialization = nullptr;
13839 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13841 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13842 Specialization, Info, /*IsAddressOfFunction*/ true);
13843 Result != TemplateDeductionResult::Success) {
13844 // Make a note of the failed deduction for diagnostics.
13845 FailedCandidates.addCandidate()
13846 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13847 MakeDeductionFailureInfo(Context, Result, Info));
13848 return false;
13849 }
13850
13851 // Template argument deduction ensures that we have an exact match or
13852 // compatible pointer-to-function arguments that would be adjusted by ICS.
13853 // This function template specicalization works.
13855 Context.getCanonicalType(Specialization->getType()),
13856 Context.getCanonicalType(TargetFunctionType)));
13857
13859 return false;
13860
13861 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13862 return true;
13863 }
13864
13865 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13866 const DeclAccessPair& CurAccessFunPair) {
13867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13868 // Skip non-static functions when converting to pointer, and static
13869 // when converting to member pointer.
13870 bool CanConvertToFunctionPointer =
13871 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13872 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13873 return false;
13874 }
13875 else if (TargetTypeIsNonStaticMemberFunction)
13876 return false;
13877
13878 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13879 if (S.getLangOpts().CUDA) {
13880 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13881 if (!(Caller && Caller->isImplicit()) &&
13882 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13883 return false;
13884 }
13885 if (FunDecl->isMultiVersion()) {
13886 const auto *TA = FunDecl->getAttr<TargetAttr>();
13887 if (TA && !TA->isDefaultVersion())
13888 return false;
13889 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13890 if (TVA && !TVA->isDefaultVersion())
13891 return false;
13892 }
13893
13894 // If any candidate has a placeholder return type, trigger its deduction
13895 // now.
13896 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13897 Complain)) {
13898 HasComplained |= Complain;
13899 return false;
13900 }
13901
13902 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13903 return false;
13904
13905 // If we're in C, we need to support types that aren't exactly identical.
13906 if (!S.getLangOpts().CPlusPlus ||
13907 candidateHasExactlyCorrectType(FunDecl)) {
13908 Matches.push_back(std::make_pair(
13909 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13910 FoundNonTemplateFunction = true;
13911 return true;
13912 }
13913 }
13914
13915 return false;
13916 }
13917
13918 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13919 bool Ret = false;
13920
13921 // If the overload expression doesn't have the form of a pointer to
13922 // member, don't try to convert it to a pointer-to-member type.
13923 if (IsInvalidFormOfPointerToMemberFunction())
13924 return false;
13925
13926 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13927 E = OvlExpr->decls_end();
13928 I != E; ++I) {
13929 // Look through any using declarations to find the underlying function.
13930 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13931
13932 // C++ [over.over]p3:
13933 // Non-member functions and static member functions match
13934 // targets of type "pointer-to-function" or "reference-to-function."
13935 // Nonstatic member functions match targets of
13936 // type "pointer-to-member-function."
13937 // Note that according to DR 247, the containing class does not matter.
13938 if (FunctionTemplateDecl *FunctionTemplate
13939 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13940 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13941 Ret = true;
13942 }
13943 // If we have explicit template arguments supplied, skip non-templates.
13944 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13945 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13946 Ret = true;
13947 }
13948 assert(Ret || Matches.empty());
13949 return Ret;
13950 }
13951
13952 void EliminateAllExceptMostSpecializedTemplate() {
13953 // [...] and any given function template specialization F1 is
13954 // eliminated if the set contains a second function template
13955 // specialization whose function template is more specialized
13956 // than the function template of F1 according to the partial
13957 // ordering rules of 14.5.5.2.
13958
13959 // The algorithm specified above is quadratic. We instead use a
13960 // two-pass algorithm (similar to the one used to identify the
13961 // best viable function in an overload set) that identifies the
13962 // best function template (if it exists).
13963
13964 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13965 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13966 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13967
13968 // TODO: It looks like FailedCandidates does not serve much purpose
13969 // here, since the no_viable diagnostic has index 0.
13970 UnresolvedSetIterator Result = S.getMostSpecialized(
13971 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13972 SourceExpr->getBeginLoc(), S.PDiag(),
13973 S.PDiag(diag::err_addr_ovl_ambiguous)
13974 << Matches[0].second->getDeclName(),
13975 S.PDiag(diag::note_ovl_candidate)
13976 << (unsigned)oc_function << (unsigned)ocs_described_template,
13977 Complain, TargetFunctionType);
13978
13979 if (Result != MatchesCopy.end()) {
13980 // Make it the first and only element
13981 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13982 Matches[0].second = cast<FunctionDecl>(*Result);
13983 Matches.resize(1);
13984 } else
13985 HasComplained |= Complain;
13986 }
13987
13988 void EliminateAllTemplateMatches() {
13989 // [...] any function template specializations in the set are
13990 // eliminated if the set also contains a non-template function, [...]
13991 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13992 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13993 ++I;
13994 else {
13995 Matches[I] = Matches[--N];
13996 Matches.resize(N);
13997 }
13998 }
13999 }
14000
14001 void EliminateLessPartialOrderingConstrainedMatches() {
14002 // C++ [over.over]p5:
14003 // [...] Any given non-template function F0 is eliminated if the set
14004 // contains a second non-template function that is more
14005 // partial-ordering-constrained than F0. [...]
14006 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14007 "Call EliminateAllTemplateMatches() first");
14008 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14009 Results.push_back(Matches[0]);
14010 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14011 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14012 FunctionDecl *F = getMorePartialOrderingConstrained(
14013 S, Matches[I].second, Results[0].second,
14014 /*IsFn1Reversed=*/false,
14015 /*IsFn2Reversed=*/false);
14016 if (!F) {
14017 Results.push_back(Matches[I]);
14018 continue;
14019 }
14020 if (F == Matches[I].second) {
14021 Results.clear();
14022 Results.push_back(Matches[I]);
14023 }
14024 }
14025 std::swap(Matches, Results);
14026 }
14027
14028 void EliminateSuboptimalCudaMatches() {
14029 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14030 Matches);
14031 }
14032
14033public:
14034 void ComplainNoMatchesFound() const {
14035 assert(Matches.empty());
14036 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14037 << OvlExpr->getName() << TargetFunctionType
14038 << OvlExpr->getSourceRange();
14039 if (FailedCandidates.empty())
14040 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14041 /*TakingAddress=*/true);
14042 else {
14043 // We have some deduction failure messages. Use them to diagnose
14044 // the function templates, and diagnose the non-template candidates
14045 // normally.
14046 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14047 IEnd = OvlExpr->decls_end();
14048 I != IEnd; ++I)
14049 if (FunctionDecl *Fun =
14050 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14052 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14053 /*TakingAddress=*/true);
14054 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14055 }
14056 }
14057
14058 bool IsInvalidFormOfPointerToMemberFunction() const {
14059 return TargetTypeIsNonStaticMemberFunction &&
14060 !OvlExprInfo.HasFormOfMemberPointer;
14061 }
14062
14063 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14064 // TODO: Should we condition this on whether any functions might
14065 // have matched, or is it more appropriate to do that in callers?
14066 // TODO: a fixit wouldn't hurt.
14067 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14068 << TargetType << OvlExpr->getSourceRange();
14069 }
14070
14071 bool IsStaticMemberFunctionFromBoundPointer() const {
14072 return StaticMemberFunctionFromBoundPointer;
14073 }
14074
14075 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14076 S.Diag(OvlExpr->getBeginLoc(),
14077 diag::err_invalid_form_pointer_member_function)
14078 << OvlExpr->getSourceRange();
14079 }
14080
14081 void ComplainOfInvalidConversion() const {
14082 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14083 << OvlExpr->getName() << TargetType;
14084 }
14085
14086 void ComplainMultipleMatchesFound() const {
14087 assert(Matches.size() > 1);
14088 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14089 << OvlExpr->getName() << OvlExpr->getSourceRange();
14090 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14091 /*TakingAddress=*/true);
14092 }
14093
14094 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14095
14096 int getNumMatches() const { return Matches.size(); }
14097
14098 FunctionDecl* getMatchingFunctionDecl() const {
14099 if (Matches.size() != 1) return nullptr;
14100 return Matches[0].second;
14101 }
14102
14103 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14104 if (Matches.size() != 1) return nullptr;
14105 return &Matches[0].first;
14106 }
14107};
14108}
14109
14110FunctionDecl *
14112 QualType TargetType,
14113 bool Complain,
14114 DeclAccessPair &FoundResult,
14115 bool *pHadMultipleCandidates) {
14116 assert(AddressOfExpr->getType() == Context.OverloadTy);
14117
14118 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14119 Complain);
14120 int NumMatches = Resolver.getNumMatches();
14121 FunctionDecl *Fn = nullptr;
14122 bool ShouldComplain = Complain && !Resolver.hasComplained();
14123 if (NumMatches == 0 && ShouldComplain) {
14124 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14125 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14126 else
14127 Resolver.ComplainNoMatchesFound();
14128 }
14129 else if (NumMatches > 1 && ShouldComplain)
14130 Resolver.ComplainMultipleMatchesFound();
14131 else if (NumMatches == 1) {
14132 Fn = Resolver.getMatchingFunctionDecl();
14133 assert(Fn);
14134 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14135 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14136 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14137 if (Complain) {
14138 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14139 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14140 else
14141 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14142 }
14143 }
14144
14145 if (pHadMultipleCandidates)
14146 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14147 return Fn;
14148}
14149
14153 OverloadExpr *Ovl = R.Expression;
14154 bool IsResultAmbiguous = false;
14155 FunctionDecl *Result = nullptr;
14156 DeclAccessPair DAP;
14157 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14158
14159 // Return positive for better, negative for worse, 0 for equal preference.
14160 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14161 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14162 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14163 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14164 };
14165
14166 // Don't use the AddressOfResolver because we're specifically looking for
14167 // cases where we have one overload candidate that lacks
14168 // enable_if/pass_object_size/...
14169 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14170 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14171 if (!FD)
14172 return nullptr;
14173
14175 continue;
14176
14177 // If we found a better result, update Result.
14178 auto FoundBetter = [&]() {
14179 IsResultAmbiguous = false;
14180 DAP = I.getPair();
14181 Result = FD;
14182 };
14183
14184 // We have more than one result - see if it is more
14185 // partial-ordering-constrained than the previous one.
14186 if (Result) {
14187 // Check CUDA preference first. If the candidates have differennt CUDA
14188 // preference, choose the one with higher CUDA preference. Otherwise,
14189 // choose the one with more constraints.
14190 if (getLangOpts().CUDA) {
14191 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14192 // FD has different preference than Result.
14193 if (PreferenceByCUDA != 0) {
14194 // FD is more preferable than Result.
14195 if (PreferenceByCUDA > 0)
14196 FoundBetter();
14197 continue;
14198 }
14199 }
14200 // FD has the same CUDA preference than Result. Continue to check
14201 // constraints.
14202
14203 // C++ [over.over]p5:
14204 // [...] Any given non-template function F0 is eliminated if the set
14205 // contains a second non-template function that is more
14206 // partial-ordering-constrained than F0 [...]
14207 FunctionDecl *MoreConstrained =
14209 /*IsFn1Reversed=*/false,
14210 /*IsFn2Reversed=*/false);
14211 if (MoreConstrained != FD) {
14212 if (!MoreConstrained) {
14213 IsResultAmbiguous = true;
14214 AmbiguousDecls.push_back(FD);
14215 }
14216 continue;
14217 }
14218 // FD is more constrained - replace Result with it.
14219 }
14220 FoundBetter();
14221 }
14222
14223 if (IsResultAmbiguous)
14224 return nullptr;
14225
14226 if (Result) {
14227 // We skipped over some ambiguous declarations which might be ambiguous with
14228 // the selected result.
14229 for (FunctionDecl *Skipped : AmbiguousDecls) {
14230 // If skipped candidate has different CUDA preference than the result,
14231 // there is no ambiguity. Otherwise check whether they have different
14232 // constraints.
14233 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14234 continue;
14235 if (!getMoreConstrainedFunction(Skipped, Result))
14236 return nullptr;
14237 }
14238 Pair = DAP;
14239 }
14240 return Result;
14241}
14242
14244 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14245 Expr *E = SrcExpr.get();
14246 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14247
14248 DeclAccessPair DAP;
14250 if (!Found || Found->isCPUDispatchMultiVersion() ||
14251 Found->isCPUSpecificMultiVersion())
14252 return false;
14253
14254 // Emitting multiple diagnostics for a function that is both inaccessible and
14255 // unavailable is consistent with our behavior elsewhere. So, always check
14256 // for both.
14260 if (Res.isInvalid())
14261 return false;
14262 Expr *Fixed = Res.get();
14263 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14264 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14265 else
14266 SrcExpr = Fixed;
14267 return true;
14268}
14269
14271 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14272 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14273 // C++ [over.over]p1:
14274 // [...] [Note: any redundant set of parentheses surrounding the
14275 // overloaded function name is ignored (5.1). ]
14276 // C++ [over.over]p1:
14277 // [...] The overloaded function name can be preceded by the &
14278 // operator.
14279
14280 // If we didn't actually find any template-ids, we're done.
14281 if (!ovl->hasExplicitTemplateArgs())
14282 return nullptr;
14283
14284 TemplateArgumentListInfo ExplicitTemplateArgs;
14285 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14286
14287 // Look through all of the overloaded functions, searching for one
14288 // whose type matches exactly.
14289 FunctionDecl *Matched = nullptr;
14290 for (UnresolvedSetIterator I = ovl->decls_begin(),
14291 E = ovl->decls_end(); I != E; ++I) {
14292 // C++0x [temp.arg.explicit]p3:
14293 // [...] In contexts where deduction is done and fails, or in contexts
14294 // where deduction is not done, if a template argument list is
14295 // specified and it, along with any default template arguments,
14296 // identifies a single function template specialization, then the
14297 // template-id is an lvalue for the function template specialization.
14299 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14300 if (!FunctionTemplate)
14301 continue;
14302
14303 // C++ [over.over]p2:
14304 // If the name is a function template, template argument deduction is
14305 // done (14.8.2.2), and if the argument deduction succeeds, the
14306 // resulting template argument list is used to generate a single
14307 // function template specialization, which is added to the set of
14308 // overloaded functions considered.
14309 FunctionDecl *Specialization = nullptr;
14310 TemplateDeductionInfo Info(ovl->getNameLoc());
14312 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14313 /*IsAddressOfFunction*/ true);
14315 // Make a note of the failed deduction for diagnostics.
14316 if (FailedTSC)
14317 FailedTSC->addCandidate().set(
14318 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14320 continue;
14321 }
14322
14323 assert(Specialization && "no specialization and no error?");
14324
14325 // C++ [temp.deduct.call]p6:
14326 // [...] If all successful deductions yield the same deduced A, that
14327 // deduced A is the result of deduction; otherwise, the parameter is
14328 // treated as a non-deduced context.
14329 if (Matched) {
14330 if (ForTypeDeduction &&
14332 Specialization->getType()))
14333 continue;
14334 // Multiple matches; we can't resolve to a single declaration.
14335 if (Complain) {
14336 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14337 << ovl->getName();
14339 }
14340 return nullptr;
14341 }
14342
14343 Matched = Specialization;
14344 if (FoundResult) *FoundResult = I.getPair();
14345 }
14346
14347 if (Matched &&
14348 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14349 return nullptr;
14350
14351 return Matched;
14352}
14353
14355 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14356 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14357 unsigned DiagIDForComplaining) {
14358 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14359
14361
14362 DeclAccessPair found;
14363 ExprResult SingleFunctionExpression;
14365 ovl.Expression, /*complain*/ false, &found)) {
14366 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14367 SrcExpr = ExprError();
14368 return true;
14369 }
14370
14371 // It is only correct to resolve to an instance method if we're
14372 // resolving a form that's permitted to be a pointer to member.
14373 // Otherwise we'll end up making a bound member expression, which
14374 // is illegal in all the contexts we resolve like this.
14375 if (!ovl.HasFormOfMemberPointer &&
14376 isa<CXXMethodDecl>(fn) &&
14377 cast<CXXMethodDecl>(fn)->isInstance()) {
14378 if (!complain) return false;
14379
14380 Diag(ovl.Expression->getExprLoc(),
14381 diag::err_bound_member_function)
14382 << 0 << ovl.Expression->getSourceRange();
14383
14384 // TODO: I believe we only end up here if there's a mix of
14385 // static and non-static candidates (otherwise the expression
14386 // would have 'bound member' type, not 'overload' type).
14387 // Ideally we would note which candidate was chosen and why
14388 // the static candidates were rejected.
14389 SrcExpr = ExprError();
14390 return true;
14391 }
14392
14393 // Fix the expression to refer to 'fn'.
14394 SingleFunctionExpression =
14395 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14396
14397 // If desired, do function-to-pointer decay.
14398 if (doFunctionPointerConversion) {
14399 SingleFunctionExpression =
14400 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14401 if (SingleFunctionExpression.isInvalid()) {
14402 SrcExpr = ExprError();
14403 return true;
14404 }
14405 }
14406 }
14407
14408 if (!SingleFunctionExpression.isUsable()) {
14409 if (complain) {
14410 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14411 << ovl.Expression->getName()
14412 << DestTypeForComplaining
14413 << OpRangeForComplaining
14415 NoteAllOverloadCandidates(SrcExpr.get());
14416
14417 SrcExpr = ExprError();
14418 return true;
14419 }
14420
14421 return false;
14422 }
14423
14424 SrcExpr = SingleFunctionExpression;
14425 return true;
14426}
14427
14428/// Add a single candidate to the overload set.
14430 DeclAccessPair FoundDecl,
14431 TemplateArgumentListInfo *ExplicitTemplateArgs,
14432 ArrayRef<Expr *> Args,
14433 OverloadCandidateSet &CandidateSet,
14434 bool PartialOverloading,
14435 bool KnownValid) {
14436 NamedDecl *Callee = FoundDecl.getDecl();
14437 if (isa<UsingShadowDecl>(Callee))
14438 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14439
14440 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14441 if (ExplicitTemplateArgs) {
14442 assert(!KnownValid && "Explicit template arguments?");
14443 return;
14444 }
14445 // Prevent ill-formed function decls to be added as overload candidates.
14446 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14447 return;
14448
14449 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14450 /*SuppressUserConversions=*/false,
14451 PartialOverloading);
14452 return;
14453 }
14454
14455 if (FunctionTemplateDecl *FuncTemplate
14456 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14457 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14458 ExplicitTemplateArgs, Args, CandidateSet,
14459 /*SuppressUserConversions=*/false,
14460 PartialOverloading);
14461 return;
14462 }
14463
14464 assert(!KnownValid && "unhandled case in overloaded call candidate");
14465}
14466
14468 ArrayRef<Expr *> Args,
14469 OverloadCandidateSet &CandidateSet,
14470 bool PartialOverloading) {
14471
14472#ifndef NDEBUG
14473 // Verify that ArgumentDependentLookup is consistent with the rules
14474 // in C++0x [basic.lookup.argdep]p3:
14475 //
14476 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14477 // and let Y be the lookup set produced by argument dependent
14478 // lookup (defined as follows). If X contains
14479 //
14480 // -- a declaration of a class member, or
14481 //
14482 // -- a block-scope function declaration that is not a
14483 // using-declaration, or
14484 //
14485 // -- a declaration that is neither a function or a function
14486 // template
14487 //
14488 // then Y is empty.
14489
14490 if (ULE->requiresADL()) {
14492 E = ULE->decls_end(); I != E; ++I) {
14493 assert(!(*I)->getDeclContext()->isRecord());
14494 assert(isa<UsingShadowDecl>(*I) ||
14495 !(*I)->getDeclContext()->isFunctionOrMethod());
14496 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14497 }
14498 }
14499#endif
14500
14501 // It would be nice to avoid this copy.
14502 TemplateArgumentListInfo TABuffer;
14503 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14504 if (ULE->hasExplicitTemplateArgs()) {
14505 ULE->copyTemplateArgumentsInto(TABuffer);
14506 ExplicitTemplateArgs = &TABuffer;
14507 }
14508
14510 E = ULE->decls_end(); I != E; ++I)
14511 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14512 CandidateSet, PartialOverloading,
14513 /*KnownValid*/ true);
14514
14515 if (ULE->requiresADL())
14517 Args, ExplicitTemplateArgs,
14518 CandidateSet, PartialOverloading);
14519}
14520
14522 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14523 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14524 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14525 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14526 CandidateSet, false, /*KnownValid*/ false);
14527}
14528
14529/// Determine whether a declaration with the specified name could be moved into
14530/// a different namespace.
14532 switch (Name.getCXXOverloadedOperator()) {
14533 case OO_New: case OO_Array_New:
14534 case OO_Delete: case OO_Array_Delete:
14535 return false;
14536
14537 default:
14538 return true;
14539 }
14540}
14541
14542/// Attempt to recover from an ill-formed use of a non-dependent name in a
14543/// template, where the non-dependent name was declared after the template
14544/// was defined. This is common in code written for a compilers which do not
14545/// correctly implement two-stage name lookup.
14546///
14547/// Returns true if a viable candidate was found and a diagnostic was issued.
14549 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14551 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14552 CXXRecordDecl **FoundInClass = nullptr) {
14553 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14554 return false;
14555
14556 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14557 if (DC->isTransparentContext())
14558 continue;
14559
14560 SemaRef.LookupQualifiedName(R, DC);
14561
14562 if (!R.empty()) {
14563 R.suppressDiagnostics();
14564
14565 OverloadCandidateSet Candidates(FnLoc, CSK);
14566 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14567 Candidates);
14568
14571 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14572
14573 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14574 // We either found non-function declarations or a best viable function
14575 // at class scope. A class-scope lookup result disables ADL. Don't
14576 // look past this, but let the caller know that we found something that
14577 // either is, or might be, usable in this class.
14578 if (FoundInClass) {
14579 *FoundInClass = RD;
14580 if (OR == OR_Success) {
14581 R.clear();
14582 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14583 R.resolveKind();
14584 }
14585 }
14586 return false;
14587 }
14588
14589 if (OR != OR_Success) {
14590 // There wasn't a unique best function or function template.
14591 return false;
14592 }
14593
14594 // Find the namespaces where ADL would have looked, and suggest
14595 // declaring the function there instead.
14596 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14597 Sema::AssociatedClassSet AssociatedClasses;
14598 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14599 AssociatedNamespaces,
14600 AssociatedClasses);
14601 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14602 if (canBeDeclaredInNamespace(R.getLookupName())) {
14603 DeclContext *Std = SemaRef.getStdNamespace();
14604 for (Sema::AssociatedNamespaceSet::iterator
14605 it = AssociatedNamespaces.begin(),
14606 end = AssociatedNamespaces.end(); it != end; ++it) {
14607 // Never suggest declaring a function within namespace 'std'.
14608 if (Std && Std->Encloses(*it))
14609 continue;
14610
14611 // Never suggest declaring a function within a namespace with a
14612 // reserved name, like __gnu_cxx.
14613 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14614 if (NS &&
14615 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14616 continue;
14617
14618 SuggestedNamespaces.insert(*it);
14619 }
14620 }
14621
14622 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14623 << R.getLookupName();
14624 if (SuggestedNamespaces.empty()) {
14625 SemaRef.Diag(Best->Function->getLocation(),
14626 diag::note_not_found_by_two_phase_lookup)
14627 << R.getLookupName() << 0;
14628 } else if (SuggestedNamespaces.size() == 1) {
14629 SemaRef.Diag(Best->Function->getLocation(),
14630 diag::note_not_found_by_two_phase_lookup)
14631 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14632 } else {
14633 // FIXME: It would be useful to list the associated namespaces here,
14634 // but the diagnostics infrastructure doesn't provide a way to produce
14635 // a localized representation of a list of items.
14636 SemaRef.Diag(Best->Function->getLocation(),
14637 diag::note_not_found_by_two_phase_lookup)
14638 << R.getLookupName() << 2;
14639 }
14640
14641 // Try to recover by calling this function.
14642 return true;
14643 }
14644
14645 R.clear();
14646 }
14647
14648 return false;
14649}
14650
14651/// Attempt to recover from ill-formed use of a non-dependent operator in a
14652/// template, where the non-dependent operator was declared after the template
14653/// was defined.
14654///
14655/// Returns true if a viable candidate was found and a diagnostic was issued.
14656static bool
14658 SourceLocation OpLoc,
14659 ArrayRef<Expr *> Args) {
14660 DeclarationName OpName =
14662 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14663 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14665 /*ExplicitTemplateArgs=*/nullptr, Args);
14666}
14667
14668namespace {
14669class BuildRecoveryCallExprRAII {
14670 Sema &SemaRef;
14671 Sema::SatisfactionStackResetRAII SatStack;
14672
14673public:
14674 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14675 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14676 SemaRef.IsBuildingRecoveryCallExpr = true;
14677 }
14678
14679 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14680};
14681}
14682
14683/// Attempts to recover from a call where no functions were found.
14684///
14685/// This function will do one of three things:
14686/// * Diagnose, recover, and return a recovery expression.
14687/// * Diagnose, fail to recover, and return ExprError().
14688/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14689/// expected to diagnose as appropriate.
14690static ExprResult
14693 SourceLocation LParenLoc,
14695 SourceLocation RParenLoc,
14696 bool EmptyLookup, bool AllowTypoCorrection) {
14697 // Do not try to recover if it is already building a recovery call.
14698 // This stops infinite loops for template instantiations like
14699 //
14700 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14701 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14702 if (SemaRef.IsBuildingRecoveryCallExpr)
14703 return ExprResult();
14704 BuildRecoveryCallExprRAII RCE(SemaRef);
14705
14706 CXXScopeSpec SS;
14707 SS.Adopt(ULE->getQualifierLoc());
14708 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14709
14710 TemplateArgumentListInfo TABuffer;
14711 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14712 if (ULE->hasExplicitTemplateArgs()) {
14713 ULE->copyTemplateArgumentsInto(TABuffer);
14714 ExplicitTemplateArgs = &TABuffer;
14715 }
14716
14717 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14719 CXXRecordDecl *FoundInClass = nullptr;
14720 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14722 ExplicitTemplateArgs, Args, &FoundInClass)) {
14723 // OK, diagnosed a two-phase lookup issue.
14724 } else if (EmptyLookup) {
14725 // Try to recover from an empty lookup with typo correction.
14726 R.clear();
14727 NoTypoCorrectionCCC NoTypoValidator{};
14728 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14729 ExplicitTemplateArgs != nullptr,
14730 dyn_cast<MemberExpr>(Fn));
14731 CorrectionCandidateCallback &Validator =
14732 AllowTypoCorrection
14733 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14734 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14735 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14736 Args))
14737 return ExprError();
14738 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14739 // We found a usable declaration of the name in a dependent base of some
14740 // enclosing class.
14741 // FIXME: We should also explain why the candidates found by name lookup
14742 // were not viable.
14743 if (SemaRef.DiagnoseDependentMemberLookup(R))
14744 return ExprError();
14745 } else {
14746 // We had viable candidates and couldn't recover; let the caller diagnose
14747 // this.
14748 return ExprResult();
14749 }
14750
14751 // If we get here, we should have issued a diagnostic and formed a recovery
14752 // lookup result.
14753 assert(!R.empty() && "lookup results empty despite recovery");
14754
14755 // If recovery created an ambiguity, just bail out.
14756 if (R.isAmbiguous()) {
14757 R.suppressDiagnostics();
14758 return ExprError();
14759 }
14760
14761 // Build an implicit member call if appropriate. Just drop the
14762 // casts and such from the call, we don't really care.
14763 ExprResult NewFn = ExprError();
14764 if ((*R.begin())->isCXXClassMember())
14765 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14766 ExplicitTemplateArgs, S);
14767 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14768 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14769 ExplicitTemplateArgs);
14770 else
14771 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14772
14773 if (NewFn.isInvalid())
14774 return ExprError();
14775
14776 // This shouldn't cause an infinite loop because we're giving it
14777 // an expression with viable lookup results, which should never
14778 // end up here.
14779 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14780 MultiExprArg(Args.data(), Args.size()),
14781 RParenLoc);
14782}
14783
14786 MultiExprArg Args,
14787 SourceLocation RParenLoc,
14788 OverloadCandidateSet *CandidateSet,
14789 ExprResult *Result) {
14790#ifndef NDEBUG
14791 if (ULE->requiresADL()) {
14792 // To do ADL, we must have found an unqualified name.
14793 assert(!ULE->getQualifier() && "qualified name with ADL");
14794
14795 // We don't perform ADL for implicit declarations of builtins.
14796 // Verify that this was correctly set up.
14797 FunctionDecl *F;
14798 if (ULE->decls_begin() != ULE->decls_end() &&
14799 ULE->decls_begin() + 1 == ULE->decls_end() &&
14800 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14801 F->getBuiltinID() && F->isImplicit())
14802 llvm_unreachable("performing ADL for builtin");
14803
14804 // We don't perform ADL in C.
14805 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14806 }
14807#endif
14808
14809 UnbridgedCastsSet UnbridgedCasts;
14810 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14811 *Result = ExprError();
14812 return true;
14813 }
14814
14815 // Add the functions denoted by the callee to the set of candidate
14816 // functions, including those from argument-dependent lookup.
14817 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14818
14819 if (getLangOpts().MSVCCompat &&
14820 CurContext->isDependentContext() && !isSFINAEContext() &&
14822
14824 if (CandidateSet->empty() ||
14825 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14827 // In Microsoft mode, if we are inside a template class member function
14828 // then create a type dependent CallExpr. The goal is to postpone name
14829 // lookup to instantiation time to be able to search into type dependent
14830 // base classes.
14831 CallExpr *CE =
14832 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14833 RParenLoc, CurFPFeatureOverrides());
14835 *Result = CE;
14836 return true;
14837 }
14838 }
14839
14840 if (CandidateSet->empty())
14841 return false;
14842
14843 UnbridgedCasts.restore();
14844 return false;
14845}
14846
14847// Guess at what the return type for an unresolvable overload should be.
14850 std::optional<QualType> Result;
14851 // Adjust Type after seeing a candidate.
14852 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14853 if (!Candidate.Function)
14854 return;
14855 if (Candidate.Function->isInvalidDecl())
14856 return;
14857 QualType T = Candidate.Function->getReturnType();
14858 if (T.isNull())
14859 return;
14860 if (!Result)
14861 Result = T;
14862 else if (Result != T)
14863 Result = QualType();
14864 };
14865
14866 // Look for an unambiguous type from a progressively larger subset.
14867 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14868 //
14869 // First, consider only the best candidate.
14870 if (Best && *Best != CS.end())
14871 ConsiderCandidate(**Best);
14872 // Next, consider only viable candidates.
14873 if (!Result)
14874 for (const auto &C : CS)
14875 if (C.Viable)
14876 ConsiderCandidate(C);
14877 // Finally, consider all candidates.
14878 if (!Result)
14879 for (const auto &C : CS)
14880 ConsiderCandidate(C);
14881
14882 if (!Result)
14883 return QualType();
14884 auto Value = *Result;
14885 if (Value.isNull() || Value->isUndeducedType())
14886 return QualType();
14887 return Value;
14888}
14889
14890/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14891/// the completed call expression. If overload resolution fails, emits
14892/// diagnostics and returns ExprError()
14895 SourceLocation LParenLoc,
14896 MultiExprArg Args,
14897 SourceLocation RParenLoc,
14898 Expr *ExecConfig,
14899 OverloadCandidateSet *CandidateSet,
14901 OverloadingResult OverloadResult,
14902 bool AllowTypoCorrection) {
14903 switch (OverloadResult) {
14904 case OR_Success: {
14905 FunctionDecl *FDecl = (*Best)->Function;
14906 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14907 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14908 return ExprError();
14909 ExprResult Res =
14910 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14911 if (Res.isInvalid())
14912 return ExprError();
14913 return SemaRef.BuildResolvedCallExpr(
14914 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14915 /*IsExecConfig=*/false,
14916 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14917 }
14918
14919 case OR_No_Viable_Function: {
14920 if (*Best != CandidateSet->end() &&
14921 CandidateSet->getKind() ==
14923 if (CXXMethodDecl *M =
14924 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14926 CandidateSet->NoteCandidates(
14928 Fn->getBeginLoc(),
14929 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14930 SemaRef, OCD_AmbiguousCandidates, Args);
14931 return ExprError();
14932 }
14933 }
14934
14935 // Try to recover by looking for viable functions which the user might
14936 // have meant to call.
14937 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14938 Args, RParenLoc,
14939 CandidateSet->empty(),
14940 AllowTypoCorrection);
14941 if (Recovery.isInvalid() || Recovery.isUsable())
14942 return Recovery;
14943
14944 // If the user passes in a function that we can't take the address of, we
14945 // generally end up emitting really bad error messages. Here, we attempt to
14946 // emit better ones.
14947 for (const Expr *Arg : Args) {
14948 if (!Arg->getType()->isFunctionType())
14949 continue;
14950 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14951 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14952 if (FD &&
14953 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14954 Arg->getExprLoc()))
14955 return ExprError();
14956 }
14957 }
14958
14959 CandidateSet->NoteCandidates(
14961 Fn->getBeginLoc(),
14962 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14963 << ULE->getName() << Fn->getSourceRange()),
14964 SemaRef, OCD_AllCandidates, Args);
14965 break;
14966 }
14967
14968 case OR_Ambiguous:
14969 CandidateSet->NoteCandidates(
14970 PartialDiagnosticAt(Fn->getBeginLoc(),
14971 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14972 << ULE->getName() << Fn->getSourceRange()),
14973 SemaRef, OCD_AmbiguousCandidates, Args);
14974 break;
14975
14976 case OR_Deleted: {
14977 FunctionDecl *FDecl = (*Best)->Function;
14978 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14979 Fn->getSourceRange(), ULE->getName(),
14980 *CandidateSet, FDecl, Args);
14981
14982 // We emitted an error for the unavailable/deleted function call but keep
14983 // the call in the AST.
14984 ExprResult Res =
14985 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14986 if (Res.isInvalid())
14987 return ExprError();
14988 return SemaRef.BuildResolvedCallExpr(
14989 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14990 /*IsExecConfig=*/false,
14991 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14992 }
14993 }
14994
14995 // Overload resolution failed, try to recover.
14996 SmallVector<Expr *, 8> SubExprs = {Fn};
14997 SubExprs.append(Args.begin(), Args.end());
14998 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14999 chooseRecoveryType(*CandidateSet, Best));
15000}
15001
15004 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15005 if (I->Viable &&
15006 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15007 I->Viable = false;
15008 I->FailureKind = ovl_fail_addr_not_available;
15009 }
15010 }
15011}
15012
15015 SourceLocation LParenLoc,
15016 MultiExprArg Args,
15017 SourceLocation RParenLoc,
15018 Expr *ExecConfig,
15019 bool AllowTypoCorrection,
15020 bool CalleesAddressIsTaken) {
15021
15025
15026 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15027 ExprResult result;
15028
15029 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15030 &result))
15031 return result;
15032
15033 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15034 // functions that aren't addressible are considered unviable.
15035 if (CalleesAddressIsTaken)
15036 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15037
15039 OverloadingResult OverloadResult =
15040 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15041
15042 // [C++23][over.call.func]
15043 // if overload resolution selects a non-static member function,
15044 // the call is ill-formed;
15046 Best != CandidateSet.end()) {
15047 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15048 M && M->isImplicitObjectMemberFunction()) {
15049 OverloadResult = OR_No_Viable_Function;
15050 }
15051 }
15052
15053 // Model the case with a call to a templated function whose definition
15054 // encloses the call and whose return type contains a placeholder type as if
15055 // the UnresolvedLookupExpr was type-dependent.
15056 if (OverloadResult == OR_Success) {
15057 const FunctionDecl *FDecl = Best->Function;
15058 if (LangOpts.CUDA)
15059 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15060 if (FDecl && FDecl->isTemplateInstantiation() &&
15061 FDecl->getReturnType()->isUndeducedType()) {
15062
15063 // Creating dependent CallExpr is not okay if the enclosing context itself
15064 // is not dependent. This situation notably arises if a non-dependent
15065 // member function calls the later-defined overloaded static function.
15066 //
15067 // For example, in
15068 // class A {
15069 // void c() { callee(1); }
15070 // static auto callee(auto x) { }
15071 // };
15072 //
15073 // Here callee(1) is unresolved at the call site, but is not inside a
15074 // dependent context. There will be no further attempt to resolve this
15075 // call if it is made dependent.
15076
15077 if (const auto *TP =
15078 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15079 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15080 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15081 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15082 }
15083 }
15084 }
15085
15086 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15087 ExecConfig, &CandidateSet, &Best,
15088 OverloadResult, AllowTypoCorrection);
15089}
15090
15094 const UnresolvedSetImpl &Fns,
15095 bool PerformADL) {
15097 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15098 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15099}
15100
15103 bool HadMultipleCandidates) {
15104 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15105 // the FoundDecl as it impedes TransformMemberExpr.
15106 // We go a bit further here: if there's no difference in UnderlyingDecl,
15107 // then using FoundDecl vs Method shouldn't make a difference either.
15108 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15109 FoundDecl = Method;
15110 // Convert the expression to match the conversion function's implicit object
15111 // parameter.
15112 ExprResult Exp;
15113 if (Method->isExplicitObjectMemberFunction())
15115 else
15117 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15118 if (Exp.isInvalid())
15119 return true;
15120
15121 if (Method->getParent()->isLambda() &&
15122 Method->getConversionType()->isBlockPointerType()) {
15123 // This is a lambda conversion to block pointer; check if the argument
15124 // was a LambdaExpr.
15125 Expr *SubE = E;
15126 auto *CE = dyn_cast<CastExpr>(SubE);
15127 if (CE && CE->getCastKind() == CK_NoOp)
15128 SubE = CE->getSubExpr();
15129 SubE = SubE->IgnoreParens();
15130 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15131 SubE = BE->getSubExpr();
15132 if (isa<LambdaExpr>(SubE)) {
15133 // For the conversion to block pointer on a lambda expression, we
15134 // construct a special BlockLiteral instead; this doesn't really make
15135 // a difference in ARC, but outside of ARC the resulting block literal
15136 // follows the normal lifetime rules for block literals instead of being
15137 // autoreleased.
15141 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15143
15144 // FIXME: This note should be produced by a CodeSynthesisContext.
15145 if (BlockExp.isInvalid())
15146 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15147 return BlockExp;
15148 }
15149 }
15150 CallExpr *CE;
15151 QualType ResultType = Method->getReturnType();
15153 ResultType = ResultType.getNonLValueExprType(Context);
15154 if (Method->isExplicitObjectMemberFunction()) {
15155 ExprResult FnExpr =
15156 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15157 HadMultipleCandidates, E->getBeginLoc());
15158 if (FnExpr.isInvalid())
15159 return ExprError();
15160 Expr *ObjectParam = Exp.get();
15161 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15162 ResultType, VK, Exp.get()->getEndLoc(),
15164 CE->setUsesMemberSyntax(true);
15165 } else {
15166 MemberExpr *ME =
15167 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15169 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15170 HadMultipleCandidates, DeclarationNameInfo(),
15171 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15172
15173 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15174 Exp.get()->getEndLoc(),
15176 }
15177
15178 if (CheckFunctionCall(Method, CE,
15179 Method->getType()->castAs<FunctionProtoType>()))
15180 return ExprError();
15181
15183}
15184
15187 const UnresolvedSetImpl &Fns,
15188 Expr *Input, bool PerformADL) {
15190 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15191 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15192 // TODO: provide better source location info.
15193 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15194
15195 if (checkPlaceholderForOverload(*this, Input))
15196 return ExprError();
15197
15198 Expr *Args[2] = { Input, nullptr };
15199 unsigned NumArgs = 1;
15200
15201 // For post-increment and post-decrement, add the implicit '0' as
15202 // the second argument, so that we know this is a post-increment or
15203 // post-decrement.
15204 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15205 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15206 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15207 SourceLocation());
15208 NumArgs = 2;
15209 }
15210
15211 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15212
15213 if (Input->isTypeDependent()) {
15215 // [C++26][expr.unary.op][expr.pre.incr]
15216 // The * operator yields an lvalue of type
15217 // The pre/post increment operators yied an lvalue.
15218 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15219 VK = VK_LValue;
15220
15221 if (Fns.empty())
15222 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15223 OK_Ordinary, OpLoc, false,
15225
15226 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15228 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15229 if (Fn.isInvalid())
15230 return ExprError();
15231 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15232 Context.DependentTy, VK_PRValue, OpLoc,
15234 }
15235
15236 // Build an empty overload set.
15238
15239 // Add the candidates from the given function set.
15240 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15241
15242 // Add operator candidates that are member functions.
15243 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15244
15245 // Add candidates from ADL.
15246 if (PerformADL) {
15247 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15248 /*ExplicitTemplateArgs*/nullptr,
15249 CandidateSet);
15250 }
15251
15252 // Add builtin operator candidates.
15253 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15254
15255 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15256
15257 // Perform overload resolution.
15259 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15260 case OR_Success: {
15261 // We found a built-in operator or an overloaded operator.
15262 FunctionDecl *FnDecl = Best->Function;
15263
15264 if (FnDecl) {
15265 Expr *Base = nullptr;
15266 // We matched an overloaded operator. Build a call to that
15267 // operator.
15268
15269 // Convert the arguments.
15270 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15271 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15272
15273 ExprResult InputInit;
15274 if (Method->isExplicitObjectMemberFunction())
15275 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15276 else
15278 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15279 if (InputInit.isInvalid())
15280 return ExprError();
15281 Base = Input = InputInit.get();
15282 } else {
15283 // Convert the arguments.
15284 ExprResult InputInit
15286 Context,
15287 FnDecl->getParamDecl(0)),
15289 Input);
15290 if (InputInit.isInvalid())
15291 return ExprError();
15292 Input = InputInit.get();
15293 }
15294
15295 // Build the actual expression node.
15296 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15297 Base, HadMultipleCandidates,
15298 OpLoc);
15299 if (FnExpr.isInvalid())
15300 return ExprError();
15301
15302 // Determine the result type.
15303 QualType ResultTy = FnDecl->getReturnType();
15305 ResultTy = ResultTy.getNonLValueExprType(Context);
15306
15307 Args[0] = Input;
15309 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15311 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15312
15313 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15314 return ExprError();
15315
15316 if (CheckFunctionCall(FnDecl, TheCall,
15317 FnDecl->getType()->castAs<FunctionProtoType>()))
15318 return ExprError();
15319 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15320 } else {
15321 // We matched a built-in operator. Convert the arguments, then
15322 // break out so that we will build the appropriate built-in
15323 // operator node.
15325 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15328 if (InputRes.isInvalid())
15329 return ExprError();
15330 Input = InputRes.get();
15331 break;
15332 }
15333 }
15334
15336 // This is an erroneous use of an operator which can be overloaded by
15337 // a non-member function. Check for non-member operators which were
15338 // defined too late to be candidates.
15339 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15340 // FIXME: Recover by calling the found function.
15341 return ExprError();
15342
15343 // No viable function; fall through to handling this as a
15344 // built-in operator, which will produce an error message for us.
15345 break;
15346
15347 case OR_Ambiguous:
15348 CandidateSet.NoteCandidates(
15349 PartialDiagnosticAt(OpLoc,
15350 PDiag(diag::err_ovl_ambiguous_oper_unary)
15352 << Input->getType() << Input->getSourceRange()),
15353 *this, OCD_AmbiguousCandidates, ArgsArray,
15354 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15355 return ExprError();
15356
15357 case OR_Deleted: {
15358 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15359 // object whose method was called. Later in NoteCandidates size of ArgsArray
15360 // is passed further and it eventually ends up compared to number of
15361 // function candidate parameters which never includes the object parameter,
15362 // so slice ArgsArray to make sure apples are compared to apples.
15363 StringLiteral *Msg = Best->Function->getDeletedMessage();
15364 CandidateSet.NoteCandidates(
15365 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15367 << (Msg != nullptr)
15368 << (Msg ? Msg->getString() : StringRef())
15369 << Input->getSourceRange()),
15370 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15371 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15372 return ExprError();
15373 }
15374 }
15375
15376 // Either we found no viable overloaded operator or we matched a
15377 // built-in operator. In either case, fall through to trying to
15378 // build a built-in operation.
15379 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15380}
15381
15384 const UnresolvedSetImpl &Fns,
15385 ArrayRef<Expr *> Args, bool PerformADL) {
15386 SourceLocation OpLoc = CandidateSet.getLocation();
15387
15388 OverloadedOperatorKind ExtraOp =
15391 : OO_None;
15392
15393 // Add the candidates from the given function set. This also adds the
15394 // rewritten candidates using these functions if necessary.
15395 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15396
15397 // As template candidates are not deduced immediately,
15398 // persist the array in the overload set.
15399 ArrayRef<Expr *> ReversedArgs;
15400 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15401 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15402 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15403
15404 // Add operator candidates that are member functions.
15405 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15406 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15407 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15409
15410 // In C++20, also add any rewritten member candidates.
15411 if (ExtraOp) {
15412 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15413 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15414 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15416 }
15417
15418 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15419 // performed for an assignment operator (nor for operator[] nor operator->,
15420 // which don't get here).
15421 if (Op != OO_Equal && PerformADL) {
15422 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15423 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15424 /*ExplicitTemplateArgs*/ nullptr,
15425 CandidateSet);
15426 if (ExtraOp) {
15427 DeclarationName ExtraOpName =
15428 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15429 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15430 /*ExplicitTemplateArgs*/ nullptr,
15431 CandidateSet);
15432 }
15433 }
15434
15435 // Add builtin operator candidates.
15436 //
15437 // FIXME: We don't add any rewritten candidates here. This is strictly
15438 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15439 // resulting in our selecting a rewritten builtin candidate. For example:
15440 //
15441 // enum class E { e };
15442 // bool operator!=(E, E) requires false;
15443 // bool k = E::e != E::e;
15444 //
15445 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15446 // it seems unreasonable to consider rewritten builtin candidates. A core
15447 // issue has been filed proposing to removed this requirement.
15448 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15449}
15450
15453 const UnresolvedSetImpl &Fns, Expr *LHS,
15454 Expr *RHS, bool PerformADL,
15455 bool AllowRewrittenCandidates,
15456 FunctionDecl *DefaultedFn) {
15457 Expr *Args[2] = { LHS, RHS };
15458 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15459
15460 if (!getLangOpts().CPlusPlus20)
15461 AllowRewrittenCandidates = false;
15462
15464
15465 // If either side is type-dependent, create an appropriate dependent
15466 // expression.
15467 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15468 if (Fns.empty()) {
15469 // If there are no functions to store, just build a dependent
15470 // BinaryOperator or CompoundAssignment.
15473 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15474 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15475 Context.DependentTy);
15477 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15479 }
15480
15481 // FIXME: save results of ADL from here?
15482 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15483 // TODO: provide better source location info in DNLoc component.
15484 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15485 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15487 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15488 if (Fn.isInvalid())
15489 return ExprError();
15490 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15491 Context.DependentTy, VK_PRValue, OpLoc,
15493 }
15494
15495 // If this is the .* operator, which is not overloadable, just
15496 // create a built-in binary operator.
15497 if (Opc == BO_PtrMemD) {
15498 auto CheckPlaceholder = [&](Expr *&Arg) {
15500 if (Res.isUsable())
15501 Arg = Res.get();
15502 return !Res.isUsable();
15503 };
15504
15505 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15506 // expression that contains placeholders (in either the LHS or RHS).
15507 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15508 return ExprError();
15509 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15510 }
15511
15512 // Always do placeholder-like conversions on the RHS.
15513 if (checkPlaceholderForOverload(*this, Args[1]))
15514 return ExprError();
15515
15516 // Do placeholder-like conversion on the LHS; note that we should
15517 // not get here with a PseudoObject LHS.
15518 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15519 if (checkPlaceholderForOverload(*this, Args[0]))
15520 return ExprError();
15521
15522 // If this is the assignment operator, we only perform overload resolution
15523 // if the left-hand side is a class or enumeration type. This is actually
15524 // a hack. The standard requires that we do overload resolution between the
15525 // various built-in candidates, but as DR507 points out, this can lead to
15526 // problems. So we do it this way, which pretty much follows what GCC does.
15527 // Note that we go the traditional code path for compound assignment forms.
15528 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15529 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15530
15531 // Build the overload set.
15534 Op, OpLoc, AllowRewrittenCandidates));
15535 if (DefaultedFn)
15536 CandidateSet.exclude(DefaultedFn);
15537 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15538
15539 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15540
15541 // Perform overload resolution.
15543 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15544 case OR_Success: {
15545 // We found a built-in operator or an overloaded operator.
15546 FunctionDecl *FnDecl = Best->Function;
15547
15548 bool IsReversed = Best->isReversed();
15549 if (IsReversed)
15550 std::swap(Args[0], Args[1]);
15551
15552 if (FnDecl) {
15553
15554 if (FnDecl->isInvalidDecl())
15555 return ExprError();
15556
15557 Expr *Base = nullptr;
15558 // We matched an overloaded operator. Build a call to that
15559 // operator.
15560
15561 OverloadedOperatorKind ChosenOp =
15563
15564 // C++2a [over.match.oper]p9:
15565 // If a rewritten operator== candidate is selected by overload
15566 // resolution for an operator@, its return type shall be cv bool
15567 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15568 !FnDecl->getReturnType()->isBooleanType()) {
15569 bool IsExtension =
15571 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15572 : diag::err_ovl_rewrite_equalequal_not_bool)
15573 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15574 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15575 Diag(FnDecl->getLocation(), diag::note_declared_at);
15576 if (!IsExtension)
15577 return ExprError();
15578 }
15579
15580 if (AllowRewrittenCandidates && !IsReversed &&
15581 CandidateSet.getRewriteInfo().isReversible()) {
15582 // We could have reversed this operator, but didn't. Check if some
15583 // reversed form was a viable candidate, and if so, if it had a
15584 // better conversion for either parameter. If so, this call is
15585 // formally ambiguous, and allowing it is an extension.
15587 for (OverloadCandidate &Cand : CandidateSet) {
15588 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15589 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15590 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15592 *this, OpLoc, Cand.Conversions[ArgIdx],
15593 Best->Conversions[ArgIdx]) ==
15595 AmbiguousWith.push_back(Cand.Function);
15596 break;
15597 }
15598 }
15599 }
15600 }
15601
15602 if (!AmbiguousWith.empty()) {
15603 bool AmbiguousWithSelf =
15604 AmbiguousWith.size() == 1 &&
15605 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15606 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15608 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15609 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15610 if (AmbiguousWithSelf) {
15611 Diag(FnDecl->getLocation(),
15612 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15613 // Mark member== const or provide matching != to disallow reversed
15614 // args. Eg.
15615 // struct S { bool operator==(const S&); };
15616 // S()==S();
15617 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15618 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15619 !MD->isConst() &&
15620 !MD->hasCXXExplicitFunctionObjectParameter() &&
15621 Context.hasSameUnqualifiedType(
15622 MD->getFunctionObjectParameterType(),
15623 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15624 Context.hasSameUnqualifiedType(
15625 MD->getFunctionObjectParameterType(),
15626 Args[0]->getType()) &&
15627 Context.hasSameUnqualifiedType(
15628 MD->getFunctionObjectParameterType(),
15629 Args[1]->getType()))
15630 Diag(FnDecl->getLocation(),
15631 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15632 } else {
15633 Diag(FnDecl->getLocation(),
15634 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15635 for (auto *F : AmbiguousWith)
15636 Diag(F->getLocation(),
15637 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15638 }
15639 }
15640 }
15641
15642 // Check for nonnull = nullable.
15643 // This won't be caught in the arg's initialization: the parameter to
15644 // the assignment operator is not marked nonnull.
15645 if (Op == OO_Equal)
15647 Args[1]->getType(), OpLoc);
15648
15649 // Convert the arguments.
15650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15651 // Best->Access is only meaningful for class members.
15652 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15653
15654 ExprResult Arg0, Arg1;
15655 unsigned ParamIdx = 0;
15656 if (Method->isExplicitObjectMemberFunction()) {
15657 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15658 ParamIdx = 1;
15659 } else {
15661 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15662 }
15665 Context, FnDecl->getParamDecl(ParamIdx)),
15666 SourceLocation(), Args[1]);
15667 if (Arg0.isInvalid() || Arg1.isInvalid())
15668 return ExprError();
15669
15670 Base = Args[0] = Arg0.getAs<Expr>();
15671 Args[1] = RHS = Arg1.getAs<Expr>();
15672 } else {
15673 // Convert the arguments.
15676 FnDecl->getParamDecl(0)),
15677 SourceLocation(), Args[0]);
15678 if (Arg0.isInvalid())
15679 return ExprError();
15680
15681 ExprResult Arg1 =
15684 FnDecl->getParamDecl(1)),
15685 SourceLocation(), Args[1]);
15686 if (Arg1.isInvalid())
15687 return ExprError();
15688 Args[0] = LHS = Arg0.getAs<Expr>();
15689 Args[1] = RHS = Arg1.getAs<Expr>();
15690 }
15691
15692 // Build the actual expression node.
15693 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15694 Best->FoundDecl, Base,
15695 HadMultipleCandidates, OpLoc);
15696 if (FnExpr.isInvalid())
15697 return ExprError();
15698
15699 // Determine the result type.
15700 QualType ResultTy = FnDecl->getReturnType();
15702 ResultTy = ResultTy.getNonLValueExprType(Context);
15703
15704 CallExpr *TheCall;
15705 ArrayRef<const Expr *> ArgsArray(Args, 2);
15706 const Expr *ImplicitThis = nullptr;
15707
15708 // We always create a CXXOperatorCallExpr, even for explicit object
15709 // members; CodeGen should take care not to emit the this pointer.
15711 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15713 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15714 IsReversed);
15715
15716 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15717 Method && Method->isImplicitObjectMemberFunction()) {
15718 // Cut off the implicit 'this'.
15719 ImplicitThis = ArgsArray[0];
15720 ArgsArray = ArgsArray.slice(1);
15721 }
15722
15723 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15724 FnDecl))
15725 return ExprError();
15726
15727 if (Op == OO_Equal) {
15728 // Check for a self move.
15729 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15730 // lifetime check.
15732 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15733 Args[1]);
15734 }
15735 if (ImplicitThis) {
15736 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15737 QualType ThisTypeFromDecl = Context.getPointerType(
15738 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15739
15740 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15741 ThisTypeFromDecl);
15742 }
15743
15744 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15745 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15747
15748 ExprResult R = MaybeBindToTemporary(TheCall);
15749 if (R.isInvalid())
15750 return ExprError();
15751
15752 R = CheckForImmediateInvocation(R, FnDecl);
15753 if (R.isInvalid())
15754 return ExprError();
15755
15756 // For a rewritten candidate, we've already reversed the arguments
15757 // if needed. Perform the rest of the rewrite now.
15758 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15759 (Op == OO_Spaceship && IsReversed)) {
15760 if (Op == OO_ExclaimEqual) {
15761 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15762 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15763 } else {
15764 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15765 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15766 Expr *ZeroLiteral =
15768
15771 Ctx.Entity = FnDecl;
15773
15775 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15776 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15777 /*AllowRewrittenCandidates=*/false);
15778
15780 }
15781 if (R.isInvalid())
15782 return ExprError();
15783 } else {
15784 assert(ChosenOp == Op && "unexpected operator name");
15785 }
15786
15787 // Make a note in the AST if we did any rewriting.
15788 if (Best->RewriteKind != CRK_None)
15789 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15790
15791 return R;
15792 } else {
15793 // We matched a built-in operator. Convert the arguments, then
15794 // break out so that we will build the appropriate built-in
15795 // operator node.
15797 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15800 if (ArgsRes0.isInvalid())
15801 return ExprError();
15802 Args[0] = ArgsRes0.get();
15803
15805 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15808 if (ArgsRes1.isInvalid())
15809 return ExprError();
15810 Args[1] = ArgsRes1.get();
15811 break;
15812 }
15813 }
15814
15815 case OR_No_Viable_Function: {
15816 // C++ [over.match.oper]p9:
15817 // If the operator is the operator , [...] and there are no
15818 // viable functions, then the operator is assumed to be the
15819 // built-in operator and interpreted according to clause 5.
15820 if (Opc == BO_Comma)
15821 break;
15822
15823 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15824 // compare result using '==' and '<'.
15825 if (DefaultedFn && Opc == BO_Cmp) {
15826 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15827 Args[1], DefaultedFn);
15828 if (E.isInvalid() || E.isUsable())
15829 return E;
15830 }
15831
15832 // For class as left operand for assignment or compound assignment
15833 // operator do not fall through to handling in built-in, but report that
15834 // no overloaded assignment operator found
15836 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15837 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15838 Args, OpLoc);
15839 DeferDiagsRAII DDR(*this,
15840 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15841 if (Args[0]->getType()->isRecordType() &&
15842 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15843 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15845 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15846 if (Args[0]->getType()->isIncompleteType()) {
15847 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15848 << Args[0]->getType()
15849 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15850 }
15851 } else {
15852 // This is an erroneous use of an operator which can be overloaded by
15853 // a non-member function. Check for non-member operators which were
15854 // defined too late to be candidates.
15855 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15856 // FIXME: Recover by calling the found function.
15857 return ExprError();
15858
15859 // No viable function; try to create a built-in operation, which will
15860 // produce an error. Then, show the non-viable candidates.
15861 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15862 }
15863 assert(Result.isInvalid() &&
15864 "C++ binary operator overloading is missing candidates!");
15865 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15866 return Result;
15867 }
15868
15869 case OR_Ambiguous:
15870 CandidateSet.NoteCandidates(
15871 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15873 << Args[0]->getType()
15874 << Args[1]->getType()
15875 << Args[0]->getSourceRange()
15876 << Args[1]->getSourceRange()),
15878 OpLoc);
15879 return ExprError();
15880
15881 case OR_Deleted: {
15882 if (isImplicitlyDeleted(Best->Function)) {
15883 FunctionDecl *DeletedFD = Best->Function;
15885 if (DFK.isSpecialMember()) {
15886 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15887 << Args[0]->getType() << DFK.asSpecialMember();
15888 } else {
15889 assert(DFK.isComparison());
15890 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15891 << Args[0]->getType() << DeletedFD;
15892 }
15893
15894 // The user probably meant to call this special member. Just
15895 // explain why it's deleted.
15896 NoteDeletedFunction(DeletedFD);
15897 return ExprError();
15898 }
15899
15900 StringLiteral *Msg = Best->Function->getDeletedMessage();
15901 CandidateSet.NoteCandidates(
15903 OpLoc,
15904 PDiag(diag::err_ovl_deleted_oper)
15905 << getOperatorSpelling(Best->Function->getDeclName()
15906 .getCXXOverloadedOperator())
15907 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15908 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15910 OpLoc);
15911 return ExprError();
15912 }
15913 }
15914
15915 // We matched a built-in operator; build it.
15916 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15917}
15918
15920 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15921 FunctionDecl *DefaultedFn) {
15922 const ComparisonCategoryInfo *Info =
15923 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15924 // If we're not producing a known comparison category type, we can't
15925 // synthesize a three-way comparison. Let the caller diagnose this.
15926 if (!Info)
15927 return ExprResult((Expr*)nullptr);
15928
15929 // If we ever want to perform this synthesis more generally, we will need to
15930 // apply the temporary materialization conversion to the operands.
15931 assert(LHS->isGLValue() && RHS->isGLValue() &&
15932 "cannot use prvalue expressions more than once");
15933 Expr *OrigLHS = LHS;
15934 Expr *OrigRHS = RHS;
15935
15936 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15937 // each of them multiple times below.
15938 LHS = new (Context)
15939 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15940 LHS->getObjectKind(), LHS);
15941 RHS = new (Context)
15942 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15943 RHS->getObjectKind(), RHS);
15944
15945 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15946 DefaultedFn);
15947 if (Eq.isInvalid())
15948 return ExprError();
15949
15950 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15951 true, DefaultedFn);
15952 if (Less.isInvalid())
15953 return ExprError();
15954
15956 if (Info->isPartial()) {
15957 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15958 DefaultedFn);
15959 if (Greater.isInvalid())
15960 return ExprError();
15961 }
15962
15963 // Form the list of comparisons we're going to perform.
15964 struct Comparison {
15967 } Comparisons[4] =
15973 };
15974
15975 int I = Info->isPartial() ? 3 : 2;
15976
15977 // Combine the comparisons with suitable conditional expressions.
15979 for (; I >= 0; --I) {
15980 // Build a reference to the comparison category constant.
15981 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15982 // FIXME: Missing a constant for a comparison category. Diagnose this?
15983 if (!VI)
15984 return ExprResult((Expr*)nullptr);
15985 ExprResult ThisResult =
15987 if (ThisResult.isInvalid())
15988 return ExprError();
15989
15990 // Build a conditional unless this is the final case.
15991 if (Result.get()) {
15992 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15993 ThisResult.get(), Result.get());
15994 if (Result.isInvalid())
15995 return ExprError();
15996 } else {
15997 Result = ThisResult;
15998 }
15999 }
16000
16001 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16002 // bind the OpaqueValueExprs before they're (repeatedly) used.
16003 Expr *SyntacticForm = BinaryOperator::Create(
16004 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16005 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16007 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16008 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16009}
16010
16012 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16013 MultiExprArg Args, SourceLocation LParenLoc) {
16014
16015 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16016 unsigned NumParams = Proto->getNumParams();
16017 unsigned NumArgsSlots =
16018 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16019 // Build the full argument list for the method call (the implicit object
16020 // parameter is placed at the beginning of the list).
16021 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16022 bool IsError = false;
16023 // Initialize the implicit object parameter.
16024 // Check the argument types.
16025 for (unsigned i = 0; i != NumParams; i++) {
16026 Expr *Arg;
16027 if (i < Args.size()) {
16028 Arg = Args[i];
16029 ExprResult InputInit =
16031 S.Context, Method->getParamDecl(i)),
16032 SourceLocation(), Arg);
16033 IsError |= InputInit.isInvalid();
16034 Arg = InputInit.getAs<Expr>();
16035 } else {
16036 ExprResult DefArg =
16037 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16038 if (DefArg.isInvalid()) {
16039 IsError = true;
16040 break;
16041 }
16042 Arg = DefArg.getAs<Expr>();
16043 }
16044
16045 MethodArgs.push_back(Arg);
16046 }
16047 return IsError;
16048}
16049
16051 SourceLocation RLoc,
16052 Expr *Base,
16053 MultiExprArg ArgExpr) {
16055 Args.push_back(Base);
16056 for (auto *e : ArgExpr) {
16057 Args.push_back(e);
16058 }
16059 DeclarationName OpName =
16060 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16061
16062 SourceRange Range = ArgExpr.empty()
16063 ? SourceRange{}
16064 : SourceRange(ArgExpr.front()->getBeginLoc(),
16065 ArgExpr.back()->getEndLoc());
16066
16067 // If either side is type-dependent, create an appropriate dependent
16068 // expression.
16070
16071 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16072 // CHECKME: no 'operator' keyword?
16073 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16074 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16076 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16077 if (Fn.isInvalid())
16078 return ExprError();
16079 // Can't add any actual overloads yet
16080
16081 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16082 Context.DependentTy, VK_PRValue, RLoc,
16084 }
16085
16086 // Handle placeholders
16087 UnbridgedCastsSet UnbridgedCasts;
16088 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16089 return ExprError();
16090 }
16091 // Build an empty overload set.
16093
16094 // Subscript can only be overloaded as a member function.
16095
16096 // Add operator candidates that are member functions.
16097 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16098
16099 // Add builtin operator candidates.
16100 if (Args.size() == 2)
16101 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16102
16103 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16104
16105 // Perform overload resolution.
16107 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16108 case OR_Success: {
16109 // We found a built-in operator or an overloaded operator.
16110 FunctionDecl *FnDecl = Best->Function;
16111
16112 if (FnDecl) {
16113 // We matched an overloaded operator. Build a call to that
16114 // operator.
16115
16116 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16117
16118 // Convert the arguments.
16120 SmallVector<Expr *, 2> MethodArgs;
16121
16122 // Initialize the object parameter.
16123 if (Method->isExplicitObjectMemberFunction()) {
16124 ExprResult Res =
16126 if (Res.isInvalid())
16127 return ExprError();
16128 Args[0] = Res.get();
16129 ArgExpr = Args;
16130 } else {
16132 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16133 if (Arg0.isInvalid())
16134 return ExprError();
16135
16136 MethodArgs.push_back(Arg0.get());
16137 }
16138
16140 *this, MethodArgs, Method, ArgExpr, LLoc);
16141 if (IsError)
16142 return ExprError();
16143
16144 // Build the actual expression node.
16145 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16146 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16148 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16149 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16150 if (FnExpr.isInvalid())
16151 return ExprError();
16152
16153 // Determine the result type
16154 QualType ResultTy = FnDecl->getReturnType();
16156 ResultTy = ResultTy.getNonLValueExprType(Context);
16157
16159 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16161
16162 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16163 return ExprError();
16164
16165 if (CheckFunctionCall(Method, TheCall,
16166 Method->getType()->castAs<FunctionProtoType>()))
16167 return ExprError();
16168
16170 FnDecl);
16171 } else {
16172 // We matched a built-in operator. Convert the arguments, then
16173 // break out so that we will build the appropriate built-in
16174 // operator node.
16176 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16179 if (ArgsRes0.isInvalid())
16180 return ExprError();
16181 Args[0] = ArgsRes0.get();
16182
16184 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16187 if (ArgsRes1.isInvalid())
16188 return ExprError();
16189 Args[1] = ArgsRes1.get();
16190
16191 break;
16192 }
16193 }
16194
16195 case OR_No_Viable_Function: {
16197 CandidateSet.empty()
16198 ? (PDiag(diag::err_ovl_no_oper)
16199 << Args[0]->getType() << /*subscript*/ 0
16200 << Args[0]->getSourceRange() << Range)
16201 : (PDiag(diag::err_ovl_no_viable_subscript)
16202 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16203 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16204 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16205 return ExprError();
16206 }
16207
16208 case OR_Ambiguous:
16209 if (Args.size() == 2) {
16210 CandidateSet.NoteCandidates(
16212 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16213 << "[]" << Args[0]->getType() << Args[1]->getType()
16214 << Args[0]->getSourceRange() << Range),
16215 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16216 } else {
16217 CandidateSet.NoteCandidates(
16219 PDiag(diag::err_ovl_ambiguous_subscript_call)
16220 << Args[0]->getType()
16221 << Args[0]->getSourceRange() << Range),
16222 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16223 }
16224 return ExprError();
16225
16226 case OR_Deleted: {
16227 StringLiteral *Msg = Best->Function->getDeletedMessage();
16228 CandidateSet.NoteCandidates(
16230 PDiag(diag::err_ovl_deleted_oper)
16231 << "[]" << (Msg != nullptr)
16232 << (Msg ? Msg->getString() : StringRef())
16233 << Args[0]->getSourceRange() << Range),
16234 *this, OCD_AllCandidates, Args, "[]", LLoc);
16235 return ExprError();
16236 }
16237 }
16238
16239 // We matched a built-in operator; build it.
16240 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16241}
16242
16244 SourceLocation LParenLoc,
16245 MultiExprArg Args,
16246 SourceLocation RParenLoc,
16247 Expr *ExecConfig, bool IsExecConfig,
16248 bool AllowRecovery) {
16249 assert(MemExprE->getType() == Context.BoundMemberTy ||
16250 MemExprE->getType() == Context.OverloadTy);
16251
16252 // Dig out the member expression. This holds both the object
16253 // argument and the member function we're referring to.
16254 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16255
16256 // Determine whether this is a call to a pointer-to-member function.
16257 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16258 assert(op->getType() == Context.BoundMemberTy);
16259 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16260
16261 QualType fnType =
16262 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16263
16264 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16265 QualType resultType = proto->getCallResultType(Context);
16267
16268 // Check that the object type isn't more qualified than the
16269 // member function we're calling.
16270 Qualifiers funcQuals = proto->getMethodQuals();
16271
16272 QualType objectType = op->getLHS()->getType();
16273 if (op->getOpcode() == BO_PtrMemI)
16274 objectType = objectType->castAs<PointerType>()->getPointeeType();
16275 Qualifiers objectQuals = objectType.getQualifiers();
16276
16277 Qualifiers difference = objectQuals - funcQuals;
16278 difference.removeObjCGCAttr();
16279 difference.removeAddressSpace();
16280 if (difference) {
16281 std::string qualsString = difference.getAsString();
16282 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16283 << fnType.getUnqualifiedType()
16284 << qualsString
16285 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16286 }
16287
16289 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16291
16292 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16293 call, nullptr))
16294 return ExprError();
16295
16296 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16297 return ExprError();
16298
16299 if (CheckOtherCall(call, proto))
16300 return ExprError();
16301
16302 return MaybeBindToTemporary(call);
16303 }
16304
16305 // We only try to build a recovery expr at this level if we can preserve
16306 // the return type, otherwise we return ExprError() and let the caller
16307 // recover.
16308 auto BuildRecoveryExpr = [&](QualType Type) {
16309 if (!AllowRecovery)
16310 return ExprError();
16311 std::vector<Expr *> SubExprs = {MemExprE};
16312 llvm::append_range(SubExprs, Args);
16313 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16314 Type);
16315 };
16316 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16317 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16318 RParenLoc, CurFPFeatureOverrides());
16319
16320 UnbridgedCastsSet UnbridgedCasts;
16321 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16322 return ExprError();
16323
16324 MemberExpr *MemExpr;
16325 CXXMethodDecl *Method = nullptr;
16326 bool HadMultipleCandidates = false;
16327 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16328 NestedNameSpecifier Qualifier = std::nullopt;
16329 if (isa<MemberExpr>(NakedMemExpr)) {
16330 MemExpr = cast<MemberExpr>(NakedMemExpr);
16332 FoundDecl = MemExpr->getFoundDecl();
16333 Qualifier = MemExpr->getQualifier();
16334 UnbridgedCasts.restore();
16335 } else {
16336 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16337 Qualifier = UnresExpr->getQualifier();
16338
16339 QualType ObjectType = UnresExpr->getBaseType();
16340 Expr::Classification ObjectClassification
16342 : UnresExpr->getBase()->Classify(Context);
16343
16344 // Add overload candidates
16345 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16347
16348 // FIXME: avoid copy.
16349 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16350 if (UnresExpr->hasExplicitTemplateArgs()) {
16351 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16352 TemplateArgs = &TemplateArgsBuffer;
16353 }
16354
16356 E = UnresExpr->decls_end(); I != E; ++I) {
16357
16358 QualType ExplicitObjectType = ObjectType;
16359
16360 NamedDecl *Func = *I;
16361 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16363 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16364
16365 bool HasExplicitParameter = false;
16366 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16367 M && M->hasCXXExplicitFunctionObjectParameter())
16368 HasExplicitParameter = true;
16369 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16370 M &&
16371 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16372 HasExplicitParameter = true;
16373
16374 if (HasExplicitParameter)
16375 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16376
16377 // Microsoft supports direct constructor calls.
16378 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16380 CandidateSet,
16381 /*SuppressUserConversions*/ false);
16382 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16383 // If explicit template arguments were provided, we can't call a
16384 // non-template member function.
16385 if (TemplateArgs)
16386 continue;
16387
16388 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16389 ObjectClassification, Args, CandidateSet,
16390 /*SuppressUserConversions=*/false);
16391 } else {
16393 I.getPair(), ActingDC, TemplateArgs,
16394 ExplicitObjectType, ObjectClassification,
16395 Args, CandidateSet,
16396 /*SuppressUserConversions=*/false);
16397 }
16398 }
16399
16400 HadMultipleCandidates = (CandidateSet.size() > 1);
16401
16402 DeclarationName DeclName = UnresExpr->getMemberName();
16403
16404 UnbridgedCasts.restore();
16405
16407 bool Succeeded = false;
16408 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16409 Best)) {
16410 case OR_Success:
16411 Method = cast<CXXMethodDecl>(Best->Function);
16412 FoundDecl = Best->FoundDecl;
16413 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16414 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16415 break;
16416 // If FoundDecl is different from Method (such as if one is a template
16417 // and the other a specialization), make sure DiagnoseUseOfDecl is
16418 // called on both.
16419 // FIXME: This would be more comprehensively addressed by modifying
16420 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16421 // being used.
16422 if (Method != FoundDecl.getDecl() &&
16424 break;
16425 Succeeded = true;
16426 break;
16427
16429 CandidateSet.NoteCandidates(
16431 UnresExpr->getMemberLoc(),
16432 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16433 << DeclName << MemExprE->getSourceRange()),
16434 *this, OCD_AllCandidates, Args);
16435 break;
16436 case OR_Ambiguous:
16437 CandidateSet.NoteCandidates(
16438 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16439 PDiag(diag::err_ovl_ambiguous_member_call)
16440 << DeclName << MemExprE->getSourceRange()),
16441 *this, OCD_AmbiguousCandidates, Args);
16442 break;
16443 case OR_Deleted:
16445 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16446 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16447 break;
16448 }
16449 // Overload resolution fails, try to recover.
16450 if (!Succeeded)
16451 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16452
16453 ExprResult Res =
16454 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16455 if (Res.isInvalid())
16456 return ExprError();
16457 MemExprE = Res.get();
16458
16459 // If overload resolution picked a static member
16460 // build a non-member call based on that function.
16461 if (Method->isStatic()) {
16462 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16463 ExecConfig, IsExecConfig);
16464 }
16465
16466 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16467 }
16468
16469 QualType ResultType = Method->getReturnType();
16471 ResultType = ResultType.getNonLValueExprType(Context);
16472
16473 assert(Method && "Member call to something that isn't a method?");
16474 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16475
16476 CallExpr *TheCall = nullptr;
16478 if (Method->isExplicitObjectMemberFunction()) {
16479 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16480 NewArgs))
16481 return ExprError();
16482
16483 // Build the actual expression node.
16484 ExprResult FnExpr =
16485 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16486 HadMultipleCandidates, MemExpr->getExprLoc());
16487 if (FnExpr.isInvalid())
16488 return ExprError();
16489
16490 TheCall =
16491 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16492 CurFPFeatureOverrides(), Proto->getNumParams());
16493 TheCall->setUsesMemberSyntax(true);
16494 } else {
16495 // Convert the object argument (for a non-static member function call).
16497 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16498 if (ObjectArg.isInvalid())
16499 return ExprError();
16500 MemExpr->setBase(ObjectArg.get());
16501 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16502 RParenLoc, CurFPFeatureOverrides(),
16503 Proto->getNumParams());
16504 }
16505
16506 // Check for a valid return type.
16507 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16508 TheCall, Method))
16509 return BuildRecoveryExpr(ResultType);
16510
16511 // Convert the rest of the arguments
16512 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16513 RParenLoc))
16514 return BuildRecoveryExpr(ResultType);
16515
16516 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16517
16518 if (CheckFunctionCall(Method, TheCall, Proto))
16519 return ExprError();
16520
16521 // In the case the method to call was not selected by the overloading
16522 // resolution process, we still need to handle the enable_if attribute. Do
16523 // that here, so it will not hide previous -- and more relevant -- errors.
16524 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16525 if (const EnableIfAttr *Attr =
16526 CheckEnableIf(Method, LParenLoc, Args, true)) {
16527 Diag(MemE->getMemberLoc(),
16528 diag::err_ovl_no_viable_member_function_in_call)
16529 << Method << Method->getSourceRange();
16530 Diag(Method->getLocation(),
16531 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16532 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16533 return ExprError();
16534 }
16535 }
16536
16538 TheCall->getDirectCallee()->isPureVirtual()) {
16539 const FunctionDecl *MD = TheCall->getDirectCallee();
16540
16541 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16543 Diag(MemExpr->getBeginLoc(),
16544 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16546 << MD->getParent();
16547
16548 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16549 if (getLangOpts().AppleKext)
16550 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16551 << MD->getParent() << MD->getDeclName();
16552 }
16553 }
16554
16555 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16556 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16557 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16558 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16559 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16560 MemExpr->getMemberLoc());
16561 }
16562
16564 TheCall->getDirectCallee());
16565}
16566
16569 SourceLocation LParenLoc,
16570 MultiExprArg Args,
16571 SourceLocation RParenLoc) {
16572 if (checkPlaceholderForOverload(*this, Obj))
16573 return ExprError();
16574 ExprResult Object = Obj;
16575
16576 UnbridgedCastsSet UnbridgedCasts;
16577 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16578 return ExprError();
16579
16580 assert(Object.get()->getType()->isRecordType() &&
16581 "Requires object type argument");
16582
16583 // C++ [over.call.object]p1:
16584 // If the primary-expression E in the function call syntax
16585 // evaluates to a class object of type "cv T", then the set of
16586 // candidate functions includes at least the function call
16587 // operators of T. The function call operators of T are obtained by
16588 // ordinary lookup of the name operator() in the context of
16589 // (E).operator().
16590 OverloadCandidateSet CandidateSet(LParenLoc,
16592 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16593
16594 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16595 diag::err_incomplete_object_call, Object.get()))
16596 return true;
16597
16598 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16599 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16601 R.suppressAccessDiagnostics();
16602
16603 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16604 Oper != OperEnd; ++Oper) {
16605 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16606 Object.get()->Classify(Context), Args, CandidateSet,
16607 /*SuppressUserConversion=*/false);
16608 }
16609
16610 // When calling a lambda, both the call operator, and
16611 // the conversion operator to function pointer
16612 // are considered. But when constraint checking
16613 // on the call operator fails, it will also fail on the
16614 // conversion operator as the constraints are always the same.
16615 // As the user probably does not intend to perform a surrogate call,
16616 // we filter them out to produce better error diagnostics, ie to avoid
16617 // showing 2 failed overloads instead of one.
16618 bool IgnoreSurrogateFunctions = false;
16619 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16620 const OverloadCandidate &Candidate = *CandidateSet.begin();
16621 if (!Candidate.Viable &&
16623 IgnoreSurrogateFunctions = true;
16624 }
16625
16626 // C++ [over.call.object]p2:
16627 // In addition, for each (non-explicit in C++0x) conversion function
16628 // declared in T of the form
16629 //
16630 // operator conversion-type-id () cv-qualifier;
16631 //
16632 // where cv-qualifier is the same cv-qualification as, or a
16633 // greater cv-qualification than, cv, and where conversion-type-id
16634 // denotes the type "pointer to function of (P1,...,Pn) returning
16635 // R", or the type "reference to pointer to function of
16636 // (P1,...,Pn) returning R", or the type "reference to function
16637 // of (P1,...,Pn) returning R", a surrogate call function [...]
16638 // is also considered as a candidate function. Similarly,
16639 // surrogate call functions are added to the set of candidate
16640 // functions for each conversion function declared in an
16641 // accessible base class provided the function is not hidden
16642 // within T by another intervening declaration.
16643 const auto &Conversions = Record->getVisibleConversionFunctions();
16644 for (auto I = Conversions.begin(), E = Conversions.end();
16645 !IgnoreSurrogateFunctions && I != E; ++I) {
16646 NamedDecl *D = *I;
16647 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16648 if (isa<UsingShadowDecl>(D))
16649 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16650
16651 // Skip over templated conversion functions; they aren't
16652 // surrogates.
16654 continue;
16655
16657 if (!Conv->isExplicit()) {
16658 // Strip the reference type (if any) and then the pointer type (if
16659 // any) to get down to what might be a function type.
16660 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16661 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16662 ConvType = ConvPtrType->getPointeeType();
16663
16664 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16665 {
16666 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16667 Object.get(), Args, CandidateSet);
16668 }
16669 }
16670 }
16671
16672 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16673
16674 // Perform overload resolution.
16676 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16677 Best)) {
16678 case OR_Success:
16679 // Overload resolution succeeded; we'll build the appropriate call
16680 // below.
16681 break;
16682
16683 case OR_No_Viable_Function: {
16685 CandidateSet.empty()
16686 ? (PDiag(diag::err_ovl_no_oper)
16687 << Object.get()->getType() << /*call*/ 1
16688 << Object.get()->getSourceRange())
16689 : (PDiag(diag::err_ovl_no_viable_object_call)
16690 << Object.get()->getType() << Object.get()->getSourceRange());
16691 CandidateSet.NoteCandidates(
16692 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16693 OCD_AllCandidates, Args);
16694 break;
16695 }
16696 case OR_Ambiguous:
16697 if (!R.isAmbiguous())
16698 CandidateSet.NoteCandidates(
16699 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16700 PDiag(diag::err_ovl_ambiguous_object_call)
16701 << Object.get()->getType()
16702 << Object.get()->getSourceRange()),
16703 *this, OCD_AmbiguousCandidates, Args);
16704 break;
16705
16706 case OR_Deleted: {
16707 // FIXME: Is this diagnostic here really necessary? It seems that
16708 // 1. we don't have any tests for this diagnostic, and
16709 // 2. we already issue err_deleted_function_use for this later on anyway.
16710 StringLiteral *Msg = Best->Function->getDeletedMessage();
16711 CandidateSet.NoteCandidates(
16712 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16713 PDiag(diag::err_ovl_deleted_object_call)
16714 << Object.get()->getType() << (Msg != nullptr)
16715 << (Msg ? Msg->getString() : StringRef())
16716 << Object.get()->getSourceRange()),
16717 *this, OCD_AllCandidates, Args);
16718 break;
16719 }
16720 }
16721
16722 if (Best == CandidateSet.end())
16723 return true;
16724
16725 UnbridgedCasts.restore();
16726
16727 if (Best->Function == nullptr) {
16728 // Since there is no function declaration, this is one of the
16729 // surrogate candidates. Dig out the conversion function.
16730 CXXConversionDecl *Conv
16732 Best->Conversions[0].UserDefined.ConversionFunction);
16733
16734 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16735 Best->FoundDecl);
16736 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16737 return ExprError();
16738 assert(Conv == Best->FoundDecl.getDecl() &&
16739 "Found Decl & conversion-to-functionptr should be same, right?!");
16740 // We selected one of the surrogate functions that converts the
16741 // object parameter to a function pointer. Perform the conversion
16742 // on the object argument, then let BuildCallExpr finish the job.
16743
16744 // Create an implicit member expr to refer to the conversion operator.
16745 // and then call it.
16746 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16747 Conv, HadMultipleCandidates);
16748 if (Call.isInvalid())
16749 return ExprError();
16750 // Record usage of conversion in an implicit cast.
16752 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16753 nullptr, VK_PRValue, CurFPFeatureOverrides());
16754
16755 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16756 }
16757
16758 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16759
16760 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16761 // that calls this method, using Object for the implicit object
16762 // parameter and passing along the remaining arguments.
16763 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16764
16765 // An error diagnostic has already been printed when parsing the declaration.
16766 if (Method->isInvalidDecl())
16767 return ExprError();
16768
16769 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16770 unsigned NumParams = Proto->getNumParams();
16771
16772 DeclarationNameInfo OpLocInfo(
16773 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16774 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16775 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16776 Obj, HadMultipleCandidates,
16777 OpLocInfo.getLoc(),
16778 OpLocInfo.getInfo());
16779 if (NewFn.isInvalid())
16780 return true;
16781
16782 SmallVector<Expr *, 8> MethodArgs;
16783 MethodArgs.reserve(NumParams + 1);
16784
16785 bool IsError = false;
16786
16787 // Initialize the object parameter.
16789 if (Method->isExplicitObjectMemberFunction()) {
16790 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16791 } else {
16793 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16794 if (ObjRes.isInvalid())
16795 IsError = true;
16796 else
16797 Object = ObjRes;
16798 MethodArgs.push_back(Object.get());
16799 }
16800
16802 *this, MethodArgs, Method, Args, LParenLoc);
16803
16804 // If this is a variadic call, handle args passed through "...".
16805 if (Proto->isVariadic()) {
16806 // Promote the arguments (C99 6.5.2.2p7).
16807 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16809 Args[i], VariadicCallType::Method, nullptr);
16810 IsError |= Arg.isInvalid();
16811 MethodArgs.push_back(Arg.get());
16812 }
16813 }
16814
16815 if (IsError)
16816 return true;
16817
16818 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16819
16820 // Once we've built TheCall, all of the expressions are properly owned.
16821 QualType ResultTy = Method->getReturnType();
16823 ResultTy = ResultTy.getNonLValueExprType(Context);
16824
16826 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16828
16829 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16830 return true;
16831
16832 if (CheckFunctionCall(Method, TheCall, Proto))
16833 return true;
16834
16836}
16837
16839 SourceLocation OpLoc,
16840 bool *NoArrowOperatorFound) {
16841 assert(Base->getType()->isRecordType() &&
16842 "left-hand side must have class type");
16843
16845 return ExprError();
16846
16847 SourceLocation Loc = Base->getExprLoc();
16848
16849 // C++ [over.ref]p1:
16850 //
16851 // [...] An expression x->m is interpreted as (x.operator->())->m
16852 // for a class object x of type T if T::operator->() exists and if
16853 // the operator is selected as the best match function by the
16854 // overload resolution mechanism (13.3).
16855 DeclarationName OpName =
16856 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16858
16859 if (RequireCompleteType(Loc, Base->getType(),
16860 diag::err_typecheck_incomplete_tag, Base))
16861 return ExprError();
16862
16863 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16864 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16865 R.suppressAccessDiagnostics();
16866
16867 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16868 Oper != OperEnd; ++Oper) {
16869 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16870 {}, CandidateSet,
16871 /*SuppressUserConversion=*/false);
16872 }
16873
16874 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16875
16876 // Perform overload resolution.
16878 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16879 case OR_Success:
16880 // Overload resolution succeeded; we'll build the call below.
16881 break;
16882
16883 case OR_No_Viable_Function: {
16884 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16885 if (CandidateSet.empty()) {
16886 QualType BaseType = Base->getType();
16887 if (NoArrowOperatorFound) {
16888 // Report this specific error to the caller instead of emitting a
16889 // diagnostic, as requested.
16890 *NoArrowOperatorFound = true;
16891 return ExprError();
16892 }
16893 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16894 << BaseType << Base->getSourceRange();
16895 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16896 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16897 << FixItHint::CreateReplacement(OpLoc, ".");
16898 }
16899 } else
16900 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16901 << "operator->" << Base->getSourceRange();
16902 CandidateSet.NoteCandidates(*this, Base, Cands);
16903 return ExprError();
16904 }
16905 case OR_Ambiguous:
16906 if (!R.isAmbiguous())
16907 CandidateSet.NoteCandidates(
16908 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16909 << "->" << Base->getType()
16910 << Base->getSourceRange()),
16912 return ExprError();
16913
16914 case OR_Deleted: {
16915 StringLiteral *Msg = Best->Function->getDeletedMessage();
16916 CandidateSet.NoteCandidates(
16917 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16918 << "->" << (Msg != nullptr)
16919 << (Msg ? Msg->getString() : StringRef())
16920 << Base->getSourceRange()),
16921 *this, OCD_AllCandidates, Base);
16922 return ExprError();
16923 }
16924 }
16925
16926 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16927
16928 // Convert the object parameter.
16929 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16930
16931 if (Method->isExplicitObjectMemberFunction()) {
16933 if (R.isInvalid())
16934 return ExprError();
16935 Base = R.get();
16936 } else {
16938 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16939 if (BaseResult.isInvalid())
16940 return ExprError();
16941 Base = BaseResult.get();
16942 }
16943
16944 // Build the operator call.
16945 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16946 Base, HadMultipleCandidates, OpLoc);
16947 if (FnExpr.isInvalid())
16948 return ExprError();
16949
16950 QualType ResultTy = Method->getReturnType();
16952 ResultTy = ResultTy.getNonLValueExprType(Context);
16953
16954 CallExpr *TheCall =
16955 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16956 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16957
16958 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16959 return ExprError();
16960
16961 if (CheckFunctionCall(Method, TheCall,
16962 Method->getType()->castAs<FunctionProtoType>()))
16963 return ExprError();
16964
16966}
16967
16969 DeclarationNameInfo &SuffixInfo,
16970 ArrayRef<Expr*> Args,
16971 SourceLocation LitEndLoc,
16972 TemplateArgumentListInfo *TemplateArgs) {
16973 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16974
16975 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16977 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16978 TemplateArgs);
16979
16980 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16981
16982 // Perform overload resolution. This will usually be trivial, but might need
16983 // to perform substitutions for a literal operator template.
16985 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16986 case OR_Success:
16987 case OR_Deleted:
16988 break;
16989
16991 CandidateSet.NoteCandidates(
16992 PartialDiagnosticAt(UDSuffixLoc,
16993 PDiag(diag::err_ovl_no_viable_function_in_call)
16994 << R.getLookupName()),
16995 *this, OCD_AllCandidates, Args);
16996 return ExprError();
16997
16998 case OR_Ambiguous:
16999 CandidateSet.NoteCandidates(
17000 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17001 << R.getLookupName()),
17002 *this, OCD_AmbiguousCandidates, Args);
17003 return ExprError();
17004 }
17005
17006 FunctionDecl *FD = Best->Function;
17007 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
17008 nullptr, HadMultipleCandidates,
17009 SuffixInfo.getLoc(),
17010 SuffixInfo.getInfo());
17011 if (Fn.isInvalid())
17012 return true;
17013
17014 // Check the argument types. This should almost always be a no-op, except
17015 // that array-to-pointer decay is applied to string literals.
17016 Expr *ConvArgs[2];
17017 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17020 SourceLocation(), Args[ArgIdx]);
17021 if (InputInit.isInvalid())
17022 return true;
17023 ConvArgs[ArgIdx] = InputInit.get();
17024 }
17025
17026 QualType ResultTy = FD->getReturnType();
17028 ResultTy = ResultTy.getNonLValueExprType(Context);
17029
17031 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17032 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17033
17034 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17035 return ExprError();
17036
17037 if (CheckFunctionCall(FD, UDL, nullptr))
17038 return ExprError();
17039
17041}
17042
17045 SourceLocation RangeLoc,
17046 const DeclarationNameInfo &NameInfo,
17047 LookupResult &MemberLookup,
17048 OverloadCandidateSet *CandidateSet,
17049 Expr *Range, ExprResult *CallExpr) {
17050 Scope *S = nullptr;
17051
17053 if (!MemberLookup.empty()) {
17054 ExprResult MemberRef =
17055 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17056 /*IsPtr=*/false, CXXScopeSpec(),
17057 /*TemplateKWLoc=*/SourceLocation(),
17058 /*FirstQualifierInScope=*/nullptr,
17059 MemberLookup,
17060 /*TemplateArgs=*/nullptr, S);
17061 if (MemberRef.isInvalid()) {
17062 *CallExpr = ExprError();
17063 return FRS_DiagnosticIssued;
17064 }
17065 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17066 if (CallExpr->isInvalid()) {
17067 *CallExpr = ExprError();
17068 return FRS_DiagnosticIssued;
17069 }
17070 } else {
17071 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17073 NameInfo, UnresolvedSet<0>());
17074 if (FnR.isInvalid())
17075 return FRS_DiagnosticIssued;
17077
17078 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17079 CandidateSet, CallExpr);
17080 if (CandidateSet->empty() || CandidateSetError) {
17081 *CallExpr = ExprError();
17082 return FRS_NoViableFunction;
17083 }
17085 OverloadingResult OverloadResult =
17086 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17087
17088 if (OverloadResult == OR_No_Viable_Function) {
17089 *CallExpr = ExprError();
17090 return FRS_NoViableFunction;
17091 }
17092 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17093 Loc, nullptr, CandidateSet, &Best,
17094 OverloadResult,
17095 /*AllowTypoCorrection=*/false);
17096 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17097 *CallExpr = ExprError();
17098 return FRS_DiagnosticIssued;
17099 }
17100 }
17101 return FRS_Success;
17102}
17103
17105 FunctionDecl *Fn) {
17106 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17107 ExprResult SubExpr =
17108 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17109 if (SubExpr.isInvalid())
17110 return ExprError();
17111 if (SubExpr.get() == PE->getSubExpr())
17112 return PE;
17113
17114 return new (Context)
17115 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17116 }
17117
17118 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17119 ExprResult SubExpr =
17120 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17121 if (SubExpr.isInvalid())
17122 return ExprError();
17123 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17124 SubExpr.get()->getType()) &&
17125 "Implicit cast type cannot be determined from overload");
17126 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17127 if (SubExpr.get() == ICE->getSubExpr())
17128 return ICE;
17129
17130 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17131 SubExpr.get(), nullptr, ICE->getValueKind(),
17133 }
17134
17135 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17136 if (!GSE->isResultDependent()) {
17137 ExprResult SubExpr =
17138 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17139 if (SubExpr.isInvalid())
17140 return ExprError();
17141 if (SubExpr.get() == GSE->getResultExpr())
17142 return GSE;
17143
17144 // Replace the resulting type information before rebuilding the generic
17145 // selection expression.
17146 ArrayRef<Expr *> A = GSE->getAssocExprs();
17147 SmallVector<Expr *, 4> AssocExprs(A);
17148 unsigned ResultIdx = GSE->getResultIndex();
17149 AssocExprs[ResultIdx] = SubExpr.get();
17150
17151 if (GSE->isExprPredicate())
17153 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17154 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17155 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17156 ResultIdx);
17158 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17159 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17160 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17161 ResultIdx);
17162 }
17163 // Rather than fall through to the unreachable, return the original generic
17164 // selection expression.
17165 return GSE;
17166 }
17167
17168 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17169 assert(UnOp->getOpcode() == UO_AddrOf &&
17170 "Can only take the address of an overloaded function");
17171 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17172 if (!Method->isImplicitObjectMemberFunction()) {
17173 // Do nothing: the address of static and
17174 // explicit object member functions is a (non-member) function pointer.
17175 } else {
17176 // Fix the subexpression, which really has to be an
17177 // UnresolvedLookupExpr holding an overloaded member function
17178 // or template.
17179 ExprResult SubExpr =
17180 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17181 if (SubExpr.isInvalid())
17182 return ExprError();
17183 if (SubExpr.get() == UnOp->getSubExpr())
17184 return UnOp;
17185
17186 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17187 SubExpr.get(), Method))
17188 return ExprError();
17189
17190 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17191 "fixed to something other than a decl ref");
17192 NestedNameSpecifier Qualifier =
17193 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17194 assert(Qualifier &&
17195 "fixed to a member ref with no nested name qualifier");
17196
17197 // We have taken the address of a pointer to member
17198 // function. Perform the computation here so that we get the
17199 // appropriate pointer to member type.
17200 QualType MemPtrType = Context.getMemberPointerType(
17201 Fn->getType(), Qualifier,
17202 cast<CXXRecordDecl>(Method->getDeclContext()));
17203 // Under the MS ABI, lock down the inheritance model now.
17204 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17205 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17206
17207 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17208 MemPtrType, VK_PRValue, OK_Ordinary,
17209 UnOp->getOperatorLoc(), false,
17211 }
17212 }
17213 ExprResult SubExpr =
17214 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17215 if (SubExpr.isInvalid())
17216 return ExprError();
17217 if (SubExpr.get() == UnOp->getSubExpr())
17218 return UnOp;
17219
17220 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17221 SubExpr.get());
17222 }
17223
17224 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17225 if (Found.getAccess() == AS_none) {
17227 }
17228 // FIXME: avoid copy.
17229 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17230 if (ULE->hasExplicitTemplateArgs()) {
17231 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17232 TemplateArgs = &TemplateArgsBuffer;
17233 }
17234
17235 QualType Type = Fn->getType();
17236 ExprValueKind ValueKind =
17237 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17238 ? VK_LValue
17239 : VK_PRValue;
17240
17241 // FIXME: Duplicated from BuildDeclarationNameExpr.
17242 if (unsigned BID = Fn->getBuiltinID()) {
17243 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17244 Type = Context.BuiltinFnTy;
17245 ValueKind = VK_PRValue;
17246 }
17247 }
17248
17250 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17251 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17252 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17253 return DRE;
17254 }
17255
17256 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17257 // FIXME: avoid copy.
17258 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17259 if (MemExpr->hasExplicitTemplateArgs()) {
17260 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17261 TemplateArgs = &TemplateArgsBuffer;
17262 }
17263
17264 Expr *Base;
17265
17266 // If we're filling in a static method where we used to have an
17267 // implicit member access, rewrite to a simple decl ref.
17268 if (MemExpr->isImplicitAccess()) {
17269 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17271 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17272 MemExpr->getQualifierLoc(), Found.getDecl(),
17273 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17274 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17275 return DRE;
17276 } else {
17277 SourceLocation Loc = MemExpr->getMemberLoc();
17278 if (MemExpr->getQualifier())
17279 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17280 Base =
17281 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17282 }
17283 } else
17284 Base = MemExpr->getBase();
17285
17286 ExprValueKind valueKind;
17287 QualType type;
17288 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17289 valueKind = VK_LValue;
17290 type = Fn->getType();
17291 } else {
17292 valueKind = VK_PRValue;
17293 type = Context.BoundMemberTy;
17294 }
17295
17296 return BuildMemberExpr(
17297 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17298 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17299 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17300 type, valueKind, OK_Ordinary, TemplateArgs);
17301 }
17302
17303 llvm_unreachable("Invalid reference to overloaded function");
17304}
17305
17311
17312bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17314 if (!PartialOverloading || !Function)
17315 return true;
17316 if (Function->isVariadic())
17317 return false;
17318 if (const auto *Proto =
17319 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17320 if (Proto->isTemplateVariadic())
17321 return false;
17322 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17323 if (const auto *Proto =
17324 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17325 if (Proto->isTemplateVariadic())
17326 return false;
17327 return true;
17328}
17329
17331 DeclarationName Name,
17332 OverloadCandidateSet &CandidateSet,
17333 FunctionDecl *Fn, MultiExprArg Args,
17334 bool IsMember) {
17335 StringLiteral *Msg = Fn->getDeletedMessage();
17336 CandidateSet.NoteCandidates(
17337 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17338 << IsMember << Name << (Msg != nullptr)
17339 << (Msg ? Msg->getString() : StringRef())
17340 << Range),
17341 *this, OCD_AllCandidates, Args);
17342}
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.
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.
__device__ __2f16 b
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:481
bool isFloat() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
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:809
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:959
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:925
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:924
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:3947
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:3777
QualType getElementType() const
Definition TypeBase.h:3789
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8235
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2180
StringRef getOpcodeStr() const
Definition Expr.h:4107
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2133
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:5094
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
Pointer to a block type.
Definition TypeBase.h:3597
This class is used for builtin types like 'int'.
Definition TypeBase.h:3219
Kind getKind() const
Definition TypeBase.h:3267
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:2620
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3071
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:3108
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2952
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2984
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2988
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
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:694
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
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:2721
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:2728
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2872
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
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:624
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:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1987
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:1742
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:75
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:180
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:2946
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:1517
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3110
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3328
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:3330
QualType getElementType() const
Definition TypeBase.h:3340
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:5116
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3815
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4442
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4461
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4458
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
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:1273
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:1466
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:547
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:931
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:786
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:771
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:762
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:598
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4029
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4247
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4145
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1955
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1939
const Expr * getExpr() const
Definition DeclCXX.h:1940
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2372
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1466
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:3095
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:3086
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:3339
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4229
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
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:814
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:4068
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h: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:4322
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3178
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
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:104
Represents a function declaration or definition.
Definition Decl.h:2018
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2707
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4188
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3757
param_iterator param_end()
Definition Decl.h:2805
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3661
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3860
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
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:4259
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4308
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3742
param_iterator param_begin()
Definition Decl.h:2804
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3128
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4324
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4252
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3864
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2488
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4125
bool isConsteval() const
Definition Decl.h:2500
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3705
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:2880
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:3710
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3821
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2703
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5362
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5866
unsigned getNumParams() const
Definition TypeBase.h:5640
Qualifiers getMethodQuals() const
Definition TypeBase.h:5788
QualType getParamType(unsigned i) const
Definition TypeBase.h:5642
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5766
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5802
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:4669
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4740
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4597
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4558
ExtInfo getExtInfo() const
Definition TypeBase.h:4914
CallingConv getCallConv() const
Definition TypeBase.h:4913
QualType getReturnType() const
Definition TypeBase.h:4898
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4926
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:4716
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:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
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:5302
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5415
unsigned getNumInits() const
Definition Expr.h:5332
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2496
const Expr * getInit(unsigned Init) const
Definition Expr.h:5354
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2514
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:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3672
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:4406
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3478
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3464
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3585
Expr * getBase() const
Definition Expr.h:3444
void setBase(Expr *E)
Definition Expr.h:3443
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1794
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3562
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3454
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3708
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3740
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5582
QualType getPointeeType() const
Definition TypeBase.h:3726
Describes a module or submodule.
Definition Module.h:301
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:239
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:1681
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:7998
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8054
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8143
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8112
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8066
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8106
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:8118
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
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
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
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1549
@ 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
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:3132
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3284
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3248
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3245
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3223
decls_iterator decls_begin() const
Definition ExprCXX.h:3225
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3236
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3258
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3254
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3342
decls_iterator decls_end() const
Definition ExprCXX.h:3228
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3242
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
Represents a parameter to a function.
Definition Decl.h:1808
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3053
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3383
QualType getPointeeType() const
Definition TypeBase.h:3393
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5188
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8520
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8514
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8525
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3677
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1236
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8436
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8562
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8476
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:8621
QualType getCanonicalType() const
Definition TypeBase.h:8488
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8530
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
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:8590
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8509
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8557
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8482
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1343
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:8601
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8468
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8376
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8383
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4787
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:860
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
bool hasOnlyConst() const
Definition TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasRestrict() const
Definition TypeBase.h:477
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:708
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeUnaligned()
Definition TypeBase.h:515
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3690
Represents a struct/union/class.
Definition Decl.h:4343
field_range fields() const
Definition Decl.h:4546
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3628
QualType getPointeeType() const
Definition TypeBase.h:3646
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:1505
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1550
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:455
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:402
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:10404
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:6436
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6465
RAII class to control scope of DeferDiags.
Definition Sema.h:10127
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1386
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1421
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:12551
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12585
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:1448
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:10145
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:9415
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9442
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9427
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
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:416
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:1473
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:10487
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10490
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10496
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10494
@ AR_dependent
Definition Sema.h:1688
@ AR_accessible
Definition Sema.h:1686
@ AR_inaccessible
Definition Sema.h:1687
@ AR_delayed
Definition Sema.h:1689
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:2077
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:1725
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:1308
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:686
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:226
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
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:1518
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:759
ASTContext & getASTContext() const
Definition Sema.h:939
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:762
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....
@ FRS_Success
Definition Sema.h:10875
@ FRS_DiagnosticIssued
Definition Sema.h:10877
@ FRS_NoViableFunction
Definition Sema.h:10876
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9408
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:10196
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:1212
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:3638
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:12249
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:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:1306
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:1483
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9407
MemberPointerConversionDirection
Definition Sema.h:10328
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:10515
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:644
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:15625
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
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:7058
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:1446
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:8261
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:14063
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:7555
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:13796
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:15580
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:125
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:6821
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6790
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:10320
SourceManager & SourceMgr
Definition Sema.h:1311
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1310
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
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:6498
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:1453
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:8743
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:1802
StringRef getString() const
Definition Expr.h:1870
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:679
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:733
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:718
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:3556
The base class of the type hierarchy.
Definition TypeBase.h:1871
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2538
bool isBlockPointerType() const
Definition TypeBase.h:8693
bool isVoidType() const
Definition TypeBase.h:9039
bool isBooleanType() const
Definition TypeBase.h:9176
bool isObjCBuiltinType() const
Definition TypeBase.h:8903
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
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:8780
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isFloat16Type() const
Definition TypeBase.h:9048
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:2173
bool isRValueReferenceType() const
Definition TypeBase.h:8705
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:8776
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9206
bool isArrayType() const
Definition TypeBase.h:8772
bool isCharType() const
Definition Type.cpp:2193
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9111
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2422
bool isPointerType() const
Definition TypeBase.h:8673
bool isArrayParameterType() const
Definition TypeBase.h:8788
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9083
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2667
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9333
bool isReferenceType() const
Definition TypeBase.h:8697
bool isEnumeralType() const
Definition TypeBase.h:8804
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8873
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:9161
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2229
bool isExtVectorBoolType() const
Definition TypeBase.h:8820
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8860
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2845
bool isLValueReferenceType() const
Definition TypeBase.h:8701
bool isBitIntType() const
Definition TypeBase.h:8948
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2837
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2503
bool isAnyComplexType() const
Definition TypeBase.h:8808
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9099
bool isHalfType() const
Definition TypeBase.h:9043
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9021
bool isQueueT() const
Definition TypeBase.h:8929
bool isMemberPointerType() const
Definition TypeBase.h:8754
bool isObjCIdType() const
Definition TypeBase.h:8885
bool isMatrixType() const
Definition TypeBase.h:8836
bool isOverflowBehaviorType() const
Definition TypeBase.h:8844
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9182
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2563
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8921
bool isBFloat16Type() const
Definition TypeBase.h:9060
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8669
bool isObjCObjectPointerType() const
Definition TypeBase.h:8852
bool isVectorType() const
Definition TypeBase.h:8812
bool isObjCClassType() const
Definition TypeBase.h:8891
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2688
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2976
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8996
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:2332
bool isAnyPointerType() const
Definition TypeBase.h:8681
TypeClass getTypeClass() const
Definition TypeBase.h:2438
bool isSamplerT() const
Definition TypeBase.h:8917
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9266
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:9076
bool isRecordType() const
Definition TypeBase.h:8800
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1430
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:5151
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1406
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3459
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:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4234
QualType getBaseType() const
Definition ExprCXX.h:4208
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4218
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4199
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4244
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4238
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:644
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:968
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4245
QualType getElementType() const
Definition TypeBase.h:4244
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, CodePtr &PC)
Definition Interp.h:258
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:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
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:61
@ 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:667
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1793
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1796
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1799
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:1045
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:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
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:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
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:587
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:216
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
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:151
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:310
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
@ 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:180
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
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:5975
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:448
__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:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
Extra information about a function prototype.
Definition TypeBase.h:5447
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5452
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:10607
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10614
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13287
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13333
Abstract class used to diagnose incomplete types.
Definition Sema.h:8342
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
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.