clang 24.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaHLSL.h"
39#include "clang/Sema/SemaObjC.h"
41#include "clang/Sema/Template.h"
43#include "llvm/ADT/DenseSet.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/STLForwardCompat.h"
46#include "llvm/ADT/ScopeExit.h"
47#include "llvm/ADT/SmallPtrSet.h"
48#include "llvm/ADT/SmallVector.h"
49#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdlib>
53#include <optional>
54
55using namespace clang;
56using namespace sema;
57
59
61 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
62 return P->hasAttr<PassObjectSizeAttr>();
63 });
64}
65
66/// A convenience routine for creating a decayed reference to a function.
68 Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
69 FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
70 bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo,
71 const TemplateArgumentListInfo *TemplateArgs) {
72 SourceLocation Loc = NameInfo.getLoc();
73
74 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
75 return ExprError();
76 // If FoundDecl is different from Fn (such as if one is a template
77 // and the other a specialization), make sure DiagnoseUseOfDecl is
78 // called on both.
79 // FIXME: This would be more comprehensively addressed by modifying
80 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
81 // being used.
82 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
83 return ExprError();
84 auto *DRE = DeclRefExpr::Create(S.Context, QualifierLoc, TemplateKWLoc, Fn,
85 /*RefersToEnclosingVariableOrCapture=*/false,
86 NameInfo, Fn->getType(), VK_LValue, FoundDecl,
87 TemplateArgs);
88 if (HadMultipleCandidates)
89 DRE->setHadMultipleCandidates(true);
90
92 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
93 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
94 S.ResolveExceptionSpec(Loc, FPT);
95 DRE->setType(Fn->getType());
96 }
97 }
98 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
99 CK_FunctionToPointerDecay);
100}
101
103 NamedDecl *FoundDecl, const Expr *Base,
104 bool HadMultipleCandidates,
105 const DeclarationNameInfo &NameInfo) {
106 return CreateFunctionRefExpr(S, /*QualifierLoc=*/{}, /*TemplateKWLoc=*/{}, Fn,
107 FoundDecl, Base, HadMultipleCandidates, NameInfo,
108 /*TemplateArgs=*/nullptr);
109}
110
112 NamedDecl *FoundDecl, const Expr *Base,
113 bool HadMultipleCandidates,
114 SourceLocation Loc) {
115 return CreateFunctionRefExpr(S, Fn, FoundDecl, Base, HadMultipleCandidates,
116 DeclarationNameInfo(Fn->getDeclName(), Loc));
117}
118
119static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
120 bool InOverloadResolution,
122 bool CStyle,
123 bool AllowObjCWritebackConversion);
124
126 QualType &ToType,
127 bool InOverloadResolution,
129 bool CStyle);
131IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
133 OverloadCandidateSet& Conversions,
134 AllowedExplicit AllowExplicit,
135 bool AllowObjCConversionOnExplicit);
136
139 const StandardConversionSequence& SCS1,
140 const StandardConversionSequence& SCS2);
141
144 const StandardConversionSequence& SCS1,
145 const StandardConversionSequence& SCS2);
146
149 const StandardConversionSequence &SCS1,
150 const StandardConversionSequence &SCS2);
151
154 const StandardConversionSequence& SCS1,
155 const StandardConversionSequence& SCS2);
156
157/// GetConversionRank - Retrieve the implicit conversion rank
158/// corresponding to the given implicit conversion kind.
160 static const ImplicitConversionRank Rank[] = {
187 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
188 // it was omitted by the patch that added
189 // ICK_Zero_Event_Conversion
190 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
191 // it was omitted by the patch that added
192 // ICK_Zero_Queue_Conversion
202 };
203 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
204 return Rank[(int)Kind];
205}
206
225
226/// GetImplicitConversionName - Return the name of this kind of
227/// implicit conversion.
229 static const char *const Name[] = {
230 "No conversion",
231 "Lvalue-to-rvalue",
232 "Array-to-pointer",
233 "Function-to-pointer",
234 "Function pointer conversion",
235 "Qualification",
236 "Integral promotion",
237 "Floating point promotion",
238 "Complex promotion",
239 "Integral conversion",
240 "Floating conversion",
241 "Complex conversion",
242 "Floating-integral conversion",
243 "Pointer conversion",
244 "Pointer-to-member conversion",
245 "Boolean conversion",
246 "Compatible-types conversion",
247 "Derived-to-base conversion",
248 "Vector conversion",
249 "SVE Vector conversion",
250 "RVV Vector conversion",
251 "Vector splat",
252 "Complex-real conversion",
253 "Block Pointer conversion",
254 "Transparent Union Conversion",
255 "Writeback conversion",
256 "OpenCL Zero Event Conversion",
257 "OpenCL Zero Queue Conversion",
258 "C specific type conversion",
259 "Incompatible pointer conversion",
260 "Fixed point conversion",
261 "HLSL vector truncation",
262 "HLSL matrix truncation",
263 "Non-decaying array conversion",
264 "HLSL vector splat",
265 "HLSL matrix splat",
266 "HLSL packed type conversion",
267 };
268 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
269 return Name[Kind];
270}
271
272/// StandardConversionSequence - Set the standard conversion
273/// sequence to the identity conversion.
291
292/// getRank - Retrieve the rank of this standard conversion sequence
293/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
294/// implicit conversions.
307
308/// isPointerConversionToBool - Determines whether this conversion is
309/// a conversion of a pointer or pointer-to-member to bool. This is
310/// used as part of the ranking of standard conversion sequences
311/// (C++ 13.3.3.2p4).
313 // Note that FromType has not necessarily been transformed by the
314 // array-to-pointer or function-to-pointer implicit conversions, so
315 // check for their presence as well as checking whether FromType is
316 // a pointer.
317 if (getToType(1)->isBooleanType() &&
318 (getFromType()->isPointerType() ||
319 getFromType()->isMemberPointerType() ||
320 getFromType()->isObjCObjectPointerType() ||
321 getFromType()->isBlockPointerType() ||
323 return true;
324
325 return false;
326}
327
328/// isPointerConversionToVoidPointer - Determines whether this
329/// conversion is a conversion of a pointer to a void pointer. This is
330/// used as part of the ranking of standard conversion sequences (C++
331/// 13.3.3.2p4).
332bool
335 QualType FromType = getFromType();
336 QualType ToType = getToType(1);
337
338 // Note that FromType has not necessarily been transformed by the
339 // array-to-pointer implicit conversion, so check for its presence
340 // and redo the conversion to get a pointer.
342 FromType = Context.getArrayDecayedType(FromType);
343
344 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
345 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
346 return ToPtrType->getPointeeType()->isVoidType();
347
348 return false;
349}
350
351/// Skip any implicit casts which could be either part of a narrowing conversion
352/// or after one in an implicit conversion.
354 const Expr *Converted) {
355 // We can have cleanups wrapping the converted expression; these need to be
356 // preserved so that destructors run if necessary.
357 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
358 Expr *Inner =
359 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
360 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
361 EWC->getObjects());
362 }
363
364 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
365 switch (ICE->getCastKind()) {
366 case CK_NoOp:
367 case CK_IntegralCast:
368 case CK_IntegralToBoolean:
369 case CK_IntegralToFloating:
370 case CK_BooleanToSignedIntegral:
371 case CK_FloatingToIntegral:
372 case CK_FloatingToBoolean:
373 case CK_FloatingCast:
374 Converted = ICE->getSubExpr();
375 continue;
376
377 default:
378 return Converted;
379 }
380 }
381
382 return Converted;
383}
384
385/// Check if this standard conversion sequence represents a narrowing
386/// conversion, according to C++11 [dcl.init.list]p7.
387///
388/// \param Ctx The AST context.
389/// \param Converted The result of applying this standard conversion sequence.
390/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
391/// value of the expression prior to the narrowing conversion.
392/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
393/// type of the expression prior to the narrowing conversion.
394/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
395/// from floating point types to integral types should be ignored.
396/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
397/// to conform MSVC compiler behavior.
399 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
400 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
401 bool AllowRelaxedEval) const {
402 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
403 "narrowing check outside C++");
404
405 // C++11 [dcl.init.list]p7:
406 // A narrowing conversion is an implicit conversion ...
407 QualType FromType = getToType(0);
408 QualType ToType = getToType(1);
409
410 // A conversion to an enumeration type is narrowing if the conversion to
411 // the underlying type is narrowing. This only arises for expressions of
412 // the form 'Enum{init}'.
413 if (const auto *ED = ToType->getAsEnumDecl())
414 ToType = ED->getIntegerType();
415
416 switch (Second) {
417 // 'bool' is an integral type; dispatch to the right place to handle it.
419 if (FromType->isRealFloatingType())
420 goto FloatingIntegralConversion;
422 goto IntegralConversion;
423 // -- from a pointer type or pointer-to-member type to bool, or
424 return NK_Type_Narrowing;
425
426 // -- from a floating-point type to an integer type, or
427 //
428 // -- from an integer type or unscoped enumeration type to a floating-point
429 // type, except where the source is a constant expression and the actual
430 // value after conversion will fit into the target type and will produce
431 // the original value when converted back to the original type, or
433 FloatingIntegralConversion:
434 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
435 return NK_Type_Narrowing;
436 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
437 ToType->isRealFloatingType()) {
438 if (IgnoreFloatToIntegralConversion)
439 return NK_Not_Narrowing;
440 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
441 assert(Initializer && "Unknown conversion expression");
442
443 // If it's value-dependent, we can't tell whether it's narrowing.
444 if (Initializer->isValueDependent())
446
447 if (std::optional<llvm::APSInt> IntConstantValue =
448 Initializer->getIntegerConstantExpr(Ctx)) {
449 // Convert the integer to the floating type.
450 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
451 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
452 llvm::APFloat::rmNearestTiesToEven);
453 // And back.
454 llvm::APSInt ConvertedValue = *IntConstantValue;
455 bool ignored;
456 llvm::APFloat::opStatus Status = Result.convertToInteger(
457 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
458 // If the converted-back integer has unspecified value, or if the
459 // resulting value is different, this was a narrowing conversion.
460 if (Status == llvm::APFloat::opInvalidOp ||
461 *IntConstantValue != ConvertedValue) {
462 ConstantValue = APValue(*IntConstantValue);
463 ConstantType = Initializer->getType();
465 }
466 } else {
467 // Variables are always narrowings.
469 }
470 }
471 return NK_Not_Narrowing;
472
473 // -- from long double to double or float, or from double to float, except
474 // where the source is a constant expression and the actual value after
475 // conversion is within the range of values that can be represented (even
476 // if it cannot be represented exactly), or
478 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
479 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
480 // FromType is larger than ToType.
481 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
482
483 // If it's value-dependent, we can't tell whether it's narrowing.
484 if (Initializer->isValueDependent())
486
488 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
489 ((Ctx.getLangOpts().CPlusPlus &&
490 Initializer->isCXX11ConstantExpr(Ctx, ConstantValue,
491 AllowRelaxedEval)))) {
492 // Constant!
493 if (Ctx.getLangOpts().C23)
494 ConstantValue = R.Val;
495 assert(ConstantValue.isFloat());
496 llvm::APFloat FloatVal = ConstantValue.getFloat();
497 // Convert the source value into the target type.
498 bool ignored;
499 llvm::APFloat Converted = FloatVal;
500 llvm::APFloat::opStatus ConvertStatus =
501 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
502 llvm::APFloat::rmNearestTiesToEven, &ignored);
503 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
504 llvm::APFloat::rmNearestTiesToEven, &ignored);
505 if (Ctx.getLangOpts().C23) {
506 if (FloatVal.isNaN() && Converted.isNaN() &&
507 !FloatVal.isSignaling() && !Converted.isSignaling()) {
508 // Quiet NaNs are considered the same value, regardless of
509 // payloads.
510 return NK_Not_Narrowing;
511 }
512 // For normal values, check exact equality.
513 if (!Converted.bitwiseIsEqual(FloatVal)) {
514 ConstantType = Initializer->getType();
516 }
517 } else {
518 // If there was no overflow, the source value is within the range of
519 // values that can be represented.
520 if (ConvertStatus & llvm::APFloat::opOverflow) {
521 ConstantType = Initializer->getType();
523 }
524 }
525 } else {
527 }
528 }
529 return NK_Not_Narrowing;
530
531 // -- from an integer type or unscoped enumeration type to an integer type
532 // that cannot represent all the values of the original type, except where
533 // (CWG2627) -- the source is a bit-field whose width w is less than that
534 // of its type (or, for an enumeration type, its underlying type) and the
535 // target type can represent all the values of a hypothetical extended
536 // integer type with width w and with the same signedness as the original
537 // type or
538 // -- the source is a constant expression and the actual value after
539 // conversion will fit into the target type and will produce the original
540 // value when converted back to the original type.
542 IntegralConversion: {
543 assert(FromType->isIntegralOrUnscopedEnumerationType());
544 assert(ToType->isIntegralOrUnscopedEnumerationType());
545 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
546 unsigned FromWidth = Ctx.getIntWidth(FromType);
547 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
548 const unsigned ToWidth = Ctx.getIntWidth(ToType);
549
550 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
551 bool ToSigned, unsigned ToWidth) {
552 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
553 !(FromSigned && !ToSigned);
554 };
555
556 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
557 return NK_Not_Narrowing;
558
559 // Not all values of FromType can be represented in ToType.
560 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
561
562 bool DependentBitField = false;
563 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
564 if (BitField->getBitWidth()->isValueDependent())
565 DependentBitField = true;
566 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
567 BitFieldWidth < FromWidth) {
568 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
569 return NK_Not_Narrowing;
570
571 // The initializer will be truncated to the bit-field width
572 FromWidth = BitFieldWidth;
573 }
574 }
575
576 // If it's value-dependent, we can't tell whether it's narrowing.
577 if (Initializer->isValueDependent())
579
580 std::optional<llvm::APSInt> OptInitializerValue =
581 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
582 if (!OptInitializerValue) {
583 // If the bit-field width was dependent, it might end up being small
584 // enough to fit in the target type (unless the target type is unsigned
585 // and the source type is signed, in which case it will never fit)
586 if (DependentBitField && !(FromSigned && !ToSigned))
588
589 // Otherwise, such a conversion is always narrowing
591 }
592 llvm::APSInt &InitializerValue = *OptInitializerValue;
593 bool Narrowing = false;
594 if (FromWidth < ToWidth) {
595 // Negative -> unsigned is narrowing. Otherwise, more bits is never
596 // narrowing.
597 if (InitializerValue.isSigned() && InitializerValue.isNegative())
598 Narrowing = true;
599 } else {
600 // Add a bit to the InitializerValue so we don't have to worry about
601 // signed vs. unsigned comparisons.
602 InitializerValue =
603 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
604 // Convert the initializer to and from the target width and signed-ness.
605 llvm::APSInt ConvertedValue = InitializerValue;
606 ConvertedValue = ConvertedValue.trunc(ToWidth);
607 ConvertedValue.setIsSigned(ToSigned);
608 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
609 ConvertedValue.setIsSigned(InitializerValue.isSigned());
610 // If the result is different, this was a narrowing conversion.
611 if (ConvertedValue != InitializerValue)
612 Narrowing = true;
613 }
614 if (Narrowing) {
615 ConstantType = Initializer->getType();
616 ConstantValue = APValue(InitializerValue);
618 }
619
620 return NK_Not_Narrowing;
621 }
622 case ICK_Complex_Real:
623 if (FromType->isComplexType() && !ToType->isComplexType())
624 return NK_Type_Narrowing;
625 return NK_Not_Narrowing;
626
628 if (Ctx.getLangOpts().C23) {
629 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
631 if (Initializer->EvaluateAsRValue(R, Ctx)) {
632 ConstantValue = R.Val;
633 assert(ConstantValue.isFloat());
634 llvm::APFloat FloatVal = ConstantValue.getFloat();
635 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
636 // value, the unqualified versions of the type of the initializer and
637 // the corresponding real type of the object declared shall be
638 // compatible.
639 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
640 ConstantType = Initializer->getType();
642 }
643 }
644 }
645 return NK_Not_Narrowing;
646 default:
647 // Other kinds of conversions are not narrowings.
648 return NK_Not_Narrowing;
649 }
650}
651
652/// dump - Print this standard conversion sequence to standard
653/// error. Useful for debugging overloading issues.
654LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
655 raw_ostream &OS = llvm::errs();
656 bool PrintedSomething = false;
657 if (First != ICK_Identity) {
659 PrintedSomething = true;
660 }
661
662 if (Second != ICK_Identity) {
663 if (PrintedSomething) {
664 OS << " -> ";
665 }
667
668 if (CopyConstructor) {
669 OS << " (by copy constructor)";
670 } else if (DirectBinding) {
671 OS << " (direct reference binding)";
672 } else if (ReferenceBinding) {
673 OS << " (reference binding)";
674 }
675 PrintedSomething = true;
676 }
677
678 if (Third != ICK_Identity) {
679 if (PrintedSomething) {
680 OS << " -> ";
681 }
683 PrintedSomething = true;
684 }
685
686 if (!PrintedSomething) {
687 OS << "No conversions required";
688 }
689}
690
691/// dump - Print this user-defined conversion sequence to standard
692/// error. Useful for debugging overloading issues.
694 raw_ostream &OS = llvm::errs();
695 if (Before.First || Before.Second || Before.Third) {
696 Before.dump();
697 OS << " -> ";
698 }
700 OS << '\'' << *ConversionFunction << '\'';
701 else
702 OS << "aggregate initialization";
703 if (After.First || After.Second || After.Third) {
704 OS << " -> ";
705 After.dump();
706 }
707}
708
709/// dump - Print this implicit conversion sequence to standard
710/// error. Useful for debugging overloading issues.
712 raw_ostream &OS = llvm::errs();
714 OS << "Worst list element conversion: ";
715 switch (ConversionKind) {
717 OS << "Standard conversion: ";
718 Standard.dump();
719 break;
721 OS << "User-defined conversion: ";
722 UserDefined.dump();
723 break;
725 OS << "Ellipsis conversion";
726 break;
728 OS << "Ambiguous conversion";
729 break;
730 case BadConversion:
731 OS << "Bad conversion";
732 break;
733 }
734
735 OS << "\n";
736}
737
741
743 conversions().~ConversionSet();
744}
745
746void
752
753namespace {
754 // Structure used by DeductionFailureInfo to store
755 // template argument information.
756 struct DFIArguments {
757 TemplateArgument FirstArg;
758 TemplateArgument SecondArg;
759 };
760 // Structure used by DeductionFailureInfo to store
761 // template parameter and template argument information.
762 struct DFIParamWithArguments : DFIArguments {
763 TemplateParameter Param;
764 };
765 // Structure used by DeductionFailureInfo to store template argument
766 // information and the index of the problematic call argument.
767 struct DFIDeducedMismatchArgs : DFIArguments {
768 TemplateArgumentList *TemplateArgs;
769 unsigned CallArgIndex;
770 };
771 // Structure used by DeductionFailureInfo to store information about
772 // unsatisfied constraints.
773 struct CNSInfo {
774 TemplateArgumentList *TemplateArgs;
775 ConstraintSatisfaction Satisfaction;
776 };
777}
778
779/// Convert from Sema's representation of template deduction information
780/// to the form used in overload-candidate information.
784 TemplateDeductionInfo &Info) {
786 Result.Result = static_cast<unsigned>(TDK);
787 Result.HasDiagnostic = false;
788 switch (TDK) {
795 Result.Data = nullptr;
796 break;
797
799 Result.Data = Info.Param.getOpaqueValue();
800 break;
802 Result.Data = Info.Param.getOpaqueValue();
803 if (Info.hasSFINAEDiagnostic()) {
807 Result.HasDiagnostic = true;
808 }
809 break;
810
813 // FIXME: Should allocate from normal heap so that we can free this later.
814 auto *Saved = new (Context) DFIDeducedMismatchArgs;
815 Saved->FirstArg = Info.FirstArg;
816 Saved->SecondArg = Info.SecondArg;
817 Saved->TemplateArgs = Info.takeSugared();
818 Saved->CallArgIndex = Info.CallArgIndex;
819 Result.Data = Saved;
820 break;
821 }
822
824 // FIXME: Should allocate from normal heap so that we can free this later.
825 DFIArguments *Saved = new (Context) DFIArguments;
826 Saved->FirstArg = Info.FirstArg;
827 Saved->SecondArg = Info.SecondArg;
828 Result.Data = Saved;
829 break;
830 }
831
833 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
836 // FIXME: Should allocate from normal heap so that we can free this later.
837 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
838 Saved->Param = Info.Param;
839 Saved->FirstArg = Info.FirstArg;
840 Saved->SecondArg = Info.SecondArg;
841 Result.Data = Saved;
842 break;
843 }
844
846 Result.Data = Info.takeSugared();
847 if (Info.hasSFINAEDiagnostic()) {
851 Result.HasDiagnostic = true;
852 }
853 break;
854
856 CNSInfo *Saved = new (Context) CNSInfo;
857 Saved->TemplateArgs = Info.takeSugared();
858 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
859 Result.Data = Saved;
860 break;
861 }
862
866 llvm_unreachable("not a deduction failure");
867 }
868
869 return Result;
870}
871
873 switch (static_cast<TemplateDeductionResult>(Result)) {
882 break;
883
890 // FIXME: Destroy the data?
891 Data = nullptr;
892 break;
893
896 // FIXME: Destroy the template argument list?
897 Data = nullptr;
899 Diag->~PartialDiagnosticAt();
900 HasDiagnostic = false;
901 }
902 break;
903
905 // FIXME: Destroy the template argument list?
906 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
907 Data = nullptr;
909 Diag->~PartialDiagnosticAt();
910 HasDiagnostic = false;
911 }
912 break;
913
914 // Unhandled
917 break;
918 }
919}
920
922 if (HasDiagnostic)
923 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
924 return nullptr;
925}
926
960
996
1028
1060
1062 switch (static_cast<TemplateDeductionResult>(Result)) {
1065 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1066
1067 default:
1068 return std::nullopt;
1069 }
1070}
1071
1073 const FunctionDecl *Y) {
1074 if (!X || !Y)
1075 return false;
1076 if (X->getNumParams() != Y->getNumParams())
1077 return false;
1078 // FIXME: when do rewritten comparison operators
1079 // with explicit object parameters correspond?
1080 // https://cplusplus.github.io/CWG/issues/2797.html
1081 for (unsigned I = 0; I < X->getNumParams(); ++I)
1082 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1083 Y->getParamDecl(I)->getType()))
1084 return false;
1085 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1086 auto *FTY = Y->getDescribedFunctionTemplate();
1087 if (!FTY)
1088 return false;
1089 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1090 FTY->getTemplateParameters()))
1091 return false;
1092 }
1093 return true;
1094}
1095
1097 Expr *FirstOperand, FunctionDecl *EqFD) {
1098 assert(EqFD->getOverloadedOperator() ==
1099 OverloadedOperatorKind::OO_EqualEqual);
1100 // C++2a [over.match.oper]p4:
1101 // A non-template function or function template F named operator== is a
1102 // rewrite target with first operand o unless a search for the name operator!=
1103 // in the scope S from the instantiation context of the operator expression
1104 // finds a function or function template that would correspond
1105 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1106 // scope of the class type of o if F is a class member, and the namespace
1107 // scope of which F is a member otherwise. A function template specialization
1108 // named operator== is a rewrite target if its function template is a rewrite
1109 // target.
1111 OverloadedOperatorKind::OO_ExclaimEqual);
1112 if (isa<CXXMethodDecl>(EqFD)) {
1113 // If F is a class member, search scope is class type of first operand.
1114 QualType RHS = FirstOperand->getType();
1115 auto *RHSRec = RHS->getAsCXXRecordDecl();
1116 if (!RHSRec)
1117 return true;
1118 LookupResult Members(S, NotEqOp, OpLoc,
1120 S.LookupQualifiedName(Members, RHSRec);
1121 Members.suppressAccessDiagnostics();
1122 for (NamedDecl *Op : Members)
1123 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1124 return false;
1125 return true;
1126 }
1127 // Otherwise the search scope is the namespace scope of which F is a member.
1128 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1129 auto *NotEqFD = Op->getAsFunction();
1130 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1131 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1132 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1134 cast<Decl>(Op->getLexicalDeclContext())))
1135 return false;
1136 }
1137 return true;
1138}
1139
1141 OverloadedOperatorKind Op) const {
1143 return false;
1144 return Op == OO_EqualEqual || Op == OO_Spaceship;
1145}
1146
1148 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1149 auto Op = FD->getOverloadedOperator();
1150 if (!allowsReversed(Op))
1151 return false;
1152 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1153 assert(OriginalArgs.size() == 2);
1155 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1156 return false;
1157 }
1158 // Don't bother adding a reversed candidate that can never be a better
1159 // match than the non-reversed version.
1160 return FD->getNumNonObjectParams() != 2 ||
1162 FD->getParamDecl(1)->getType()) ||
1163 FD->hasAttr<EnableIfAttr>();
1164}
1165
1166void OverloadCandidateSet::destroyCandidates() {
1167 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1168 for (auto &C : i->Conversions)
1169 C.~ImplicitConversionSequence();
1170 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1171 i->DeductionFailure.Destroy();
1172 }
1173}
1174
1176 destroyCandidates();
1177 SlabAllocator.Reset();
1178 NumInlineBytesUsed = 0;
1179 Candidates.clear();
1180 Functions.clear();
1181 Kind = CSK;
1182 FirstDeferredCandidate = nullptr;
1183 DeferredCandidatesCount = 0;
1184 HasDeferredTemplateConstructors = false;
1185 ResolutionByPerfectCandidateIsDisabled = false;
1186}
1187
1188namespace {
1189 class UnbridgedCastsSet {
1190 struct Entry {
1191 Expr **Addr;
1192 Expr *Saved;
1193 };
1194 SmallVector<Entry, 2> Entries;
1195
1196 public:
1197 void save(Sema &S, Expr *&E) {
1198 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1199 Entry entry = { &E, E };
1200 Entries.push_back(entry);
1201 E = S.ObjC().stripARCUnbridgedCast(E);
1202 }
1203
1204 void restore() {
1205 for (SmallVectorImpl<Entry>::iterator
1206 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1207 *i->Addr = i->Saved;
1208 }
1209 };
1210}
1211
1212/// checkPlaceholderForOverload - Do any interesting placeholder-like
1213/// preprocessing on the given expression.
1214///
1215/// \param unbridgedCasts a collection to which to add unbridged casts;
1216/// without this, they will be immediately diagnosed as errors
1217///
1218/// Return true on unrecoverable error.
1219static bool
1221 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1222 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1223 // We can't handle overloaded expressions here because overload
1224 // resolution might reasonably tweak them.
1225 if (placeholder->getKind() == BuiltinType::Overload) return false;
1226
1227 // If the context potentially accepts unbridged ARC casts, strip
1228 // the unbridged cast and add it to the collection for later restoration.
1229 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1230 unbridgedCasts) {
1231 unbridgedCasts->save(S, E);
1232 return false;
1233 }
1234
1235 // Go ahead and check everything else.
1236 ExprResult result = S.CheckPlaceholderExpr(E);
1237 if (result.isInvalid())
1238 return true;
1239
1240 E = result.get();
1241 return false;
1242 }
1243
1244 // Nothing to do.
1245 return false;
1246}
1247
1248/// checkArgPlaceholdersForOverload - Check a set of call operands for
1249/// placeholders.
1251 UnbridgedCastsSet &unbridged) {
1252 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1253 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1254 return true;
1255
1256 return false;
1257}
1258
1260 const LookupResult &Old, NamedDecl *&Match,
1261 bool NewIsUsingDecl) {
1262 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1263 I != E; ++I) {
1264 NamedDecl *OldD = *I;
1265
1266 bool OldIsUsingDecl = false;
1267 if (isa<UsingShadowDecl>(OldD)) {
1268 OldIsUsingDecl = true;
1269
1270 // We can always introduce two using declarations into the same
1271 // context, even if they have identical signatures.
1272 if (NewIsUsingDecl) continue;
1273
1274 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1275 }
1276
1277 // A using-declaration does not conflict with another declaration
1278 // if one of them is hidden.
1279 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1280 continue;
1281
1282 // If either declaration was introduced by a using declaration,
1283 // we'll need to use slightly different rules for matching.
1284 // Essentially, these rules are the normal rules, except that
1285 // function templates hide function templates with different
1286 // return types or template parameter lists.
1287 bool UseMemberUsingDeclRules =
1288 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1289 !New->getFriendObjectKind();
1290
1291 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1292 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1293 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1295 continue;
1296 }
1297
1298 if (!isa<FunctionTemplateDecl>(OldD) &&
1299 !shouldLinkPossiblyHiddenDecl(*I, New))
1300 continue;
1301
1302 Match = *I;
1303 return OverloadKind::Match;
1304 }
1305
1306 // Builtins that have custom typechecking or have a reference should
1307 // not be overloadable or redeclarable.
1308 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1309 Match = *I;
1311 }
1312 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1313 // We can overload with these, which can show up when doing
1314 // redeclaration checks for UsingDecls.
1315 assert(Old.getLookupKind() == LookupUsingDeclName);
1316 } else if (isa<TagDecl>(OldD)) {
1317 // We can always overload with tags by hiding them.
1318 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1319 // Optimistically assume that an unresolved using decl will
1320 // overload; if it doesn't, we'll have to diagnose during
1321 // template instantiation.
1322 //
1323 // Exception: if the scope is dependent and this is not a class
1324 // member, the using declaration can only introduce an enumerator.
1325 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1326 Match = *I;
1328 }
1329 } else {
1330 // (C++ 13p1):
1331 // Only function declarations can be overloaded; object and type
1332 // declarations cannot be overloaded.
1333 Match = *I;
1335 }
1336 }
1337
1338 // C++ [temp.friend]p1:
1339 // For a friend function declaration that is not a template declaration:
1340 // -- if the name of the friend is a qualified or unqualified template-id,
1341 // [...], otherwise
1342 // -- if the name of the friend is a qualified-id and a matching
1343 // non-template function is found in the specified class or namespace,
1344 // the friend declaration refers to that function, otherwise,
1345 // -- if the name of the friend is a qualified-id and a matching function
1346 // template is found in the specified class or namespace, the friend
1347 // declaration refers to the deduced specialization of that function
1348 // template, otherwise
1349 // -- the name shall be an unqualified-id [...]
1350 // If we get here for a qualified friend declaration, we've just reached the
1351 // third bullet. If the type of the friend is dependent, skip this lookup
1352 // until instantiation.
1353 if (New->getFriendObjectKind() && New->getQualifier() &&
1354 !New->getDescribedFunctionTemplate() &&
1355 !New->getDependentSpecializationInfo() &&
1356 !New->getType()->isDependentType()) {
1357 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1358 TemplateSpecResult.addAllDecls(Old);
1359 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1360 /*QualifiedFriend*/true)) {
1361 New->setInvalidDecl();
1363 }
1364
1365 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1366 return OverloadKind::Match;
1367 }
1368
1370}
1371
1372template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1373 assert(D && "function decl should not be null");
1374 if (auto *A = D->getAttr<AttrT>())
1375 return !A->isImplicit();
1376 return false;
1377}
1378
1380 FunctionDecl *Old,
1381 bool UseMemberUsingDeclRules,
1382 bool ConsiderCudaAttrs,
1383 bool UseOverrideRules = false) {
1384 // C++ [basic.start.main]p2: This function shall not be overloaded.
1385 if (New->isMain())
1386 return false;
1387
1388 // MSVCRT user defined entry points cannot be overloaded.
1389 if (New->isMSVCRTEntryPoint())
1390 return false;
1391
1392 NamedDecl *OldDecl = Old;
1393 NamedDecl *NewDecl = New;
1395 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1396
1397 // C++ [temp.fct]p2:
1398 // A function template can be overloaded with other function templates
1399 // and with normal (non-template) functions.
1400 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1401 return true;
1402
1403 // Is the function New an overload of the function Old?
1404 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1405 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1406
1407 // Compare the signatures (C++ 1.3.10) of the two functions to
1408 // determine whether they are overloads. If we find any mismatch
1409 // in the signature, they are overloads.
1410
1411 // If either of these functions is a K&R-style function (no
1412 // prototype), then we consider them to have matching signatures.
1413 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1415 return false;
1416
1417 const auto *OldType = cast<FunctionProtoType>(OldQType);
1418 const auto *NewType = cast<FunctionProtoType>(NewQType);
1419
1420 // The signature of a function includes the types of its
1421 // parameters (C++ 1.3.10), which includes the presence or absence
1422 // of the ellipsis; see C++ DR 357).
1423 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1424 return true;
1425
1426 // For member-like friends, the enclosing class is part of the signature.
1427 if ((New->isMemberLikeConstrainedFriend() ||
1429 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1430 return true;
1431
1432 // Compare the parameter lists.
1433 // This can only be done once we have establish that friend functions
1434 // inhabit the same context, otherwise we might tried to instantiate
1435 // references to non-instantiated entities during constraint substitution.
1436 // GH78101.
1437 if (NewTemplate) {
1438 OldDecl = OldTemplate;
1439 NewDecl = NewTemplate;
1440 // C++ [temp.over.link]p4:
1441 // The signature of a function template consists of its function
1442 // signature, its return type and its template parameter list. The names
1443 // of the template parameters are significant only for establishing the
1444 // relationship between the template parameters and the rest of the
1445 // signature.
1446 //
1447 // We check the return type and template parameter lists for function
1448 // templates first; the remaining checks follow.
1449 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1450 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1451 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1452 bool SameReturnType = SemaRef.Context.hasSameType(
1453 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1454 // FIXME(GH58571): Match template parameter list even for non-constrained
1455 // template heads. This currently ensures that the code prior to C++20 is
1456 // not newly broken.
1457 bool ConstraintsInTemplateHead =
1460 // C++ [namespace.udecl]p11:
1461 // The set of declarations named by a using-declarator that inhabits a
1462 // class C does not include member functions and member function
1463 // templates of a base class that "correspond" to (and thus would
1464 // conflict with) a declaration of a function or function template in
1465 // C.
1466 // Comparing return types is not required for the "correspond" check to
1467 // decide whether a member introduced by a shadow declaration is hidden.
1468 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1469 !SameTemplateParameterList)
1470 return true;
1471 if (!UseMemberUsingDeclRules &&
1472 (!SameTemplateParameterList || !SameReturnType))
1473 return true;
1474 }
1475
1476 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1477 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1478
1479 int OldParamsOffset = 0;
1480 int NewParamsOffset = 0;
1481
1482 // When determining if a method is an overload from a base class, act as if
1483 // the implicit object parameter are of the same type.
1484
1485 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1487 auto ThisType = M->getFunctionObjectParameterReferenceType();
1488 if (ThisType.isConstQualified())
1489 Q.removeConst();
1490 return Q;
1491 }
1492
1493 // We do not allow overloading based off of '__restrict'.
1494 Q.removeRestrict();
1495
1496 // We may not have applied the implicit const for a constexpr member
1497 // function yet (because we haven't yet resolved whether this is a static
1498 // or non-static member function). Add it now, on the assumption that this
1499 // is a redeclaration of OldMethod.
1500 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1501 (M->isConstexpr() || M->isConsteval()) &&
1502 !isa<CXXConstructorDecl>(NewMethod))
1503 Q.addConst();
1504 return Q;
1505 };
1506
1507 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1508 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1509 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1510
1511 if (OldMethod->isExplicitObjectMemberFunction()) {
1512 BS.Quals.removeVolatile();
1513 DS.Quals.removeVolatile();
1514 }
1515
1516 return BS.Quals == DS.Quals;
1517 };
1518
1519 auto CompareType = [&](QualType Base, QualType D) {
1520 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1521 auto DS = D.getNonReferenceType().getCanonicalType().split();
1522
1523 if (!AreQualifiersEqual(BS, DS))
1524 return false;
1525
1526 if (OldMethod->isImplicitObjectMemberFunction() &&
1527 OldMethod->getParent() != NewMethod->getParent()) {
1528 CanQualType ParentType =
1529 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1530 if (ParentType.getTypePtr() != BS.Ty)
1531 return false;
1532 BS.Ty = DS.Ty;
1533 }
1534
1535 // FIXME: should we ignore some type attributes here?
1536 if (BS.Ty != DS.Ty)
1537 return false;
1538
1539 if (Base->isLValueReferenceType())
1540 return D->isLValueReferenceType();
1541 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1542 };
1543
1544 // If the function is a class member, its signature includes the
1545 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1546 auto DiagnoseInconsistentRefQualifiers = [&]() {
1547 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1548 return false;
1549 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1550 return false;
1551 if (OldMethod->isExplicitObjectMemberFunction() ||
1552 NewMethod->isExplicitObjectMemberFunction())
1553 return false;
1554 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1555 NewMethod->getRefQualifier() == RQ_None)) {
1556 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1557 << OldMethod->getRefQualifier() << NewMethod->getRefQualifier();
1558 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1559 return true;
1560 }
1561 return false;
1562 };
1563
1564 // We look at the parameters first, as it is the common case.
1565 // However we should not emit diagnostic before checking
1566 // the overloads do not differ by constraints or other discriminant.
1567 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1568 bool HaveInconsistentQualifiers = false;
1569
1570 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1571 OldParamsOffset++;
1572 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1573 NewParamsOffset++;
1574
1575 if (OldType->getNumParams() - OldParamsOffset !=
1576 NewType->getNumParams() - NewParamsOffset ||
1578 {OldType->param_type_begin() + OldParamsOffset,
1579 OldType->param_type_end()},
1580 {NewType->param_type_begin() + NewParamsOffset,
1581 NewType->param_type_end()},
1582 nullptr)) {
1583 return true;
1584 }
1585
1586 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1587 !NewMethod->isStatic()) {
1588 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1589 const CXXMethodDecl *New) {
1590 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1591 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1592
1593 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1594 return F->getRefQualifier() == RQ_None &&
1595 !F->isExplicitObjectMemberFunction();
1596 };
1597
1598 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1599 CompareType(OldObjectType.getNonReferenceType(),
1600 NewObjectType.getNonReferenceType()))
1601 return true;
1602 return CompareType(OldObjectType, NewObjectType);
1603 }(OldMethod, NewMethod);
1604
1605 if (!HaveCorrespondingObjectParameters) {
1606 ShouldDiagnoseInconsistentRefQualifiers = true;
1607 // CWG2554
1608 // and, if at least one is an explicit object member function, ignoring
1609 // object parameters
1610 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1611 !OldMethod->isExplicitObjectMemberFunction()))
1612 HaveInconsistentQualifiers = true;
1613 }
1614 }
1615
1616 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1617 NewMethod->isImplicitObjectMemberFunction())
1618 ShouldDiagnoseInconsistentRefQualifiers = true;
1619
1620 if (!UseOverrideRules &&
1621 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1622 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1623 OldRC = Old->getTrailingRequiresClause();
1624 if (!NewRC != !OldRC)
1625 return true;
1626 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1627 return true;
1628 if (NewRC &&
1629 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1630 NewDecl, NewRC.ConstraintExpr))
1631 return true;
1632 }
1633
1634 // Though pass_object_size is placed on parameters and takes an argument, we
1635 // consider it to be a function-level modifier for the sake of function
1636 // identity. Either the function has one or more parameters with
1637 // pass_object_size or it doesn't.
1640 return true;
1641
1642 // enable_if attributes are an order-sensitive part of the signature.
1644 NewI = New->specific_attr_begin<EnableIfAttr>(),
1645 NewE = New->specific_attr_end<EnableIfAttr>(),
1646 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1647 OldE = Old->specific_attr_end<EnableIfAttr>();
1648 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1649 if (NewI == NewE || OldI == OldE)
1650 return true;
1651 llvm::FoldingSetNodeID NewID, OldID;
1652 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1653 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1654 if (NewID != OldID)
1655 return true;
1656 }
1657
1658 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1659 DiagnoseInconsistentRefQualifiers()) ||
1660 HaveInconsistentQualifiers)
1661 return true;
1662
1663 // At this point, it is known that the two functions have the same signature.
1664 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1665 // Don't allow overloading of destructors. (In theory we could, but it
1666 // would be a giant change to clang.)
1668 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1669 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1670 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1671 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1672 "Unexpected invalid target.");
1673
1674 // Allow overloading of functions with same signature and different CUDA
1675 // target attributes.
1676 if (NewTarget != OldTarget) {
1677 // Special case: non-constexpr function is allowed to override
1678 // constexpr virtual function
1679 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1680 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1685 return false;
1686 }
1687 return true;
1688 }
1689 }
1690 }
1691 }
1692
1693 // The signatures match; this is not an overload.
1694 return false;
1695}
1696
1698 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1699 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1700 ConsiderCudaAttrs);
1701}
1702
1704 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1705 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1706 /*UseMemberUsingDeclRules=*/false,
1707 /*ConsiderCudaAttrs=*/true,
1708 /*UseOverrideRules=*/true);
1709}
1710
1711/// Tries a user-defined conversion from From to ToType.
1712///
1713/// Produces an implicit conversion sequence for when a standard conversion
1714/// is not an option. See TryImplicitConversion for more information.
1717 bool SuppressUserConversions,
1718 AllowedExplicit AllowExplicit,
1719 bool InOverloadResolution,
1720 bool CStyle,
1721 bool AllowObjCWritebackConversion,
1722 bool AllowObjCConversionOnExplicit) {
1724
1725 if (SuppressUserConversions) {
1726 // We're not in the case above, so there is no conversion that
1727 // we can perform.
1729 return ICS;
1730 }
1731
1732 // Attempt user-defined conversion.
1733 OverloadCandidateSet Conversions(From->getExprLoc(),
1735 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1736 Conversions, AllowExplicit,
1737 AllowObjCConversionOnExplicit)) {
1738 case OR_Success:
1739 case OR_Deleted:
1740 ICS.setUserDefined();
1741 // C++ [over.ics.user]p4:
1742 // A conversion of an expression of class type to the same class
1743 // type is given Exact Match rank, and a conversion of an
1744 // expression of class type to a base class of that type is
1745 // given Conversion rank, in spite of the fact that a copy
1746 // constructor (i.e., a user-defined conversion function) is
1747 // called for those cases.
1749 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1750 QualType FromType;
1751 SourceLocation FromLoc;
1752 // C++11 [over.ics.list]p6, per DR2137:
1753 // C++17 [over.ics.list]p6:
1754 // If C is not an initializer-list constructor and the initializer list
1755 // has a single element of type cv U, where U is X or a class derived
1756 // from X, the implicit conversion sequence has Exact Match rank if U is
1757 // X, or Conversion rank if U is derived from X.
1758 bool FromListInit = false;
1759 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1760 InitList && InitList->getNumInits() == 1 &&
1762 const Expr *SingleInit = InitList->getInit(0);
1763 FromType = SingleInit->getType();
1764 FromLoc = SingleInit->getBeginLoc();
1765 FromListInit = true;
1766 } else {
1767 FromType = From->getType();
1768 FromLoc = From->getBeginLoc();
1769 }
1770 QualType FromCanon =
1772 QualType ToCanon
1774 if ((FromCanon == ToCanon ||
1775 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1776 // Turn this into a "standard" conversion sequence, so that it
1777 // gets ranked with standard conversion sequences.
1779 ICS.setStandard();
1781 ICS.Standard.setFromType(FromType);
1782 ICS.Standard.setAllToTypes(ToType);
1783 ICS.Standard.FromBracedInitList = FromListInit;
1786 if (ToCanon != FromCanon)
1788 }
1789 }
1790 break;
1791
1792 case OR_Ambiguous:
1793 ICS.setAmbiguous();
1794 ICS.Ambiguous.setFromType(From->getType());
1795 ICS.Ambiguous.setToType(ToType);
1796 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1797 Cand != Conversions.end(); ++Cand)
1798 if (Cand->Best)
1799 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1800 break;
1801
1802 // Fall through.
1805 break;
1806 }
1807
1808 return ICS;
1809}
1810
1811/// TryImplicitConversion - Attempt to perform an implicit conversion
1812/// from the given expression (Expr) to the given type (ToType). This
1813/// function returns an implicit conversion sequence that can be used
1814/// to perform the initialization. Given
1815///
1816/// void f(float f);
1817/// void g(int i) { f(i); }
1818///
1819/// this routine would produce an implicit conversion sequence to
1820/// describe the initialization of f from i, which will be a standard
1821/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1822/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1823//
1824/// Note that this routine only determines how the conversion can be
1825/// performed; it does not actually perform the conversion. As such,
1826/// it will not produce any diagnostics if no conversion is available,
1827/// but will instead return an implicit conversion sequence of kind
1828/// "BadConversion".
1829///
1830/// If @p SuppressUserConversions, then user-defined conversions are
1831/// not permitted.
1832/// If @p AllowExplicit, then explicit user-defined conversions are
1833/// permitted.
1834///
1835/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1836/// writeback conversion, which allows __autoreleasing id* parameters to
1837/// be initialized with __strong id* or __weak id* arguments.
1838static ImplicitConversionSequence
1840 bool SuppressUserConversions,
1841 AllowedExplicit AllowExplicit,
1842 bool InOverloadResolution,
1843 bool CStyle,
1844 bool AllowObjCWritebackConversion,
1845 bool AllowObjCConversionOnExplicit) {
1847 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1848 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1849 ICS.setStandard();
1850 return ICS;
1851 }
1852
1853 if (!S.getLangOpts().CPlusPlus) {
1855 return ICS;
1856 }
1857
1858 // C++ [over.ics.user]p4:
1859 // A conversion of an expression of class type to the same class
1860 // type is given Exact Match rank, and a conversion of an
1861 // expression of class type to a base class of that type is
1862 // given Conversion rank, in spite of the fact that a copy/move
1863 // constructor (i.e., a user-defined conversion function) is
1864 // called for those cases.
1865 QualType FromType = From->getType();
1866 if (ToType->isRecordType() &&
1867 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1868 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1869 ICS.setStandard();
1871 ICS.Standard.setFromType(FromType);
1872 ICS.Standard.setAllToTypes(ToType);
1873
1874 // We don't actually check at this point whether there is a valid
1875 // copy/move constructor, since overloading just assumes that it
1876 // exists. When we actually perform initialization, we'll find the
1877 // appropriate constructor to copy the returned object, if needed.
1878 ICS.Standard.CopyConstructor = nullptr;
1879
1880 // In HLSL, a conversion of an expression of class type to the same class
1881 // type needs implicit LvaluetoRvalue conversion.
1882 if (S.getLangOpts().HLSL)
1884
1885 // Determine whether this is considered a derived-to-base conversion.
1886 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1888
1889 return ICS;
1890 }
1891
1892 if (S.getLangOpts().HLSL) {
1893 // Handle conversion of the HLSL resource types.
1894 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1895 if (FromTy->isHLSLAttributedResourceType()) {
1896 // Attributed resource types can convert to other attributed
1897 // resource types with the same attributes and contained types,
1898 // or to __hlsl_resource_t without any attributes.
1899 bool CanConvert = false;
1900 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1901 if (ToTy->isHLSLAttributedResourceType()) {
1902 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1903 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1904 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1905 FromResType->getWrappedType()) &&
1906 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1907 FromResType->getContainedType()) &&
1908 ToResType->getAttrs() == FromResType->getAttrs())
1909 CanConvert = true;
1910 } else if (ToTy->isHLSLResourceType()) {
1911 CanConvert = true;
1912 }
1913 if (CanConvert) {
1914 ICS.setStandard();
1916 ICS.Standard.setFromType(FromType);
1917 ICS.Standard.setAllToTypes(ToType);
1918 return ICS;
1919 }
1920 }
1921 }
1922
1923 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1924 AllowExplicit, InOverloadResolution, CStyle,
1925 AllowObjCWritebackConversion,
1926 AllowObjCConversionOnExplicit);
1927}
1928
1929ImplicitConversionSequence
1931 bool SuppressUserConversions,
1932 AllowedExplicit AllowExplicit,
1933 bool InOverloadResolution,
1934 bool CStyle,
1935 bool AllowObjCWritebackConversion) {
1936 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1937 AllowExplicit, InOverloadResolution, CStyle,
1938 AllowObjCWritebackConversion,
1939 /*AllowObjCConversionOnExplicit=*/false);
1940}
1941
1943 AssignmentAction Action,
1944 bool AllowExplicit) {
1945 if (checkPlaceholderForOverload(*this, From))
1946 return ExprError();
1947
1948 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1949 bool AllowObjCWritebackConversion =
1950 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1951 Action == AssignmentAction::Sending);
1952 if (getLangOpts().ObjC)
1953 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1954 From->getType(), From);
1956 *this, From, ToType,
1957 /*SuppressUserConversions=*/false,
1958 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1959 /*InOverloadResolution=*/false,
1960 /*CStyle=*/false, AllowObjCWritebackConversion,
1961 /*AllowObjCConversionOnExplicit=*/false);
1962 return PerformImplicitConversion(From, ToType, ICS, Action);
1963}
1964
1966 QualType &ResultTy) const {
1967 bool Changed = IsFunctionConversion(FromType, ToType);
1968 if (Changed)
1969 ResultTy = ToType;
1970 return Changed;
1971}
1972
1973bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1974 if (Context.hasSameUnqualifiedType(FromType, ToType))
1975 return false;
1976
1977 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1978 // or F(t noexcept) -> F(t)
1979 // where F adds one of the following at most once:
1980 // - a pointer
1981 // - a member pointer
1982 // - a block pointer
1983 // Changes here need matching changes in FindCompositePointerType.
1984 CanQualType CanTo = Context.getCanonicalType(ToType);
1985 CanQualType CanFrom = Context.getCanonicalType(FromType);
1986 Type::TypeClass TyClass = CanTo->getTypeClass();
1987 if (TyClass != CanFrom->getTypeClass()) return false;
1988 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1989 if (TyClass == Type::Pointer) {
1990 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1991 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1992 } else if (TyClass == Type::BlockPointer) {
1993 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1994 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1995 } else if (TyClass == Type::MemberPointer) {
1996 auto ToMPT = CanTo.castAs<MemberPointerType>();
1997 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1998 // A function pointer conversion cannot change the class of the function.
1999 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
2000 FromMPT->getMostRecentCXXRecordDecl()))
2001 return false;
2002 CanTo = ToMPT->getPointeeType();
2003 CanFrom = FromMPT->getPointeeType();
2004 } else {
2005 return false;
2006 }
2007
2008 TyClass = CanTo->getTypeClass();
2009 if (TyClass != CanFrom->getTypeClass()) return false;
2010 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
2011 return false;
2012 }
2013
2014 const auto *FromFn = cast<FunctionType>(CanFrom);
2015 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
2016
2017 const auto *ToFn = cast<FunctionType>(CanTo);
2018 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
2019
2020 bool Changed = false;
2021
2022 // Drop 'noreturn' if not present in target type.
2023 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
2024 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
2025 Changed = true;
2026 }
2027
2028 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
2029 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
2030
2031 if (FromFPT && ToFPT) {
2032 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2033 QualType NewTy = Context.getFunctionType(
2034 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2035 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2036 ToFPT->hasCFIUncheckedCallee()));
2037 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2038 FromFn = FromFPT;
2039 Changed = true;
2040 }
2041 }
2042
2043 // Drop 'noexcept' if not present in target type.
2044 if (FromFPT && ToFPT) {
2045 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2046 FromFn = cast<FunctionType>(
2047 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2048 EST_None)
2049 .getTypePtr());
2050 Changed = true;
2051 }
2052
2053 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2054 // only if the ExtParameterInfo lists of the two function prototypes can be
2055 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2057 bool CanUseToFPT, CanUseFromFPT;
2058 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2059 CanUseFromFPT, NewParamInfos) &&
2060 CanUseToFPT && !CanUseFromFPT) {
2061 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2062 ExtInfo.ExtParameterInfos =
2063 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2064 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2065 FromFPT->getParamTypes(), ExtInfo);
2066 FromFn = QT->getAs<FunctionType>();
2067 Changed = true;
2068 }
2069
2070 if (Context.hasAnyFunctionEffects()) {
2071 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2072
2073 // Transparently add/drop effects; here we are concerned with
2074 // language rules/canonicalization. Adding/dropping effects is a warning.
2075 const auto FromFX = FromFPT->getFunctionEffects();
2076 const auto ToFX = ToFPT->getFunctionEffects();
2077 if (FromFX != ToFX) {
2078 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2079 ExtInfo.FunctionEffects = ToFX;
2080 QualType QT = Context.getFunctionType(
2081 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2082 FromFn = QT->getAs<FunctionType>();
2083 Changed = true;
2084 }
2085 }
2086 }
2087
2088 if (!Changed)
2089 return false;
2090
2091 assert(QualType(FromFn, 0).isCanonical());
2092 if (QualType(FromFn, 0) != CanTo) return false;
2093
2094 return true;
2095}
2096
2097/// Determine whether the conversion from FromType to ToType is a valid
2098/// floating point conversion.
2099///
2100static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2101 QualType ToType) {
2102 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2103 return false;
2104 // FIXME: disable conversions between long double, __ibm128 and __float128
2105 // if their representation is different until there is back end support
2106 // We of course allow this conversion if long double is really double.
2107
2108 // Conversions between bfloat16 and float16 are currently not supported.
2109 if ((FromType->isBFloat16Type() &&
2110 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2111 (ToType->isBFloat16Type() &&
2112 (FromType->isFloat16Type() || FromType->isHalfType())))
2113 return false;
2114
2115 // Conversions between IEEE-quad and IBM-extended semantics are not
2116 // permitted.
2117 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2118 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2119 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2120 &ToSem == &llvm::APFloat::IEEEquad()) ||
2121 (&FromSem == &llvm::APFloat::IEEEquad() &&
2122 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2123 return false;
2124 return true;
2125}
2126
2128 QualType ToType,
2130 Expr *From) {
2131 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2132 return true;
2133
2134 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2136 return true;
2137 }
2138
2139 if (IsFloatingPointConversion(S, FromType, ToType)) {
2141 return true;
2142 }
2143
2144 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2146 return true;
2147 }
2148
2149 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2151 ToType->isRealFloatingType())) {
2153 return true;
2154 }
2155
2156 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2158 return true;
2159 }
2160
2161 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2162 ToType->isIntegralType(S.Context)) {
2164 return true;
2165 }
2166
2167 return false;
2168}
2169
2170/// Determine whether the conversion from FromType to ToType is a valid
2171/// matrix conversion.
2172///
2173/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2174/// conversion.
2175static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2177 ImplicitConversionKind &ElConv, Expr *From,
2178 bool InOverloadResolution, bool CStyle) {
2179 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2180 if (!S.getLangOpts().HLSL)
2181 return false;
2182
2183 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2184 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2185
2186 // If both arguments are matrix, handle possible matrix truncation and
2187 // element conversion.
2188 if (ToMatrixType && FromMatrixType) {
2189 unsigned FromCols = FromMatrixType->getNumColumns();
2190 unsigned ToCols = ToMatrixType->getNumColumns();
2191 if (FromCols < ToCols)
2192 return false;
2193
2194 unsigned FromRows = FromMatrixType->getNumRows();
2195 unsigned ToRows = ToMatrixType->getNumRows();
2196 if (FromRows < ToRows)
2197 return false;
2198
2199 if (FromRows == ToRows && FromCols == ToCols)
2200 ElConv = ICK_Identity;
2201 else
2203
2204 QualType FromElTy = FromMatrixType->getElementType();
2205 QualType ToElTy = ToMatrixType->getElementType();
2206 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2207 return true;
2208 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2209 }
2210
2211 // Matrix splat from any arithmetic type to a matrix.
2212 if (ToMatrixType && FromType->isArithmeticType()) {
2213 ElConv = ICK_HLSL_Matrix_Splat;
2214 QualType ToElTy = ToMatrixType->getElementType();
2215 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2216 }
2217 if (FromMatrixType && !ToMatrixType) {
2219 QualType FromElTy = FromMatrixType->getElementType();
2220 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2221 return true;
2222 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2223 }
2224
2225 return false;
2226}
2227
2228/// Determine whether the conversion from FromType to ToType is a valid
2229/// vector conversion.
2230///
2231/// \param ICK Will be set to the vector conversion kind, if this is a vector
2232/// conversion.
2233static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2235 ImplicitConversionKind &ElConv, Expr *From,
2236 bool InOverloadResolution, bool CStyle) {
2237 // We need at least one of these types to be a vector type to have a vector
2238 // conversion.
2239 if (!ToType->isVectorType() && !FromType->isVectorType())
2240 return false;
2241
2242 // Identical types require no conversions.
2243 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2244 return false;
2245
2246 // HLSL allows implicit truncation of vector types.
2247 if (S.getLangOpts().HLSL) {
2248 auto *ToExtType = ToType->getAs<ExtVectorType>();
2249 auto *FromExtType = FromType->getAs<ExtVectorType>();
2250
2251 // If both arguments are vectors, handle possible vector truncation and
2252 // element conversion.
2253 if (ToExtType && FromExtType) {
2254 unsigned FromElts = FromExtType->getNumElements();
2255 unsigned ToElts = ToExtType->getNumElements();
2256 if (FromElts < ToElts)
2257 return false;
2258 if (FromElts == ToElts)
2259 ElConv = ICK_Identity;
2260 else
2262
2263 QualType FromElTy = FromExtType->getElementType();
2264 QualType ToElTy = ToExtType->getElementType();
2265 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2266 return true;
2267 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2268 }
2269 if (FromExtType && !ToExtType) {
2271 QualType FromElTy = FromExtType->getElementType();
2272 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2273 return true;
2274 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2275 }
2276 // Fallthrough for the case where ToType is a vector and FromType is not.
2277 }
2278
2279 // There are no conversions between extended vector types, only identity.
2280 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2281 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2282 // Implicit conversions require the same number of elements.
2283 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2284 return false;
2285
2286 // Permit implicit conversions from integral values to boolean vectors.
2287 if (ToType->isExtVectorBoolType() &&
2288 FromExtType->getElementType()->isIntegerType()) {
2290 return true;
2291 }
2292 // There are no other conversions between extended vector types.
2293 return false;
2294 }
2295
2296 // Vector splat from any arithmetic type to a vector.
2297 if (FromType->isArithmeticType()) {
2298 if (S.getLangOpts().HLSL) {
2299 ElConv = ICK_HLSL_Vector_Splat;
2300 QualType ToElTy = ToExtType->getElementType();
2301 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2302 From);
2303 }
2304 ICK = ICK_Vector_Splat;
2305 return true;
2306 }
2307 }
2308
2309 if (ToType->isSVESizelessBuiltinType() ||
2310 FromType->isSVESizelessBuiltinType())
2311 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2312 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2314 return true;
2315 }
2316
2317 if (ToType->isRVVSizelessBuiltinType() ||
2318 FromType->isRVVSizelessBuiltinType())
2319 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2320 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2322 return true;
2323 }
2324
2325 // We can perform the conversion between vector types in the following cases:
2326 // 1)vector types are equivalent AltiVec and GCC vector types
2327 // 2)lax vector conversions are permitted and the vector types are of the
2328 // same size
2329 // 3)the destination type does not have the ARM MVE strict-polymorphism
2330 // attribute, which inhibits lax vector conversion for overload resolution
2331 // only
2332 if (ToType->isVectorType() && FromType->isVectorType()) {
2333 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2334 (S.isLaxVectorConversion(FromType, ToType) &&
2335 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2336 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2337 S.isLaxVectorConversion(FromType, ToType) &&
2338 S.anyAltivecTypes(FromType, ToType) &&
2339 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2340 !InOverloadResolution && !CStyle) {
2341 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2342 << FromType << ToType;
2343 }
2345 return true;
2346 }
2347 }
2348
2349 return false;
2350}
2351
2353 QualType ToType,
2355 ImplicitConversionKind &DimensionICK,
2356 Expr *From) {
2357 if (!S.getLangOpts().HLSL)
2358 return false;
2359 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2360 return false;
2361
2362 const bool FromPacked = FromType->isHLSLBuiltinPackedType();
2363 const bool ToPacked = ToType->isHLSLBuiltinPackedType();
2364
2365 if (FromPacked && ToPacked) {
2367 DimensionICK = ICK_Identity;
2368 return true;
2369 }
2370
2371 // Only convert packed types to and from uint
2372 QualType UIntTy = S.Context.UnsignedIntTy;
2373 const bool ToIsUint = S.Context.hasSameUnqualifiedType(ToType, UIntTy);
2374 if (FromPacked && !ToIsUint)
2375 return false;
2376
2377 const bool FromIsUint = S.Context.hasSameUnqualifiedType(FromType, UIntTy);
2378 if (ToPacked && !FromIsUint)
2379 return false;
2380
2381 // Converting to or from uint
2382 if (FromIsUint || ToIsUint) {
2384 DimensionICK = ICK_Identity;
2385 return true;
2386 }
2387
2388 return false;
2389}
2390
2391static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2392 bool InOverloadResolution,
2393 StandardConversionSequence &SCS,
2394 bool CStyle);
2395
2396static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2397 QualType ToType,
2398 bool InOverloadResolution,
2399 StandardConversionSequence &SCS,
2400 bool CStyle);
2401
2402/// IsStandardConversion - Determines whether there is a standard
2403/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2404/// expression From to the type ToType. Standard conversion sequences
2405/// only consider non-class types; for conversions that involve class
2406/// types, use TryImplicitConversion. If a conversion exists, SCS will
2407/// contain the standard conversion sequence required to perform this
2408/// conversion and this routine will return true. Otherwise, this
2409/// routine will return false and the value of SCS is unspecified.
2410static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2411 bool InOverloadResolution,
2413 bool CStyle,
2414 bool AllowObjCWritebackConversion) {
2415 QualType FromType = From->getType();
2416
2417 // Standard conversions (C++ [conv])
2419 SCS.IncompatibleObjC = false;
2420 SCS.setFromType(FromType);
2421 SCS.CopyConstructor = nullptr;
2422
2423 // There are no standard conversions for class types in C++, so
2424 // abort early. When overloading in C, however, we do permit them.
2425 if (S.getLangOpts().CPlusPlus &&
2426 (FromType->isRecordType() || ToType->isRecordType()))
2427 return false;
2428
2429 // The first conversion can be an lvalue-to-rvalue conversion,
2430 // array-to-pointer conversion, or function-to-pointer conversion
2431 // (C++ 4p1).
2432
2433 if (FromType == S.Context.OverloadTy) {
2434 DeclAccessPair AccessPair;
2435 if (FunctionDecl *Fn
2436 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2437 AccessPair)) {
2438 // We were able to resolve the address of the overloaded function,
2439 // so we can convert to the type of that function.
2440 FromType = Fn->getType();
2441 SCS.setFromType(FromType);
2442
2443 // we can sometimes resolve &foo<int> regardless of ToType, so check
2444 // if the type matches (identity) or we are converting to bool
2446 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2447 // if the function type matches except for [[noreturn]], it's ok
2448 if (!S.IsFunctionConversion(FromType,
2450 // otherwise, only a boolean conversion is standard
2451 if (!ToType->isBooleanType())
2452 return false;
2453 }
2454
2455 // Check if the "from" expression is taking the address of an overloaded
2456 // function and recompute the FromType accordingly. Take advantage of the
2457 // fact that non-static member functions *must* have such an address-of
2458 // expression.
2459 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2460 if (Method && !Method->isStatic() &&
2461 !Method->isExplicitObjectMemberFunction()) {
2462 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2463 "Non-unary operator on non-static member address");
2464 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2465 == UO_AddrOf &&
2466 "Non-address-of operator on non-static member address");
2467 FromType = S.Context.getMemberPointerType(
2468 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2469 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2470 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2471 UO_AddrOf &&
2472 "Non-address-of operator for overloaded function expression");
2473 FromType = S.Context.getPointerType(FromType);
2474 }
2475 } else {
2476 return false;
2477 }
2478 }
2479
2480 bool argIsLValue = From->isGLValue();
2481 // To handle conversion from ArrayParameterType to ConstantArrayType
2482 // this block must be above the one below because Array parameters
2483 // do not decay and when handling HLSLOutArgExprs and
2484 // the From expression is an LValue.
2485 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2486 ToType->isConstantArrayType()) {
2487 // HLSL constant array parameters do not decay, so if the argument is a
2488 // constant array and the parameter is an ArrayParameterType we have special
2489 // handling here.
2490 if (ToType->isArrayParameterType()) {
2491 FromType = S.Context.getArrayParameterType(FromType);
2492 } else if (FromType->isArrayParameterType()) {
2493 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2494 FromType = APT->getConstantArrayType(S.Context);
2495 }
2496
2498
2499 // Don't consider qualifiers, which include things like address spaces
2500 if (FromType.getCanonicalType().getUnqualifiedType() !=
2502 return false;
2503
2504 SCS.setAllToTypes(ToType);
2505 return true;
2506 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2507 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2508 // Lvalue-to-rvalue conversion (C++11 4.1):
2509 // A glvalue (3.10) of a non-function, non-array type T can
2510 // be converted to a prvalue.
2511
2513
2514 // C11 6.3.2.1p2:
2515 // ... if the lvalue has atomic type, the value has the non-atomic version
2516 // of the type of the lvalue ...
2517 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2518 FromType = Atomic->getValueType();
2519
2520 // If T is a non-class type, the type of the rvalue is the
2521 // cv-unqualified version of T. Otherwise, the type of the rvalue
2522 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2523 // just strip the qualifiers because they don't matter.
2524 FromType = FromType.getUnqualifiedType();
2525 } else if (FromType->isArrayType()) {
2526 // Array-to-pointer conversion (C++ 4.2)
2528
2529 // An lvalue or rvalue of type "array of N T" or "array of unknown
2530 // bound of T" can be converted to an rvalue of type "pointer to
2531 // T" (C++ 4.2p1).
2532 FromType = S.Context.getArrayDecayedType(FromType);
2533
2534 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2535 // This conversion is deprecated in C++03 (D.4)
2537
2538 // For the purpose of ranking in overload resolution
2539 // (13.3.3.1.1), this conversion is considered an
2540 // array-to-pointer conversion followed by a qualification
2541 // conversion (4.4). (C++ 4.2p2)
2542 SCS.Second = ICK_Identity;
2545 SCS.setAllToTypes(FromType);
2546 return true;
2547 }
2548 } else if (FromType->isFunctionType() && argIsLValue) {
2549 // Function-to-pointer conversion (C++ 4.3).
2551
2552 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2553 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2555 return false;
2556
2557 // An lvalue of function type T can be converted to an rvalue of
2558 // type "pointer to T." The result is a pointer to the
2559 // function. (C++ 4.3p1).
2560 FromType = S.Context.getPointerType(FromType);
2561 } else {
2562 // We don't require any conversions for the first step.
2563 SCS.First = ICK_Identity;
2564 }
2565 SCS.setToType(0, FromType);
2566
2567 // The second conversion can be an integral promotion, floating
2568 // point promotion, integral conversion, floating point conversion,
2569 // floating-integral conversion, pointer conversion,
2570 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2571 // For overloading in C, this can also be a "compatible-type"
2572 // conversion.
2573 bool IncompatibleObjC = false;
2575 ImplicitConversionKind DimensionICK = ICK_Identity;
2576 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2577 // The unqualified versions of the types are the same: there's no
2578 // conversion to do.
2579 SCS.Second = ICK_Identity;
2580 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2581 // Integral promotion (C++ 4.5).
2583 FromType = ToType.getUnqualifiedType();
2584 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2585 // Floating point promotion (C++ 4.6).
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (S.IsComplexPromotion(FromType, ToType)) {
2589 // Complex promotion (Clang extension)
2591 FromType = ToType.getUnqualifiedType();
2592 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2593 // OverflowBehaviorType promotions
2595 FromType = ToType.getUnqualifiedType();
2596 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2597 // OverflowBehaviorType conversions
2599 FromType = ToType.getUnqualifiedType();
2600 } else if (ToType->isBooleanType() &&
2601 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2602 FromType->isBlockPointerType() ||
2603 FromType->isMemberPointerType())) {
2604 // Boolean conversions (C++ 4.12).
2606 FromType = S.Context.BoolTy;
2607 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2608 ToType->isIntegralType(S.Context)) {
2609 // Integral conversions (C++ 4.7).
2611 FromType = ToType.getUnqualifiedType();
2612 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2613 // Complex conversions (C99 6.3.1.6)
2615 FromType = ToType.getUnqualifiedType();
2616 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2617 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2618 // Complex-real conversions (C99 6.3.1.7)
2620 FromType = ToType.getUnqualifiedType();
2621 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2622 // Floating point conversions (C++ 4.8).
2624 FromType = ToType.getUnqualifiedType();
2625 } else if ((FromType->isRealFloatingType() &&
2626 ToType->isIntegralType(S.Context)) ||
2628 ToType->isRealFloatingType())) {
2629
2630 // Floating-integral conversions (C++ 4.9).
2632 FromType = ToType.getUnqualifiedType();
2633 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2635 } else if (AllowObjCWritebackConversion &&
2636 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2638 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2639 FromType, IncompatibleObjC)) {
2640 // Pointer conversions (C++ 4.10).
2642 SCS.IncompatibleObjC = IncompatibleObjC;
2643 FromType = FromType.getUnqualifiedType();
2644 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2645 InOverloadResolution, FromType)) {
2646 // Pointer to member conversions (4.11).
2648 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2649 From, InOverloadResolution, CStyle)) {
2650 SCS.Second = SecondICK;
2651 SCS.Dimension = DimensionICK;
2652 FromType = ToType.getUnqualifiedType();
2653 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2654 From, InOverloadResolution, CStyle)) {
2655 SCS.Second = SecondICK;
2656 SCS.Dimension = DimensionICK;
2657 FromType = ToType.getUnqualifiedType();
2658 } else if (IsHLSLPackedTypeConversion(S, FromType, ToType, SecondICK,
2659 DimensionICK, From)) {
2660 SCS.Second = SecondICK;
2661 SCS.Dimension = DimensionICK;
2662 FromType = ToType.getUnqualifiedType();
2663 } else if (!S.getLangOpts().CPlusPlus &&
2664 S.Context.typesAreCompatible(ToType, FromType)) {
2665 // Compatible conversions (Clang extension for C function overloading)
2667 FromType = ToType.getUnqualifiedType();
2669 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2671 FromType = ToType;
2672 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2673 CStyle)) {
2674 // tryAtomicConversion has updated the standard conversion sequence
2675 // appropriately.
2676 return true;
2678 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2679 return true;
2680 } else if (ToType->isEventT() &&
2682 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2684 FromType = ToType;
2685 } else if (ToType->isQueueT() &&
2687 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2689 FromType = ToType;
2690 } else if (ToType->isSamplerT() &&
2693 FromType = ToType;
2694 } else if ((ToType->isFixedPointType() &&
2695 FromType->isConvertibleToFixedPointType()) ||
2696 (FromType->isFixedPointType() &&
2697 ToType->isConvertibleToFixedPointType())) {
2699 FromType = ToType;
2700 } else {
2701 // No second conversion required.
2702 SCS.Second = ICK_Identity;
2703 }
2704 SCS.setToType(1, FromType);
2705
2706 // The third conversion can be a function pointer conversion or a
2707 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2708 bool ObjCLifetimeConversion;
2709 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2710 // Function pointer conversions (removing 'noexcept') including removal of
2711 // 'noreturn' (Clang extension).
2713 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2714 ObjCLifetimeConversion)) {
2716 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2717 FromType = ToType;
2718 } else {
2719 // No conversion required
2720 SCS.Third = ICK_Identity;
2721 }
2722
2723 // C++ [over.best.ics]p6:
2724 // [...] Any difference in top-level cv-qualification is
2725 // subsumed by the initialization itself and does not constitute
2726 // a conversion. [...]
2727 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2728 QualType CanonTo = S.Context.getCanonicalType(ToType);
2729 if (CanonFrom.getLocalUnqualifiedType()
2730 == CanonTo.getLocalUnqualifiedType() &&
2731 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2732 FromType = ToType;
2733 CanonFrom = CanonTo;
2734 }
2735
2736 SCS.setToType(2, FromType);
2737
2738 if (CanonFrom == CanonTo)
2739 return true;
2740
2741 // If we have not converted the argument type to the parameter type,
2742 // this is a bad conversion sequence, unless we're resolving an overload in C.
2743 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2744 return false;
2745
2746 ExprResult ER = ExprResult{From};
2747 AssignConvertType Conv =
2749 /*Diagnose=*/false,
2750 /*DiagnoseCFAudited=*/false,
2751 /*ConvertRHS=*/false);
2752 ImplicitConversionKind SecondConv;
2753 switch (Conv) {
2755 case AssignConvertType::
2756 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2757 SecondConv = ICK_C_Only_Conversion;
2758 break;
2759 // For our purposes, discarding qualifiers is just as bad as using an
2760 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2761 // qualifiers, as well.
2766 break;
2767 default:
2768 return false;
2769 }
2770
2771 // First can only be an lvalue conversion, so we pretend that this was the
2772 // second conversion. First should already be valid from earlier in the
2773 // function.
2774 SCS.Second = SecondConv;
2775 SCS.setToType(1, ToType);
2776
2777 // Third is Identity, because Second should rank us worse than any other
2778 // conversion. This could also be ICK_Qualification, but it's simpler to just
2779 // lump everything in with the second conversion, and we don't gain anything
2780 // from making this ICK_Qualification.
2781 SCS.Third = ICK_Identity;
2782 SCS.setToType(2, ToType);
2783 return true;
2784}
2785
2786static bool
2788 QualType &ToType,
2789 bool InOverloadResolution,
2791 bool CStyle) {
2792
2793 const RecordType *UT = ToType->getAsUnionType();
2794 if (!UT)
2795 return false;
2796 // The field to initialize within the transparent union.
2797 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2798 if (!UD->hasAttr<TransparentUnionAttr>())
2799 return false;
2800 // It's compatible if the expression matches any of the fields.
2801 for (const auto *it : UD->fields()) {
2802 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2803 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2804 ToType = it->getType();
2805 return true;
2806 }
2807 }
2808 return false;
2809}
2810
2811bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2812 const BuiltinType *To = ToType->getAs<BuiltinType>();
2813 // All integers are built-in.
2814 if (!To) {
2815 return false;
2816 }
2817
2818 // An rvalue of type char, signed char, unsigned char, short int, or
2819 // unsigned short int can be converted to an rvalue of type int if
2820 // int can represent all the values of the source type; otherwise,
2821 // the source rvalue can be converted to an rvalue of type unsigned
2822 // int (C++ 4.5p1).
2823 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2824 !FromType->isEnumeralType()) {
2825 if ( // We can promote any signed, promotable integer type to an int
2826 (FromType->isSignedIntegerType() ||
2827 // We can promote any unsigned integer type whose size is
2828 // less than int to an int.
2829 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2830 return To->getKind() == BuiltinType::Int;
2831 }
2832
2833 return To->getKind() == BuiltinType::UInt;
2834 }
2835
2836 // C++11 [conv.prom]p3:
2837 // A prvalue of an unscoped enumeration type whose underlying type is not
2838 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2839 // following types that can represent all the values of the enumeration
2840 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2841 // unsigned int, long int, unsigned long int, long long int, or unsigned
2842 // long long int. If none of the types in that list can represent all the
2843 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2844 // type can be converted to an rvalue a prvalue of the extended integer type
2845 // with lowest integer conversion rank (4.13) greater than the rank of long
2846 // long in which all the values of the enumeration can be represented. If
2847 // there are two such extended types, the signed one is chosen.
2848 // C++11 [conv.prom]p4:
2849 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2850 // can be converted to a prvalue of its underlying type. Moreover, if
2851 // integral promotion can be applied to its underlying type, a prvalue of an
2852 // unscoped enumeration type whose underlying type is fixed can also be
2853 // converted to a prvalue of the promoted underlying type.
2854 if (const auto *FromED = FromType->getAsEnumDecl()) {
2855 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2856 // provided for a scoped enumeration.
2857 if (FromED->isScoped())
2858 return false;
2859
2860 // We can perform an integral promotion to the underlying type of the enum,
2861 // even if that's not the promoted type. Note that the check for promoting
2862 // the underlying type is based on the type alone, and does not consider
2863 // the bitfield-ness of the actual source expression.
2864 if (FromED->isFixed()) {
2865 QualType Underlying = FromED->getIntegerType();
2866 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2867 IsIntegralPromotion(nullptr, Underlying, ToType);
2868 }
2869
2870 // We have already pre-calculated the promotion type, so this is trivial.
2871 if (ToType->isIntegerType() &&
2872 isCompleteType(From->getBeginLoc(), FromType))
2873 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2874
2875 // C++ [conv.prom]p5:
2876 // If the bit-field has an enumerated type, it is treated as any other
2877 // value of that type for promotion purposes.
2878 //
2879 // ... so do not fall through into the bit-field checks below in C++.
2880 if (getLangOpts().CPlusPlus)
2881 return false;
2882 }
2883
2884 // C++0x [conv.prom]p2:
2885 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2886 // to an rvalue a prvalue of the first of the following types that can
2887 // represent all the values of its underlying type: int, unsigned int,
2888 // long int, unsigned long int, long long int, or unsigned long long int.
2889 // If none of the types in that list can represent all the values of its
2890 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2891 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2892 // type.
2893 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2894 ToType->isIntegerType()) {
2895 // Determine whether the type we're converting from is signed or
2896 // unsigned.
2897 bool FromIsSigned = FromType->isSignedIntegerType();
2898 uint64_t FromSize = Context.getTypeSize(FromType);
2899
2900 // The types we'll try to promote to, in the appropriate
2901 // order. Try each of these types.
2902 QualType PromoteTypes[6] = {
2903 Context.IntTy, Context.UnsignedIntTy,
2904 Context.LongTy, Context.UnsignedLongTy ,
2905 Context.LongLongTy, Context.UnsignedLongLongTy
2906 };
2907 for (int Idx = 0; Idx < 6; ++Idx) {
2908 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2909 if (FromSize < ToSize ||
2910 (FromSize == ToSize &&
2911 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2912 // We found the type that we can promote to. If this is the
2913 // type we wanted, we have a promotion. Otherwise, no
2914 // promotion.
2915 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2916 }
2917 }
2918 }
2919
2920 // An rvalue for an integral bit-field (9.6) can be converted to an
2921 // rvalue of type int if int can represent all the values of the
2922 // bit-field; otherwise, it can be converted to unsigned int if
2923 // unsigned int can represent all the values of the bit-field. If
2924 // the bit-field is larger yet, no integral promotion applies to
2925 // it. If the bit-field has an enumerated type, it is treated as any
2926 // other value of that type for promotion purposes (C++ 4.5p3).
2927 // FIXME: We should delay checking of bit-fields until we actually perform the
2928 // conversion.
2929 //
2930 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2931 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2932 // bit-fields and those whose underlying type is larger than int) for GCC
2933 // compatibility.
2934 if (From) {
2935 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2936 std::optional<llvm::APSInt> BitWidth;
2937 if (FromType->isIntegralType(Context) &&
2938 (BitWidth =
2939 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2940 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2941 ToSize = Context.getTypeSize(ToType);
2942
2943 // Are we promoting to an int from a bitfield that fits in an int?
2944 if (*BitWidth < ToSize ||
2945 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2946 return To->getKind() == BuiltinType::Int;
2947 }
2948
2949 // Are we promoting to an unsigned int from an unsigned bitfield
2950 // that fits into an unsigned int?
2951 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2952 return To->getKind() == BuiltinType::UInt;
2953 }
2954
2955 return false;
2956 }
2957 }
2958 }
2959
2960 // An rvalue of type bool can be converted to an rvalue of type int,
2961 // with false becoming zero and true becoming one (C++ 4.5p4).
2962 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2963 return true;
2964 }
2965
2966 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2967 // integral type.
2968 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2969 ToType->isIntegerType())
2970 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2971
2972 return false;
2973}
2974
2976 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2977 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2978 /// An rvalue of type float can be converted to an rvalue of type
2979 /// double. (C++ 4.6p1).
2980 if (FromBuiltin->getKind() == BuiltinType::Float &&
2981 ToBuiltin->getKind() == BuiltinType::Double)
2982 return true;
2983
2984 // C99 6.3.1.5p1:
2985 // When a float is promoted to double or long double, or a
2986 // double is promoted to long double [...].
2987 if (!getLangOpts().CPlusPlus &&
2988 (FromBuiltin->getKind() == BuiltinType::Float ||
2989 FromBuiltin->getKind() == BuiltinType::Double) &&
2990 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2991 ToBuiltin->getKind() == BuiltinType::Float128 ||
2992 ToBuiltin->getKind() == BuiltinType::Ibm128))
2993 return true;
2994
2995 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2996 // or not native half types are enabled.
2997 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2998 (ToBuiltin->getKind() == BuiltinType::Float ||
2999 ToBuiltin->getKind() == BuiltinType::Double))
3000 return true;
3001
3002 // Half can be promoted to float.
3003 if (!getLangOpts().NativeHalfType &&
3004 FromBuiltin->getKind() == BuiltinType::Half &&
3005 ToBuiltin->getKind() == BuiltinType::Float)
3006 return true;
3007 }
3008
3009 return false;
3010}
3011
3013 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
3014 if (!FromComplex)
3015 return false;
3016
3017 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
3018 if (!ToComplex)
3019 return false;
3020
3021 return IsFloatingPointPromotion(FromComplex->getElementType(),
3022 ToComplex->getElementType()) ||
3023 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
3024 ToComplex->getElementType());
3025}
3026
3028 if (!getLangOpts().OverflowBehaviorTypes)
3029 return false;
3030
3031 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
3032 return false;
3033
3034 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
3035}
3036
3038 QualType ToType) {
3039 if (!getLangOpts().OverflowBehaviorTypes)
3040 return false;
3041
3042 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
3043 if (ToType->isBooleanType())
3044 return false;
3045 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
3046 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
3047 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
3048 if (ToED->isScoped())
3049 return false;
3050 }
3051 return true;
3052 }
3053
3054 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3055 return true;
3056
3057 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3058 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
3059
3060 return false;
3061}
3062
3063/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
3064/// the pointer type FromPtr to a pointer to type ToPointee, with the
3065/// same type qualifiers as FromPtr has on its pointee type. ToType,
3066/// if non-empty, will be a pointer to ToType that may or may not have
3067/// the right set of qualifiers on its pointee.
3068///
3069static QualType
3071 QualType ToPointee, QualType ToType,
3072 ASTContext &Context,
3073 bool StripObjCLifetime = false) {
3074 assert((FromPtr->getTypeClass() == Type::Pointer ||
3075 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3076 "Invalid similarly-qualified pointer type");
3077
3078 /// Conversions to 'id' subsume cv-qualifier conversions.
3079 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3080 return ToType.getUnqualifiedType();
3081
3082 QualType CanonFromPointee
3083 = Context.getCanonicalType(FromPtr->getPointeeType());
3084 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3085 Qualifiers Quals = CanonFromPointee.getQualifiers();
3086
3087 if (StripObjCLifetime)
3088 Quals.removeObjCLifetime();
3089
3090 // Exact qualifier match -> return the pointer type we're converting to.
3091 if (CanonToPointee.getLocalQualifiers() == Quals) {
3092 // ToType is exactly what we need. Return it.
3093 if (!ToType.isNull())
3094 return ToType.getUnqualifiedType();
3095
3096 // Build a pointer to ToPointee. It has the right qualifiers
3097 // already.
3098 if (isa<ObjCObjectPointerType>(ToType))
3099 return Context.getObjCObjectPointerType(ToPointee);
3100 return Context.getPointerType(ToPointee);
3101 }
3102
3103 // Just build a canonical type that has the right qualifiers.
3104 QualType QualifiedCanonToPointee
3105 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3106
3107 if (isa<ObjCObjectPointerType>(ToType))
3108 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3109 return Context.getPointerType(QualifiedCanonToPointee);
3110}
3111
3113 bool InOverloadResolution,
3114 ASTContext &Context) {
3115 // Handle value-dependent integral null pointer constants correctly.
3116 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3117 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3119 return !InOverloadResolution;
3120
3121 return Expr->isNullPointerConstant(Context,
3122 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3124}
3125
3127 bool InOverloadResolution,
3128 QualType& ConvertedType,
3129 bool &IncompatibleObjC) {
3130 IncompatibleObjC = false;
3131 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3132 IncompatibleObjC))
3133 return true;
3134
3135 // Conversion from a null pointer constant to any Objective-C pointer type.
3136 if (ToType->isObjCObjectPointerType() &&
3137 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3138 ConvertedType = ToType;
3139 return true;
3140 }
3141
3142 // Blocks: Block pointers can be converted to void*.
3143 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3144 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3145 ConvertedType = ToType;
3146 return true;
3147 }
3148 // Blocks: A null pointer constant can be converted to a block
3149 // pointer type.
3150 if (ToType->isBlockPointerType() &&
3151 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3152 ConvertedType = ToType;
3153 return true;
3154 }
3155
3156 // If the left-hand-side is nullptr_t, the right side can be a null
3157 // pointer constant.
3158 if (ToType->isNullPtrType() &&
3159 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3160 ConvertedType = ToType;
3161 return true;
3162 }
3163
3164 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3165 if (!ToTypePtr)
3166 return false;
3167
3168 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3169 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3170 ConvertedType = ToType;
3171 return true;
3172 }
3173
3174 // Beyond this point, both types need to be pointers
3175 // , including objective-c pointers.
3176 QualType ToPointeeType = ToTypePtr->getPointeeType();
3177 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3178 !getLangOpts().ObjCAutoRefCount) {
3179 ConvertedType = BuildSimilarlyQualifiedPointerType(
3180 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3181 Context);
3182 return true;
3183 }
3184 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3185 if (!FromTypePtr)
3186 return false;
3187
3188 QualType FromPointeeType = FromTypePtr->getPointeeType();
3189
3190 // If the unqualified pointee types are the same, this can't be a
3191 // pointer conversion, so don't do all of the work below.
3192 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3193 return false;
3194
3195 // An rvalue of type "pointer to cv T," where T is an object type,
3196 // can be converted to an rvalue of type "pointer to cv void" (C++
3197 // 4.10p2).
3198 if (FromPointeeType->isIncompleteOrObjectType() &&
3199 ToPointeeType->isVoidType()) {
3200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3201 ToPointeeType,
3202 ToType, Context,
3203 /*StripObjCLifetime=*/true);
3204 return true;
3205 }
3206
3207 // MSVC allows implicit function to void* type conversion.
3208 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3209 ToPointeeType->isVoidType()) {
3210 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3211 ToPointeeType,
3212 ToType, Context);
3213 return true;
3214 }
3215
3216 // When we're overloading in C, we allow a special kind of pointer
3217 // conversion for compatible-but-not-identical pointee types.
3218 if (!getLangOpts().CPlusPlus &&
3219 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3220 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3221 ToPointeeType,
3222 ToType, Context);
3223 return true;
3224 }
3225
3226 // C++ [conv.ptr]p3:
3227 //
3228 // An rvalue of type "pointer to cv D," where D is a class type,
3229 // can be converted to an rvalue of type "pointer to cv B," where
3230 // B is a base class (clause 10) of D. If B is an inaccessible
3231 // (clause 11) or ambiguous (10.2) base class of D, a program that
3232 // necessitates this conversion is ill-formed. The result of the
3233 // conversion is a pointer to the base class sub-object of the
3234 // derived class object. The null pointer value is converted to
3235 // the null pointer value of the destination type.
3236 //
3237 // Note that we do not check for ambiguity or inaccessibility
3238 // here. That is handled by CheckPointerConversion.
3239 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3240 ToPointeeType->isRecordType() &&
3241 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3242 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3243 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3244 ToPointeeType,
3245 ToType, Context);
3246 return true;
3247 }
3248
3249 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3250 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3251 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3252 ToPointeeType,
3253 ToType, Context);
3254 return true;
3255 }
3256
3257 return false;
3258}
3259
3260/// Adopt the given qualifiers for the given type.
3262 Qualifiers TQs = T.getQualifiers();
3263
3264 // Check whether qualifiers already match.
3265 if (TQs == Qs)
3266 return T;
3267
3268 if (Qs.compatiblyIncludes(TQs, Context))
3269 return Context.getQualifiedType(T, Qs);
3270
3271 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3272}
3273
3275 QualType& ConvertedType,
3276 bool &IncompatibleObjC) {
3277 if (!getLangOpts().ObjC)
3278 return false;
3279
3280 // The set of qualifiers on the type we're converting from.
3281 Qualifiers FromQualifiers = FromType.getQualifiers();
3282
3283 // First, we handle all conversions on ObjC object pointer types.
3284 const ObjCObjectPointerType* ToObjCPtr =
3285 ToType->getAs<ObjCObjectPointerType>();
3286 const ObjCObjectPointerType *FromObjCPtr =
3287 FromType->getAs<ObjCObjectPointerType>();
3288
3289 if (ToObjCPtr && FromObjCPtr) {
3290 // If the pointee types are the same (ignoring qualifications),
3291 // then this is not a pointer conversion.
3292 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3293 FromObjCPtr->getPointeeType()))
3294 return false;
3295
3296 // Conversion between Objective-C pointers.
3297 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3298 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3299 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3300 if (getLangOpts().CPlusPlus && LHS && RHS &&
3302 FromObjCPtr->getPointeeType(), getASTContext()))
3303 return false;
3304 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3305 ToObjCPtr->getPointeeType(),
3306 ToType, Context);
3307 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3308 return true;
3309 }
3310
3311 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3312 // Okay: this is some kind of implicit downcast of Objective-C
3313 // interfaces, which is permitted. However, we're going to
3314 // complain about it.
3315 IncompatibleObjC = true;
3316 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3317 ToObjCPtr->getPointeeType(),
3318 ToType, Context);
3319 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3320 return true;
3321 }
3322 }
3323 // Beyond this point, both types need to be C pointers or block pointers.
3324 QualType ToPointeeType;
3325 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3326 ToPointeeType = ToCPtr->getPointeeType();
3327 else if (const BlockPointerType *ToBlockPtr =
3328 ToType->getAs<BlockPointerType>()) {
3329 // Objective C++: We're able to convert from a pointer to any object
3330 // to a block pointer type.
3331 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3332 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3333 return true;
3334 }
3335 ToPointeeType = ToBlockPtr->getPointeeType();
3336 }
3337 else if (FromType->getAs<BlockPointerType>() &&
3338 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3339 // Objective C++: We're able to convert from a block pointer type to a
3340 // pointer to any object.
3341 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3342 return true;
3343 }
3344 else
3345 return false;
3346
3347 QualType FromPointeeType;
3348 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3349 FromPointeeType = FromCPtr->getPointeeType();
3350 else if (const BlockPointerType *FromBlockPtr =
3351 FromType->getAs<BlockPointerType>())
3352 FromPointeeType = FromBlockPtr->getPointeeType();
3353 else
3354 return false;
3355
3356 // If we have pointers to pointers, recursively check whether this
3357 // is an Objective-C conversion.
3358 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3359 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3360 IncompatibleObjC)) {
3361 // We always complain about this conversion.
3362 IncompatibleObjC = true;
3363 ConvertedType = Context.getPointerType(ConvertedType);
3364 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3365 return true;
3366 }
3367 // Allow conversion of pointee being objective-c pointer to another one;
3368 // as in I* to id.
3369 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3370 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3371 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3372 IncompatibleObjC)) {
3373
3374 ConvertedType = Context.getPointerType(ConvertedType);
3375 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3376 return true;
3377 }
3378
3379 // If we have pointers to functions or blocks, check whether the only
3380 // differences in the argument and result types are in Objective-C
3381 // pointer conversions. If so, we permit the conversion (but
3382 // complain about it).
3383 const FunctionProtoType *FromFunctionType
3384 = FromPointeeType->getAs<FunctionProtoType>();
3385 const FunctionProtoType *ToFunctionType
3386 = ToPointeeType->getAs<FunctionProtoType>();
3387 if (FromFunctionType && ToFunctionType) {
3388 // If the function types are exactly the same, this isn't an
3389 // Objective-C pointer conversion.
3390 if (Context.getCanonicalType(FromPointeeType)
3391 == Context.getCanonicalType(ToPointeeType))
3392 return false;
3393
3394 // Perform the quick checks that will tell us whether these
3395 // function types are obviously different.
3396 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3397 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3398 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3399 return false;
3400
3401 bool HasObjCConversion = false;
3402 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3403 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3404 // Okay, the types match exactly. Nothing to do.
3405 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3406 ToFunctionType->getReturnType(),
3407 ConvertedType, IncompatibleObjC)) {
3408 // Okay, we have an Objective-C pointer conversion.
3409 HasObjCConversion = true;
3410 } else {
3411 // Function types are too different. Abort.
3412 return false;
3413 }
3414
3415 // Check argument types.
3416 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3417 ArgIdx != NumArgs; ++ArgIdx) {
3418 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3419 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3420 if (Context.getCanonicalType(FromArgType)
3421 == Context.getCanonicalType(ToArgType)) {
3422 // Okay, the types match exactly. Nothing to do.
3423 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3424 ConvertedType, IncompatibleObjC)) {
3425 // Okay, we have an Objective-C pointer conversion.
3426 HasObjCConversion = true;
3427 } else {
3428 // Argument types are too different. Abort.
3429 return false;
3430 }
3431 }
3432
3433 if (HasObjCConversion) {
3434 // We had an Objective-C conversion. Allow this pointer
3435 // conversion, but complain about it.
3436 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3437 IncompatibleObjC = true;
3438 return true;
3439 }
3440 }
3441
3442 return false;
3443}
3444
3446 QualType& ConvertedType) {
3447 QualType ToPointeeType;
3448 if (const BlockPointerType *ToBlockPtr =
3449 ToType->getAs<BlockPointerType>())
3450 ToPointeeType = ToBlockPtr->getPointeeType();
3451 else
3452 return false;
3453
3454 QualType FromPointeeType;
3455 if (const BlockPointerType *FromBlockPtr =
3456 FromType->getAs<BlockPointerType>())
3457 FromPointeeType = FromBlockPtr->getPointeeType();
3458 else
3459 return false;
3460 // We have pointer to blocks, check whether the only
3461 // differences in the argument and result types are in Objective-C
3462 // pointer conversions. If so, we permit the conversion.
3463
3464 const FunctionProtoType *FromFunctionType
3465 = FromPointeeType->getAs<FunctionProtoType>();
3466 const FunctionProtoType *ToFunctionType
3467 = ToPointeeType->getAs<FunctionProtoType>();
3468
3469 if (!FromFunctionType || !ToFunctionType)
3470 return false;
3471
3472 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3473 return true;
3474
3475 // Perform the quick checks that will tell us whether these
3476 // function types are obviously different.
3477 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3478 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3479 return false;
3480
3481 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3482 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3483 if (FromEInfo != ToEInfo)
3484 return false;
3485
3486 bool IncompatibleObjC = false;
3487 if (Context.hasSameType(FromFunctionType->getReturnType(),
3488 ToFunctionType->getReturnType())) {
3489 // Okay, the types match exactly. Nothing to do.
3490 } else {
3491 QualType RHS = FromFunctionType->getReturnType();
3492 QualType LHS = ToFunctionType->getReturnType();
3493 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3494 !RHS.hasQualifiers() && LHS.hasQualifiers())
3495 LHS = LHS.getUnqualifiedType();
3496
3497 if (Context.hasSameType(RHS,LHS)) {
3498 // OK exact match.
3499 } else if (isObjCPointerConversion(RHS, LHS,
3500 ConvertedType, IncompatibleObjC)) {
3501 if (IncompatibleObjC)
3502 return false;
3503 // Okay, we have an Objective-C pointer conversion.
3504 }
3505 else
3506 return false;
3507 }
3508
3509 // Check argument types.
3510 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3511 ArgIdx != NumArgs; ++ArgIdx) {
3512 IncompatibleObjC = false;
3513 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3514 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3515 if (Context.hasSameType(FromArgType, ToArgType)) {
3516 // Okay, the types match exactly. Nothing to do.
3517 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3518 ConvertedType, IncompatibleObjC)) {
3519 if (IncompatibleObjC)
3520 return false;
3521 // Okay, we have an Objective-C pointer conversion.
3522 } else
3523 // Argument types are too different. Abort.
3524 return false;
3525 }
3526
3528 bool CanUseToFPT, CanUseFromFPT;
3529 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3530 CanUseToFPT, CanUseFromFPT,
3531 NewParamInfos))
3532 return false;
3533
3534 ConvertedType = ToType;
3535 return true;
3536}
3537
3538enum {
3546};
3547
3548/// Attempts to get the FunctionProtoType from a Type. Handles
3549/// MemberFunctionPointers properly.
3551 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3552 return FPT;
3553
3554 if (auto *MPT = FromType->getAs<MemberPointerType>())
3555 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3556
3557 return nullptr;
3558}
3559
3561 QualType FromType, QualType ToType) {
3562 // If either type is not valid, include no extra info.
3563 if (FromType.isNull() || ToType.isNull()) {
3564 PDiag << ft_default;
3565 return;
3566 }
3567
3568 // Get the function type from the pointers.
3569 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3570 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3571 *ToMember = ToType->castAs<MemberPointerType>();
3572 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3573 ToMember->getMostRecentCXXRecordDecl())) {
3575 if (ToMember->isSugared())
3576 PDiag << Context.getCanonicalTagType(
3577 ToMember->getMostRecentCXXRecordDecl());
3578 else
3579 PDiag << ToMember->getQualifier();
3580 if (FromMember->isSugared())
3581 PDiag << Context.getCanonicalTagType(
3582 FromMember->getMostRecentCXXRecordDecl());
3583 else
3584 PDiag << FromMember->getQualifier();
3585 return;
3586 }
3587 FromType = FromMember->getPointeeType();
3588 ToType = ToMember->getPointeeType();
3589 }
3590
3591 if (FromType->isPointerType())
3592 FromType = FromType->getPointeeType();
3593 if (ToType->isPointerType())
3594 ToType = ToType->getPointeeType();
3595
3596 // Remove references.
3597 FromType = FromType.getNonReferenceType();
3598 ToType = ToType.getNonReferenceType();
3599
3600 // Don't print extra info for non-specialized template functions.
3601 if (FromType->isInstantiationDependentType() &&
3602 !FromType->getAs<TemplateSpecializationType>()) {
3603 PDiag << ft_default;
3604 return;
3605 }
3606
3607 // No extra info for same types.
3608 if (Context.hasSameType(FromType, ToType)) {
3609 PDiag << ft_default;
3610 return;
3611 }
3612
3613 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3614 *ToFunction = tryGetFunctionProtoType(ToType);
3615
3616 // Both types need to be function types.
3617 if (!FromFunction || !ToFunction) {
3618 PDiag << ft_default;
3619 return;
3620 }
3621
3622 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3623 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3624 << FromFunction->getNumParams();
3625 return;
3626 }
3627
3628 // Handle different parameter types.
3629 unsigned ArgPos;
3630 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3631 PDiag << ft_parameter_mismatch << ArgPos + 1
3632 << ToFunction->getParamType(ArgPos)
3633 << FromFunction->getParamType(ArgPos);
3634 return;
3635 }
3636
3637 // Handle different return type.
3638 if (!Context.hasSameType(FromFunction->getReturnType(),
3639 ToFunction->getReturnType())) {
3640 PDiag << ft_return_type << ToFunction->getReturnType()
3641 << FromFunction->getReturnType();
3642 return;
3643 }
3644
3645 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3646 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3647 << FromFunction->getMethodQuals();
3648 return;
3649 }
3650
3651 // Handle exception specification differences on canonical type (in C++17
3652 // onwards).
3654 ->isNothrow() !=
3655 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3656 ->isNothrow()) {
3657 PDiag << ft_noexcept;
3658 return;
3659 }
3660
3661 // Unable to find a difference, so add no extra info.
3662 PDiag << ft_default;
3663}
3664
3666 ArrayRef<QualType> New, unsigned *ArgPos,
3667 bool Reversed) {
3668 assert(llvm::size(Old) == llvm::size(New) &&
3669 "Can't compare parameters of functions with different number of "
3670 "parameters!");
3671
3672 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3673 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3674 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3675
3676 // Ignore address spaces in pointee type. This is to disallow overloading
3677 // on __ptr32/__ptr64 address spaces.
3678 QualType OldType =
3679 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3680 QualType NewType =
3681 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3682
3683 if (!Context.hasSameType(OldType, NewType)) {
3684 if (ArgPos)
3685 *ArgPos = Idx;
3686 return false;
3687 }
3688 }
3689 return true;
3690}
3691
3693 const FunctionProtoType *NewType,
3694 unsigned *ArgPos, bool Reversed) {
3695 return FunctionParamTypesAreEqual(OldType->param_types(),
3696 NewType->param_types(), ArgPos, Reversed);
3697}
3698
3700 const FunctionDecl *NewFunction,
3701 unsigned *ArgPos,
3702 bool Reversed) {
3703
3704 if (OldFunction->getNumNonObjectParams() !=
3705 NewFunction->getNumNonObjectParams())
3706 return false;
3707
3708 unsigned OldIgnore =
3710 unsigned NewIgnore =
3712
3713 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3714 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3715
3716 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3717 NewPT->param_types().slice(NewIgnore),
3718 ArgPos, Reversed);
3719}
3720
3722 CastKind &Kind,
3723 CXXCastPath& BasePath,
3724 bool IgnoreBaseAccess,
3725 bool Diagnose) {
3726 QualType FromType = From->getType();
3727 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3728
3729 Kind = CK_BitCast;
3730
3731 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3734 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3735 DiagRuntimeBehavior(From->getExprLoc(), From,
3736 PDiag(diag::warn_impcast_bool_to_null_pointer)
3737 << ToType << From->getSourceRange());
3738 else if (!isUnevaluatedContext())
3739 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3740 << ToType << From->getSourceRange();
3741 }
3742 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3743 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3744 QualType FromPointeeType = FromPtrType->getPointeeType(),
3745 ToPointeeType = ToPtrType->getPointeeType();
3746
3747 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3748 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3749 // We must have a derived-to-base conversion. Check an
3750 // ambiguous or inaccessible conversion.
3751 unsigned InaccessibleID = 0;
3752 unsigned AmbiguousID = 0;
3753 if (Diagnose) {
3754 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3755 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3756 }
3758 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3759 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3760 &BasePath, IgnoreBaseAccess))
3761 return true;
3762
3763 // The conversion was successful.
3764 Kind = CK_DerivedToBase;
3765 }
3766
3767 if (Diagnose && !IsCStyleOrFunctionalCast &&
3768 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3769 assert(getLangOpts().MSVCCompat &&
3770 "this should only be possible with MSVCCompat!");
3771 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3772 << From->getSourceRange();
3773 }
3774 }
3775 } else if (const ObjCObjectPointerType *ToPtrType =
3776 ToType->getAs<ObjCObjectPointerType>()) {
3777 if (const ObjCObjectPointerType *FromPtrType =
3778 FromType->getAs<ObjCObjectPointerType>()) {
3779 // Objective-C++ conversions are always okay.
3780 // FIXME: We should have a different class of conversions for the
3781 // Objective-C++ implicit conversions.
3782 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3783 return false;
3784 } else if (FromType->isBlockPointerType()) {
3785 Kind = CK_BlockPointerToObjCPointerCast;
3786 } else {
3787 Kind = CK_CPointerToObjCPointerCast;
3788 }
3789 } else if (ToType->isBlockPointerType()) {
3790 if (!FromType->isBlockPointerType())
3791 Kind = CK_AnyPointerToBlockPointerCast;
3792 }
3793
3794 // We shouldn't fall into this case unless it's valid for other
3795 // reasons.
3797 Kind = CK_NullToPointer;
3798
3799 return false;
3800}
3801
3803 QualType ToType,
3804 bool InOverloadResolution,
3805 QualType &ConvertedType) {
3806 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3807 if (!ToTypePtr)
3808 return false;
3809
3810 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3812 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3814 ConvertedType = ToType;
3815 return true;
3816 }
3817
3818 // Otherwise, both types have to be member pointers.
3819 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3820 if (!FromTypePtr)
3821 return false;
3822
3823 // A pointer to member of B can be converted to a pointer to member of D,
3824 // where D is derived from B (C++ 4.11p2).
3825 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3826 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3827
3828 if (!declaresSameEntity(FromClass, ToClass) &&
3829 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3830 ConvertedType = Context.getMemberPointerType(
3831 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3832 return true;
3833 }
3834
3835 return false;
3836}
3837
3839 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3840 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3841 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3842 // Lock down the inheritance model right now in MS ABI, whether or not the
3843 // pointee types are the same.
3844 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3845 (void)isCompleteType(CheckLoc, FromType);
3846 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3847 }
3848
3849 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3850 if (!FromPtrType) {
3851 // This must be a null pointer to member pointer conversion
3852 Kind = CK_NullToMemberPointer;
3854 }
3855
3856 // T == T, modulo cv
3858 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3859 ToPtrType->getPointeeType()))
3861
3862 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3863 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3864
3865 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3866 const CXXRecordDecl *Cls) {
3867 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3868 PD << Qual;
3869 else
3870 PD << Context.getCanonicalTagType(Cls);
3871 };
3872 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3873 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3874 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3875 return PD;
3876 };
3877
3878 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3880 std::swap(Base, Derived);
3881
3882 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3883 /*DetectVirtual=*/true);
3884 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3886
3887 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3888 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3889 PD << int(Direction);
3890 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3891 Diag(CheckLoc, PD);
3893 }
3894
3895 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3896 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3897 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3898 Diag(CheckLoc, PD);
3900 }
3901
3902 // Must be a base to derived member conversion.
3903 BuildBasePathArray(Paths, BasePath);
3905 ? CK_DerivedToBaseMemberPointer
3906 : CK_BaseToDerivedMemberPointer;
3907
3908 if (!IgnoreBaseAccess)
3909 switch (CheckBaseClassAccess(
3910 CheckLoc, Base, Derived, Paths.front(),
3912 ? diag::err_upcast_to_inaccessible_base
3913 : diag::err_downcast_from_inaccessible_base,
3914 [&](PartialDiagnostic &PD) {
3915 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3916 DerivedQual = ToPtrType->getQualifier();
3917 if (Direction == MemberPointerConversionDirection::Upcast)
3918 std::swap(BaseQual, DerivedQual);
3919 DiagCls(PD, DerivedQual, Derived);
3920 DiagCls(PD, BaseQual, Base);
3921 })) {
3923 case Sema::AR_delayed:
3924 case Sema::AR_dependent:
3925 // Optimistically assume that the delayed and dependent cases
3926 // will work out.
3927 break;
3928
3931 }
3932
3934}
3935
3936/// Determine whether the lifetime conversion between the two given
3937/// qualifiers sets is nontrivial.
3939 Qualifiers ToQuals) {
3940 // Converting anything to const __unsafe_unretained is trivial.
3941 if (ToQuals.hasConst() &&
3943 return false;
3944
3945 return true;
3946}
3947
3948/// Perform a single iteration of the loop for checking if a qualification
3949/// conversion is valid.
3950///
3951/// Specifically, check whether any change between the qualifiers of \p
3952/// FromType and \p ToType is permissible, given knowledge about whether every
3953/// outer layer is const-qualified.
3955 bool CStyle, bool IsTopLevel,
3956 bool &PreviousToQualsIncludeConst,
3957 bool &ObjCLifetimeConversion,
3958 const ASTContext &Ctx) {
3959 Qualifiers FromQuals = FromType.getQualifiers();
3960 Qualifiers ToQuals = ToType.getQualifiers();
3961
3962 // Ignore __unaligned qualifier.
3963 FromQuals.removeUnaligned();
3964
3965 // Objective-C ARC:
3966 // Check Objective-C lifetime conversions.
3967 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3968 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3969 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3970 ObjCLifetimeConversion = true;
3971 FromQuals.removeObjCLifetime();
3972 ToQuals.removeObjCLifetime();
3973 } else {
3974 // Qualification conversions cannot cast between different
3975 // Objective-C lifetime qualifiers.
3976 return false;
3977 }
3978 }
3979
3980 // Allow addition/removal of GC attributes but not changing GC attributes.
3981 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3982 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3983 FromQuals.removeObjCGCAttr();
3984 ToQuals.removeObjCGCAttr();
3985 }
3986
3987 // __ptrauth qualifiers must match exactly.
3988 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3989 return false;
3990
3991 // -- for every j > 0, if const is in cv 1,j then const is in cv
3992 // 2,j, and similarly for volatile.
3993 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3994 return false;
3995
3996 // If address spaces mismatch:
3997 // - in top level it is only valid to convert to addr space that is a
3998 // superset in all cases apart from C-style casts where we allow
3999 // conversions between overlapping address spaces.
4000 // - in non-top levels it is not a valid conversion.
4001 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
4002 (!IsTopLevel ||
4003 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
4004 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
4005 return false;
4006
4007 // -- if the cv 1,j and cv 2,j are different, then const is in
4008 // every cv for 0 < k < j.
4009 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
4010 !PreviousToQualsIncludeConst)
4011 return false;
4012
4013 // The following wording is from C++20, where the result of the conversion
4014 // is T3, not T2.
4015 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
4016 // "array of unknown bound of"
4017 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
4018 return false;
4019
4020 // -- if the resulting P3,i is different from P1,i [...], then const is
4021 // added to every cv 3_k for 0 < k < i.
4022 if (!CStyle && FromType->isConstantArrayType() &&
4023 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
4024 return false;
4025
4026 // Keep track of whether all prior cv-qualifiers in the "to" type
4027 // include const.
4028 PreviousToQualsIncludeConst =
4029 PreviousToQualsIncludeConst && ToQuals.hasConst();
4030 return true;
4031}
4032
4033bool
4035 bool CStyle, bool &ObjCLifetimeConversion) {
4036 FromType = Context.getCanonicalType(FromType);
4037 ToType = Context.getCanonicalType(ToType);
4038 ObjCLifetimeConversion = false;
4039
4040 // If FromType and ToType are the same type, this is not a
4041 // qualification conversion.
4042 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
4043 return false;
4044
4045 // (C++ 4.4p4):
4046 // A conversion can add cv-qualifiers at levels other than the first
4047 // in multi-level pointers, subject to the following rules: [...]
4048 bool PreviousToQualsIncludeConst = true;
4049 bool UnwrappedAnyPointer = false;
4050 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
4051 if (!isQualificationConversionStep(FromType, ToType, CStyle,
4052 !UnwrappedAnyPointer,
4053 PreviousToQualsIncludeConst,
4054 ObjCLifetimeConversion, getASTContext()))
4055 return false;
4056 UnwrappedAnyPointer = true;
4057 }
4058
4059 // We are left with FromType and ToType being the pointee types
4060 // after unwrapping the original FromType and ToType the same number
4061 // of times. If we unwrapped any pointers, and if FromType and
4062 // ToType have the same unqualified type (since we checked
4063 // qualifiers above), then this is a qualification conversion.
4064 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
4065}
4066
4067/// - Determine whether this is a conversion from a scalar type to an
4068/// atomic type.
4069///
4070/// If successful, updates \c SCS's second and third steps in the conversion
4071/// sequence to finish the conversion.
4072static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4073 bool InOverloadResolution,
4075 bool CStyle) {
4076 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4077 if (!ToAtomic)
4078 return false;
4079
4081 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4082 InOverloadResolution, InnerSCS,
4083 CStyle, /*AllowObjCWritebackConversion=*/false))
4084 return false;
4085
4086 SCS.Second = InnerSCS.Second;
4087 SCS.setToType(1, InnerSCS.getToType(1));
4088 SCS.Third = InnerSCS.Third;
4091 SCS.setToType(2, InnerSCS.getToType(2));
4092 return true;
4093}
4094
4096 QualType ToType,
4097 bool InOverloadResolution,
4099 bool CStyle) {
4100 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4101 if (!ToOBT)
4102 return false;
4103
4104 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4105 QualType FromType = From->getType();
4106 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4107 return false;
4108
4110 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4111 InOverloadResolution, InnerSCS, CStyle,
4112 /*AllowObjCWritebackConversion=*/false))
4113 return false;
4114
4115 SCS.Second = InnerSCS.Second;
4116 SCS.setToType(1, InnerSCS.getToType(1));
4117 SCS.Third = InnerSCS.Third;
4120 SCS.setToType(2, InnerSCS.getToType(2));
4121 return true;
4122}
4123
4126 QualType Type) {
4127 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4128 if (CtorType->getNumParams() > 0) {
4129 QualType FirstArg = CtorType->getParamType(0);
4130 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4131 return true;
4132 }
4133 return false;
4134}
4135
4136static OverloadingResult
4138 CXXRecordDecl *To,
4140 OverloadCandidateSet &CandidateSet,
4141 bool AllowExplicit) {
4143 for (auto *D : S.LookupConstructors(To)) {
4144 auto Info = getConstructorInfo(D);
4145 if (!Info)
4146 continue;
4147
4148 bool Usable = !Info.Constructor->isInvalidDecl() &&
4149 S.isInitListConstructor(Info.Constructor);
4150 if (Usable) {
4151 bool SuppressUserConversions = false;
4152 if (Info.ConstructorTmpl)
4153 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4154 /*ExplicitArgs*/ nullptr, From,
4155 CandidateSet, SuppressUserConversions,
4156 /*PartialOverloading*/ false,
4157 AllowExplicit);
4158 else
4159 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4160 CandidateSet, SuppressUserConversions,
4161 /*PartialOverloading*/ false, AllowExplicit);
4162 }
4163 }
4164
4165 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4166
4168 switch (auto Result =
4169 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4170 case OR_Deleted:
4171 case OR_Success: {
4172 // Record the standard conversion we used and the conversion function.
4174 QualType ThisType = Constructor->getFunctionObjectParameterType();
4175 // Initializer lists don't have conversions as such.
4177 User.HadMultipleCandidates = HadMultipleCandidates;
4179 User.FoundConversionFunction = Best->FoundDecl;
4181 User.After.setFromType(ThisType);
4182 User.After.setAllToTypes(ToType);
4183 return Result;
4184 }
4185
4187 return OR_No_Viable_Function;
4188 case OR_Ambiguous:
4189 return OR_Ambiguous;
4190 }
4191
4192 llvm_unreachable("Invalid OverloadResult!");
4193}
4194
4195/// Determines whether there is a user-defined conversion sequence
4196/// (C++ [over.ics.user]) that converts expression From to the type
4197/// ToType. If such a conversion exists, User will contain the
4198/// user-defined conversion sequence that performs such a conversion
4199/// and this routine will return true. Otherwise, this routine returns
4200/// false and User is unspecified.
4201///
4202/// \param AllowExplicit true if the conversion should consider C++0x
4203/// "explicit" conversion functions as well as non-explicit conversion
4204/// functions (C++0x [class.conv.fct]p2).
4205///
4206/// \param AllowObjCConversionOnExplicit true if the conversion should
4207/// allow an extra Objective-C pointer conversion on uses of explicit
4208/// constructors. Requires \c AllowExplicit to also be set.
4209static OverloadingResult
4212 OverloadCandidateSet &CandidateSet,
4213 AllowedExplicit AllowExplicit,
4214 bool AllowObjCConversionOnExplicit) {
4215 assert(AllowExplicit != AllowedExplicit::None ||
4216 !AllowObjCConversionOnExplicit);
4218
4219 // Whether we will only visit constructors.
4220 bool ConstructorsOnly = false;
4221
4222 // If the type we are conversion to is a class type, enumerate its
4223 // constructors.
4224 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4225 // C++ [over.match.ctor]p1:
4226 // When objects of class type are direct-initialized (8.5), or
4227 // copy-initialized from an expression of the same or a
4228 // derived class type (8.5), overload resolution selects the
4229 // constructor. [...] For copy-initialization, the candidate
4230 // functions are all the converting constructors (12.3.1) of
4231 // that class. The argument list is the expression-list within
4232 // the parentheses of the initializer.
4233 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4234 (From->getType()->isRecordType() &&
4235 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4236 ConstructorsOnly = true;
4237
4238 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4239 // We're not going to find any constructors.
4240 } else if (auto *ToRecordDecl =
4241 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4242 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4243
4244 Expr **Args = &From;
4245 unsigned NumArgs = 1;
4246 bool ListInitializing = false;
4247 SmallVector<Expr *, 8> ExpandedInits;
4248 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4249 // But first, see if there is an init-list-constructor that will work.
4251 S, From, ToType, ToRecordDecl, User, CandidateSet,
4252 AllowExplicit == AllowedExplicit::All);
4254 return Result;
4255 // Never mind.
4256 CandidateSet.clear(
4258
4259 // If we're list-initializing, we pass the individual elements as
4260 // arguments, not the entire list.
4262 S.getInitsWithEmbedExpanded(InitList, ExpandedInits);
4263 Args = Inits.data();
4264 NumArgs = Inits.size();
4265 ListInitializing = true;
4266 }
4267
4268 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4269 auto Info = getConstructorInfo(D);
4270 if (!Info)
4271 continue;
4272
4273 bool Usable = !Info.Constructor->isInvalidDecl();
4274 if (!ListInitializing)
4275 Usable = Usable && Info.Constructor->isConvertingConstructor(
4276 /*AllowExplicit*/ true);
4277 if (Usable) {
4278 bool SuppressUserConversions = !ConstructorsOnly;
4279 // C++20 [over.best.ics.general]/4.5:
4280 // if the target is the first parameter of a constructor [of class
4281 // X] and the constructor [...] is a candidate by [...] the second
4282 // phase of [over.match.list] when the initializer list has exactly
4283 // one element that is itself an initializer list, [...] and the
4284 // conversion is to X or reference to cv X, user-defined conversion
4285 // sequences are not considered.
4286 if (SuppressUserConversions && ListInitializing) {
4287 SuppressUserConversions =
4288 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4289 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4290 ToType);
4291 }
4292 if (Info.ConstructorTmpl)
4294 Info.ConstructorTmpl, Info.FoundDecl,
4295 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4296 CandidateSet, SuppressUserConversions,
4297 /*PartialOverloading*/ false,
4298 AllowExplicit == AllowedExplicit::All);
4299 else
4300 // Allow one user-defined conversion when user specifies a
4301 // From->ToType conversion via an static cast (c-style, etc).
4302 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4303 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4304 SuppressUserConversions,
4305 /*PartialOverloading*/ false,
4306 AllowExplicit == AllowedExplicit::All);
4307 }
4308 }
4309 }
4310 }
4311
4312 // Enumerate conversion functions, if we're allowed to.
4313 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4314 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4315 // No conversion functions from incomplete types.
4316 } else if (const RecordType *FromRecordType =
4317 From->getType()->getAsCanonical<RecordType>()) {
4318 if (auto *FromRecordDecl =
4319 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4320 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4321 // Add all of the conversion functions as candidates.
4322 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4323 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4324 DeclAccessPair FoundDecl = I.getPair();
4325 NamedDecl *D = FoundDecl.getDecl();
4326 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4327 if (isa<UsingShadowDecl>(D))
4328 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4329
4330 CXXConversionDecl *Conv;
4331 FunctionTemplateDecl *ConvTemplate;
4332 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4333 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4334 else
4335 Conv = cast<CXXConversionDecl>(D);
4336
4337 if (ConvTemplate)
4339 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4340 CandidateSet, AllowObjCConversionOnExplicit,
4341 AllowExplicit != AllowedExplicit::None);
4342 else
4343 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4344 CandidateSet, AllowObjCConversionOnExplicit,
4345 AllowExplicit != AllowedExplicit::None);
4346 }
4347 }
4348 }
4349
4350 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4351
4353 switch (auto Result =
4354 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4355 case OR_Success:
4356 case OR_Deleted:
4357 // Record the standard conversion we used and the conversion function.
4359 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4360 // C++ [over.ics.user]p1:
4361 // If the user-defined conversion is specified by a
4362 // constructor (12.3.1), the initial standard conversion
4363 // sequence converts the source type to the type required by
4364 // the argument of the constructor.
4365 //
4366 if (isa<InitListExpr>(From)) {
4367 // Initializer lists don't have conversions as such.
4369 User.Before.FromBracedInitList = true;
4370 } else {
4371 if (Best->Conversions[0].isEllipsis())
4372 User.EllipsisConversion = true;
4373 else {
4374 User.Before = Best->Conversions[0].Standard;
4375 User.EllipsisConversion = false;
4376 }
4377 }
4378 User.HadMultipleCandidates = HadMultipleCandidates;
4380 User.FoundConversionFunction = Best->FoundDecl;
4382 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4383 User.After.setAllToTypes(ToType);
4384 return Result;
4385 }
4386 if (CXXConversionDecl *Conversion
4387 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4388
4389 assert(Best->HasFinalConversion);
4390
4391 // C++ [over.ics.user]p1:
4392 //
4393 // [...] If the user-defined conversion is specified by a
4394 // conversion function (12.3.2), the initial standard
4395 // conversion sequence converts the source type to the
4396 // implicit object parameter of the conversion function.
4397 User.Before = Best->Conversions[0].Standard;
4398 User.HadMultipleCandidates = HadMultipleCandidates;
4399 User.ConversionFunction = Conversion;
4400 User.FoundConversionFunction = Best->FoundDecl;
4401 User.EllipsisConversion = false;
4402
4403 // C++ [over.ics.user]p2:
4404 // The second standard conversion sequence converts the
4405 // result of the user-defined conversion to the target type
4406 // for the sequence. Since an implicit conversion sequence
4407 // is an initialization, the special rules for
4408 // initialization by user-defined conversion apply when
4409 // selecting the best user-defined conversion for a
4410 // user-defined conversion sequence (see 13.3.3 and
4411 // 13.3.3.1).
4412 User.After = Best->FinalConversion;
4413 return Result;
4414 }
4415 llvm_unreachable("Not a constructor or conversion function?");
4416
4418 return OR_No_Viable_Function;
4419
4420 case OR_Ambiguous:
4421 return OR_Ambiguous;
4422 }
4423
4424 llvm_unreachable("Invalid OverloadResult!");
4425}
4426
4427bool
4430 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4432 OverloadingResult OvResult =
4433 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4434 CandidateSet, AllowedExplicit::None, false);
4435
4436 if (!(OvResult == OR_Ambiguous ||
4437 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4438 return false;
4439
4440 auto Cands = CandidateSet.CompleteCandidates(
4441 *this,
4443 From);
4444 if (OvResult == OR_Ambiguous)
4445 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4446 << From->getType() << ToType << From->getSourceRange();
4447 else { // OR_No_Viable_Function && !CandidateSet.empty()
4448 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4449 diag::err_typecheck_nonviable_condition_incomplete,
4450 From->getType(), From->getSourceRange()))
4451 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4452 << false << From->getType() << From->getSourceRange() << ToType;
4453 }
4454
4455 CandidateSet.NoteCandidates(
4456 *this, From, Cands);
4457 return true;
4458}
4459
4460// Helper for compareConversionFunctions that gets the FunctionType that the
4461// conversion-operator return value 'points' to, or nullptr.
4462static const FunctionType *
4464 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4465 const PointerType *RetPtrTy =
4466 ConvFuncTy->getReturnType()->getAs<PointerType>();
4467
4468 if (!RetPtrTy)
4469 return nullptr;
4470
4471 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4472}
4473
4474/// Compare the user-defined conversion functions or constructors
4475/// of two user-defined conversion sequences to determine whether any ordering
4476/// is possible.
4479 FunctionDecl *Function2) {
4480 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4481 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4482 if (!Conv1 || !Conv2)
4484
4485 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4487
4488 // Objective-C++:
4489 // If both conversion functions are implicitly-declared conversions from
4490 // a lambda closure type to a function pointer and a block pointer,
4491 // respectively, always prefer the conversion to a function pointer,
4492 // because the function pointer is more lightweight and is more likely
4493 // to keep code working.
4494 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4495 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4496 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4497 if (Block1 != Block2)
4498 return Block1 ? ImplicitConversionSequence::Worse
4500 }
4501
4502 // In order to support multiple calling conventions for the lambda conversion
4503 // operator (such as when the free and member function calling convention is
4504 // different), prefer the 'free' mechanism, followed by the calling-convention
4505 // of operator(). The latter is in place to support the MSVC-like solution of
4506 // defining ALL of the possible conversions in regards to calling-convention.
4507 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4508 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4509
4510 if (Conv1FuncRet && Conv2FuncRet &&
4511 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4512 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4513 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4514
4515 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4516 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4517
4518 CallingConv CallOpCC =
4519 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4521 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4523 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4524
4525 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4526 for (CallingConv CC : PrefOrder) {
4527 if (Conv1CC == CC)
4529 if (Conv2CC == CC)
4531 }
4532 }
4533
4535}
4536
4543
4544/// CompareImplicitConversionSequences - Compare two implicit
4545/// conversion sequences to determine whether one is better than the
4546/// other or if they are indistinguishable (C++ 13.3.3.2).
4549 const ImplicitConversionSequence& ICS1,
4550 const ImplicitConversionSequence& ICS2)
4551{
4552 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4553 // conversion sequences (as defined in 13.3.3.1)
4554 // -- a standard conversion sequence (13.3.3.1.1) is a better
4555 // conversion sequence than a user-defined conversion sequence or
4556 // an ellipsis conversion sequence, and
4557 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4558 // conversion sequence than an ellipsis conversion sequence
4559 // (13.3.3.1.3).
4560 //
4561 // C++0x [over.best.ics]p10:
4562 // For the purpose of ranking implicit conversion sequences as
4563 // described in 13.3.3.2, the ambiguous conversion sequence is
4564 // treated as a user-defined sequence that is indistinguishable
4565 // from any other user-defined conversion sequence.
4566
4567 // String literal to 'char *' conversion has been deprecated in C++03. It has
4568 // been removed from C++11. We still accept this conversion, if it happens at
4569 // the best viable function. Otherwise, this conversion is considered worse
4570 // than ellipsis conversion. Consider this as an extension; this is not in the
4571 // standard. For example:
4572 //
4573 // int &f(...); // #1
4574 // void f(char*); // #2
4575 // void g() { int &r = f("foo"); }
4576 //
4577 // In C++03, we pick #2 as the best viable function.
4578 // In C++11, we pick #1 as the best viable function, because ellipsis
4579 // conversion is better than string-literal to char* conversion (since there
4580 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4581 // convert arguments, #2 would be the best viable function in C++11.
4582 // If the best viable function has this conversion, a warning will be issued
4583 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4584
4585 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4588 // Ill-formedness must not differ
4589 ICS1.isBad() == ICS2.isBad())
4593
4594 if (ICS1.getKindRank() < ICS2.getKindRank())
4596 if (ICS2.getKindRank() < ICS1.getKindRank())
4598
4599 // The following checks require both conversion sequences to be of
4600 // the same kind.
4601 if (ICS1.getKind() != ICS2.getKind())
4603
4606
4607 // Two implicit conversion sequences of the same form are
4608 // indistinguishable conversion sequences unless one of the
4609 // following rules apply: (C++ 13.3.3.2p3):
4610
4611 // List-initialization sequence L1 is a better conversion sequence than
4612 // list-initialization sequence L2 if:
4613 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4614 // if not that,
4615 // — L1 and L2 convert to arrays of the same element type, and either the
4616 // number of elements n_1 initialized by L1 is less than the number of
4617 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4618 // an array of unknown bound and L1 does not,
4619 // even if one of the other rules in this paragraph would otherwise apply.
4620 if (!ICS1.isBad()) {
4621 bool StdInit1 = false, StdInit2 = false;
4624 nullptr);
4627 nullptr);
4628 if (StdInit1 != StdInit2)
4629 return StdInit1 ? ImplicitConversionSequence::Better
4631
4634 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4636 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4638 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4639 CAT2->getElementType())) {
4640 // Both to arrays of the same element type
4641 if (CAT1->getSize() != CAT2->getSize())
4642 // Different sized, the smaller wins
4643 return CAT1->getSize().ult(CAT2->getSize())
4648 // One is incomplete, it loses
4652 }
4653 }
4654 }
4655
4656 if (ICS1.isStandard())
4657 // Standard conversion sequence S1 is a better conversion sequence than
4658 // standard conversion sequence S2 if [...]
4660 ICS1.Standard, ICS2.Standard);
4661 else if (ICS1.isUserDefined()) {
4662 // With lazy template loading, it is possible to find non-canonical
4663 // FunctionDecls, depending on when redecl chains are completed. Make sure
4664 // to compare the canonical decls of conversion functions. This avoids
4665 // ambiguity problems for templated conversion operators.
4666 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4667 if (ConvFunc1)
4668 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4669 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4670 if (ConvFunc2)
4671 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4672 // User-defined conversion sequence U1 is a better conversion
4673 // sequence than another user-defined conversion sequence U2 if
4674 // they contain the same user-defined conversion function or
4675 // constructor and if the second standard conversion sequence of
4676 // U1 is better than the second standard conversion sequence of
4677 // U2 (C++ 13.3.3.2p3).
4678 if (ConvFunc1 == ConvFunc2)
4680 ICS1.UserDefined.After,
4681 ICS2.UserDefined.After);
4682 else
4686 }
4687
4688 return Result;
4689}
4690
4691// Per 13.3.3.2p3, compare the given standard conversion sequences to
4692// determine if one is a proper subset of the other.
4695 const StandardConversionSequence& SCS1,
4696 const StandardConversionSequence& SCS2) {
4699
4700 // the identity conversion sequence is considered to be a subsequence of
4701 // any non-identity conversion sequence
4702 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4704 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4706
4707 if (SCS1.Second != SCS2.Second) {
4708 if (SCS1.Second == ICK_Identity)
4710 else if (SCS2.Second == ICK_Identity)
4712 else
4714 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4716
4717 if (SCS1.Third == SCS2.Third) {
4718 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4720 }
4721
4722 if (SCS1.Third == ICK_Identity)
4726
4727 if (SCS2.Third == ICK_Identity)
4731
4733}
4734
4735/// Determine whether one of the given reference bindings is better
4736/// than the other based on what kind of bindings they are.
4737static bool
4739 const StandardConversionSequence &SCS2) {
4740 // C++0x [over.ics.rank]p3b4:
4741 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4742 // implicit object parameter of a non-static member function declared
4743 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4744 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4745 // lvalue reference to a function lvalue and S2 binds an rvalue
4746 // reference*.
4747 //
4748 // FIXME: Rvalue references. We're going rogue with the above edits,
4749 // because the semantics in the current C++0x working paper (N3225 at the
4750 // time of this writing) break the standard definition of std::forward
4751 // and std::reference_wrapper when dealing with references to functions.
4752 // Proposed wording changes submitted to CWG for consideration.
4755 return false;
4756
4757 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4758 SCS2.IsLvalueReference) ||
4761}
4762
4768
4769/// Returns kind of fixed enum promotion the \a SCS uses.
4770static FixedEnumPromotion
4772
4773 if (SCS.Second != ICK_Integral_Promotion)
4775
4776 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4777 if (!Enum)
4779
4780 if (!Enum->isFixed())
4782
4783 QualType UnderlyingType = Enum->getIntegerType();
4784 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4786
4788}
4789
4790/// CompareStandardConversionSequences - Compare two standard
4791/// conversion sequences to determine whether one is better than the
4792/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4795 const StandardConversionSequence& SCS1,
4796 const StandardConversionSequence& SCS2)
4797{
4798 // Standard conversion sequence S1 is a better conversion sequence
4799 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4800
4801 // -- S1 is a proper subsequence of S2 (comparing the conversion
4802 // sequences in the canonical form defined by 13.3.3.1.1,
4803 // excluding any Lvalue Transformation; the identity conversion
4804 // sequence is considered to be a subsequence of any
4805 // non-identity conversion sequence) or, if not that,
4808 return CK;
4809
4810 // -- the rank of S1 is better than the rank of S2 (by the rules
4811 // defined below), or, if not that,
4812 ImplicitConversionRank Rank1 = SCS1.getRank();
4813 ImplicitConversionRank Rank2 = SCS2.getRank();
4814 if (Rank1 < Rank2)
4816 else if (Rank2 < Rank1)
4818
4819 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4820 // are indistinguishable unless one of the following rules
4821 // applies:
4822
4823 // A conversion that is not a conversion of a pointer, or
4824 // pointer to member, to bool is better than another conversion
4825 // that is such a conversion.
4827 return SCS2.isPointerConversionToBool()
4830
4831 // C++14 [over.ics.rank]p4b2:
4832 // This is retroactively applied to C++11 by CWG 1601.
4833 //
4834 // A conversion that promotes an enumeration whose underlying type is fixed
4835 // to its underlying type is better than one that promotes to the promoted
4836 // underlying type, if the two are different.
4839 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4840 FEP1 != FEP2)
4844
4845 // C++ [over.ics.rank]p4b2:
4846 //
4847 // If class B is derived directly or indirectly from class A,
4848 // conversion of B* to A* is better than conversion of B* to
4849 // void*, and conversion of A* to void* is better than conversion
4850 // of B* to void*.
4851 bool SCS1ConvertsToVoid
4853 bool SCS2ConvertsToVoid
4855 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4856 // Exactly one of the conversion sequences is a conversion to
4857 // a void pointer; it's the worse conversion.
4858 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4860 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4861 // Neither conversion sequence converts to a void pointer; compare
4862 // their derived-to-base conversions.
4864 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4865 return DerivedCK;
4866 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4867 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4868 // Both conversion sequences are conversions to void
4869 // pointers. Compare the source types to determine if there's an
4870 // inheritance relationship in their sources.
4871 QualType FromType1 = SCS1.getFromType();
4872 QualType FromType2 = SCS2.getFromType();
4873
4874 // Adjust the types we're converting from via the array-to-pointer
4875 // conversion, if we need to.
4876 if (SCS1.First == ICK_Array_To_Pointer)
4877 FromType1 = S.Context.getArrayDecayedType(FromType1);
4878 if (SCS2.First == ICK_Array_To_Pointer)
4879 FromType2 = S.Context.getArrayDecayedType(FromType2);
4880
4881 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4882 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4883
4884 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4886 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4888
4889 // Objective-C++: If one interface is more specific than the
4890 // other, it is the better one.
4891 const ObjCObjectPointerType* FromObjCPtr1
4892 = FromType1->getAs<ObjCObjectPointerType>();
4893 const ObjCObjectPointerType* FromObjCPtr2
4894 = FromType2->getAs<ObjCObjectPointerType>();
4895 if (FromObjCPtr1 && FromObjCPtr2) {
4896 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4897 FromObjCPtr2);
4898 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4899 FromObjCPtr1);
4900 if (AssignLeft != AssignRight) {
4901 return AssignLeft? ImplicitConversionSequence::Better
4903 }
4904 }
4905 }
4906
4907 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4908 // Check for a better reference binding based on the kind of bindings.
4909 if (isBetterReferenceBindingKind(SCS1, SCS2))
4911 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4913 }
4914
4915 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4916 // bullet 3).
4918 = CompareQualificationConversions(S, SCS1, SCS2))
4919 return QualCK;
4920
4923 return ObtCK;
4924
4925 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4926 // C++ [over.ics.rank]p3b4:
4927 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4928 // which the references refer are the same type except for
4929 // top-level cv-qualifiers, and the type to which the reference
4930 // initialized by S2 refers is more cv-qualified than the type
4931 // to which the reference initialized by S1 refers.
4932 QualType T1 = SCS1.getToType(2);
4933 QualType T2 = SCS2.getToType(2);
4934 T1 = S.Context.getCanonicalType(T1);
4935 T2 = S.Context.getCanonicalType(T2);
4936 Qualifiers T1Quals, T2Quals;
4937 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4938 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4939 if (UnqualT1 == UnqualT2) {
4940 // Objective-C++ ARC: If the references refer to objects with different
4941 // lifetimes, prefer bindings that don't change lifetime.
4947 }
4948
4949 // If the type is an array type, promote the element qualifiers to the
4950 // type for comparison.
4951 if (isa<ArrayType>(T1) && T1Quals)
4952 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4953 if (isa<ArrayType>(T2) && T2Quals)
4954 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4955 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4957 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4959 }
4960 }
4961
4962 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4963 // floating-to-integral conversion if the integral conversion
4964 // is between types of the same size.
4965 // For example:
4966 // void f(float);
4967 // void f(int);
4968 // int main {
4969 // long a;
4970 // f(a);
4971 // }
4972 // Here, MSVC will call f(int) instead of generating a compile error
4973 // as clang will do in standard mode.
4974 if (S.getLangOpts().MSVCCompat &&
4977 SCS2.Second == ICK_Floating_Integral &&
4978 S.Context.getTypeSize(SCS1.getFromType()) ==
4979 S.Context.getTypeSize(SCS1.getToType(2)))
4981
4982 // Prefer a compatible vector conversion over a lax vector conversion
4983 // For example:
4984 //
4985 // typedef float __v4sf __attribute__((__vector_size__(16)));
4986 // void f(vector float);
4987 // void f(vector signed int);
4988 // int main() {
4989 // __v4sf a;
4990 // f(a);
4991 // }
4992 // Here, we'd like to choose f(vector float) and not
4993 // report an ambiguous call error
4994 if (SCS1.Second == ICK_Vector_Conversion &&
4995 SCS2.Second == ICK_Vector_Conversion) {
4996 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4997 SCS1.getFromType(), SCS1.getToType(2));
4998 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4999 SCS2.getFromType(), SCS2.getToType(2));
5000
5001 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
5002 return SCS1IsCompatibleVectorConversion
5005 }
5006
5007 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
5009 bool SCS1IsCompatibleSVEVectorConversion =
5010 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
5011 bool SCS2IsCompatibleSVEVectorConversion =
5012 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
5013
5014 if (SCS1IsCompatibleSVEVectorConversion !=
5015 SCS2IsCompatibleSVEVectorConversion)
5016 return SCS1IsCompatibleSVEVectorConversion
5019 }
5020
5021 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
5023 bool SCS1IsCompatibleRVVVectorConversion =
5025 bool SCS2IsCompatibleRVVVectorConversion =
5027
5028 if (SCS1IsCompatibleRVVVectorConversion !=
5029 SCS2IsCompatibleRVVVectorConversion)
5030 return SCS1IsCompatibleRVVVectorConversion
5033 }
5035}
5036
5037/// CompareOverflowBehaviorConversions - Compares two standard conversion
5038/// sequences to determine whether they can be ranked based on their
5039/// OverflowBehaviorType's underlying type.
5055
5056/// CompareQualificationConversions - Compares two standard conversion
5057/// sequences to determine whether they can be ranked based on their
5058/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
5061 const StandardConversionSequence& SCS1,
5062 const StandardConversionSequence& SCS2) {
5063 // C++ [over.ics.rank]p3:
5064 // -- S1 and S2 differ only in their qualification conversion and
5065 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
5066 // [C++98]
5067 // [...] and the cv-qualification signature of type T1 is a proper subset
5068 // of the cv-qualification signature of type T2, and S1 is not the
5069 // deprecated string literal array-to-pointer conversion (4.2).
5070 // [C++2a]
5071 // [...] where T1 can be converted to T2 by a qualification conversion.
5072 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5073 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5075
5076 // FIXME: the example in the standard doesn't use a qualification
5077 // conversion (!)
5078 QualType T1 = SCS1.getToType(2);
5079 QualType T2 = SCS2.getToType(2);
5080 T1 = S.Context.getCanonicalType(T1);
5081 T2 = S.Context.getCanonicalType(T2);
5082 assert(!T1->isReferenceType() && !T2->isReferenceType());
5083 Qualifiers T1Quals, T2Quals;
5084 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5085 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5086
5087 // If the types are the same, we won't learn anything by unwrapping
5088 // them.
5089 if (UnqualT1 == UnqualT2)
5091
5092 // Don't ever prefer a standard conversion sequence that uses the deprecated
5093 // string literal array to pointer conversion.
5094 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5095 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5096
5097 // Objective-C++ ARC:
5098 // Prefer qualification conversions not involving a change in lifetime
5099 // to qualification conversions that do change lifetime.
5102 CanPick1 = false;
5105 CanPick2 = false;
5106
5107 bool ObjCLifetimeConversion;
5108 if (CanPick1 &&
5109 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5110 CanPick1 = false;
5111 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5112 // directions, so we can't short-cut this second check in general.
5113 if (CanPick2 &&
5114 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5115 CanPick2 = false;
5116
5117 if (CanPick1 != CanPick2)
5118 return CanPick1 ? ImplicitConversionSequence::Better
5121}
5122
5123/// CompareDerivedToBaseConversions - Compares two standard conversion
5124/// sequences to determine whether they can be ranked based on their
5125/// various kinds of derived-to-base conversions (C++
5126/// [over.ics.rank]p4b3). As part of these checks, we also look at
5127/// conversions between Objective-C interface types.
5130 const StandardConversionSequence& SCS1,
5131 const StandardConversionSequence& SCS2) {
5132 QualType FromType1 = SCS1.getFromType();
5133 QualType ToType1 = SCS1.getToType(1);
5134 QualType FromType2 = SCS2.getFromType();
5135 QualType ToType2 = SCS2.getToType(1);
5136
5137 // Adjust the types we're converting from via the array-to-pointer
5138 // conversion, if we need to.
5139 if (SCS1.First == ICK_Array_To_Pointer)
5140 FromType1 = S.Context.getArrayDecayedType(FromType1);
5141 if (SCS2.First == ICK_Array_To_Pointer)
5142 FromType2 = S.Context.getArrayDecayedType(FromType2);
5143
5144 // Canonicalize all of the types.
5145 FromType1 = S.Context.getCanonicalType(FromType1);
5146 ToType1 = S.Context.getCanonicalType(ToType1);
5147 FromType2 = S.Context.getCanonicalType(FromType2);
5148 ToType2 = S.Context.getCanonicalType(ToType2);
5149
5150 // C++ [over.ics.rank]p4b3:
5151 //
5152 // If class B is derived directly or indirectly from class A and
5153 // class C is derived directly or indirectly from B,
5154 //
5155 // Compare based on pointer conversions.
5156 if (SCS1.Second == ICK_Pointer_Conversion &&
5158 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5159 FromType1->isPointerType() && FromType2->isPointerType() &&
5160 ToType1->isPointerType() && ToType2->isPointerType()) {
5161 QualType FromPointee1 =
5163 QualType ToPointee1 =
5165 QualType FromPointee2 =
5167 QualType ToPointee2 =
5169
5170 // -- conversion of C* to B* is better than conversion of C* to A*,
5171 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5172 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5174 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5176 }
5177
5178 // -- conversion of B* to A* is better than conversion of C* to A*,
5179 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5180 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5182 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5184 }
5185 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5187 const ObjCObjectPointerType *FromPtr1
5188 = FromType1->getAs<ObjCObjectPointerType>();
5189 const ObjCObjectPointerType *FromPtr2
5190 = FromType2->getAs<ObjCObjectPointerType>();
5191 const ObjCObjectPointerType *ToPtr1
5192 = ToType1->getAs<ObjCObjectPointerType>();
5193 const ObjCObjectPointerType *ToPtr2
5194 = ToType2->getAs<ObjCObjectPointerType>();
5195
5196 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5197 // Apply the same conversion ranking rules for Objective-C pointer types
5198 // that we do for C++ pointers to class types. However, we employ the
5199 // Objective-C pseudo-subtyping relationship used for assignment of
5200 // Objective-C pointer types.
5201 bool FromAssignLeft
5202 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5203 bool FromAssignRight
5204 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5205 bool ToAssignLeft
5206 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5207 bool ToAssignRight
5208 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5209
5210 // A conversion to an a non-id object pointer type or qualified 'id'
5211 // type is better than a conversion to 'id'.
5212 if (ToPtr1->isObjCIdType() &&
5213 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5215 if (ToPtr2->isObjCIdType() &&
5216 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5218
5219 // A conversion to a non-id object pointer type is better than a
5220 // conversion to a qualified 'id' type
5221 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5223 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5225
5226 // A conversion to an a non-Class object pointer type or qualified 'Class'
5227 // type is better than a conversion to 'Class'.
5228 if (ToPtr1->isObjCClassType() &&
5229 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5231 if (ToPtr2->isObjCClassType() &&
5232 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5234
5235 // A conversion to a non-Class object pointer type is better than a
5236 // conversion to a qualified 'Class' type.
5237 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5239 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5241
5242 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5243 if (S.Context.hasSameType(FromType1, FromType2) &&
5244 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5245 (ToAssignLeft != ToAssignRight)) {
5246 if (FromPtr1->isSpecialized()) {
5247 // "conversion of B<A> * to B * is better than conversion of B * to
5248 // C *.
5249 bool IsFirstSame =
5250 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5251 bool IsSecondSame =
5252 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5253 if (IsFirstSame) {
5254 if (!IsSecondSame)
5256 } else if (IsSecondSame)
5258 }
5259 return ToAssignLeft? ImplicitConversionSequence::Worse
5261 }
5262
5263 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5264 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5265 (FromAssignLeft != FromAssignRight))
5266 return FromAssignLeft? ImplicitConversionSequence::Better
5268 }
5269 }
5270
5271 // Ranking of member-pointer types.
5272 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5273 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5274 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5275 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5276 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5277 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5278 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5279 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5280 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5281 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5282 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5283 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5284 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5285 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5287 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5289 }
5290 // conversion of B::* to C::* is better than conversion of A::* to C::*
5291 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5292 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5294 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5296 }
5297 }
5298
5299 if (SCS1.Second == ICK_Derived_To_Base) {
5300 // -- conversion of C to B is better than conversion of C to A,
5301 // -- binding of an expression of type C to a reference of type
5302 // B& is better than binding an expression of type C to a
5303 // reference of type A&,
5304 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5305 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5306 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5308 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5310 }
5311
5312 // -- conversion of B to A is better than conversion of C to A.
5313 // -- binding of an expression of type B to a reference of type
5314 // A& is better than binding an expression of type C to a
5315 // reference of type A&,
5316 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5317 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5318 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5320 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5322 }
5323 }
5324
5326}
5327
5329 if (!T.getQualifiers().hasUnaligned())
5330 return T;
5331
5332 Qualifiers Q;
5333 T = Ctx.getUnqualifiedArrayType(T, Q);
5334 Q.removeUnaligned();
5335 return Ctx.getQualifiedType(T, Q);
5336}
5337
5340 QualType OrigT1, QualType OrigT2,
5341 ReferenceConversions *ConvOut) {
5342 assert(!OrigT1->isReferenceType() &&
5343 "T1 must be the pointee type of the reference type");
5344 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5345
5346 QualType T1 = Context.getCanonicalType(OrigT1);
5347 QualType T2 = Context.getCanonicalType(OrigT2);
5348 Qualifiers T1Quals, T2Quals;
5349 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5350 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5351
5352 ReferenceConversions ConvTmp;
5353 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5354 Conv = ReferenceConversions();
5355
5356 // C++2a [dcl.init.ref]p4:
5357 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5358 // reference-related to "cv2 T2" if T1 is similar to T2, or
5359 // T1 is a base class of T2.
5360 // "cv1 T1" is reference-compatible with "cv2 T2" if
5361 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5362 // "pointer to cv1 T1" via a standard conversion sequence.
5363
5364 // Check for standard conversions we can apply to pointers: derived-to-base
5365 // conversions, ObjC pointer conversions, and function pointer conversions.
5366 // (Qualification conversions are checked last.)
5367 if (UnqualT1 == UnqualT2) {
5368 // Nothing to do.
5369 } else if (isCompleteType(Loc, OrigT2) &&
5370 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5371 Conv |= ReferenceConversions::DerivedToBase;
5372 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5373 UnqualT2->isObjCObjectOrInterfaceType() &&
5374 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5375 Conv |= ReferenceConversions::ObjC;
5376 else if (UnqualT2->isFunctionType() &&
5377 IsFunctionConversion(UnqualT2, UnqualT1)) {
5378 Conv |= ReferenceConversions::Function;
5379 // No need to check qualifiers; function types don't have them.
5380 return Ref_Compatible;
5381 }
5382 bool ConvertedReferent = Conv != 0;
5383
5384 // We can have a qualification conversion. Compute whether the types are
5385 // similar at the same time.
5386 bool PreviousToQualsIncludeConst = true;
5387 bool TopLevel = true;
5388 do {
5389 if (T1 == T2)
5390 break;
5391
5392 // We will need a qualification conversion.
5393 Conv |= ReferenceConversions::Qualification;
5394
5395 // Track whether we performed a qualification conversion anywhere other
5396 // than the top level. This matters for ranking reference bindings in
5397 // overload resolution.
5398 if (!TopLevel)
5399 Conv |= ReferenceConversions::NestedQualification;
5400
5401 // MS compiler ignores __unaligned qualifier for references; do the same.
5402 T1 = withoutUnaligned(Context, T1);
5403 T2 = withoutUnaligned(Context, T2);
5404
5405 // If we find a qualifier mismatch, the types are not reference-compatible,
5406 // but are still be reference-related if they're similar.
5407 bool ObjCLifetimeConversion = false;
5408 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5409 PreviousToQualsIncludeConst,
5410 ObjCLifetimeConversion, getASTContext()))
5411 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5412 ? Ref_Related
5414
5415 // FIXME: Should we track this for any level other than the first?
5416 if (ObjCLifetimeConversion)
5417 Conv |= ReferenceConversions::ObjCLifetime;
5418
5419 TopLevel = false;
5420 } while (Context.UnwrapSimilarTypes(T1, T2));
5421
5422 // At this point, if the types are reference-related, we must either have the
5423 // same inner type (ignoring qualifiers), or must have already worked out how
5424 // to convert the referent.
5425 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5428}
5429
5430/// Look for a user-defined conversion to a value reference-compatible
5431/// with DeclType. Return true if something definite is found.
5432static bool
5434 QualType DeclType, SourceLocation DeclLoc,
5435 Expr *Init, QualType T2, bool AllowRvalues,
5436 bool AllowExplicit) {
5437 assert(T2->isRecordType() && "Can only find conversions of record types.");
5438 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5439 OverloadCandidateSet CandidateSet(
5441 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5442 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5443 NamedDecl *D = *I;
5445 if (isa<UsingShadowDecl>(D))
5446 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5447
5448 FunctionTemplateDecl *ConvTemplate
5449 = dyn_cast<FunctionTemplateDecl>(D);
5450 CXXConversionDecl *Conv;
5451 if (ConvTemplate)
5452 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5453 else
5454 Conv = cast<CXXConversionDecl>(D);
5455
5456 if (AllowRvalues) {
5457 // If we are initializing an rvalue reference, don't permit conversion
5458 // functions that return lvalues.
5459 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5460 const ReferenceType *RefType
5462 if (RefType && !RefType->getPointeeType()->isFunctionType())
5463 continue;
5464 }
5465
5466 if (!ConvTemplate &&
5468 DeclLoc,
5469 Conv->getConversionType()
5474 continue;
5475 } else {
5476 // If the conversion function doesn't return a reference type,
5477 // it can't be considered for this conversion. An rvalue reference
5478 // is only acceptable if its referencee is a function type.
5479
5480 const ReferenceType *RefType =
5482 if (!RefType ||
5483 (!RefType->isLValueReferenceType() &&
5484 !RefType->getPointeeType()->isFunctionType()))
5485 continue;
5486 }
5487
5488 if (ConvTemplate)
5490 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5491 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5492 else
5494 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5495 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5496 }
5497
5498 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5499
5501 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5502 case OR_Success:
5503
5504 assert(Best->HasFinalConversion);
5505
5506 // C++ [over.ics.ref]p1:
5507 //
5508 // [...] If the parameter binds directly to the result of
5509 // applying a conversion function to the argument
5510 // expression, the implicit conversion sequence is a
5511 // user-defined conversion sequence (13.3.3.1.2), with the
5512 // second standard conversion sequence either an identity
5513 // conversion or, if the conversion function returns an
5514 // entity of a type that is a derived class of the parameter
5515 // type, a derived-to-base Conversion.
5516 if (!Best->FinalConversion.DirectBinding)
5517 return false;
5518
5519 ICS.setUserDefined();
5520 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5521 ICS.UserDefined.After = Best->FinalConversion;
5522 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5523 ICS.UserDefined.ConversionFunction = Best->Function;
5524 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5525 ICS.UserDefined.EllipsisConversion = false;
5526 assert(ICS.UserDefined.After.ReferenceBinding &&
5528 "Expected a direct reference binding!");
5529 return true;
5530
5531 case OR_Ambiguous:
5532 ICS.setAmbiguous();
5533 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5534 Cand != CandidateSet.end(); ++Cand)
5535 if (Cand->Best)
5536 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5537 return true;
5538
5540 case OR_Deleted:
5541 // There was no suitable conversion, or we found a deleted
5542 // conversion; continue with other checks.
5543 return false;
5544 }
5545
5546 llvm_unreachable("Invalid OverloadResult!");
5547}
5548
5549/// Compute an implicit conversion sequence for reference
5550/// initialization.
5551static ImplicitConversionSequence
5553 SourceLocation DeclLoc,
5554 bool SuppressUserConversions,
5555 bool AllowExplicit) {
5556 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5557
5558 // Most paths end in a failed conversion.
5561
5562 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5563 QualType T2 = Init->getType();
5564
5565 // If the initializer is the address of an overloaded function, try
5566 // to resolve the overloaded function. If all goes well, T2 is the
5567 // type of the resulting function.
5568 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5571 false, Found))
5572 T2 = Fn->getType();
5573 }
5574
5575 // Compute some basic properties of the types and the initializer.
5576 bool isRValRef = DeclType->isRValueReferenceType();
5577 Expr::Classification InitCategory = Init->Classify(S.Context);
5578
5580 Sema::ReferenceCompareResult RefRelationship =
5581 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5582
5583 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5584 ICS.setStandard();
5586 // FIXME: A reference binding can be a function conversion too. We should
5587 // consider that when ordering reference-to-function bindings.
5588 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5590 : (RefConv & Sema::ReferenceConversions::ObjC)
5592 : ICK_Identity;
5594 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5595 // a reference binding that performs a non-top-level qualification
5596 // conversion as a qualification conversion, not as an identity conversion.
5597 ICS.Standard.Third = (RefConv &
5598 Sema::ReferenceConversions::NestedQualification)
5600 : ICK_Identity;
5601 ICS.Standard.setFromType(T2);
5602 ICS.Standard.setToType(0, T2);
5603 ICS.Standard.setToType(1, T1);
5604 ICS.Standard.setToType(2, T1);
5605 ICS.Standard.ReferenceBinding = true;
5606 ICS.Standard.DirectBinding = BindsDirectly;
5607 ICS.Standard.IsLvalueReference = !isRValRef;
5609 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5612 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5613 ICS.Standard.FromBracedInitList = false;
5614 ICS.Standard.CopyConstructor = nullptr;
5616 };
5617
5618 // C++0x [dcl.init.ref]p5:
5619 // A reference to type "cv1 T1" is initialized by an expression
5620 // of type "cv2 T2" as follows:
5621
5622 // -- If reference is an lvalue reference and the initializer expression
5623 if (!isRValRef) {
5624 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5625 // reference-compatible with "cv2 T2," or
5626 //
5627 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5628 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5629 // C++ [over.ics.ref]p1:
5630 // When a parameter of reference type binds directly (8.5.3)
5631 // to an argument expression, the implicit conversion sequence
5632 // is the identity conversion, unless the argument expression
5633 // has a type that is a derived class of the parameter type,
5634 // in which case the implicit conversion sequence is a
5635 // derived-to-base Conversion (13.3.3.1).
5636 SetAsReferenceBinding(/*BindsDirectly=*/true);
5637
5638 // Nothing more to do: the inaccessibility/ambiguity check for
5639 // derived-to-base conversions is suppressed when we're
5640 // computing the implicit conversion sequence (C++
5641 // [over.best.ics]p2).
5642 return ICS;
5643 }
5644
5645 // -- has a class type (i.e., T2 is a class type), where T1 is
5646 // not reference-related to T2, and can be implicitly
5647 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5648 // is reference-compatible with "cv3 T3" 92) (this
5649 // conversion is selected by enumerating the applicable
5650 // conversion functions (13.3.1.6) and choosing the best
5651 // one through overload resolution (13.3)),
5652 if (!SuppressUserConversions && T2->isRecordType() &&
5653 S.isCompleteType(DeclLoc, T2) &&
5654 RefRelationship == Sema::Ref_Incompatible) {
5655 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5656 Init, T2, /*AllowRvalues=*/false,
5657 AllowExplicit))
5658 return ICS;
5659 }
5660 }
5661
5662 // -- Otherwise, the reference shall be an lvalue reference to a
5663 // non-volatile const type (i.e., cv1 shall be const), or the reference
5664 // shall be an rvalue reference.
5665 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5666 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5668 return ICS;
5669 }
5670
5671 // -- If the initializer expression
5672 //
5673 // -- is an xvalue, class prvalue, array prvalue or function
5674 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5675 if (RefRelationship == Sema::Ref_Compatible &&
5676 (InitCategory.isXValue() ||
5677 (InitCategory.isPRValue() &&
5678 (T2->isRecordType() || T2->isArrayType())) ||
5679 (InitCategory.isLValue() && T2->isFunctionType()))) {
5680 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5681 // binding unless we're binding to a class prvalue.
5682 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5683 // allow the use of rvalue references in C++98/03 for the benefit of
5684 // standard library implementors; therefore, we need the xvalue check here.
5685 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5686 !(InitCategory.isPRValue() || T2->isRecordType()));
5687 return ICS;
5688 }
5689
5690 // -- has a class type (i.e., T2 is a class type), where T1 is not
5691 // reference-related to T2, and can be implicitly converted to
5692 // an xvalue, class prvalue, or function lvalue of type
5693 // "cv3 T3", where "cv1 T1" is reference-compatible with
5694 // "cv3 T3",
5695 //
5696 // then the reference is bound to the value of the initializer
5697 // expression in the first case and to the result of the conversion
5698 // in the second case (or, in either case, to an appropriate base
5699 // class subobject).
5700 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5701 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5702 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5703 Init, T2, /*AllowRvalues=*/true,
5704 AllowExplicit)) {
5705 // In the second case, if the reference is an rvalue reference
5706 // and the second standard conversion sequence of the
5707 // user-defined conversion sequence includes an lvalue-to-rvalue
5708 // conversion, the program is ill-formed.
5709 if (ICS.isUserDefined() && isRValRef &&
5712
5713 return ICS;
5714 }
5715
5716 // A temporary of function type cannot be created; don't even try.
5717 if (T1->isFunctionType())
5718 return ICS;
5719
5720 // -- Otherwise, a temporary of type "cv1 T1" is created and
5721 // initialized from the initializer expression using the
5722 // rules for a non-reference copy initialization (8.5). The
5723 // reference is then bound to the temporary. If T1 is
5724 // reference-related to T2, cv1 must be the same
5725 // cv-qualification as, or greater cv-qualification than,
5726 // cv2; otherwise, the program is ill-formed.
5727 if (RefRelationship == Sema::Ref_Related) {
5728 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5729 // we would be reference-compatible or reference-compatible with
5730 // added qualification. But that wasn't the case, so the reference
5731 // initialization fails.
5732 //
5733 // Note that we only want to check address spaces and cvr-qualifiers here.
5734 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5735 Qualifiers T1Quals = T1.getQualifiers();
5736 Qualifiers T2Quals = T2.getQualifiers();
5737 T1Quals.removeObjCGCAttr();
5738 T1Quals.removeObjCLifetime();
5739 T2Quals.removeObjCGCAttr();
5740 T2Quals.removeObjCLifetime();
5741 // MS compiler ignores __unaligned qualifier for references; do the same.
5742 T1Quals.removeUnaligned();
5743 T2Quals.removeUnaligned();
5744 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5745 return ICS;
5746 }
5747
5748 // If at least one of the types is a class type, the types are not
5749 // related, and we aren't allowed any user conversions, the
5750 // reference binding fails. This case is important for breaking
5751 // recursion, since TryImplicitConversion below will attempt to
5752 // create a temporary through the use of a copy constructor.
5753 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5754 (T1->isRecordType() || T2->isRecordType()))
5755 return ICS;
5756
5757 // If T1 is reference-related to T2 and the reference is an rvalue
5758 // reference, the initializer expression shall not be an lvalue.
5759 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5760 Init->Classify(S.Context).isLValue()) {
5762 return ICS;
5763 }
5764
5765 // C++ [over.ics.ref]p2:
5766 // When a parameter of reference type is not bound directly to
5767 // an argument expression, the conversion sequence is the one
5768 // required to convert the argument expression to the
5769 // underlying type of the reference according to
5770 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5771 // to copy-initializing a temporary of the underlying type with
5772 // the argument expression. Any difference in top-level
5773 // cv-qualification is subsumed by the initialization itself
5774 // and does not constitute a conversion.
5775 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5776 AllowedExplicit::None,
5777 /*InOverloadResolution=*/false,
5778 /*CStyle=*/false,
5779 /*AllowObjCWritebackConversion=*/false,
5780 /*AllowObjCConversionOnExplicit=*/false);
5781
5782 // Of course, that's still a reference binding.
5783 if (ICS.isStandard()) {
5784 ICS.Standard.ReferenceBinding = true;
5785 ICS.Standard.IsLvalueReference = !isRValRef;
5786 ICS.Standard.BindsToFunctionLvalue = false;
5787 ICS.Standard.BindsToRvalue = true;
5790 } else if (ICS.isUserDefined()) {
5791 const ReferenceType *LValRefType =
5794
5795 // C++ [over.ics.ref]p3:
5796 // Except for an implicit object parameter, for which see 13.3.1, a
5797 // standard conversion sequence cannot be formed if it requires [...]
5798 // binding an rvalue reference to an lvalue other than a function
5799 // lvalue.
5800 // Note that the function case is not possible here.
5801 if (isRValRef && LValRefType) {
5803 return ICS;
5804 }
5805
5807 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5809 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5813 }
5814
5815 return ICS;
5816}
5817
5818static ImplicitConversionSequence
5819TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5820 bool SuppressUserConversions,
5821 bool InOverloadResolution,
5822 bool AllowObjCWritebackConversion,
5823 bool AllowExplicit = false);
5824
5825/// TryListConversion - Try to copy-initialize a value of type ToType from the
5826/// initializer list From.
5827static ImplicitConversionSequence
5829 bool SuppressUserConversions,
5830 bool InOverloadResolution,
5831 bool AllowObjCWritebackConversion) {
5832 // C++11 [over.ics.list]p1:
5833 // When an argument is an initializer list, it is not an expression and
5834 // special rules apply for converting it to a parameter type.
5835
5837 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5838
5839 // We need a complete type for what follows. With one C++20 exception,
5840 // incomplete types can never be initialized from init lists.
5841 QualType InitTy = ToType;
5842 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5843 if (AT && S.getLangOpts().CPlusPlus20)
5844 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5845 // C++20 allows list initialization of an incomplete array type.
5846 InitTy = IAT->getElementType();
5847 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5848 return Result;
5849
5850 // C++20 [over.ics.list]/2:
5851 // If the initializer list is a designated-initializer-list, a conversion
5852 // is only possible if the parameter has an aggregate type
5853 //
5854 // FIXME: The exception for reference initialization here is not part of the
5855 // language rules, but follow other compilers in adding it as a tentative DR
5856 // resolution.
5857 bool IsDesignatedInit = From->hasDesignatedInit();
5858 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5859 IsDesignatedInit)
5860 return Result;
5861
5862 // Per DR1467 and DR2137:
5863 // If the parameter type is an aggregate class X and the initializer list
5864 // has a single element of type cv U, where U is X or a class derived from
5865 // X, the implicit conversion sequence is the one required to convert the
5866 // element to the parameter type.
5867 //
5868 // Otherwise, if the parameter type is a character array [... ]
5869 // and the initializer list has a single element that is an
5870 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5871 // implicit conversion sequence is the identity conversion.
5872 if (From->hasOneInit() && !IsDesignatedInit) {
5873 if (ToType->isRecordType() && ToType->isAggregateType()) {
5874 QualType InitType = From->getInit(0)->getType();
5875 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5876 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5877 return TryCopyInitialization(S, From->getInit(0), ToType,
5878 SuppressUserConversions,
5879 InOverloadResolution,
5880 AllowObjCWritebackConversion);
5881 }
5882
5883 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5884 InitializedEntity Entity =
5886 /*Consumed=*/false);
5887 if (S.CanPerformCopyInitialization(Entity, From)) {
5888 Result.setStandard();
5889 Result.Standard.setAsIdentityConversion();
5890 Result.Standard.setFromType(ToType);
5891 Result.Standard.setAllToTypes(ToType);
5892 return Result;
5893 }
5894 }
5895 }
5896
5897 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5898 // C++11 [over.ics.list]p2:
5899 // If the parameter type is std::initializer_list<X> or "array of X" and
5900 // all the elements can be implicitly converted to X, the implicit
5901 // conversion sequence is the worst conversion necessary to convert an
5902 // element of the list to X.
5903 //
5904 // C++14 [over.ics.list]p3:
5905 // Otherwise, if the parameter type is "array of N X", if the initializer
5906 // list has exactly N elements or if it has fewer than N elements and X is
5907 // default-constructible, and if all the elements of the initializer list
5908 // can be implicitly converted to X, the implicit conversion sequence is
5909 // the worst conversion necessary to convert an element of the list to X.
5910 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5911 unsigned e = From->getNumInitsWithEmbedExpanded();
5914 QualType());
5915 QualType ContTy = ToType;
5916 bool IsUnbounded = false;
5917 if (AT) {
5918 InitTy = AT->getElementType();
5919 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5920 if (CT->getSize().ult(e)) {
5921 // Too many inits, fatally bad
5923 ToType);
5924 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5925 return Result;
5926 }
5927 if (CT->getSize().ugt(e)) {
5928 // Need an init from empty {}, is there one?
5929 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5930 From->getEndLoc(), /*isExplicit=*/false);
5931 EmptyList.setType(S.Context.VoidTy);
5932 DfltElt = TryListConversion(
5933 S, &EmptyList, InitTy, SuppressUserConversions,
5934 InOverloadResolution, AllowObjCWritebackConversion);
5935 if (DfltElt.isBad()) {
5936 // No {} init, fatally bad
5938 ToType);
5939 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5940 return Result;
5941 }
5942 }
5943 } else {
5944 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5945 IsUnbounded = true;
5946 if (!e) {
5947 // Cannot convert to zero-sized.
5949 ToType);
5950 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5951 return Result;
5952 }
5953 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5954 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5956 }
5957 }
5958
5959 Result.setStandard();
5960 Result.Standard.setAsIdentityConversion();
5961 Result.Standard.setFromType(InitTy);
5962 Result.Standard.setAllToTypes(InitTy);
5963 // An EmbedExpr is a single int prvalue, so one conversion sequence covers
5964 // all of its elements; narrowing is checked per element after resolution.
5965 for (Expr *Init : From->inits()) {
5967 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5968 AllowObjCWritebackConversion);
5969
5970 // Keep the worse conversion seen so far.
5971 // FIXME: Sequences are not totally ordered, so 'worse' can be
5972 // ambiguous. CWG has been informed.
5974 Result) ==
5976 Result = ICS;
5977 // Bail as soon as we find something unconvertible.
5978 if (Result.isBad()) {
5979 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5980 return Result;
5981 }
5982 }
5983 }
5984
5985 // If we needed any implicit {} initialization, compare that now.
5986 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5987 // has been informed that this might not be the best thing.
5988 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5989 S, From->getEndLoc(), DfltElt, Result) ==
5991 Result = DfltElt;
5992 // Record the type being initialized so that we may compare sequences
5993 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5994 return Result;
5995 }
5996
5997 // C++14 [over.ics.list]p4:
5998 // C++11 [over.ics.list]p3:
5999 // Otherwise, if the parameter is a non-aggregate class X and overload
6000 // resolution chooses a single best constructor [...] the implicit
6001 // conversion sequence is a user-defined conversion sequence. If multiple
6002 // constructors are viable but none is better than the others, the
6003 // implicit conversion sequence is a user-defined conversion sequence.
6004 if (ToType->isRecordType() && !ToType->isAggregateType()) {
6005 // This function can deal with initializer lists.
6006 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
6007 AllowedExplicit::None,
6008 InOverloadResolution, /*CStyle=*/false,
6009 AllowObjCWritebackConversion,
6010 /*AllowObjCConversionOnExplicit=*/false);
6011 }
6012
6013 // C++14 [over.ics.list]p5:
6014 // C++11 [over.ics.list]p4:
6015 // Otherwise, if the parameter has an aggregate type which can be
6016 // initialized from the initializer list [...] the implicit conversion
6017 // sequence is a user-defined conversion sequence.
6018 if (ToType->isAggregateType()) {
6019 // Type is an aggregate, argument is an init list. At this point it comes
6020 // down to checking whether the initialization works.
6021 // FIXME: Find out whether this parameter is consumed or not.
6022 InitializedEntity Entity =
6024 /*Consumed=*/false);
6026 From)) {
6027 Result.setUserDefined();
6028 Result.UserDefined.Before.setAsIdentityConversion();
6029 // Initializer lists don't have a type.
6030 Result.UserDefined.Before.setFromType(QualType());
6031 Result.UserDefined.Before.setAllToTypes(QualType());
6032
6033 Result.UserDefined.After.setAsIdentityConversion();
6034 Result.UserDefined.After.setFromType(ToType);
6035 Result.UserDefined.After.setAllToTypes(ToType);
6036 Result.UserDefined.ConversionFunction = nullptr;
6037 }
6038 return Result;
6039 }
6040
6041 // C++14 [over.ics.list]p6:
6042 // C++11 [over.ics.list]p5:
6043 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
6044 if (ToType->isReferenceType()) {
6045 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
6046 // mention initializer lists in any way. So we go by what list-
6047 // initialization would do and try to extrapolate from that.
6048
6049 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
6050
6051 // If the initializer list has a single element that is reference-related
6052 // to the parameter type, we initialize the reference from that.
6053 if (From->hasOneInit() && !IsDesignatedInit) {
6054 Expr *Init = From->getInit(0);
6055
6056 QualType T2 = Init->getType();
6057
6058 // If the initializer is the address of an overloaded function, try
6059 // to resolve the overloaded function. If all goes well, T2 is the
6060 // type of the resulting function.
6061 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
6064 Init, ToType, false, Found))
6065 T2 = Fn->getType();
6066 }
6067
6068 // Compute some basic properties of the types and the initializer.
6069 Sema::ReferenceCompareResult RefRelationship =
6070 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
6071
6072 if (RefRelationship >= Sema::Ref_Related) {
6073 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
6074 SuppressUserConversions,
6075 /*AllowExplicit=*/false);
6076 }
6077 }
6078
6079 // Otherwise, we bind the reference to a temporary created from the
6080 // initializer list.
6081 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6082 InOverloadResolution,
6083 AllowObjCWritebackConversion);
6084 if (Result.isFailure())
6085 return Result;
6086 assert(!Result.isEllipsis() &&
6087 "Sub-initialization cannot result in ellipsis conversion.");
6088
6089 // Can we even bind to a temporary?
6090 if (ToType->isRValueReferenceType() ||
6091 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6092 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6093 Result.UserDefined.After;
6094 SCS.ReferenceBinding = true;
6096 SCS.BindsToRvalue = true;
6097 SCS.BindsToFunctionLvalue = false;
6100 SCS.FromBracedInitList = false;
6101
6102 } else
6104 From, ToType);
6105 return Result;
6106 }
6107
6108 // C++14 [over.ics.list]p7:
6109 // C++11 [over.ics.list]p6:
6110 // Otherwise, if the parameter type is not a class:
6111 if (!ToType->isRecordType()) {
6112 // - if the initializer list has one element that is not itself an
6113 // initializer list, the implicit conversion sequence is the one
6114 // required to convert the element to the parameter type.
6115 if (From->hasOneInit() && !isa<InitListExpr>(From->getInit(0))) {
6117 S, From->getInit(0), ToType, SuppressUserConversions,
6118 InOverloadResolution, AllowObjCWritebackConversion);
6119 if (Result.isStandard())
6120 Result.Standard.FromBracedInitList = true;
6121 }
6122 // - if the initializer list has no elements, the implicit conversion
6123 // sequence is the identity conversion.
6124 else if (From->hasZeroInits()) {
6125 Result.setStandard();
6126 Result.Standard.setAsIdentityConversion();
6127 Result.Standard.setFromType(ToType);
6128 Result.Standard.setAllToTypes(ToType);
6129 }
6130 return Result;
6131 }
6132
6133 // C++14 [over.ics.list]p8:
6134 // C++11 [over.ics.list]p7:
6135 // In all cases other than those enumerated above, no conversion is possible
6136 return Result;
6137}
6138
6139/// TryCopyInitialization - Try to copy-initialize a value of type
6140/// ToType from the expression From. Return the implicit conversion
6141/// sequence required to pass this argument, which may be a bad
6142/// conversion sequence (meaning that the argument cannot be passed to
6143/// a parameter of this type). If @p SuppressUserConversions, then we
6144/// do not permit any user-defined conversion sequences.
6145static ImplicitConversionSequence
6147 bool SuppressUserConversions,
6148 bool InOverloadResolution,
6149 bool AllowObjCWritebackConversion,
6150 bool AllowExplicit) {
6151 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6152 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6153 InOverloadResolution,AllowObjCWritebackConversion);
6154
6155 if (ToType->isReferenceType())
6156 return TryReferenceInit(S, From, ToType,
6157 /*FIXME:*/ From->getBeginLoc(),
6158 SuppressUserConversions, AllowExplicit);
6159
6160 return TryImplicitConversion(S, From, ToType,
6161 SuppressUserConversions,
6162 AllowedExplicit::None,
6163 InOverloadResolution,
6164 /*CStyle=*/false,
6165 AllowObjCWritebackConversion,
6166 /*AllowObjCConversionOnExplicit=*/false);
6167}
6168
6169static bool TryCopyInitialization(const CanQualType FromQTy,
6170 const CanQualType ToQTy,
6171 Sema &S,
6172 SourceLocation Loc,
6173 ExprValueKind FromVK) {
6174 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6176 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6177
6178 return !ICS.isBad();
6179}
6180
6181/// TryObjectArgumentInitialization - Try to initialize the object
6182/// parameter of the given member function (@c Method) from the
6183/// expression @p From.
6185 Sema &S, SourceLocation Loc, QualType FromType,
6186 Expr::Classification FromClassification, CXXMethodDecl *Method,
6187 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6188 QualType ExplicitParameterType = QualType(),
6189 bool SuppressUserConversion = false) {
6190
6191 // We need to have an object of class type.
6192 if (const auto *PT = FromType->getAs<PointerType>()) {
6193 FromType = PT->getPointeeType();
6194
6195 // When we had a pointer, it's implicitly dereferenced, so we
6196 // better have an lvalue.
6197 assert(FromClassification.isLValue());
6198 }
6199
6200 auto ValueKindFromClassification = [](Expr::Classification C) {
6201 if (C.isPRValue())
6202 return clang::VK_PRValue;
6203 if (C.isXValue())
6204 return VK_XValue;
6205 return clang::VK_LValue;
6206 };
6207
6208 if (Method->isExplicitObjectMemberFunction()) {
6209 if (ExplicitParameterType.isNull())
6210 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6211 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6212 ValueKindFromClassification(FromClassification));
6214 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6215 /*InOverloadResolution=*/true, false);
6216 if (ICS.isBad())
6217 ICS.Bad.FromExpr = nullptr;
6218 return ICS;
6219 }
6220
6221 assert(FromType->isRecordType());
6222
6223 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6224 // C++98 [class.dtor]p2:
6225 // A destructor can be invoked for a const, volatile or const volatile
6226 // object.
6227 // C++98 [over.match.funcs]p4:
6228 // For static member functions, the implicit object parameter is considered
6229 // to match any object (since if the function is selected, the object is
6230 // discarded).
6231 Qualifiers Quals = Method->getMethodQualifiers();
6232 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6233 Quals.addConst();
6234 Quals.addVolatile();
6235 }
6236
6237 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6238
6239 // Set up the conversion sequence as a "bad" conversion, to allow us
6240 // to exit early.
6242
6243 // C++0x [over.match.funcs]p4:
6244 // For non-static member functions, the type of the implicit object
6245 // parameter is
6246 //
6247 // - "lvalue reference to cv X" for functions declared without a
6248 // ref-qualifier or with the & ref-qualifier
6249 // - "rvalue reference to cv X" for functions declared with the &&
6250 // ref-qualifier
6251 //
6252 // where X is the class of which the function is a member and cv is the
6253 // cv-qualification on the member function declaration.
6254 //
6255 // However, when finding an implicit conversion sequence for the argument, we
6256 // are not allowed to perform user-defined conversions
6257 // (C++ [over.match.funcs]p5). We perform a simplified version of
6258 // reference binding here, that allows class rvalues to bind to
6259 // non-constant references.
6260
6261 // First check the qualifiers.
6262 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6263 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6264 if (ImplicitParamType.getCVRQualifiers() !=
6265 FromTypeCanon.getLocalCVRQualifiers() &&
6266 !ImplicitParamType.isAtLeastAsQualifiedAs(
6267 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6269 FromType, ImplicitParamType);
6270 return ICS;
6271 }
6272
6273 if (FromTypeCanon.hasAddressSpace()) {
6274 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6275 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6276 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6277 S.getASTContext())) {
6279 FromType, ImplicitParamType);
6280 return ICS;
6281 }
6282 }
6283
6284 // Check that we have either the same type or a derived type. It
6285 // affects the conversion rank.
6286 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6287 ImplicitConversionKind SecondKind;
6288 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6289 SecondKind = ICK_Identity;
6290 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6291 SecondKind = ICK_Derived_To_Base;
6292 } else if (!Method->isExplicitObjectMemberFunction()) {
6294 FromType, ImplicitParamType);
6295 return ICS;
6296 }
6297
6298 // Check the ref-qualifier.
6299 switch (Method->getRefQualifier()) {
6300 case RQ_None:
6301 // Do nothing; we don't care about lvalueness or rvalueness.
6302 break;
6303
6304 case RQ_LValue:
6305 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6306 // non-const lvalue reference cannot bind to an rvalue
6308 ImplicitParamType);
6309 return ICS;
6310 }
6311 break;
6312
6313 case RQ_RValue:
6314 if (!FromClassification.isRValue()) {
6315 // rvalue reference cannot bind to an lvalue
6317 ImplicitParamType);
6318 return ICS;
6319 }
6320 break;
6321 }
6322
6323 // Success. Mark this as a reference binding.
6324 ICS.setStandard();
6326 ICS.Standard.Second = SecondKind;
6327 ICS.Standard.setFromType(FromType);
6328 ICS.Standard.setAllToTypes(ImplicitParamType);
6329 ICS.Standard.ReferenceBinding = true;
6330 ICS.Standard.DirectBinding = true;
6331 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6332 ICS.Standard.BindsToFunctionLvalue = false;
6333 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6334 ICS.Standard.FromBracedInitList = false;
6336 = (Method->getRefQualifier() == RQ_None);
6337 return ICS;
6338}
6339
6340/// PerformObjectArgumentInitialization - Perform initialization of
6341/// the implicit object parameter for the given Method with the given
6342/// expression.
6344 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6346 QualType FromRecordType, DestType;
6347 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6348
6349 LangAS FromAS = From->getType().getAddressSpace();
6350 if (getLangOpts().HLSL &&
6351 (FromAS == LangAS::hlsl_constant ||
6352 (FromAS == LangAS::hlsl_groupshared && Method->isConst()))) {
6354 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6355 /*BasePath=*/nullptr, VK_PRValue,
6357 } else if (getLangOpts().HLSL && FromAS == LangAS::hlsl_groupshared) {
6358 ASTContext &Ctx = SemaRef.getASTContext();
6360 InitializedEntity TempEntity =
6362 ExprResult Res = SemaRef.HLSL().CreateOutArgExpr(
6363 From, Ty, Ty, TempEntity, From->getBeginLoc(), /*IsInOut=*/true);
6364 if (Res.isInvalid())
6365 return ExprError();
6366 From = Res.get();
6367 }
6368
6369 Expr::Classification FromClassification;
6370 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6371 FromRecordType = PT->getPointeeType();
6372 DestType = Method->getThisType();
6373 FromClassification = Expr::Classification::makeSimpleLValue();
6374 } else {
6375 FromRecordType = From->getType();
6376 DestType = ImplicitParamRecordType;
6377 FromClassification = From->Classify(Context);
6378
6379 // CWG2813 [expr.call]p6:
6380 // If the function is an implicit object member function, the object
6381 // expression of the class member access shall be a glvalue [...]
6382 if (From->isPRValue()) {
6383 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6384 Method->getRefQualifier() !=
6386 }
6387 }
6388
6389 // Note that we always use the true parent context when performing
6390 // the actual argument initialization.
6392 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6393 Method->getParent());
6394 if (ICS.isBad()) {
6395 switch (ICS.Bad.Kind) {
6397 Qualifiers FromQs = FromRecordType.getQualifiers();
6398 Qualifiers ToQs = DestType.getQualifiers();
6399 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6400 if (CVR) {
6401 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6402 << Method->getDeclName() << FromRecordType << (CVR - 1)
6403 << From->getSourceRange();
6404 Diag(Method->getLocation(), diag::note_previous_decl)
6405 << Method->getDeclName();
6406 return ExprError();
6407 }
6408 break;
6409 }
6410
6413 bool IsRValueQualified =
6414 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6415 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6416 << Method->getDeclName() << FromClassification.isRValue()
6417 << IsRValueQualified;
6418 Diag(Method->getLocation(), diag::note_previous_decl)
6419 << Method->getDeclName();
6420 return ExprError();
6421 }
6422
6425 break;
6426
6429 llvm_unreachable("Lists are not objects");
6430 }
6431
6432 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6433 << ImplicitParamRecordType << FromRecordType
6434 << From->getSourceRange();
6435 }
6436
6437 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6438 ExprResult FromRes =
6439 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6440 if (FromRes.isInvalid())
6441 return ExprError();
6442 From = FromRes.get();
6443 }
6444
6445 if (!Context.hasSameType(From->getType(), DestType)) {
6446 CastKind CK;
6447 QualType PteeTy = DestType->getPointeeType();
6448 LangAS DestAS =
6449 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6450 if (FromRecordType.getAddressSpace() != DestAS)
6451 CK = CK_AddressSpaceConversion;
6452 else
6453 CK = CK_NoOp;
6454 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6455 }
6456 return From;
6457}
6458
6459/// TryContextuallyConvertToBool - Attempt to contextually convert the
6460/// expression From to bool (C++0x [conv]p3).
6463 // C++ [dcl.init]/17.8:
6464 // - Otherwise, if the initialization is direct-initialization, the source
6465 // type is std::nullptr_t, and the destination type is bool, the initial
6466 // value of the object being initialized is false.
6467 if (From->getType()->isNullPtrType())
6469 S.Context.BoolTy,
6470 From->isGLValue());
6471
6472 // All other direct-initialization of bool is equivalent to an implicit
6473 // conversion to bool in which explicit conversions are permitted.
6474 return TryImplicitConversion(S, From, S.Context.BoolTy,
6475 /*SuppressUserConversions=*/false,
6476 AllowedExplicit::Conversions,
6477 /*InOverloadResolution=*/false,
6478 /*CStyle=*/false,
6479 /*AllowObjCWritebackConversion=*/false,
6480 /*AllowObjCConversionOnExplicit=*/false);
6481}
6482
6484 if (checkPlaceholderForOverload(*this, From))
6485 return ExprError();
6486 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6487 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6488
6490 if (!ICS.isBad())
6491 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6494 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6495 << From->getType() << From->getSourceRange();
6496 return ExprError();
6497}
6498
6499/// Check that the specified conversion is permitted in a converted constant
6500/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6501/// is acceptable.
6504 // Since we know that the target type is an integral or unscoped enumeration
6505 // type, most conversion kinds are impossible. All possible First and Third
6506 // conversions are fine.
6507 switch (SCS.Second) {
6508 case ICK_Identity:
6510 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6512 return true;
6513
6515 // Conversion from an integral or unscoped enumeration type to bool is
6516 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6517 // conversion, so we allow it in a converted constant expression.
6518 //
6519 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6520 // a lot of popular code. We should at least add a warning for this
6521 // (non-conforming) extension.
6523 SCS.getToType(2)->isBooleanType();
6524
6526 case ICK_Pointer_Member:
6527 // C++1z: null pointer conversions and null member pointer conversions are
6528 // only permitted if the source type is std::nullptr_t.
6529 return SCS.getFromType()->isNullPtrType();
6530
6543 case ICK_Vector_Splat:
6544 case ICK_Complex_Real:
6555 return false;
6556
6561 llvm_unreachable("found a first conversion kind in Second");
6562
6564 case ICK_Qualification:
6565 llvm_unreachable("found a third conversion kind in Second");
6566
6568 break;
6569 }
6570
6571 llvm_unreachable("unknown conversion kind");
6572}
6573
6574/// BuildConvertedConstantExpression - Check that the expression From is a
6575/// converted constant expression of type T, perform the conversion but
6576/// does not evaluate the expression
6578 QualType T, CCEKind CCE,
6579 NamedDecl *Dest,
6580 APValue &PreNarrowingValue) {
6581 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6583 CCE == CCEKind::PackIndex);
6584 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6585 "converted constant expression outside C++11 or TTP matching");
6586
6587 if (checkPlaceholderForOverload(S, From))
6588 return ExprError();
6589
6590 // C++1z [expr.const]p3:
6591 // A converted constant expression of type T is an expression,
6592 // implicitly converted to type T, where the converted
6593 // expression is a constant expression and the implicit conversion
6594 // sequence contains only [... list of conversions ...].
6596 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6598 : TryCopyInitialization(S, From, T,
6599 /*SuppressUserConversions=*/false,
6600 /*InOverloadResolution=*/false,
6601 /*AllowObjCWritebackConversion=*/false,
6602 /*AllowExplicit=*/false);
6603 StandardConversionSequence *SCS = nullptr;
6604 switch (ICS.getKind()) {
6606 SCS = &ICS.Standard;
6607 break;
6609 if (T->isRecordType())
6610 SCS = &ICS.UserDefined.Before;
6611 else
6612 SCS = &ICS.UserDefined.After;
6613 break;
6617 return S.Diag(From->getBeginLoc(),
6618 diag::err_typecheck_converted_constant_expression)
6619 << From->getType() << From->getSourceRange() << T;
6620 return ExprError();
6621
6624 llvm_unreachable("bad conversion in converted constant expression");
6625 }
6626
6627 // Check that we would only use permitted conversions.
6628 if (!CheckConvertedConstantConversions(S, *SCS)) {
6629 return S.Diag(From->getBeginLoc(),
6630 diag::err_typecheck_converted_constant_expression_disallowed)
6631 << From->getType() << From->getSourceRange() << T;
6632 }
6633 // [...] and where the reference binding (if any) binds directly.
6634 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6635 return S.Diag(From->getBeginLoc(),
6636 diag::err_typecheck_converted_constant_expression_indirect)
6637 << From->getType() << From->getSourceRange() << T;
6638 }
6639 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6640 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6641 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6642 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6643 // case explicitly.
6644 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6645 return S.Diag(From->getBeginLoc(),
6646 diag::err_reference_bind_to_bitfield_in_cce)
6647 << From->getSourceRange();
6648 }
6649
6650 // Usually we can simply apply the ImplicitConversionSequence we formed
6651 // earlier, but that's not guaranteed to work when initializing an object of
6652 // class type.
6654 bool IsTemplateArgument =
6656 if (T->isRecordType()) {
6657 assert(IsTemplateArgument &&
6658 "unexpected class type converted constant expr");
6662 SourceLocation(), From);
6663 } else {
6664 Result =
6666 }
6667 if (Result.isInvalid())
6668 return Result;
6669
6670 // C++2a [intro.execution]p5:
6671 // A full-expression is [...] a constant-expression [...]
6672 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6673 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6674 IsTemplateArgument);
6675 if (Result.isInvalid())
6676 return Result;
6677
6678 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6679
6680 // Check for a narrowing implicit conversion.
6681 bool ReturnPreNarrowingValue = false;
6682 QualType PreNarrowingType;
6683 switch (SCS->getNarrowingKind(
6684 S.Context, Result.get(), PreNarrowingValue, PreNarrowingType,
6685 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6687 // Implicit conversion to a narrower type, and the value is not a constant
6688 // expression. We'll diagnose this in a moment.
6689 case NK_Not_Narrowing:
6690 break;
6691
6693 if (CCE == CCEKind::ArrayBound &&
6694 PreNarrowingType->isIntegralOrEnumerationType() &&
6695 PreNarrowingValue.isInt()) {
6696 // Don't diagnose array bound narrowing here; we produce more precise
6697 // errors by allowing the un-narrowed value through.
6698 ReturnPreNarrowingValue = true;
6699 break;
6700 }
6701 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6702 << CCE << /*Constant*/ 1
6703 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6704 // If this is an SFINAE Context, treat the result as invalid so it stops
6705 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6706 // FIXME: Should do this whenever the above diagnostic is an error, but
6707 // without further changes this would degrade some other diagnostics.
6708 if (S.isSFINAEContext())
6709 return ExprError();
6710 break;
6711
6713 // Implicit conversion to a narrower type, but the expression is
6714 // value-dependent so we can't tell whether it's actually narrowing.
6715 // For matching the parameters of a TTP, the conversion is ill-formed
6716 // if it may narrow.
6717 if (CCE != CCEKind::TempArgStrict)
6718 break;
6719 [[fallthrough]];
6720 case NK_Type_Narrowing:
6721 // FIXME: It would be better to diagnose that the expression is not a
6722 // constant expression.
6723 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6724 << CCE << /*Constant*/ 0 << From->getType() << T;
6725 if (S.isSFINAEContext())
6726 return ExprError();
6727 break;
6728 }
6729 if (!ReturnPreNarrowingValue)
6730 PreNarrowingValue = {};
6731
6732 return Result;
6733}
6734
6735/// CheckConvertedConstantExpression - Check that the expression From is a
6736/// converted constant expression of type T, perform the conversion and produce
6737/// the converted expression, per C++11 [expr.const]p3.
6740 CCEKind CCE, bool RequireInt,
6741 NamedDecl *Dest) {
6742
6743 APValue PreNarrowingValue;
6745 PreNarrowingValue);
6746 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6747 Value = APValue();
6748 return Result;
6749 }
6750 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6751 RequireInt, PreNarrowingValue);
6752}
6753
6755 CCEKind CCE,
6756 NamedDecl *Dest) {
6757 APValue PreNarrowingValue;
6758 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6759 PreNarrowingValue);
6760}
6761
6763 APValue &Value, CCEKind CCE,
6764 NamedDecl *Dest) {
6765 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6766 Dest);
6767}
6768
6770 llvm::APSInt &Value,
6771 CCEKind CCE) {
6772 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6773
6774 APValue V;
6775 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6776 /*Dest=*/nullptr);
6777 if (!R.isInvalid() && !R.get()->isValueDependent())
6778 Value = V.getInt();
6779 return R;
6780}
6781
6784 CCEKind CCE, bool RequireInt,
6785 const APValue &PreNarrowingValue) {
6786
6787 ExprResult Result = E;
6788 // Check the expression is a constant expression.
6791 Expr::EvalResult Eval;
6792 Eval.Diag = &Notes;
6793 Eval.ExtendedDiag = &MSWarning;
6794
6795 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6796
6797 ConstantExprKind Kind;
6798 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6799 Kind = ConstantExprKind::ClassTemplateArgument;
6800 else if (CCE == CCEKind::TemplateArg)
6801 Kind = ConstantExprKind::NonClassTemplateArgument;
6802 else
6803 Kind = ConstantExprKind::Normal;
6804
6805 EvalProxy SProxy(*this);
6806 if (!E->EvaluateAsMandatedConstantExpr(Eval, Context, SProxy, Kind) ||
6807 (RequireInt && !Eval.Val.isInt())) {
6808 // The expression can't be folded, so we can't keep it at this position in
6809 // the AST.
6810 Result = ExprError();
6811 } else {
6812 Value = Eval.Val;
6813 // For -fms-compatibility mode we relax some requirements
6814 // for constant folding in non-SFINAE contexts
6815 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6816 if (Notes.empty() && !CantFold) {
6817 for (auto &Info : MSWarning)
6818 Diag(Info.first, Info.second);
6819 // It's a constant expression.
6820 Expr *E = Result.get();
6821 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6822 // We expect a ConstantExpr to have a value associated with it
6823 // by this point.
6824 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6825 "ConstantExpr has no value associated with it");
6826 (void)CE;
6827 } else {
6829 }
6830 if (!PreNarrowingValue.isAbsent())
6831 Value = std::move(PreNarrowingValue);
6832 return E;
6833 }
6834 }
6835
6836 // It's not a constant expression. Produce an appropriate diagnostic.
6837 if (Notes.size() == 1 &&
6838 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6839 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6840 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6841 diag::note_constexpr_invalid_template_arg) {
6842 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6843 for (unsigned I = 0; I < Notes.size(); ++I)
6844 Diag(Notes[I].first, Notes[I].second);
6845 } else {
6846 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6847 << CCE << E->getSourceRange();
6848 for (unsigned I = 0; I < Notes.size(); ++I)
6849 Diag(Notes[I].first, Notes[I].second);
6850 }
6851 return ExprError();
6852}
6853
6854/// dropPointerConversions - If the given standard conversion sequence
6855/// involves any pointer conversions, remove them. This may change
6856/// the result type of the conversion sequence.
6858 if (SCS.Second == ICK_Pointer_Conversion) {
6859 SCS.Second = ICK_Identity;
6860 SCS.Dimension = ICK_Identity;
6861 SCS.Third = ICK_Identity;
6862 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6863 }
6864}
6865
6866/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6867/// convert the expression From to an Objective-C pointer type.
6868static ImplicitConversionSequence
6870 // Do an implicit conversion to 'id'.
6873 = TryImplicitConversion(S, From, Ty,
6874 // FIXME: Are these flags correct?
6875 /*SuppressUserConversions=*/false,
6876 AllowedExplicit::Conversions,
6877 /*InOverloadResolution=*/false,
6878 /*CStyle=*/false,
6879 /*AllowObjCWritebackConversion=*/false,
6880 /*AllowObjCConversionOnExplicit=*/true);
6881
6882 // Strip off any final conversions to 'id'.
6883 switch (ICS.getKind()) {
6888 break;
6889
6892 break;
6893
6896 break;
6897 }
6898
6899 return ICS;
6900}
6901
6903 if (checkPlaceholderForOverload(*this, From))
6904 return ExprError();
6905
6906 QualType Ty = Context.getObjCIdType();
6909 if (!ICS.isBad())
6910 return PerformImplicitConversion(From, Ty, ICS,
6912 return ExprResult();
6913}
6914
6915static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6916 const Expr *Base = nullptr;
6917 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6918 "expected a member expression");
6919
6920 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6921 M && !M->isImplicitAccess())
6922 Base = M->getBase();
6923 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6924 M && !M->isImplicitAccess())
6925 Base = M->getBase();
6926
6927 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6928
6929 if (T->isPointerType())
6930 T = T->getPointeeType();
6931
6932 return T;
6933}
6934
6936 const FunctionDecl *Fun) {
6937 QualType ObjType = Obj->getType();
6938 if (ObjType->isPointerType()) {
6939 ObjType = ObjType->getPointeeType();
6940 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6942 /*CanOverflow=*/false, FPOptionsOverride());
6943 }
6944 return Obj;
6945}
6946
6954
6956 Expr *Object, MultiExprArg &Args,
6957 SmallVectorImpl<Expr *> &NewArgs) {
6958 assert(Method->isExplicitObjectMemberFunction() &&
6959 "Method is not an explicit member function");
6960 assert(NewArgs.empty() && "NewArgs should be empty");
6961
6962 NewArgs.reserve(Args.size() + 1);
6963 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6964 NewArgs.push_back(This);
6965 NewArgs.append(Args.begin(), Args.end());
6966 Args = NewArgs;
6968 Method, Object->getBeginLoc());
6969}
6970
6971/// Determine whether the provided type is an integral type, or an enumeration
6972/// type of a permitted flavor.
6974 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6975 : T->isIntegralOrUnscopedEnumerationType();
6976}
6977
6978static ExprResult
6981 QualType T, UnresolvedSetImpl &ViableConversions) {
6982
6983 if (Converter.Suppress)
6984 return ExprError();
6985
6986 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6987 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6988 CXXConversionDecl *Conv =
6989 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6991 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6992 }
6993 return From;
6994}
6995
6996static bool
6999 QualType T, bool HadMultipleCandidates,
7000 UnresolvedSetImpl &ExplicitConversions) {
7001 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
7002 DeclAccessPair Found = ExplicitConversions[0];
7003 CXXConversionDecl *Conversion =
7004 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
7005
7006 // The user probably meant to invoke the given explicit
7007 // conversion; use it.
7008 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
7009 std::string TypeStr;
7010 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
7011
7012 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
7014 "static_cast<" + TypeStr + ">(")
7016 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
7017 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
7018
7019 // If we aren't in a SFINAE context, build a call to the
7020 // explicit conversion function.
7021 if (SemaRef.isSFINAEContext())
7022 return true;
7023
7024 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
7025 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
7026 HadMultipleCandidates);
7027 if (Result.isInvalid())
7028 return true;
7029
7030 // Replace the conversion with a RecoveryExpr, so we don't try to
7031 // instantiate it later, but can further diagnose here.
7032 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
7033 From, Result.get()->getType());
7034 if (Result.isInvalid())
7035 return true;
7036 From = Result.get();
7037 }
7038 return false;
7039}
7040
7041static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
7043 QualType T, bool HadMultipleCandidates,
7045 CXXConversionDecl *Conversion =
7046 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
7047 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
7048
7049 QualType ToType = Conversion->getConversionType().getNonReferenceType();
7050 if (!Converter.SuppressConversion) {
7051 if (SemaRef.isSFINAEContext())
7052 return true;
7053
7054 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
7055 << From->getSourceRange();
7056 }
7057
7058 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
7059 HadMultipleCandidates);
7060 if (Result.isInvalid())
7061 return true;
7062 // Record usage of conversion in an implicit cast.
7063 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
7064 CK_UserDefinedConversion, Result.get(),
7065 nullptr, Result.get()->getValueKind(),
7066 SemaRef.CurFPFeatureOverrides());
7067 return false;
7068}
7069
7071 Sema &SemaRef, SourceLocation Loc, Expr *From,
7073 if (!Converter.match(From->getType()) && !Converter.Suppress)
7074 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
7075 << From->getSourceRange();
7076
7077 return SemaRef.DefaultLvalueConversion(From);
7078}
7079
7080static void
7082 UnresolvedSetImpl &ViableConversions,
7083 OverloadCandidateSet &CandidateSet) {
7084 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7085 NamedDecl *D = FoundDecl.getDecl();
7086 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7087 if (isa<UsingShadowDecl>(D))
7088 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7089
7090 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7092 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7093 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7094 continue;
7095 }
7097 SemaRef.AddConversionCandidate(
7098 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7099 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7100 }
7101}
7102
7103/// Attempt to convert the given expression to a type which is accepted
7104/// by the given converter.
7105///
7106/// This routine will attempt to convert an expression of class type to a
7107/// type accepted by the specified converter. In C++11 and before, the class
7108/// must have a single non-explicit conversion function converting to a matching
7109/// type. In C++1y, there can be multiple such conversion functions, but only
7110/// one target type.
7111///
7112/// \param Loc The source location of the construct that requires the
7113/// conversion.
7114///
7115/// \param From The expression we're converting from.
7116///
7117/// \param Converter Used to control and diagnose the conversion process.
7118///
7119/// \returns The expression, converted to an integral or enumeration type if
7120/// successful.
7122 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7123 // We can't perform any more checking for type-dependent expressions.
7124 if (From->isTypeDependent())
7125 return From;
7126
7127 // Process placeholders immediately.
7128 if (From->hasPlaceholderType()) {
7129 ExprResult result = CheckPlaceholderExpr(From);
7130 if (result.isInvalid())
7131 return result;
7132 From = result.get();
7133 }
7134
7135 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7136 ExprResult Converted = DefaultLvalueConversion(From);
7137 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7138 From = Converted.isUsable() ? Converted.get() : nullptr;
7139 // If the expression already has a matching type, we're golden.
7140 if (Converter.match(T))
7141 return Converted;
7142
7143 // FIXME: Check for missing '()' if T is a function type?
7144
7145 // We can only perform contextual implicit conversions on objects of class
7146 // type.
7147 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7148 if (!RecordTy || !getLangOpts().CPlusPlus) {
7149 if (!Converter.Suppress)
7150 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7151 return From;
7152 }
7153
7154 // We must have a complete class type.
7155 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7156 ContextualImplicitConverter &Converter;
7157 Expr *From;
7158
7159 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7160 : Converter(Converter), From(From) {}
7161
7162 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7163 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7164 }
7165 } IncompleteDiagnoser(Converter, From);
7166
7167 if (Converter.Suppress ? !isCompleteType(Loc, T)
7168 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7169 return From;
7170
7171 // Look for a conversion to an integral or enumeration type.
7173 ViableConversions; // These are *potentially* viable in C++1y.
7174 UnresolvedSet<4> ExplicitConversions;
7175 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7176 ->getDefinitionOrSelf()
7177 ->getVisibleConversionFunctions();
7178
7179 bool HadMultipleCandidates =
7180 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7181
7182 // To check that there is only one target type, in C++1y:
7183 QualType ToType;
7184 bool HasUniqueTargetType = true;
7185
7186 // Collect explicit or viable (potentially in C++1y) conversions.
7187 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7188 NamedDecl *D = (*I)->getUnderlyingDecl();
7189 CXXConversionDecl *Conversion;
7190 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7191 if (ConvTemplate) {
7193 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7194 else
7195 continue; // C++11 does not consider conversion operator templates(?).
7196 } else
7197 Conversion = cast<CXXConversionDecl>(D);
7198
7199 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7200 "Conversion operator templates are considered potentially "
7201 "viable in C++1y");
7202
7203 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7204 if (Converter.match(CurToType) || ConvTemplate) {
7205
7206 if (Conversion->isExplicit()) {
7207 // FIXME: For C++1y, do we need this restriction?
7208 // cf. diagnoseNoViableConversion()
7209 if (!ConvTemplate)
7210 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7211 } else {
7212 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7213 if (ToType.isNull())
7214 ToType = CurToType.getUnqualifiedType();
7215 else if (HasUniqueTargetType &&
7216 (CurToType.getUnqualifiedType() != ToType))
7217 HasUniqueTargetType = false;
7218 }
7219 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7220 }
7221 }
7222 }
7223
7224 if (getLangOpts().CPlusPlus14) {
7225 // C++1y [conv]p6:
7226 // ... An expression e of class type E appearing in such a context
7227 // is said to be contextually implicitly converted to a specified
7228 // type T and is well-formed if and only if e can be implicitly
7229 // converted to a type T that is determined as follows: E is searched
7230 // for conversion functions whose return type is cv T or reference to
7231 // cv T such that T is allowed by the context. There shall be
7232 // exactly one such T.
7233
7234 // If no unique T is found:
7235 if (ToType.isNull()) {
7236 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7237 HadMultipleCandidates,
7238 ExplicitConversions))
7239 return ExprError();
7240 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7241 }
7242
7243 // If more than one unique Ts are found:
7244 if (!HasUniqueTargetType)
7245 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7246 ViableConversions);
7247
7248 // If one unique T is found:
7249 // First, build a candidate set from the previously recorded
7250 // potentially viable conversions.
7252 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7253 CandidateSet);
7254
7255 // Then, perform overload resolution over the candidate set.
7257 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7258 case OR_Success: {
7259 // Apply this conversion.
7261 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7262 if (recordConversion(*this, Loc, From, Converter, T,
7263 HadMultipleCandidates, Found))
7264 return ExprError();
7265 break;
7266 }
7267 case OR_Ambiguous:
7268 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7269 ViableConversions);
7271 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7272 HadMultipleCandidates,
7273 ExplicitConversions))
7274 return ExprError();
7275 [[fallthrough]];
7276 case OR_Deleted:
7277 // We'll complain below about a non-integral condition type.
7278 break;
7279 }
7280 } else {
7281 switch (ViableConversions.size()) {
7282 case 0: {
7283 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7284 HadMultipleCandidates,
7285 ExplicitConversions))
7286 return ExprError();
7287
7288 // We'll complain below about a non-integral condition type.
7289 break;
7290 }
7291 case 1: {
7292 // Apply this conversion.
7293 DeclAccessPair Found = ViableConversions[0];
7294 if (recordConversion(*this, Loc, From, Converter, T,
7295 HadMultipleCandidates, Found))
7296 return ExprError();
7297 break;
7298 }
7299 default:
7300 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7301 ViableConversions);
7302 }
7303 }
7304
7305 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7306}
7307
7308/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7309/// an acceptable non-member overloaded operator for a call whose
7310/// arguments have types T1 (and, if non-empty, T2). This routine
7311/// implements the check in C++ [over.match.oper]p3b2 concerning
7312/// enumeration types.
7314 FunctionDecl *Fn,
7315 ArrayRef<Expr *> Args) {
7316 QualType T1 = Args[0]->getType();
7317 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7318
7319 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7320 return true;
7321
7322 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7323 return true;
7324
7325 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7326 if (Proto->getNumParams() < 1)
7327 return false;
7328
7329 if (T1->isEnumeralType()) {
7330 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7331 if (Context.hasSameUnqualifiedType(T1, ArgType))
7332 return true;
7333 }
7334
7335 if (Proto->getNumParams() < 2)
7336 return false;
7337
7338 if (!T2.isNull() && T2->isEnumeralType()) {
7339 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7340 if (Context.hasSameUnqualifiedType(T2, ArgType))
7341 return true;
7342 }
7343
7344 return false;
7345}
7346
7349 return false;
7350
7351 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7352 return FD->isTargetMultiVersion();
7353
7354 if (!FD->isMultiVersion())
7355 return false;
7356
7357 // Among multiple target versions consider either the default,
7358 // or the first non-default in the absence of default version.
7359 unsigned SeenAt = 0;
7360 unsigned I = 0;
7361 bool HasDefault = false;
7363 FD, [&](const FunctionDecl *CurFD) {
7364 if (FD == CurFD)
7365 SeenAt = I;
7366 else if (CurFD->isTargetMultiVersionDefault())
7367 HasDefault = true;
7368 ++I;
7369 });
7370 return HasDefault || SeenAt != 0;
7371}
7372
7375 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7376 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7377 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7378 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7379 bool StrictPackMatch) {
7380 const FunctionProtoType *Proto
7381 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7382 assert(Proto && "Functions without a prototype cannot be overloaded");
7383 assert(!Function->getDescribedFunctionTemplate() &&
7384 "Use AddTemplateOverloadCandidate for function templates");
7385
7386 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7388 // If we get here, it's because we're calling a member function
7389 // that is named without a member access expression (e.g.,
7390 // "this->f") that was either written explicitly or created
7391 // implicitly. This can happen with a qualified call to a member
7392 // function, e.g., X::f(). We use an empty type for the implied
7393 // object argument (C++ [over.call.func]p3), and the acting context
7394 // is irrelevant.
7395 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7397 CandidateSet, SuppressUserConversions,
7398 PartialOverloading, EarlyConversions, PO,
7399 StrictPackMatch);
7400 return;
7401 }
7402 // We treat a constructor like a non-member function, since its object
7403 // argument doesn't participate in overload resolution.
7404 }
7405
7406 if (!CandidateSet.isNewCandidate(Function, PO))
7407 return;
7408
7409 // C++11 [class.copy]p11: [DR1402]
7410 // A defaulted move constructor that is defined as deleted is ignored by
7411 // overload resolution.
7412 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7413 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7414 Constructor->isMoveConstructor())
7415 return;
7416
7417 // Overload resolution is always an unevaluated context.
7420
7421 // C++ [over.match.oper]p3:
7422 // if no operand has a class type, only those non-member functions in the
7423 // lookup set that have a first parameter of type T1 or "reference to
7424 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7425 // is a right operand) a second parameter of type T2 or "reference to
7426 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7427 // candidate functions.
7428 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7430 return;
7431
7432 // Add this candidate
7433 OverloadCandidate &Candidate =
7434 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7435 Candidate.FoundDecl = FoundDecl;
7436 Candidate.Function = Function;
7437 Candidate.Viable = true;
7438 Candidate.RewriteKind =
7439 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7440 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7441 Candidate.ExplicitCallArguments = Args.size();
7442 Candidate.StrictPackMatch = StrictPackMatch;
7443
7444 // Explicit functions are not actually candidates at all if we're not
7445 // allowing them in this context, but keep them around so we can point
7446 // to them in diagnostics.
7447 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7448 Candidate.Viable = false;
7449 Candidate.FailureKind = ovl_fail_explicit;
7450 return;
7451 }
7452
7453 // Functions with internal linkage are only viable in the same module unit.
7454 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7455 /// FIXME: Currently, the semantics of linkage in clang is slightly
7456 /// different from the semantics in C++ spec. In C++ spec, only names
7457 /// have linkage. So that all entities of the same should share one
7458 /// linkage. But in clang, different entities of the same could have
7459 /// different linkage.
7460 const NamedDecl *ND = Function;
7461 bool IsImplicitlyInstantiated = false;
7462 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7463 ND = SpecInfo->getTemplate();
7464 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7466 }
7467
7468 /// Don't remove inline functions with internal linkage from the overload
7469 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7470 /// However:
7471 /// - Inline functions with internal linkage are a common pattern in
7472 /// headers to avoid ODR issues.
7473 /// - The global module is meant to be a transition mechanism for C and C++
7474 /// headers, and the current rules as written work against that goal.
7475 const bool IsInlineFunctionInGMF =
7476 Function->isFromGlobalModule() &&
7477 (IsImplicitlyInstantiated || Function->isInlined());
7478
7479 // Don't exclude internal-linkage entities from the current TU's global
7480 // module fragment.
7481 const Module *CurrentModule = getCurrentModule();
7482 const bool IsCurrentUnitGMFDecl =
7483 Function->isFromGlobalModule() && CurrentModule &&
7484 Function->getOwningModule()->getTopLevelModule() ==
7485 CurrentModule->getTopLevelModule();
7486
7487 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7488 !IsCurrentUnitGMFDecl) {
7489 Candidate.Viable = false;
7491 return;
7492 }
7493 }
7494
7496 Candidate.Viable = false;
7498 return;
7499 }
7500
7501 if (Constructor) {
7502 // C++ [class.copy]p3:
7503 // A member function template is never instantiated to perform the copy
7504 // of a class object to an object of its class type.
7505 CanQualType ClassType =
7506 Context.getCanonicalTagType(Constructor->getParent());
7507 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7508 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7509 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7510 ClassType))) {
7511 Candidate.Viable = false;
7513 return;
7514 }
7515
7516 // C++ [over.match.funcs]p8: (proposed DR resolution)
7517 // A constructor inherited from class type C that has a first parameter
7518 // of type "reference to P" (including such a constructor instantiated
7519 // from a template) is excluded from the set of candidate functions when
7520 // constructing an object of type cv D if the argument list has exactly
7521 // one argument and D is reference-related to P and P is reference-related
7522 // to C.
7523 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7524 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7525 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7526 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7527 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7528 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7529 SourceLocation Loc = Args.front()->getExprLoc();
7530 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7531 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7532 Candidate.Viable = false;
7534 return;
7535 }
7536 }
7537
7538 // Check that the constructor is capable of constructing an object in the
7539 // destination address space.
7541 Constructor->getMethodQualifiers().getAddressSpace(),
7542 CandidateSet.getDestAS(), getASTContext())) {
7543 Candidate.Viable = false;
7545 }
7546 }
7547
7548 unsigned NumParams = Proto->getNumParams();
7549
7550 // (C++ 13.3.2p2): A candidate function having fewer than m
7551 // parameters is viable only if it has an ellipsis in its parameter
7552 // list (8.3.5).
7553 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7554 !Proto->isVariadic() &&
7555 shouldEnforceArgLimit(PartialOverloading, Function)) {
7556 Candidate.Viable = false;
7558 return;
7559 }
7560
7561 // (C++ 13.3.2p2): A candidate function having more than m parameters
7562 // is viable only if the (m+1)st parameter has a default argument
7563 // (8.3.6). For the purposes of overload resolution, the
7564 // parameter list is truncated on the right, so that there are
7565 // exactly m parameters.
7566 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7567 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7568 !PartialOverloading) {
7569 // Not enough arguments.
7570 Candidate.Viable = false;
7572 return;
7573 }
7574
7575 // (CUDA B.1): Check for invalid calls between targets.
7576 if (getLangOpts().CUDA) {
7577 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7578 // Skip the check for callers that are implicit members, because in this
7579 // case we may not yet know what the member's target is; the target is
7580 // inferred for the member automatically, based on the bases and fields of
7581 // the class.
7582 if (!(Caller && Caller->isImplicit()) &&
7583 !CUDA().IsAllowedCall(Caller, Function)) {
7584 Candidate.Viable = false;
7585 Candidate.FailureKind = ovl_fail_bad_target;
7586 return;
7587 }
7588 }
7589
7590 if (Function->getTrailingRequiresClause()) {
7591 ConstraintSatisfaction Satisfaction;
7592 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7593 /*ForOverloadResolution*/ true) ||
7594 !Satisfaction.IsSatisfied) {
7595 Candidate.Viable = false;
7597 return;
7598 }
7599 }
7600
7601 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7602 // Determine the implicit conversion sequences for each of the
7603 // arguments.
7604 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7605 unsigned ConvIdx =
7606 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7607 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7608 // We already formed a conversion sequence for this parameter during
7609 // template argument deduction.
7610 } else if (ArgIdx < NumParams) {
7611 // (C++ 13.3.2p3): for F to be a viable function, there shall
7612 // exist for each argument an implicit conversion sequence
7613 // (13.3.3.1) that converts that argument to the corresponding
7614 // parameter of F.
7615 QualType ParamType = Proto->getParamType(ArgIdx);
7616 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7617 if (ParamABI == ParameterABI::HLSLOut ||
7618 ParamABI == ParameterABI::HLSLInOut) {
7619 ParamType = ParamType.getNonReferenceType();
7620 if (ParamABI == ParameterABI::HLSLInOut &&
7621 Args[ArgIdx]->getType().getAddressSpace() ==
7623 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7624 }
7625 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7626 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7627 /*InOverloadResolution=*/true,
7628 /*AllowObjCWritebackConversion=*/
7629 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7630 if (Candidate.Conversions[ConvIdx].isBad()) {
7631 Candidate.Viable = false;
7633 return;
7634 }
7635 } else {
7636 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7637 // argument for which there is no corresponding parameter is
7638 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7639 Candidate.Conversions[ConvIdx].setEllipsis();
7640 }
7641 }
7642
7643 if (EnableIfAttr *FailedAttr =
7644 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7645 Candidate.Viable = false;
7646 Candidate.FailureKind = ovl_fail_enable_if;
7647 Candidate.DeductionFailure.Data = FailedAttr;
7648 return;
7649 }
7650}
7651
7655 if (Methods.size() <= 1)
7656 return nullptr;
7657
7658 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7659 bool Match = true;
7660 ObjCMethodDecl *Method = Methods[b];
7661 unsigned NumNamedArgs = Sel.getNumArgs();
7662 // Method might have more arguments than selector indicates. This is due
7663 // to addition of c-style arguments in method.
7664 if (Method->param_size() > NumNamedArgs)
7665 NumNamedArgs = Method->param_size();
7666 if (Args.size() < NumNamedArgs)
7667 continue;
7668
7669 for (unsigned i = 0; i < NumNamedArgs; i++) {
7670 // We can't do any type-checking on a type-dependent argument.
7671 if (Args[i]->isTypeDependent()) {
7672 Match = false;
7673 break;
7674 }
7675
7676 ParmVarDecl *param = Method->parameters()[i];
7677 Expr *argExpr = Args[i];
7678 assert(argExpr && "SelectBestMethod(): missing expression");
7679
7680 // Strip the unbridged-cast placeholder expression off unless it's
7681 // a consumed argument.
7682 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7683 !param->hasAttr<CFConsumedAttr>())
7684 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7685
7686 // If the parameter is __unknown_anytype, move on to the next method.
7687 if (param->getType() == Context.UnknownAnyTy) {
7688 Match = false;
7689 break;
7690 }
7691
7692 ImplicitConversionSequence ConversionState
7693 = TryCopyInitialization(*this, argExpr, param->getType(),
7694 /*SuppressUserConversions*/false,
7695 /*InOverloadResolution=*/true,
7696 /*AllowObjCWritebackConversion=*/
7697 getLangOpts().ObjCAutoRefCount,
7698 /*AllowExplicit*/false);
7699 // This function looks for a reasonably-exact match, so we consider
7700 // incompatible pointer conversions to be a failure here.
7701 if (ConversionState.isBad() ||
7702 (ConversionState.isStandard() &&
7703 ConversionState.Standard.Second ==
7705 Match = false;
7706 break;
7707 }
7708 }
7709 // Promote additional arguments to variadic methods.
7710 if (Match && Method->isVariadic()) {
7711 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7712 if (Args[i]->isTypeDependent()) {
7713 Match = false;
7714 break;
7715 }
7717 Args[i], VariadicCallType::Method, nullptr);
7718 if (Arg.isInvalid()) {
7719 Match = false;
7720 break;
7721 }
7722 }
7723 } else {
7724 // Check for extra arguments to non-variadic methods.
7725 if (Args.size() != NumNamedArgs)
7726 Match = false;
7727 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7728 // Special case when selectors have no argument. In this case, select
7729 // one with the most general result type of 'id'.
7730 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7731 QualType ReturnT = Methods[b]->getReturnType();
7732 if (ReturnT->isObjCIdType())
7733 return Methods[b];
7734 }
7735 }
7736 }
7737
7738 if (Match)
7739 return Method;
7740 }
7741 return nullptr;
7742}
7743
7745 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7746 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7747 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7748 if (ThisArg) {
7749 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7750 assert(!isa<CXXConstructorDecl>(Method) &&
7751 "Shouldn't have `this` for ctors!");
7752 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7754 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7755 if (R.isInvalid())
7756 return false;
7757 ConvertedThis = R.get();
7758 } else {
7759 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7760 (void)MD;
7761 assert((MissingImplicitThis || MD->isStatic() ||
7763 "Expected `this` for non-ctor instance methods");
7764 }
7765 ConvertedThis = nullptr;
7766 }
7767
7768 // Ignore any variadic arguments. Converting them is pointless, since the
7769 // user can't refer to them in the function condition.
7770 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7771
7772 // Convert the arguments.
7773 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7774 ExprResult R;
7776 S.Context, Function->getParamDecl(I)),
7777 SourceLocation(), Args[I]);
7778
7779 if (R.isInvalid())
7780 return false;
7781
7782 ConvertedArgs.push_back(R.get());
7783 }
7784
7785 if (Trap.hasErrorOccurred())
7786 return false;
7787
7788 // Push default arguments if needed.
7789 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7790 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7791 ParmVarDecl *P = Function->getParamDecl(i);
7792 if (!P->hasDefaultArg())
7793 return false;
7794 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7795 if (R.isInvalid())
7796 return false;
7797 ConvertedArgs.push_back(R.get());
7798 }
7799
7800 if (Trap.hasErrorOccurred())
7801 return false;
7802 }
7803 return true;
7804}
7805
7807 SourceLocation CallLoc,
7808 ArrayRef<Expr *> Args,
7809 bool MissingImplicitThis) {
7810 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7811 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7812 return nullptr;
7813
7814 SFINAETrap Trap(*this);
7815 // Perform the access checking immediately so any access diagnostics are
7816 // caught by the SFINAE trap.
7817 llvm::scope_exit UndelayDiags(
7818 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7819 DelayedDiagnostics.popUndelayed(CurrentState);
7820 });
7821 SmallVector<Expr *, 16> ConvertedArgs;
7822 // FIXME: We should look into making enable_if late-parsed.
7823 Expr *DiscardedThis;
7825 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7826 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7827 return *EnableIfAttrs.begin();
7828
7829 for (auto *EIA : EnableIfAttrs) {
7831 // FIXME: This doesn't consider value-dependent cases, because doing so is
7832 // very difficult. Ideally, we should handle them more gracefully.
7833 if (EIA->getCond()->isValueDependent() ||
7834 !EIA->getCond()->EvaluateWithSubstitution(
7835 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7836 return EIA;
7837
7838 if (!Result.isInt() || !Result.getInt().getBoolValue())
7839 return EIA;
7840 }
7841 return nullptr;
7842}
7843
7844template <typename CheckFn>
7846 bool ArgDependent, SourceLocation Loc,
7847 CheckFn &&IsSuccessful) {
7849 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7850 if (ArgDependent == DIA->getArgDependent())
7851 Attrs.push_back(DIA);
7852 }
7853
7854 // Common case: No diagnose_if attributes, so we can quit early.
7855 if (Attrs.empty())
7856 return false;
7857
7858 auto WarningBegin = std::stable_partition(
7859 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7860 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7861 DIA->getWarningGroup().empty();
7862 });
7863
7864 // Note that diagnose_if attributes are late-parsed, so they appear in the
7865 // correct order (unlike enable_if attributes).
7866 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7867 IsSuccessful);
7868 if (ErrAttr != WarningBegin) {
7869 const DiagnoseIfAttr *DIA = *ErrAttr;
7870 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7871 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7872 << DIA->getParent() << DIA->getCond()->getSourceRange();
7873 return true;
7874 }
7875
7876 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7877 switch (Sev) {
7878 case DiagnoseIfAttr::DS_warning:
7880 case DiagnoseIfAttr::DS_error:
7881 return diag::Severity::Error;
7882 }
7883 llvm_unreachable("Fully covered switch above!");
7884 };
7885
7886 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7887 if (IsSuccessful(DIA)) {
7888 if (DIA->getWarningGroup().empty() &&
7889 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7890 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7891 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7892 << DIA->getParent() << DIA->getCond()->getSourceRange();
7893 } else {
7894 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7895 DIA->getWarningGroup());
7896 assert(DiagGroup);
7897 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7898 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7899 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7900 S.Diag(Loc, DiagID) << DIA->getMessage();
7901 }
7902 }
7903
7904 return false;
7905}
7906
7908 const Expr *ThisArg,
7910 SourceLocation Loc) {
7912 *this, Function, /*ArgDependent=*/true, Loc,
7913 [&](const DiagnoseIfAttr *DIA) {
7915 // It's sane to use the same Args for any redecl of this function, since
7916 // EvaluateWithSubstitution only cares about the position of each
7917 // argument in the arg list, not the ParmVarDecl* it maps to.
7918 if (!DIA->getCond()->EvaluateWithSubstitution(
7919 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7920 return false;
7921 return Result.isInt() && Result.getInt().getBoolValue();
7922 });
7923}
7924
7926 SourceLocation Loc) {
7928 *this, ND, /*ArgDependent=*/false, Loc,
7929 [&](const DiagnoseIfAttr *DIA) {
7930 bool Result;
7931 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7932 Result;
7933 });
7934}
7935
7937 ArrayRef<Expr *> Args,
7938 OverloadCandidateSet &CandidateSet,
7939 TemplateArgumentListInfo *ExplicitTemplateArgs,
7940 bool SuppressUserConversions,
7941 bool PartialOverloading,
7942 bool FirstArgumentIsBase) {
7943 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7944 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7945 ArrayRef<Expr *> FunctionArgs = Args;
7946
7947 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7948 FunctionDecl *FD =
7949 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7950
7951 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7952 QualType ObjectType;
7953 Expr::Classification ObjectClassification;
7954 if (Args.size() > 0) {
7955 if (Expr *E = Args[0]) {
7956 // Use the explicit base to restrict the lookup:
7957 ObjectType = E->getType();
7958 // Pointers in the object arguments are implicitly dereferenced, so we
7959 // always classify them as l-values.
7960 if (!ObjectType.isNull() && ObjectType->isPointerType())
7961 ObjectClassification = Expr::Classification::makeSimpleLValue();
7962 else
7963 ObjectClassification = E->Classify(Context);
7964 } // .. else there is an implicit base.
7965 FunctionArgs = Args.slice(1);
7966 }
7967 if (FunTmpl) {
7969 FunTmpl, F.getPair(),
7971 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7972 FunctionArgs, CandidateSet, SuppressUserConversions,
7973 PartialOverloading);
7974 } else {
7975 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7976 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7977 ObjectClassification, FunctionArgs, CandidateSet,
7978 SuppressUserConversions, PartialOverloading);
7979 }
7980 } else {
7981 // This branch handles both standalone functions and static methods.
7982
7983 // Slice the first argument (which is the base) when we access
7984 // static method as non-static.
7985 if (Args.size() > 0 &&
7986 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7987 !isa<CXXConstructorDecl>(FD)))) {
7988 assert(cast<CXXMethodDecl>(FD)->isStatic());
7989 FunctionArgs = Args.slice(1);
7990 }
7991 if (FunTmpl) {
7992 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7993 ExplicitTemplateArgs, FunctionArgs,
7994 CandidateSet, SuppressUserConversions,
7995 PartialOverloading);
7996 } else {
7997 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7998 SuppressUserConversions, PartialOverloading);
7999 }
8000 }
8001 }
8002}
8003
8005 Expr::Classification ObjectClassification,
8006 ArrayRef<Expr *> Args,
8007 OverloadCandidateSet &CandidateSet,
8008 bool SuppressUserConversions,
8010 NamedDecl *Decl = FoundDecl.getDecl();
8012
8014 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
8015
8016 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
8017 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
8018 "Expected a member function template");
8019 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
8020 /*ExplicitArgs*/ nullptr, ObjectType,
8021 ObjectClassification, Args, CandidateSet,
8022 SuppressUserConversions, false, PO);
8023 } else {
8024 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
8025 ObjectType, ObjectClassification, Args, CandidateSet,
8026 SuppressUserConversions, false, {}, PO);
8027 }
8028}
8029
8032 CXXRecordDecl *ActingContext, QualType ObjectType,
8033 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8034 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8035 bool PartialOverloading, ConversionSequenceList EarlyConversions,
8036 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
8037 const FunctionProtoType *Proto
8038 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
8039 assert(Proto && "Methods without a prototype cannot be overloaded");
8041 "Use AddOverloadCandidate for constructors");
8042
8043 if (!CandidateSet.isNewCandidate(Method, PO))
8044 return;
8045
8046 // C++11 [class.copy]p23: [DR1402]
8047 // A defaulted move assignment operator that is defined as deleted is
8048 // ignored by overload resolution.
8049 if (Method->isDefaulted() && Method->isDeleted() &&
8050 Method->isMoveAssignmentOperator())
8051 return;
8052
8053 // Overload resolution is always an unevaluated context.
8056
8057 bool IgnoreExplicitObject =
8058 (Method->isExplicitObjectMemberFunction() &&
8059 CandidateSet.getKind() ==
8061 bool ImplicitObjectMethodTreatedAsStatic =
8062 CandidateSet.getKind() ==
8064 Method->isImplicitObjectMemberFunction();
8065
8066 unsigned ExplicitOffset =
8067 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
8068
8069 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
8070 int(ImplicitObjectMethodTreatedAsStatic);
8071
8072 unsigned ExtraArgs =
8074 ? 0
8075 : 1;
8076
8077 // Add this candidate
8078 OverloadCandidate &Candidate =
8079 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
8080 Candidate.FoundDecl = FoundDecl;
8081 Candidate.Function = Method;
8082 Candidate.RewriteKind =
8083 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
8084 Candidate.TookAddressOfOverload =
8086 Candidate.ExplicitCallArguments = Args.size();
8087 Candidate.StrictPackMatch = StrictPackMatch;
8088
8089 // (C++ 13.3.2p2): A candidate function having fewer than m
8090 // parameters is viable only if it has an ellipsis in its parameter
8091 // list (8.3.5).
8092 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
8093 !Proto->isVariadic() &&
8094 shouldEnforceArgLimit(PartialOverloading, Method)) {
8095 Candidate.Viable = false;
8097 return;
8098 }
8099
8100 // (C++ 13.3.2p2): A candidate function having more than m parameters
8101 // is viable only if the (m+1)st parameter has a default argument
8102 // (8.3.6). For the purposes of overload resolution, the
8103 // parameter list is truncated on the right, so that there are
8104 // exactly m parameters.
8105 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8106 ExplicitOffset +
8107 int(ImplicitObjectMethodTreatedAsStatic);
8108
8109 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8110 // Not enough arguments.
8111 Candidate.Viable = false;
8113 return;
8114 }
8115
8116 Candidate.Viable = true;
8117
8118 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8119 if (!IgnoreExplicitObject) {
8120 if (ObjectType.isNull())
8121 Candidate.IgnoreObjectArgument = true;
8122 else if (Method->isStatic()) {
8123 // [over.best.ics.general]p8
8124 // When the parameter is the implicit object parameter of a static member
8125 // function, the implicit conversion sequence is a standard conversion
8126 // sequence that is neither better nor worse than any other standard
8127 // conversion sequence.
8128 //
8129 // This is a rule that was introduced in C++23 to support static lambdas.
8130 // We apply it retroactively because we want to support static lambdas as
8131 // an extension and it doesn't hurt previous code.
8132 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8133 } else {
8134 // Determine the implicit conversion sequence for the object
8135 // parameter.
8136 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8137 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8138 Method, ActingContext, /*InOverloadResolution=*/true);
8139 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8140 Candidate.Viable = false;
8142 return;
8143 }
8144 }
8145 }
8146
8147 // (CUDA B.1): Check for invalid calls between targets.
8148 if (getLangOpts().CUDA)
8149 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8150 Method)) {
8151 Candidate.Viable = false;
8152 Candidate.FailureKind = ovl_fail_bad_target;
8153 return;
8154 }
8155
8156 if (Method->getTrailingRequiresClause()) {
8157 ConstraintSatisfaction Satisfaction;
8158 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8159 /*ForOverloadResolution*/ true) ||
8160 !Satisfaction.IsSatisfied) {
8161 Candidate.Viable = false;
8163 return;
8164 }
8165 }
8166
8167 // Determine the implicit conversion sequences for each of the
8168 // arguments.
8169 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8170 unsigned ConvIdx =
8171 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8172 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8173 // We already formed a conversion sequence for this parameter during
8174 // template argument deduction.
8175 } else if (ArgIdx < NumParams) {
8176 // (C++ 13.3.2p3): for F to be a viable function, there shall
8177 // exist for each argument an implicit conversion sequence
8178 // (13.3.3.1) that converts that argument to the corresponding
8179 // parameter of F.
8180 QualType ParamType;
8181 if (ImplicitObjectMethodTreatedAsStatic) {
8182 ParamType = ArgIdx == 0
8183 ? Method->getFunctionObjectParameterReferenceType()
8184 : Proto->getParamType(ArgIdx - 1);
8185 } else {
8186 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8187 }
8188 Candidate.Conversions[ConvIdx]
8189 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8190 SuppressUserConversions,
8191 /*InOverloadResolution=*/true,
8192 /*AllowObjCWritebackConversion=*/
8193 getLangOpts().ObjCAutoRefCount);
8194 if (Candidate.Conversions[ConvIdx].isBad()) {
8195 Candidate.Viable = false;
8197 return;
8198 }
8199 } else {
8200 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8201 // argument for which there is no corresponding parameter is
8202 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8203 Candidate.Conversions[ConvIdx].setEllipsis();
8204 }
8205 }
8206
8207 if (EnableIfAttr *FailedAttr =
8208 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8209 Candidate.Viable = false;
8210 Candidate.FailureKind = ovl_fail_enable_if;
8211 Candidate.DeductionFailure.Data = FailedAttr;
8212 return;
8213 }
8214
8216 Candidate.Viable = false;
8218 }
8219}
8220
8222 Sema &S, OverloadCandidateSet &CandidateSet,
8223 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8224 CXXRecordDecl *ActingContext,
8225 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8226 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8227 bool SuppressUserConversions, bool PartialOverloading,
8229
8230 // C++ [over.match.funcs]p7:
8231 // In each case where a candidate is a function template, candidate
8232 // function template specializations are generated using template argument
8233 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8234 // candidate functions in the usual way.113) A given name can refer to one
8235 // or more function templates and also to a set of overloaded non-template
8236 // functions. In such a case, the candidate functions generated from each
8237 // function template are combined with the set of non-template candidate
8238 // functions.
8239 TemplateDeductionInfo Info(CandidateSet.getLocation());
8240 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8241 FunctionDecl *Specialization = nullptr;
8242 ConversionSequenceList Conversions;
8244 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8245 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8246 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8247 CandidateSet.getKind() ==
8249 [&](ArrayRef<QualType> ParamTypes,
8250 bool OnlyInitializeNonUserDefinedConversions) {
8251 return S.CheckNonDependentConversions(
8252 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8253 Sema::CheckNonDependentConversionsFlag(
8254 SuppressUserConversions,
8255 OnlyInitializeNonUserDefinedConversions),
8256 ActingContext, ObjectType, ObjectClassification, PO);
8257 });
8259 OverloadCandidate &Candidate =
8260 CandidateSet.addCandidate(Conversions.size(), Conversions);
8261 Candidate.FoundDecl = FoundDecl;
8262 Candidate.Function = Method;
8263 Candidate.Viable = false;
8264 Candidate.RewriteKind =
8265 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8266 Candidate.IsSurrogate = false;
8267 Candidate.TookAddressOfOverload =
8268 CandidateSet.getKind() ==
8270
8271 Candidate.IgnoreObjectArgument =
8272 Method->isStatic() ||
8273 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8274 Candidate.ExplicitCallArguments = Args.size();
8277 else {
8279 Candidate.DeductionFailure =
8281 }
8282 return;
8283 }
8284
8285 // Add the function template specialization produced by template argument
8286 // deduction as a candidate.
8287 assert(Specialization && "Missing member function template specialization?");
8289 "Specialization is not a member function?");
8291 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8292 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8293 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8294}
8295
8297 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8298 CXXRecordDecl *ActingContext,
8299 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8300 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8301 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8302 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8303 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8304 return;
8305
8306 if (ExplicitTemplateArgs ||
8307 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8309 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8310 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8311 SuppressUserConversions, PartialOverloading, PO);
8312 return;
8313 }
8314
8316 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8317 Args, SuppressUserConversions, PartialOverloading, PO);
8318}
8319
8320/// Determine whether a given function template has a simple explicit specifier
8321/// or a non-value-dependent explicit-specification that evaluates to true.
8325
8330
8332 Sema &S, OverloadCandidateSet &CandidateSet,
8334 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8335 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8337 bool AggregateCandidateDeduction) {
8338
8339 // If the function template has a non-dependent explicit specification,
8340 // exclude it now if appropriate; we are not permitted to perform deduction
8341 // and substitution in this case.
8342 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8343 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8344 Candidate.FoundDecl = FoundDecl;
8345 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8346 Candidate.Viable = false;
8347 Candidate.FailureKind = ovl_fail_explicit;
8348 return;
8349 }
8350
8351 // C++ [over.match.funcs]p7:
8352 // In each case where a candidate is a function template, candidate
8353 // function template specializations are generated using template argument
8354 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8355 // candidate functions in the usual way.113) A given name can refer to one
8356 // or more function templates and also to a set of overloaded non-template
8357 // functions. In such a case, the candidate functions generated from each
8358 // function template are combined with the set of non-template candidate
8359 // functions.
8360 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8361 FunctionTemplate->getTemplateDepth());
8362 FunctionDecl *Specialization = nullptr;
8363 ConversionSequenceList Conversions;
8365 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8366 PartialOverloading, AggregateCandidateDeduction,
8367 /*PartialOrdering=*/false,
8368 /*ObjectType=*/QualType(),
8369 /*ObjectClassification=*/Expr::Classification(),
8370 CandidateSet.getKind() ==
8372 [&](ArrayRef<QualType> ParamTypes,
8373 bool OnlyInitializeNonUserDefinedConversions) {
8374 return S.CheckNonDependentConversions(
8375 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8376 Sema::CheckNonDependentConversionsFlag(
8377 SuppressUserConversions,
8378 OnlyInitializeNonUserDefinedConversions),
8379 nullptr, QualType(), {}, PO);
8380 });
8382 OverloadCandidate &Candidate =
8383 CandidateSet.addCandidate(Conversions.size(), Conversions);
8384 Candidate.FoundDecl = FoundDecl;
8385 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8386 Candidate.Viable = false;
8387 Candidate.RewriteKind =
8388 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8389 Candidate.IsSurrogate = false;
8390 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8391 // Ignore the object argument if there is one, since we don't have an object
8392 // type.
8393 Candidate.TookAddressOfOverload =
8394 CandidateSet.getKind() ==
8396
8397 Candidate.IgnoreObjectArgument =
8398 isa<CXXMethodDecl>(Candidate.Function) &&
8399 !cast<CXXMethodDecl>(Candidate.Function)
8400 ->isExplicitObjectMemberFunction() &&
8402
8403 Candidate.ExplicitCallArguments = Args.size();
8406 else {
8408 Candidate.DeductionFailure =
8410 }
8411 return;
8412 }
8413
8414 // Add the function template specialization produced by template argument
8415 // deduction as a candidate.
8416 assert(Specialization && "Missing function template specialization?");
8418 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8419 PartialOverloading, AllowExplicit,
8420 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8421 Info.AggregateDeductionCandidateHasMismatchedArity,
8422 Info.hasStrictPackMatch());
8423}
8424
8427 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8428 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8429 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8430 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8431 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8432 return;
8433
8434 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8435
8436 if (ExplicitTemplateArgs ||
8437 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8438 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8439 DependentExplicitSpecifier)) {
8440
8442 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8443 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8444 IsADLCandidate, PO, AggregateCandidateDeduction);
8445
8446 if (DependentExplicitSpecifier)
8448 return;
8449 }
8450
8451 CandidateSet.AddDeferredTemplateCandidate(
8452 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8453 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8454 AggregateCandidateDeduction);
8455}
8456
8459 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8461 CheckNonDependentConversionsFlag UserConversionFlag,
8462 CXXRecordDecl *ActingContext, QualType ObjectType,
8463 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8464 // FIXME: The cases in which we allow explicit conversions for constructor
8465 // arguments never consider calling a constructor template. It's not clear
8466 // that is correct.
8467 const bool AllowExplicit = false;
8468
8469 bool ForOverloadSetAddressResolution =
8471 auto *FD = FunctionTemplate->getTemplatedDecl();
8472 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8473 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8475 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8476
8477 if (Conversions.empty())
8478 Conversions =
8479 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8480
8481 // Overload resolution is always an unevaluated context.
8484
8485 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8486 // require that, but this check should never result in a hard error, and
8487 // overload resolution is permitted to sidestep instantiations.
8488 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8489 !ObjectType.isNull()) {
8490 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8491 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8492 !ParamTypes[0]->isDependentType()) {
8494 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8495 Method, ActingContext, /*InOverloadResolution=*/true,
8496 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8497 : QualType());
8498 if (Conversions[ConvIdx].isBad())
8499 return true;
8500 }
8501 }
8502
8503 // A speculative workaround for self-dependent constraint bugs that manifest
8504 // after CWG2369.
8505 // FIXME: Add references to the standard once P3606 is adopted.
8506 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8507 QualType ArgType) {
8508 ParamType = ParamType.getNonReferenceType();
8509 ArgType = ArgType.getNonReferenceType();
8510 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8511 if (PointerConv) {
8512 ParamType = ParamType->getPointeeType();
8513 ArgType = ArgType->getPointeeType();
8514 }
8515
8516 if (auto *RD = ParamType->getAsCXXRecordDecl();
8517 RD && RD->hasDefinition() &&
8518 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8519 auto Info = getConstructorInfo(ND);
8520 if (!Info)
8521 return false;
8522 CXXConstructorDecl *Ctor = Info.Constructor;
8523 /// isConvertingConstructor takes copy/move constructors into
8524 /// account!
8525 return !Ctor->isCopyOrMoveConstructor() &&
8527 /*AllowExplicit=*/true);
8528 }))
8529 return true;
8530 if (auto *RD = ArgType->getAsCXXRecordDecl();
8531 RD && RD->hasDefinition() &&
8532 !RD->getVisibleConversionFunctions().empty())
8533 return true;
8534
8535 return false;
8536 };
8537
8538 unsigned Offset =
8539 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8540 : 0;
8541
8542 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8543 I != N; ++I) {
8544 QualType ParamType = ParamTypes[I + Offset];
8545 if (!ParamType->isDependentType()) {
8546 unsigned ConvIdx;
8548 ConvIdx = Args.size() - 1 - I;
8549 assert(Args.size() + ThisConversions == 2 &&
8550 "number of args (including 'this') must be exactly 2 for "
8551 "reversed order");
8552 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8553 // would also be 0. 'this' got ConvIdx = 1 previously.
8554 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8555 } else {
8556 // For members, 'this' got ConvIdx = 0 previously.
8557 ConvIdx = ThisConversions + I;
8558 }
8559 if (Conversions[ConvIdx].isInitialized())
8560 continue;
8561 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8562 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8563 continue;
8565 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8566 /*InOverloadResolution=*/true,
8567 /*AllowObjCWritebackConversion=*/
8568 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8569 if (Conversions[ConvIdx].isBad())
8570 return true;
8571 }
8572 }
8573
8574 return false;
8575}
8576
8577/// Determine whether this is an allowable conversion from the result
8578/// of an explicit conversion operator to the expected type, per C++
8579/// [over.match.conv]p1 and [over.match.ref]p1.
8580///
8581/// \param ConvType The return type of the conversion function.
8582///
8583/// \param ToType The type we are converting to.
8584///
8585/// \param AllowObjCPointerConversion Allow a conversion from one
8586/// Objective-C pointer to another.
8587///
8588/// \returns true if the conversion is allowable, false otherwise.
8590 QualType ConvType, QualType ToType,
8591 bool AllowObjCPointerConversion) {
8592 QualType ToNonRefType = ToType.getNonReferenceType();
8593
8594 // Easy case: the types are the same.
8595 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8596 return true;
8597
8598 // Allow qualification conversions.
8599 bool ObjCLifetimeConversion;
8600 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8601 ObjCLifetimeConversion))
8602 return true;
8603
8604 // If we're not allowed to consider Objective-C pointer conversions,
8605 // we're done.
8606 if (!AllowObjCPointerConversion)
8607 return false;
8608
8609 // Is this an Objective-C pointer conversion?
8610 bool IncompatibleObjC = false;
8611 QualType ConvertedType;
8612 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8613 IncompatibleObjC);
8614}
8615
8617 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8618 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8619 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8620 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8621 assert(!Conversion->getDescribedFunctionTemplate() &&
8622 "Conversion function templates use AddTemplateConversionCandidate");
8623 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8624 if (!CandidateSet.isNewCandidate(Conversion))
8625 return;
8626
8627 // If the conversion function has an undeduced return type, trigger its
8628 // deduction now.
8629 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8630 if (DeduceReturnType(Conversion, From->getExprLoc()))
8631 return;
8632 ConvType = Conversion->getConversionType().getNonReferenceType();
8633 }
8634
8635 // If we don't allow any conversion of the result type, ignore conversion
8636 // functions that don't convert to exactly (possibly cv-qualified) T.
8637 if (!AllowResultConversion &&
8638 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8639 return;
8640
8641 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8642 // operator is only a candidate if its return type is the target type or
8643 // can be converted to the target type with a qualification conversion.
8644 //
8645 // FIXME: Include such functions in the candidate list and explain why we
8646 // can't select them.
8647 if (Conversion->isExplicit() &&
8648 !isAllowableExplicitConversion(*this, ConvType, ToType,
8649 AllowObjCConversionOnExplicit))
8650 return;
8651
8652 // Overload resolution is always an unevaluated context.
8655
8656 // Add this candidate
8657 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8658 Candidate.FoundDecl = FoundDecl;
8659 Candidate.Function = Conversion;
8661 Candidate.FinalConversion.setFromType(ConvType);
8662 Candidate.FinalConversion.setAllToTypes(ToType);
8663 Candidate.HasFinalConversion = true;
8664 Candidate.Viable = true;
8665 Candidate.ExplicitCallArguments = 1;
8666 Candidate.StrictPackMatch = StrictPackMatch;
8667
8668 // Explicit functions are not actually candidates at all if we're not
8669 // allowing them in this context, but keep them around so we can point
8670 // to them in diagnostics.
8671 if (!AllowExplicit && Conversion->isExplicit()) {
8672 Candidate.Viable = false;
8673 Candidate.FailureKind = ovl_fail_explicit;
8674 return;
8675 }
8676
8677 // C++ [over.match.funcs]p4:
8678 // For conversion functions, the function is considered to be a member of
8679 // the class of the implicit implied object argument for the purpose of
8680 // defining the type of the implicit object parameter.
8681 //
8682 // Determine the implicit conversion sequence for the implicit
8683 // object parameter.
8684 QualType ObjectType = From->getType();
8685 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8686 ObjectType = FromPtrType->getPointeeType();
8687 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8688 // C++23 [over.best.ics.general]
8689 // However, if the target is [...]
8690 // - the object parameter of a user-defined conversion function
8691 // [...] user-defined conversion sequences are not considered.
8693 *this, CandidateSet.getLocation(), From->getType(),
8694 From->Classify(Context), Conversion, ConversionContext,
8695 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8696 /*SuppressUserConversion*/ true);
8697
8698 if (Candidate.Conversions[0].isBad()) {
8699 Candidate.Viable = false;
8701 return;
8702 }
8703
8704 if (Conversion->getTrailingRequiresClause()) {
8705 ConstraintSatisfaction Satisfaction;
8706 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8707 !Satisfaction.IsSatisfied) {
8708 Candidate.Viable = false;
8710 return;
8711 }
8712 }
8713
8714 // We won't go through a user-defined type conversion function to convert a
8715 // derived to base as such conversions are given Conversion Rank. They only
8716 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8717 QualType FromCanon
8718 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8719 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8720 if (FromCanon == ToCanon ||
8721 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8722 Candidate.Viable = false;
8724 return;
8725 }
8726
8727 // To determine what the conversion from the result of calling the
8728 // conversion function to the type we're eventually trying to
8729 // convert to (ToType), we need to synthesize a call to the
8730 // conversion function and attempt copy initialization from it. This
8731 // makes sure that we get the right semantics with respect to
8732 // lvalues/rvalues and the type. Fortunately, we can allocate this
8733 // call on the stack and we don't need its arguments to be
8734 // well-formed.
8735 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8736 VK_LValue, From->getBeginLoc());
8738 Context.getPointerType(Conversion->getType()),
8739 CK_FunctionToPointerDecay, &ConversionRef,
8741
8742 QualType ConversionType = Conversion->getConversionType();
8743 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8744 Candidate.Viable = false;
8746 return;
8747 }
8748
8749 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8750
8751 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8752
8753 // Introduce a temporary expression with the right type and value category
8754 // that we can use for deduction purposes.
8755 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8756
8758 TryCopyInitialization(*this, &FakeCall, ToType,
8759 /*SuppressUserConversions=*/true,
8760 /*InOverloadResolution=*/false,
8761 /*AllowObjCWritebackConversion=*/false);
8762
8763 switch (ICS.getKind()) {
8765 Candidate.FinalConversion = ICS.Standard;
8766 Candidate.HasFinalConversion = true;
8767
8768 // C++ [over.ics.user]p3:
8769 // If the user-defined conversion is specified by a specialization of a
8770 // conversion function template, the second standard conversion sequence
8771 // shall have exact match rank.
8772 if (Conversion->getPrimaryTemplate() &&
8774 Candidate.Viable = false;
8776 return;
8777 }
8778
8779 // C++0x [dcl.init.ref]p5:
8780 // In the second case, if the reference is an rvalue reference and
8781 // the second standard conversion sequence of the user-defined
8782 // conversion sequence includes an lvalue-to-rvalue conversion, the
8783 // program is ill-formed.
8784 if (ToType->isRValueReferenceType() &&
8786 Candidate.Viable = false;
8788 return;
8789 }
8790 break;
8791
8793 Candidate.Viable = false;
8795 return;
8796
8797 default:
8798 llvm_unreachable(
8799 "Can only end up with a standard conversion sequence or failure");
8800 }
8801
8802 if (EnableIfAttr *FailedAttr =
8803 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8804 Candidate.Viable = false;
8805 Candidate.FailureKind = ovl_fail_enable_if;
8806 Candidate.DeductionFailure.Data = FailedAttr;
8807 return;
8808 }
8809
8810 if (isNonViableMultiVersionOverload(Conversion)) {
8811 Candidate.Viable = false;
8813 }
8814}
8815
8817 Sema &S, OverloadCandidateSet &CandidateSet,
8819 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8820 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8821 bool AllowResultConversion) {
8822
8823 // If the function template has a non-dependent explicit specification,
8824 // exclude it now if appropriate; we are not permitted to perform deduction
8825 // and substitution in this case.
8826 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8827 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8828 Candidate.FoundDecl = FoundDecl;
8829 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8830 Candidate.Viable = false;
8831 Candidate.FailureKind = ovl_fail_explicit;
8832 return;
8833 }
8834
8835 QualType ObjectType = From->getType();
8836 Expr::Classification ObjectClassification = From->Classify(S.Context);
8837
8838 TemplateDeductionInfo Info(CandidateSet.getLocation());
8841 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8842 Specialization, Info);
8844 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8845 Candidate.FoundDecl = FoundDecl;
8846 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8847 Candidate.Viable = false;
8849 Candidate.ExplicitCallArguments = 1;
8850 Candidate.DeductionFailure =
8852 return;
8853 }
8854
8855 // Add the conversion function template specialization produced by
8856 // template argument deduction as a candidate.
8857 assert(Specialization && "Missing function template specialization?");
8858 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8859 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8860 AllowExplicit, AllowResultConversion,
8861 Info.hasStrictPackMatch());
8862}
8863
8866 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8867 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8868 bool AllowExplicit, bool AllowResultConversion) {
8869 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8870 "Only conversion function templates permitted here");
8871
8872 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8873 return;
8874
8875 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8876 CandidateSet.getKind() ==
8880 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8881 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8882 AllowResultConversion);
8883
8885 return;
8886 }
8887
8889 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8890 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8891}
8892
8894 DeclAccessPair FoundDecl,
8895 CXXRecordDecl *ActingContext,
8896 const FunctionProtoType *Proto,
8897 Expr *Object,
8898 ArrayRef<Expr *> Args,
8899 OverloadCandidateSet& CandidateSet) {
8900 if (!CandidateSet.isNewCandidate(Conversion))
8901 return;
8902
8903 // Overload resolution is always an unevaluated context.
8906
8907 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8908 Candidate.FoundDecl = FoundDecl;
8909 Candidate.Function = nullptr;
8910 Candidate.Surrogate = Conversion;
8911 Candidate.IsSurrogate = true;
8912 Candidate.Viable = true;
8913 Candidate.ExplicitCallArguments = Args.size();
8914
8915 // Determine the implicit conversion sequence for the implicit
8916 // object parameter.
8917 ImplicitConversionSequence ObjectInit;
8918 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8919 ObjectInit = TryCopyInitialization(*this, Object,
8920 Conversion->getParamDecl(0)->getType(),
8921 /*SuppressUserConversions=*/false,
8922 /*InOverloadResolution=*/true, false);
8923 } else {
8925 *this, CandidateSet.getLocation(), Object->getType(),
8926 Object->Classify(Context), Conversion, ActingContext);
8927 }
8928
8929 if (ObjectInit.isBad()) {
8930 Candidate.Viable = false;
8932 Candidate.Conversions[0] = ObjectInit;
8933 return;
8934 }
8935
8936 // The first conversion is actually a user-defined conversion whose
8937 // first conversion is ObjectInit's standard conversion (which is
8938 // effectively a reference binding). Record it as such.
8939 Candidate.Conversions[0].setUserDefined();
8940 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8941 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8942 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8943 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8944 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8945 Candidate.Conversions[0].UserDefined.After
8946 = Candidate.Conversions[0].UserDefined.Before;
8947 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8948
8949 // Find the
8950 unsigned NumParams = Proto->getNumParams();
8951
8952 // (C++ 13.3.2p2): A candidate function having fewer than m
8953 // parameters is viable only if it has an ellipsis in its parameter
8954 // list (8.3.5).
8955 if (Args.size() > NumParams && !Proto->isVariadic()) {
8956 Candidate.Viable = false;
8958 return;
8959 }
8960
8961 // Function types don't have any default arguments, so just check if
8962 // we have enough arguments.
8963 if (Args.size() < NumParams) {
8964 // Not enough arguments.
8965 Candidate.Viable = false;
8967 return;
8968 }
8969
8970 // Determine the implicit conversion sequences for each of the
8971 // arguments.
8972 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8973 if (ArgIdx < NumParams) {
8974 // (C++ 13.3.2p3): for F to be a viable function, there shall
8975 // exist for each argument an implicit conversion sequence
8976 // (13.3.3.1) that converts that argument to the corresponding
8977 // parameter of F.
8978 QualType ParamType = Proto->getParamType(ArgIdx);
8979 Candidate.Conversions[ArgIdx + 1]
8980 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8981 /*SuppressUserConversions=*/false,
8982 /*InOverloadResolution=*/false,
8983 /*AllowObjCWritebackConversion=*/
8984 getLangOpts().ObjCAutoRefCount);
8985 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8986 Candidate.Viable = false;
8988 return;
8989 }
8990 } else {
8991 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8992 // argument for which there is no corresponding parameter is
8993 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8994 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8995 }
8996 }
8997
8998 if (Conversion->getTrailingRequiresClause()) {
8999 ConstraintSatisfaction Satisfaction;
9000 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
9001 /*ForOverloadResolution*/ true) ||
9002 !Satisfaction.IsSatisfied) {
9003 Candidate.Viable = false;
9005 return;
9006 }
9007 }
9008
9009 if (EnableIfAttr *FailedAttr =
9010 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
9011 Candidate.Viable = false;
9012 Candidate.FailureKind = ovl_fail_enable_if;
9013 Candidate.DeductionFailure.Data = FailedAttr;
9014 return;
9015 }
9016}
9017
9019 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
9020 OverloadCandidateSet &CandidateSet,
9021 TemplateArgumentListInfo *ExplicitTemplateArgs) {
9022 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
9023 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
9024 ArrayRef<Expr *> FunctionArgs = Args;
9025
9026 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
9027 FunctionDecl *FD =
9028 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
9029
9030 // Don't consider rewritten functions if we're not rewriting.
9031 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
9032 continue;
9033
9034 assert(!isa<CXXMethodDecl>(FD) &&
9035 "unqualified operator lookup found a member function");
9036
9037 if (FunTmpl) {
9038 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
9039 FunctionArgs, CandidateSet);
9040 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9041
9042 // As template candidates are not deduced immediately,
9043 // persist the array in the overload set.
9045 FunctionArgs[1], FunctionArgs[0]);
9046 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
9047 Reversed, CandidateSet, false, false, true,
9048 ADLCallKind::NotADL,
9050 }
9051 } else {
9052 if (ExplicitTemplateArgs)
9053 continue;
9054 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
9055 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
9056 AddOverloadCandidate(FD, F.getPair(),
9057 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
9058 false, false, true, false, ADLCallKind::NotADL, {},
9060 }
9061 }
9062}
9063
9065 SourceLocation OpLoc,
9066 ArrayRef<Expr *> Args,
9067 OverloadCandidateSet &CandidateSet,
9069 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9070
9071 // C++ [over.match.oper]p3:
9072 // For a unary operator @ with an operand of a type whose
9073 // cv-unqualified version is T1, and for a binary operator @ with
9074 // a left operand of a type whose cv-unqualified version is T1 and
9075 // a right operand of a type whose cv-unqualified version is T2,
9076 // three sets of candidate functions, designated member
9077 // candidates, non-member candidates and built-in candidates, are
9078 // constructed as follows:
9079 QualType T1 = Args[0]->getType();
9080
9081 // -- If T1 is a complete class type or a class currently being
9082 // defined, the set of member candidates is the result of the
9083 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9084 // the set of member candidates is empty.
9085 if (T1->isRecordType()) {
9086 bool IsComplete = isCompleteType(OpLoc, T1);
9087 auto *T1RD = T1->getAsCXXRecordDecl();
9088 // Complete the type if it can be completed.
9089 // If the type is neither complete nor being defined, bail out now.
9090 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9091 return;
9092
9093 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9094 LookupQualifiedName(Operators, T1RD);
9095 Operators.suppressAccessDiagnostics();
9096
9097 for (LookupResult::iterator Oper = Operators.begin(),
9098 OperEnd = Operators.end();
9099 Oper != OperEnd; ++Oper) {
9100 if (Oper->getAsFunction() &&
9102 !CandidateSet.getRewriteInfo().shouldAddReversed(
9103 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9104 continue;
9105 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9106 Args[0]->Classify(Context), Args.slice(1),
9107 CandidateSet, /*SuppressUserConversion=*/false, PO);
9108 }
9109 }
9110}
9111
9113 OverloadCandidateSet& CandidateSet,
9114 bool IsAssignmentOperator,
9115 unsigned NumContextualBoolArguments) {
9116 // Overload resolution is always an unevaluated context.
9119
9120 // Add this candidate
9121 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9122 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9123 Candidate.Function = nullptr;
9124 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9125
9126 // Determine the implicit conversion sequences for each of the
9127 // arguments.
9128 Candidate.Viable = true;
9129 Candidate.ExplicitCallArguments = Args.size();
9130 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9131 // C++ [over.match.oper]p4:
9132 // For the built-in assignment operators, conversions of the
9133 // left operand are restricted as follows:
9134 // -- no temporaries are introduced to hold the left operand, and
9135 // -- no user-defined conversions are applied to the left
9136 // operand to achieve a type match with the left-most
9137 // parameter of a built-in candidate.
9138 //
9139 // We block these conversions by turning off user-defined
9140 // conversions, since that is the only way that initialization of
9141 // a reference to a non-class type can occur from something that
9142 // is not of the same type.
9143 if (ArgIdx < NumContextualBoolArguments) {
9144 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9145 "Contextual conversion to bool requires bool type");
9146 Candidate.Conversions[ArgIdx]
9147 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9148 } else {
9149 Candidate.Conversions[ArgIdx]
9150 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9151 ArgIdx == 0 && IsAssignmentOperator,
9152 /*InOverloadResolution=*/false,
9153 /*AllowObjCWritebackConversion=*/
9154 getLangOpts().ObjCAutoRefCount);
9155 }
9156 if (Candidate.Conversions[ArgIdx].isBad()) {
9157 Candidate.Viable = false;
9159 break;
9160 }
9161 }
9162}
9163
9164namespace {
9165
9166/// BuiltinCandidateTypeSet - A set of types that will be used for the
9167/// candidate operator functions for built-in operators (C++
9168/// [over.built]). The types are separated into pointer types and
9169/// enumeration types.
9170class BuiltinCandidateTypeSet {
9171 /// TypeSet - A set of types.
9172 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9173
9174 /// PointerTypes - The set of pointer types that will be used in the
9175 /// built-in candidates.
9176 TypeSet PointerTypes;
9177
9178 /// MemberPointerTypes - The set of member pointer types that will be
9179 /// used in the built-in candidates.
9180 TypeSet MemberPointerTypes;
9181
9182 /// EnumerationTypes - The set of enumeration types that will be
9183 /// used in the built-in candidates.
9184 TypeSet EnumerationTypes;
9185
9186 /// The set of vector types that will be used in the built-in
9187 /// candidates.
9188 TypeSet VectorTypes;
9189
9190 /// The set of matrix types that will be used in the built-in
9191 /// candidates.
9192 TypeSet MatrixTypes;
9193
9194 /// The set of _BitInt types that will be used in the built-in candidates.
9195 TypeSet BitIntTypes;
9196
9197 /// A flag indicating non-record types are viable candidates
9198 bool HasNonRecordTypes;
9199
9200 /// A flag indicating whether either arithmetic or enumeration types
9201 /// were present in the candidate set.
9202 bool HasArithmeticOrEnumeralTypes;
9203
9204 /// A flag indicating whether the candidate set has a type that might
9205 /// convert to a promoted arithmetic type or to a vector type. This is
9206 /// conservative: only scoped enumerations, pointers, member pointers,
9207 /// nullptr_t, and classes that convert to nothing else are known not to.
9208 bool MayConvertToArithmetic;
9209
9210 /// A flag indicating whether the nullptr type was present in the
9211 /// candidate set.
9212 bool HasNullPtrType;
9213
9214 /// A flag indicating whether the reflection type was present in the
9215 /// candidate set.
9216 bool HasReflectionType;
9217
9218 /// Sema - The semantic analysis instance where we are building the
9219 /// candidate type set.
9220 Sema &SemaRef;
9221
9222 /// Context - The AST context in which we will build the type sets.
9223 ASTContext &Context;
9224
9225 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9226 const Qualifiers &VisibleQuals);
9227 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9228
9229public:
9230 /// iterator - Iterates through the types that are part of the set.
9231 typedef TypeSet::iterator iterator;
9232
9233 BuiltinCandidateTypeSet(Sema &SemaRef)
9234 : HasNonRecordTypes(false), HasArithmeticOrEnumeralTypes(false),
9235 MayConvertToArithmetic(false), HasNullPtrType(false),
9236 HasReflectionType(false), SemaRef(SemaRef), Context(SemaRef.Context) {}
9237
9238 void AddTypesConvertedFrom(QualType Ty,
9239 SourceLocation Loc,
9240 bool AllowUserConversions,
9241 bool AllowExplicitConversions,
9242 const Qualifiers &VisibleTypeConversionsQuals);
9243
9244 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9245 llvm::iterator_range<iterator> member_pointer_types() {
9246 return MemberPointerTypes;
9247 }
9248 llvm::iterator_range<iterator> enumeration_types() {
9249 return EnumerationTypes;
9250 }
9251 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9252 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9253 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9254
9255 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9256 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9257 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9258 bool mayConvertToArithmetic() const { return MayConvertToArithmetic; }
9259 bool hasNullPtrType() const { return HasNullPtrType; }
9260 bool hasReflectionType() const { return HasReflectionType; }
9261};
9262
9263} // end anonymous namespace
9264
9265/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9266/// the set of pointer types along with any more-qualified variants of
9267/// that type. For example, if @p Ty is "int const *", this routine
9268/// will add "int const *", "int const volatile *", "int const
9269/// restrict *", and "int const volatile restrict *" to the set of
9270/// pointer types. Returns true if the add of @p Ty itself succeeded,
9271/// false otherwise.
9272///
9273/// FIXME: what to do about extended qualifiers?
9274bool
9275BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9276 const Qualifiers &VisibleQuals) {
9277
9278 // Insert this type.
9279 if (!PointerTypes.insert(Ty))
9280 return false;
9281
9282 QualType PointeeTy;
9283 const PointerType *PointerTy = Ty->getAs<PointerType>();
9284 bool buildObjCPtr = false;
9285 if (!PointerTy) {
9286 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9287 PointeeTy = PTy->getPointeeType();
9288 buildObjCPtr = true;
9289 } else {
9290 PointeeTy = PointerTy->getPointeeType();
9291 }
9292
9293 // Don't add qualified variants of arrays. For one, they're not allowed
9294 // (the qualifier would sink to the element type), and for another, the
9295 // only overload situation where it matters is subscript or pointer +- int,
9296 // and those shouldn't have qualifier variants anyway.
9297 if (PointeeTy->isArrayType())
9298 return true;
9299
9300 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9301 bool hasVolatile = VisibleQuals.hasVolatile();
9302 bool hasRestrict = VisibleQuals.hasRestrict();
9303
9304 // Iterate through all strict supersets of BaseCVR.
9305 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9306 if ((CVR | BaseCVR) != CVR) continue;
9307 // Skip over volatile if no volatile found anywhere in the types.
9308 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9309
9310 // Skip over restrict if no restrict found anywhere in the types, or if
9311 // the type cannot be restrict-qualified.
9312 if ((CVR & Qualifiers::Restrict) &&
9313 (!hasRestrict ||
9314 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9315 continue;
9316
9317 // Build qualified pointee type.
9318 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9319
9320 // Build qualified pointer type.
9321 QualType QPointerTy;
9322 if (!buildObjCPtr)
9323 QPointerTy = Context.getPointerType(QPointeeTy);
9324 else
9325 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9326
9327 // Insert qualified pointer type.
9328 PointerTypes.insert(QPointerTy);
9329 }
9330
9331 return true;
9332}
9333
9334/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9335/// to the set of pointer types along with any more-qualified variants of
9336/// that type. For example, if @p Ty is "int const *", this routine
9337/// will add "int const *", "int const volatile *", "int const
9338/// restrict *", and "int const volatile restrict *" to the set of
9339/// pointer types. Returns true if the add of @p Ty itself succeeded,
9340/// false otherwise.
9341///
9342/// FIXME: what to do about extended qualifiers?
9343bool
9344BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9345 QualType Ty) {
9346 // Insert this type.
9347 if (!MemberPointerTypes.insert(Ty))
9348 return false;
9349
9350 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9351 assert(PointerTy && "type was not a member pointer type!");
9352
9353 QualType PointeeTy = PointerTy->getPointeeType();
9354 // Don't add qualified variants of arrays. For one, they're not allowed
9355 // (the qualifier would sink to the element type), and for another, the
9356 // only overload situation where it matters is subscript or pointer +- int,
9357 // and those shouldn't have qualifier variants anyway.
9358 if (PointeeTy->isArrayType())
9359 return true;
9360 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9361
9362 // Iterate through all strict supersets of the pointee type's CVR
9363 // qualifiers.
9364 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9365 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9366 if ((CVR | BaseCVR) != CVR) continue;
9367
9368 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9369 MemberPointerTypes.insert(Context.getMemberPointerType(
9370 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9371 }
9372
9373 return true;
9374}
9375
9376/// AddTypesConvertedFrom - Add each of the types to which the type @p
9377/// Ty can be implicit converted to the given set of @p Types. We're
9378/// primarily interested in pointer types and enumeration types. We also
9379/// take member pointer types, for the conditional operator.
9380/// AllowUserConversions is true if we should look at the conversion
9381/// functions of a class type, and AllowExplicitConversions if we
9382/// should also include the explicit conversion functions of a class
9383/// type.
9384void
9385BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9386 SourceLocation Loc,
9387 bool AllowUserConversions,
9388 bool AllowExplicitConversions,
9389 const Qualifiers &VisibleQuals) {
9390 // Only deal with canonical types.
9391 Ty = Context.getCanonicalType(Ty);
9392
9393 // Look through reference types; they aren't part of the type of an
9394 // expression for the purposes of conversions.
9395 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9396 Ty = RefTy->getPointeeType();
9397
9398 // If we're dealing with an array type, decay to the pointer.
9399 if (Ty->isArrayType())
9400 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9401
9402 // Otherwise, we don't care about qualifiers on the type.
9403 Ty = Ty.getLocalUnqualifiedType();
9404
9405 // Flag if we ever add a non-record type.
9406 bool TyIsRec = Ty->isRecordType();
9407 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9408
9409 // Flag if we encounter an arithmetic type.
9410 HasArithmeticOrEnumeralTypes =
9411 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9412
9413 // Flag if the type might convert to a promoted arithmetic or vector type.
9414 // For records, this is set below when visiting their conversion functions.
9415 MayConvertToArithmetic =
9416 MayConvertToArithmetic ||
9417 !(TyIsRec || Ty->isScopedEnumeralType() || Ty->isAnyPointerType() ||
9418 Ty->isMemberPointerType() || Ty->isNullPtrType());
9419
9420 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9421 PointerTypes.insert(Ty);
9422 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9423 // Insert our type, and its more-qualified variants, into the set
9424 // of types.
9425 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9426 return;
9427 } else if (Ty->isMemberPointerType()) {
9428 // Member pointers are far easier, since the pointee can't be converted.
9429 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9430 return;
9431 } else if (Ty->isEnumeralType()) {
9432 HasArithmeticOrEnumeralTypes = true;
9433 EnumerationTypes.insert(Ty);
9434 } else if (Ty->isBitIntType()) {
9435 HasArithmeticOrEnumeralTypes = true;
9436 BitIntTypes.insert(Ty);
9437 } else if (Ty->isVectorType()) {
9438 // We treat vector types as arithmetic types in many contexts as an
9439 // extension.
9440 HasArithmeticOrEnumeralTypes = true;
9441 VectorTypes.insert(Ty);
9442 } else if (Ty->isMatrixType()) {
9443 // Similar to vector types, we treat vector types as arithmetic types in
9444 // many contexts as an extension.
9445 HasArithmeticOrEnumeralTypes = true;
9446 MatrixTypes.insert(Ty);
9447 } else if (Ty->isNullPtrType()) {
9448 HasNullPtrType = true;
9449 } else if (Ty->isMetaInfoType()) {
9450 HasReflectionType = true;
9451 } else if (AllowUserConversions && TyIsRec) {
9452 // No conversion functions in incomplete types.
9453 if (!SemaRef.isCompleteType(Loc, Ty))
9454 return;
9455
9456 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9457 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9458 if (isa<UsingShadowDecl>(D))
9459 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9460
9461 // Skip conversion function templates; they don't tell us anything
9462 // about which builtin types we can convert to.
9464 MayConvertToArithmetic = true;
9465 continue;
9466 }
9467
9468 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9469 if (AllowExplicitConversions || !Conv->isExplicit()) {
9470 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9471 VisibleQuals);
9472 }
9473 }
9474 }
9475}
9476/// Helper function for adjusting address spaces for the pointer or reference
9477/// operands of builtin operators depending on the argument.
9482
9483/// Helper function for AddBuiltinOperatorCandidates() that adds
9484/// the volatile- and non-volatile-qualified assignment operators for the
9485/// given type to the candidate set.
9487 QualType T,
9488 ArrayRef<Expr *> Args,
9489 OverloadCandidateSet &CandidateSet) {
9490 QualType ParamTypes[2];
9491
9492 // T& operator=(T&, T)
9493 ParamTypes[0] = S.Context.getLValueReferenceType(
9495 ParamTypes[1] = T;
9496 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9497 /*IsAssignmentOperator=*/true);
9498
9500 // volatile T& operator=(volatile T&, T)
9501 ParamTypes[0] = S.Context.getLValueReferenceType(
9503 Args[0]));
9504 ParamTypes[1] = T;
9505 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9506 /*IsAssignmentOperator=*/true);
9507 }
9508}
9509
9510/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9511/// if any, found in visible type conversion functions found in ArgExpr's type.
9512static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9513 Qualifiers VRQuals;
9514 CXXRecordDecl *ClassDecl;
9515 if (const MemberPointerType *RHSMPType =
9516 ArgExpr->getType()->getAs<MemberPointerType>())
9517 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9518 else
9519 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9520 if (!ClassDecl) {
9521 // Just to be safe, assume the worst case.
9522 VRQuals.addVolatile();
9523 VRQuals.addRestrict();
9524 return VRQuals;
9525 }
9526 if (!ClassDecl->hasDefinition())
9527 return VRQuals;
9528
9529 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9530 if (isa<UsingShadowDecl>(D))
9531 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9532 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9533 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9534 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9535 CanTy = ResTypeRef->getPointeeType();
9536 // Need to go down the pointer/mempointer chain and add qualifiers
9537 // as see them.
9538 bool done = false;
9539 while (!done) {
9540 if (CanTy.isRestrictQualified())
9541 VRQuals.addRestrict();
9542 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9543 CanTy = ResTypePtr->getPointeeType();
9544 else if (const MemberPointerType *ResTypeMPtr =
9545 CanTy->getAs<MemberPointerType>())
9546 CanTy = ResTypeMPtr->getPointeeType();
9547 else
9548 done = true;
9549 if (CanTy.isVolatileQualified())
9550 VRQuals.addVolatile();
9551 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9552 return VRQuals;
9553 }
9554 }
9555 }
9556 return VRQuals;
9557}
9558
9559// Note: We're currently only handling qualifiers that are meaningful for the
9560// LHS of compound assignment overloading.
9562 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9563 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9564 // _Atomic
9565 if (Available.hasAtomic()) {
9566 Available.removeAtomic();
9567 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9568 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9569 return;
9570 }
9571
9572 // volatile
9573 if (Available.hasVolatile()) {
9574 Available.removeVolatile();
9575 assert(!Applied.hasVolatile());
9576 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9577 Callback);
9578 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9579 return;
9580 }
9581
9582 Callback(Applied);
9583}
9584
9586 QualifiersAndAtomic Quals,
9587 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9589 Callback);
9590}
9591
9593 QualifiersAndAtomic Quals,
9594 Sema &S) {
9595 if (Quals.hasAtomic())
9597 if (Quals.hasVolatile())
9600}
9601
9602namespace {
9603
9604/// Helper class to manage the addition of builtin operator overload
9605/// candidates. It provides shared state and utility methods used throughout
9606/// the process, as well as a helper method to add each group of builtin
9607/// operator overloads from the standard to a candidate set.
9608class BuiltinOperatorOverloadBuilder {
9609 // Common instance state available to all overload candidate addition methods.
9610 Sema &S;
9611 ArrayRef<Expr *> Args;
9612 QualifiersAndAtomic VisibleTypeConversionsQuals;
9613 // Whether a candidate whose parameters are all arithmetic, vector or matrix
9614 // types can be viable. It is viable if there is an arithmetic or enumeral
9615 // candidate type, and every argument might convert to such a type.
9616 bool ArithmeticCandidatesMayBeViable;
9617 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9618 OverloadCandidateSet &CandidateSet;
9619
9620 static constexpr int ArithmeticTypesCap = 26;
9621 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9622
9623 // Define some indices used to iterate over the arithmetic types in
9624 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9625 // types are that preserved by promotion (C++ [over.built]p2).
9626 unsigned FirstIntegralType,
9627 LastIntegralType;
9628 unsigned FirstPromotedIntegralType,
9629 LastPromotedIntegralType;
9630 unsigned FirstPromotedArithmeticType,
9631 LastPromotedArithmeticType;
9632 unsigned NumArithmeticTypes;
9633
9634 void InitArithmeticTypes() {
9635 // Start of promoted types.
9636 FirstPromotedArithmeticType = 0;
9637 ArithmeticTypes.push_back(S.Context.FloatTy);
9638 ArithmeticTypes.push_back(S.Context.DoubleTy);
9639 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9641 ArithmeticTypes.push_back(S.Context.Float128Ty);
9643 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9644
9645 // Start of integral types.
9646 FirstIntegralType = ArithmeticTypes.size();
9647 FirstPromotedIntegralType = ArithmeticTypes.size();
9648 ArithmeticTypes.push_back(S.Context.IntTy);
9649 ArithmeticTypes.push_back(S.Context.LongTy);
9650 ArithmeticTypes.push_back(S.Context.LongLongTy);
9654 ArithmeticTypes.push_back(S.Context.Int128Ty);
9655 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9656 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9657 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9661 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9662
9663 /// We add candidates for the unique, unqualified _BitInt types present in
9664 /// the candidate type set. The candidate set already handled ensuring the
9665 /// type is unqualified and canonical, but because we're adding from N
9666 /// different sets, we need to do some extra work to unique things. Insert
9667 /// the candidates into a unique set, then move from that set into the list
9668 /// of arithmetic types.
9669 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9670 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9671 for (QualType BitTy : Candidate.bitint_types())
9672 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9673 }
9674 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9675 LastPromotedIntegralType = ArithmeticTypes.size();
9676 LastPromotedArithmeticType = ArithmeticTypes.size();
9677 // End of promoted types.
9678
9679 ArithmeticTypes.push_back(S.Context.BoolTy);
9680 ArithmeticTypes.push_back(S.Context.CharTy);
9681 ArithmeticTypes.push_back(S.Context.WCharTy);
9682 if (S.Context.getLangOpts().Char8)
9683 ArithmeticTypes.push_back(S.Context.Char8Ty);
9684 ArithmeticTypes.push_back(S.Context.Char16Ty);
9685 ArithmeticTypes.push_back(S.Context.Char32Ty);
9686 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9687 ArithmeticTypes.push_back(S.Context.ShortTy);
9688 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9689 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9690 LastIntegralType = ArithmeticTypes.size();
9691 NumArithmeticTypes = ArithmeticTypes.size();
9692 // End of integral types.
9693 // FIXME: What about complex? What about half?
9694
9695 // We don't know for sure how many bit-precise candidates were involved, so
9696 // we subtract those from the total when testing whether we're under the
9697 // cap or not.
9698 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9699 ArithmeticTypesCap &&
9700 "Enough inline storage for all arithmetic types.");
9701 }
9702
9703 /// Helper method to factor out the common pattern of adding overloads
9704 /// for '++' and '--' builtin operators.
9705 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9706 bool HasVolatile,
9707 bool HasRestrict) {
9708 QualType ParamTypes[2] = {
9709 S.Context.getLValueReferenceType(CandidateTy),
9710 S.Context.IntTy
9711 };
9712
9713 // Non-volatile version.
9714 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9715
9716 // Use a heuristic to reduce number of builtin candidates in the set:
9717 // add volatile version only if there are conversions to a volatile type.
9718 if (HasVolatile) {
9719 ParamTypes[0] =
9721 S.Context.getVolatileType(CandidateTy));
9722 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9723 }
9724
9725 // Add restrict version only if there are conversions to a restrict type
9726 // and our candidate type is a non-restrict-qualified pointer.
9727 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9728 !CandidateTy.isRestrictQualified()) {
9729 ParamTypes[0]
9732 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9733
9734 if (HasVolatile) {
9735 ParamTypes[0]
9737 S.Context.getCVRQualifiedType(CandidateTy,
9740 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9741 }
9742 }
9743
9744 }
9745
9746 /// Helper to add an overload candidate for a binary builtin with types \p L
9747 /// and \p R.
9748 void AddCandidate(QualType L, QualType R) {
9749 QualType LandR[2] = {L, R};
9750 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9751 }
9752
9753public:
9754 BuiltinOperatorOverloadBuilder(
9755 Sema &S, ArrayRef<Expr *> Args,
9756 QualifiersAndAtomic VisibleTypeConversionsQuals,
9757 bool HasArithmeticOrEnumeralCandidateType,
9758 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9759 OverloadCandidateSet &CandidateSet)
9760 : S(S), Args(Args),
9761 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9762 ArithmeticCandidatesMayBeViable(
9763 HasArithmeticOrEnumeralCandidateType &&
9764 llvm::all_of(CandidateTypes,
9765 [](const BuiltinCandidateTypeSet &Types) {
9766 return Types.mayConvertToArithmetic();
9767 })),
9768 CandidateTypes(CandidateTypes), CandidateSet(CandidateSet) {
9769 InitArithmeticTypes();
9770 }
9771
9772 // Increment is deprecated for bool since C++17.
9773 //
9774 // C++ [over.built]p3:
9775 //
9776 // For every pair (T, VQ), where T is an arithmetic type other
9777 // than bool, and VQ is either volatile or empty, there exist
9778 // candidate operator functions of the form
9779 //
9780 // VQ T& operator++(VQ T&);
9781 // T operator++(VQ T&, int);
9782 //
9783 // C++ [over.built]p4:
9784 //
9785 // For every pair (T, VQ), where T is an arithmetic type other
9786 // than bool, and VQ is either volatile or empty, there exist
9787 // candidate operator functions of the form
9788 //
9789 // VQ T& operator--(VQ T&);
9790 // T operator--(VQ T&, int);
9791 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9792 if (!ArithmeticCandidatesMayBeViable)
9793 return;
9794
9795 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9796 const auto TypeOfT = ArithmeticTypes[Arith];
9797 if (TypeOfT == S.Context.BoolTy) {
9798 if (Op == OO_MinusMinus)
9799 continue;
9800 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9801 continue;
9802 }
9803 addPlusPlusMinusMinusStyleOverloads(
9804 TypeOfT,
9805 VisibleTypeConversionsQuals.hasVolatile(),
9806 VisibleTypeConversionsQuals.hasRestrict());
9807 }
9808 }
9809
9810 // C++ [over.built]p5:
9811 //
9812 // For every pair (T, VQ), where T is a cv-qualified or
9813 // cv-unqualified object type, and VQ is either volatile or
9814 // empty, there exist candidate operator functions of the form
9815 //
9816 // T*VQ& operator++(T*VQ&);
9817 // T*VQ& operator--(T*VQ&);
9818 // T* operator++(T*VQ&, int);
9819 // T* operator--(T*VQ&, int);
9820 void addPlusPlusMinusMinusPointerOverloads() {
9821 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9822 // Skip pointer types that aren't pointers to object types.
9823 if (!PtrTy->getPointeeType()->isObjectType())
9824 continue;
9825
9826 addPlusPlusMinusMinusStyleOverloads(
9827 PtrTy,
9828 (!PtrTy.isVolatileQualified() &&
9829 VisibleTypeConversionsQuals.hasVolatile()),
9830 (!PtrTy.isRestrictQualified() &&
9831 VisibleTypeConversionsQuals.hasRestrict()));
9832 }
9833 }
9834
9835 // C++ [over.built]p6:
9836 // For every cv-qualified or cv-unqualified object type T, there
9837 // exist candidate operator functions of the form
9838 //
9839 // T& operator*(T*);
9840 //
9841 // C++ [over.built]p7:
9842 // For every function type T that does not have cv-qualifiers or a
9843 // ref-qualifier, there exist candidate operator functions of the form
9844 // T& operator*(T*);
9845 void addUnaryStarPointerOverloads() {
9846 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9847 QualType PointeeTy = ParamTy->getPointeeType();
9848 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9849 continue;
9850
9851 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9852 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9853 continue;
9854
9855 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9856 }
9857 }
9858
9859 // C++ [over.built]p9:
9860 // For every promoted arithmetic type T, there exist candidate
9861 // operator functions of the form
9862 //
9863 // T operator+(T);
9864 // T operator-(T);
9865 void addUnaryPlusOrMinusArithmeticOverloads() {
9866 if (!ArithmeticCandidatesMayBeViable)
9867 return;
9868
9869 for (unsigned Arith = FirstPromotedArithmeticType;
9870 Arith < LastPromotedArithmeticType; ++Arith) {
9871 QualType ArithTy = ArithmeticTypes[Arith];
9872 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9873 }
9874
9875 // Extension: We also add these operators for vector types.
9876 for (QualType VecTy : CandidateTypes[0].vector_types())
9877 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9878 }
9879
9880 // C++ [over.built]p8:
9881 // For every type T, there exist candidate operator functions of
9882 // the form
9883 //
9884 // T* operator+(T*);
9885 void addUnaryPlusPointerOverloads() {
9886 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9887 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9888 }
9889
9890 // C++ [over.built]p10:
9891 // For every promoted integral type T, there exist candidate
9892 // operator functions of the form
9893 //
9894 // T operator~(T);
9895 void addUnaryTildePromotedIntegralOverloads() {
9896 if (!ArithmeticCandidatesMayBeViable)
9897 return;
9898
9899 for (unsigned Int = FirstPromotedIntegralType;
9900 Int < LastPromotedIntegralType; ++Int) {
9901 QualType IntTy = ArithmeticTypes[Int];
9902 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9903 }
9904
9905 // Extension: We also add this operator for vector types.
9906 for (QualType VecTy : CandidateTypes[0].vector_types())
9907 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9908 }
9909
9910 // C++ [over.match.oper]p16:
9911 // For every pointer to member type T or type std::nullptr_t, there
9912 // exist candidate operator functions of the form
9913 //
9914 // bool operator==(T,T);
9915 // bool operator!=(T,T);
9916 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9917 /// Set of (canonical) types that we've already handled.
9918 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9919
9920 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9921 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9922 // Don't add the same builtin candidate twice.
9923 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9924 continue;
9925
9926 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9927 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9928 }
9929
9930 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9932 if (AddedTypes.insert(NullPtrTy).second) {
9933 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9934 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9935 }
9936 }
9937
9938 if (CandidateTypes[ArgIdx].hasReflectionType()) {
9939 CanQualType MetaInfoTy = S.Context.MetaInfoTy;
9940 if (AddedTypes.insert(MetaInfoTy).second) {
9941 QualType ParamTypes[2] = {MetaInfoTy, MetaInfoTy};
9942 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9943 }
9944 }
9945 }
9946 }
9947
9948 // C++ [over.built]p15:
9949 //
9950 // For every T, where T is an enumeration type or a pointer type,
9951 // there exist candidate operator functions of the form
9952 //
9953 // bool operator<(T, T);
9954 // bool operator>(T, T);
9955 // bool operator<=(T, T);
9956 // bool operator>=(T, T);
9957 // bool operator==(T, T);
9958 // bool operator!=(T, T);
9959 // R operator<=>(T, T)
9960 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9961 // C++ [over.match.oper]p3:
9962 // [...]the built-in candidates include all of the candidate operator
9963 // functions defined in 13.6 that, compared to the given operator, [...]
9964 // do not have the same parameter-type-list as any non-template non-member
9965 // candidate.
9966 //
9967 // Note that in practice, this only affects enumeration types because there
9968 // aren't any built-in candidates of record type, and a user-defined operator
9969 // must have an operand of record or enumeration type. Also, the only other
9970 // overloaded operator with enumeration arguments, operator=,
9971 // cannot be overloaded for enumeration types, so this is the only place
9972 // where we must suppress candidates like this.
9973 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9974 UserDefinedBinaryOperators;
9975
9976 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9977 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9978 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9979 CEnd = CandidateSet.end();
9980 C != CEnd; ++C) {
9981 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9982 continue;
9983
9984 if (C->Function->isFunctionTemplateSpecialization())
9985 continue;
9986
9987 // We interpret "same parameter-type-list" as applying to the
9988 // "synthesized candidate, with the order of the two parameters
9989 // reversed", not to the original function.
9990 bool Reversed = C->isReversed();
9991 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9992 ->getType()
9993 .getUnqualifiedType();
9994 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9995 ->getType()
9996 .getUnqualifiedType();
9997
9998 // Skip if either parameter isn't of enumeral type.
9999 if (!FirstParamType->isEnumeralType() ||
10000 !SecondParamType->isEnumeralType())
10001 continue;
10002
10003 // Add this operator to the set of known user-defined operators.
10004 UserDefinedBinaryOperators.insert(
10005 std::make_pair(S.Context.getCanonicalType(FirstParamType),
10006 S.Context.getCanonicalType(SecondParamType)));
10007 }
10008 }
10009 }
10010
10011 /// Set of (canonical) types that we've already handled.
10012 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10013
10014 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10015 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10016 // Don't add the same builtin candidate twice.
10017 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10018 continue;
10019 if (IsSpaceship && PtrTy->isFunctionPointerType())
10020 continue;
10021
10022 QualType ParamTypes[2] = {PtrTy, PtrTy};
10023 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10024 }
10025 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10026 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
10027
10028 // Don't add the same builtin candidate twice, or if a user defined
10029 // candidate exists.
10030 if (!AddedTypes.insert(CanonType).second ||
10031 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
10032 CanonType)))
10033 continue;
10034 QualType ParamTypes[2] = {EnumTy, EnumTy};
10035 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10036 }
10037 }
10038 }
10039
10040 // C++ [over.built]p13:
10041 //
10042 // For every cv-qualified or cv-unqualified object type T
10043 // there exist candidate operator functions of the form
10044 //
10045 // T* operator+(T*, ptrdiff_t);
10046 // T& operator[](T*, ptrdiff_t); [BELOW]
10047 // T* operator-(T*, ptrdiff_t);
10048 // T* operator+(ptrdiff_t, T*);
10049 // T& operator[](ptrdiff_t, T*); [BELOW]
10050 //
10051 // C++ [over.built]p14:
10052 //
10053 // For every T, where T is a pointer to object type, there
10054 // exist candidate operator functions of the form
10055 //
10056 // ptrdiff_t operator-(T, T);
10057 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
10058 /// Set of (canonical) types that we've already handled.
10059 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10060
10061 for (int Arg = 0; Arg < 2; ++Arg) {
10062 QualType AsymmetricParamTypes[2] = {
10065 };
10066 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
10067 QualType PointeeTy = PtrTy->getPointeeType();
10068 if (!PointeeTy->isObjectType())
10069 continue;
10070
10071 AsymmetricParamTypes[Arg] = PtrTy;
10072 if (Arg == 0 || Op == OO_Plus) {
10073 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
10074 // T* operator+(ptrdiff_t, T*);
10075 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
10076 }
10077 if (Op == OO_Minus) {
10078 // ptrdiff_t operator-(T, T);
10079 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10080 continue;
10081
10082 QualType ParamTypes[2] = {PtrTy, PtrTy};
10083 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10084 }
10085 }
10086 }
10087 }
10088
10089 // C++ [over.built]p12:
10090 //
10091 // For every pair of promoted arithmetic types L and R, there
10092 // exist candidate operator functions of the form
10093 //
10094 // LR operator*(L, R);
10095 // LR operator/(L, R);
10096 // LR operator+(L, R);
10097 // LR operator-(L, R);
10098 // bool operator<(L, R);
10099 // bool operator>(L, R);
10100 // bool operator<=(L, R);
10101 // bool operator>=(L, R);
10102 // bool operator==(L, R);
10103 // bool operator!=(L, R);
10104 //
10105 // where LR is the result of the usual arithmetic conversions
10106 // between types L and R.
10107 //
10108 // C++ [over.built]p24:
10109 //
10110 // For every pair of promoted arithmetic types L and R, there exist
10111 // candidate operator functions of the form
10112 //
10113 // LR operator?(bool, L, R);
10114 //
10115 // where LR is the result of the usual arithmetic conversions
10116 // between types L and R.
10117 // Our candidates ignore the first parameter.
10118 void addGenericBinaryArithmeticOverloads() {
10119 if (!ArithmeticCandidatesMayBeViable)
10120 return;
10121
10122 for (unsigned Left = FirstPromotedArithmeticType;
10123 Left < LastPromotedArithmeticType; ++Left) {
10124 for (unsigned Right = FirstPromotedArithmeticType;
10125 Right < LastPromotedArithmeticType; ++Right) {
10126 QualType LandR[2] = { ArithmeticTypes[Left],
10127 ArithmeticTypes[Right] };
10128 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10129 }
10130 }
10131
10132 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10133 // conditional operator for vector types.
10134 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10135 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10136 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10137 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10138 }
10139 }
10140
10141 /// Add binary operator overloads for each candidate matrix type M1, M2:
10142 /// * (M1, M1) -> M1
10143 /// * (M1, M1.getElementType()) -> M1
10144 /// * (M2.getElementType(), M2) -> M2
10145 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10146 void addMatrixBinaryArithmeticOverloads() {
10147 if (!ArithmeticCandidatesMayBeViable)
10148 return;
10149
10150 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10151 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10152 AddCandidate(M1, M1);
10153 }
10154
10155 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10156 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10157 if (!CandidateTypes[0].containsMatrixType(M2))
10158 AddCandidate(M2, M2);
10159 }
10160 }
10161
10162 // C++2a [over.built]p14:
10163 //
10164 // For every integral type T there exists a candidate operator function
10165 // of the form
10166 //
10167 // std::strong_ordering operator<=>(T, T)
10168 //
10169 // C++2a [over.built]p15:
10170 //
10171 // For every pair of floating-point types L and R, there exists a candidate
10172 // operator function of the form
10173 //
10174 // std::partial_ordering operator<=>(L, R);
10175 //
10176 // FIXME: The current specification for integral types doesn't play nice with
10177 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10178 // comparisons. Under the current spec this can lead to ambiguity during
10179 // overload resolution. For example:
10180 //
10181 // enum A : int {a};
10182 // auto x = (a <=> (long)42);
10183 //
10184 // error: call is ambiguous for arguments 'A' and 'long'.
10185 // note: candidate operator<=>(int, int)
10186 // note: candidate operator<=>(long, long)
10187 //
10188 // To avoid this error, this function deviates from the specification and adds
10189 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10190 // arithmetic types (the same as the generic relational overloads).
10191 //
10192 // For now this function acts as a placeholder.
10193 void addThreeWayArithmeticOverloads() {
10194 addGenericBinaryArithmeticOverloads();
10195 }
10196
10197 // C++ [over.built]p17:
10198 //
10199 // For every pair of promoted integral types L and R, there
10200 // exist candidate operator functions of the form
10201 //
10202 // LR operator%(L, R);
10203 // LR operator&(L, R);
10204 // LR operator^(L, R);
10205 // LR operator|(L, R);
10206 // L operator<<(L, R);
10207 // L operator>>(L, R);
10208 //
10209 // where LR is the result of the usual arithmetic conversions
10210 // between types L and R.
10211 void addBinaryBitwiseArithmeticOverloads() {
10212 if (!ArithmeticCandidatesMayBeViable)
10213 return;
10214
10215 for (unsigned Left = FirstPromotedIntegralType;
10216 Left < LastPromotedIntegralType; ++Left) {
10217 for (unsigned Right = FirstPromotedIntegralType;
10218 Right < LastPromotedIntegralType; ++Right) {
10219 QualType LandR[2] = { ArithmeticTypes[Left],
10220 ArithmeticTypes[Right] };
10221 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10222 }
10223 }
10224 }
10225
10226 // C++ [over.built]p20:
10227 //
10228 // For every pair (T, VQ), where T is an enumeration or
10229 // pointer to member type and VQ is either volatile or
10230 // empty, there exist candidate operator functions of the form
10231 //
10232 // VQ T& operator=(VQ T&, T);
10233 void addAssignmentMemberPointerOrEnumeralOverloads() {
10234 /// Set of (canonical) types that we've already handled.
10235 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10236
10237 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10238 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10239 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10240 continue;
10241
10242 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10243 }
10244
10245 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10246 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10247 continue;
10248
10249 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10250 }
10251 }
10252 }
10253
10254 // C++ [over.built]p19:
10255 //
10256 // For every pair (T, VQ), where T is any type and VQ is either
10257 // volatile or empty, there exist candidate operator functions
10258 // of the form
10259 //
10260 // T*VQ& operator=(T*VQ&, T*);
10261 //
10262 // C++ [over.built]p21:
10263 //
10264 // For every pair (T, VQ), where T is a cv-qualified or
10265 // cv-unqualified object type and VQ is either volatile or
10266 // empty, there exist candidate operator functions of the form
10267 //
10268 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10269 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10270 void addAssignmentPointerOverloads(bool isEqualOp) {
10271 /// Set of (canonical) types that we've already handled.
10272 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10273
10274 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10275 // If this is operator=, keep track of the builtin candidates we added.
10276 if (isEqualOp)
10277 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10278 else if (!PtrTy->getPointeeType()->isObjectType())
10279 continue;
10280
10281 // non-volatile version
10282 QualType ParamTypes[2] = {
10284 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10285 };
10286 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10287 /*IsAssignmentOperator=*/ isEqualOp);
10288
10289 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10290 VisibleTypeConversionsQuals.hasVolatile();
10291 if (NeedVolatile) {
10292 // volatile version
10293 ParamTypes[0] =
10295 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10296 /*IsAssignmentOperator=*/isEqualOp);
10297 }
10298
10299 if (!PtrTy.isRestrictQualified() &&
10300 VisibleTypeConversionsQuals.hasRestrict()) {
10301 // restrict version
10302 ParamTypes[0] =
10304 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10305 /*IsAssignmentOperator=*/isEqualOp);
10306
10307 if (NeedVolatile) {
10308 // volatile restrict version
10309 ParamTypes[0] =
10312 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10313 /*IsAssignmentOperator=*/isEqualOp);
10314 }
10315 }
10316 }
10317
10318 if (isEqualOp) {
10319 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10320 // Make sure we don't add the same candidate twice.
10321 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10322 continue;
10323
10324 QualType ParamTypes[2] = {
10326 PtrTy,
10327 };
10328
10329 // non-volatile version
10330 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10331 /*IsAssignmentOperator=*/true);
10332
10333 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10334 VisibleTypeConversionsQuals.hasVolatile();
10335 if (NeedVolatile) {
10336 // volatile version
10337 ParamTypes[0] = S.Context.getLValueReferenceType(
10338 S.Context.getVolatileType(PtrTy));
10339 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10340 /*IsAssignmentOperator=*/true);
10341 }
10342
10343 if (!PtrTy.isRestrictQualified() &&
10344 VisibleTypeConversionsQuals.hasRestrict()) {
10345 // restrict version
10346 ParamTypes[0] = S.Context.getLValueReferenceType(
10347 S.Context.getRestrictType(PtrTy));
10348 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10349 /*IsAssignmentOperator=*/true);
10350
10351 if (NeedVolatile) {
10352 // volatile restrict version
10353 ParamTypes[0] =
10356 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10357 /*IsAssignmentOperator=*/true);
10358 }
10359 }
10360 }
10361 }
10362 }
10363
10364 // C++ [over.built]p18:
10365 //
10366 // For every triple (L, VQ, R), where L is an arithmetic type,
10367 // VQ is either volatile or empty, and R is a promoted
10368 // arithmetic type, there exist candidate operator functions of
10369 // the form
10370 //
10371 // VQ L& operator=(VQ L&, R);
10372 // VQ L& operator*=(VQ L&, R);
10373 // VQ L& operator/=(VQ L&, R);
10374 // VQ L& operator+=(VQ L&, R);
10375 // VQ L& operator-=(VQ L&, R);
10376 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10377 if (!ArithmeticCandidatesMayBeViable)
10378 return;
10379
10380 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10381 for (unsigned Right = FirstPromotedArithmeticType;
10382 Right < LastPromotedArithmeticType; ++Right) {
10383 QualType ParamTypes[2];
10384 ParamTypes[1] = ArithmeticTypes[Right];
10386 S, ArithmeticTypes[Left], Args[0]);
10387
10389 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10390 ParamTypes[0] =
10391 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10392 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10393 /*IsAssignmentOperator=*/isEqualOp);
10394 });
10395 }
10396 }
10397
10398 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10399 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10400 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10401 QualType ParamTypes[2];
10402 ParamTypes[1] = Vec2Ty;
10403 // Add this built-in operator as a candidate (VQ is empty).
10404 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10405 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10406 /*IsAssignmentOperator=*/isEqualOp);
10407
10408 // Add this built-in operator as a candidate (VQ is 'volatile').
10409 if (VisibleTypeConversionsQuals.hasVolatile()) {
10410 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10411 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10412 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10413 /*IsAssignmentOperator=*/isEqualOp);
10414 }
10415 }
10416 }
10417
10418 // C++ [over.built]p22:
10419 //
10420 // For every triple (L, VQ, R), where L is an integral type, VQ
10421 // is either volatile or empty, and R is a promoted integral
10422 // type, there exist candidate operator functions of the form
10423 //
10424 // VQ L& operator%=(VQ L&, R);
10425 // VQ L& operator<<=(VQ L&, R);
10426 // VQ L& operator>>=(VQ L&, R);
10427 // VQ L& operator&=(VQ L&, R);
10428 // VQ L& operator^=(VQ L&, R);
10429 // VQ L& operator|=(VQ L&, R);
10430 void addAssignmentIntegralOverloads() {
10431 if (!ArithmeticCandidatesMayBeViable)
10432 return;
10433
10434 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10435 for (unsigned Right = FirstPromotedIntegralType;
10436 Right < LastPromotedIntegralType; ++Right) {
10437 QualType ParamTypes[2];
10438 ParamTypes[1] = ArithmeticTypes[Right];
10440 S, ArithmeticTypes[Left], Args[0]);
10441
10443 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10444 ParamTypes[0] =
10445 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10446 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10447 });
10448 }
10449 }
10450 }
10451
10452 // C++ [over.operator]p23:
10453 //
10454 // There also exist candidate operator functions of the form
10455 //
10456 // bool operator!(bool);
10457 // bool operator&&(bool, bool);
10458 // bool operator||(bool, bool);
10459 void addExclaimOverload() {
10460 QualType ParamTy = S.Context.BoolTy;
10461 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10462 /*IsAssignmentOperator=*/false,
10463 /*NumContextualBoolArguments=*/1);
10464 }
10465 void addAmpAmpOrPipePipeOverload() {
10466 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10467 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10468 /*IsAssignmentOperator=*/false,
10469 /*NumContextualBoolArguments=*/2);
10470 }
10471
10472 // C++ [over.built]p13:
10473 //
10474 // For every cv-qualified or cv-unqualified object type T there
10475 // exist candidate operator functions of the form
10476 //
10477 // T* operator+(T*, ptrdiff_t); [ABOVE]
10478 // T& operator[](T*, ptrdiff_t);
10479 // T* operator-(T*, ptrdiff_t); [ABOVE]
10480 // T* operator+(ptrdiff_t, T*); [ABOVE]
10481 // T& operator[](ptrdiff_t, T*);
10482 void addSubscriptOverloads() {
10483 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10484 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10485 QualType PointeeType = PtrTy->getPointeeType();
10486 if (!PointeeType->isObjectType())
10487 continue;
10488
10489 // T& operator[](T*, ptrdiff_t)
10490 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10491 }
10492
10493 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10494 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10495 QualType PointeeType = PtrTy->getPointeeType();
10496 if (!PointeeType->isObjectType())
10497 continue;
10498
10499 // T& operator[](ptrdiff_t, T*)
10500 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10501 }
10502 }
10503
10504 // C++ [over.built]p11:
10505 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10506 // C1 is the same type as C2 or is a derived class of C2, T is an object
10507 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10508 // there exist candidate operator functions of the form
10509 //
10510 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10511 //
10512 // where CV12 is the union of CV1 and CV2.
10513 void addArrowStarOverloads() {
10514 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10515 QualType C1Ty = PtrTy;
10516 QualType C1;
10517 QualifierCollector Q1;
10518 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10519 if (!isa<RecordType>(C1))
10520 continue;
10521 // heuristic to reduce number of builtin candidates in the set.
10522 // Add volatile/restrict version only if there are conversions to a
10523 // volatile/restrict type.
10524 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10525 continue;
10526 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10527 continue;
10528 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10529 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10530 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10531 *D2 = mptr->getMostRecentCXXRecordDecl();
10532 if (!declaresSameEntity(D1, D2) &&
10533 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10534 break;
10535 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10536 // build CV12 T&
10537 QualType T = mptr->getPointeeType();
10538 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10539 T.isVolatileQualified())
10540 continue;
10541 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10542 T.isRestrictQualified())
10543 continue;
10544 T = Q1.apply(S.Context, T);
10545 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10546 }
10547 }
10548 }
10549
10550 // Note that we don't consider the first argument, since it has been
10551 // contextually converted to bool long ago. The candidates below are
10552 // therefore added as binary.
10553 //
10554 // C++ [over.built]p25:
10555 // For every type T, where T is a pointer, pointer-to-member, or scoped
10556 // enumeration type, there exist candidate operator functions of the form
10557 //
10558 // T operator?(bool, T, T);
10559 //
10560 void addConditionalOperatorOverloads() {
10561 /// Set of (canonical) types that we've already handled.
10562 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10563
10564 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10565 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10566 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10567 continue;
10568
10569 QualType ParamTypes[2] = {PtrTy, PtrTy};
10570 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10571 }
10572
10573 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10574 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10575 continue;
10576
10577 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10578 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10579 }
10580
10581 if (S.getLangOpts().CPlusPlus11) {
10582 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10583 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10584 continue;
10585
10586 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10587 continue;
10588
10589 QualType ParamTypes[2] = {EnumTy, EnumTy};
10590 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10591 }
10592 }
10593 }
10594 }
10595};
10596
10597} // end anonymous namespace
10598
10600 SourceLocation OpLoc,
10601 ArrayRef<Expr *> Args,
10602 OverloadCandidateSet &CandidateSet) {
10603 // Find all of the types that the arguments can convert to, but only
10604 // if the operator we're looking at has built-in operator candidates
10605 // that make use of these types. Also record whether we encounter non-record
10606 // candidate types or either arithmetic or enumeral candidate types.
10607 QualifiersAndAtomic VisibleTypeConversionsQuals;
10608 VisibleTypeConversionsQuals.addConst();
10609 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10610 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10611 if (Args[ArgIdx]->getType()->isAtomicType())
10612 VisibleTypeConversionsQuals.addAtomic();
10613 }
10614
10615 bool HasNonRecordCandidateType = false;
10616 bool HasArithmeticOrEnumeralCandidateType = false;
10618 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10619 CandidateTypes.emplace_back(*this);
10620 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10621 OpLoc,
10622 true,
10623 (Op == OO_Exclaim ||
10624 Op == OO_AmpAmp ||
10625 Op == OO_PipePipe),
10626 VisibleTypeConversionsQuals);
10627 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10628 CandidateTypes[ArgIdx].hasNonRecordTypes();
10629 HasArithmeticOrEnumeralCandidateType =
10630 HasArithmeticOrEnumeralCandidateType ||
10631 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10632 }
10633
10634 // Exit early when no non-record types have been added to the candidate set
10635 // for any of the arguments to the operator.
10636 //
10637 // We can't exit early for !, ||, or &&, since there we have always have
10638 // 'bool' overloads.
10639 if (!HasNonRecordCandidateType &&
10640 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10641 return;
10642
10643 // Setup an object to manage the common state for building overloads.
10644 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10645 VisibleTypeConversionsQuals,
10646 HasArithmeticOrEnumeralCandidateType,
10647 CandidateTypes, CandidateSet);
10648
10649 // Dispatch over the operation to add in only those overloads which apply.
10650 switch (Op) {
10651 case OO_None:
10653 llvm_unreachable("Expected an overloaded operator");
10654
10655 case OO_New:
10656 case OO_Delete:
10657 case OO_Array_New:
10658 case OO_Array_Delete:
10659 case OO_Call:
10660 llvm_unreachable(
10661 "Special operators don't use AddBuiltinOperatorCandidates");
10662
10663 case OO_Comma:
10664 case OO_Arrow:
10665 case OO_Coawait:
10666 // C++ [over.match.oper]p3:
10667 // -- For the operator ',', the unary operator '&', the
10668 // operator '->', or the operator 'co_await', the
10669 // built-in candidates set is empty.
10670 break;
10671
10672 case OO_Plus: // '+' is either unary or binary
10673 if (Args.size() == 1)
10674 OpBuilder.addUnaryPlusPointerOverloads();
10675 [[fallthrough]];
10676
10677 case OO_Minus: // '-' is either unary or binary
10678 if (Args.size() == 1) {
10679 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10680 } else {
10681 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10682 OpBuilder.addGenericBinaryArithmeticOverloads();
10683 OpBuilder.addMatrixBinaryArithmeticOverloads();
10684 }
10685 break;
10686
10687 case OO_Star: // '*' is either unary or binary
10688 if (Args.size() == 1)
10689 OpBuilder.addUnaryStarPointerOverloads();
10690 else {
10691 OpBuilder.addGenericBinaryArithmeticOverloads();
10692 OpBuilder.addMatrixBinaryArithmeticOverloads();
10693 }
10694 break;
10695
10696 case OO_Slash:
10697 OpBuilder.addGenericBinaryArithmeticOverloads();
10698 break;
10699
10700 case OO_PlusPlus:
10701 case OO_MinusMinus:
10702 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10703 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10704 break;
10705
10706 case OO_EqualEqual:
10707 case OO_ExclaimEqual:
10708 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10709 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10710 OpBuilder.addGenericBinaryArithmeticOverloads();
10711 break;
10712
10713 case OO_Less:
10714 case OO_Greater:
10715 case OO_LessEqual:
10716 case OO_GreaterEqual:
10717 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10718 OpBuilder.addGenericBinaryArithmeticOverloads();
10719 break;
10720
10721 case OO_Spaceship:
10722 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10723 OpBuilder.addThreeWayArithmeticOverloads();
10724 break;
10725
10726 case OO_Percent:
10727 case OO_Caret:
10728 case OO_Pipe:
10729 case OO_LessLess:
10730 case OO_GreaterGreater:
10731 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10732 break;
10733
10734 case OO_Amp: // '&' is either unary or binary
10735 if (Args.size() == 1)
10736 // C++ [over.match.oper]p3:
10737 // -- For the operator ',', the unary operator '&', or the
10738 // operator '->', the built-in candidates set is empty.
10739 break;
10740
10741 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10742 break;
10743
10744 case OO_Tilde:
10745 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10746 break;
10747
10748 case OO_Equal:
10749 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10750 [[fallthrough]];
10751
10752 case OO_PlusEqual:
10753 case OO_MinusEqual:
10754 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10755 [[fallthrough]];
10756
10757 case OO_StarEqual:
10758 case OO_SlashEqual:
10759 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10760 break;
10761
10762 case OO_PercentEqual:
10763 case OO_LessLessEqual:
10764 case OO_GreaterGreaterEqual:
10765 case OO_AmpEqual:
10766 case OO_CaretEqual:
10767 case OO_PipeEqual:
10768 OpBuilder.addAssignmentIntegralOverloads();
10769 break;
10770
10771 case OO_Exclaim:
10772 OpBuilder.addExclaimOverload();
10773 break;
10774
10775 case OO_AmpAmp:
10776 case OO_PipePipe:
10777 OpBuilder.addAmpAmpOrPipePipeOverload();
10778 break;
10779
10780 case OO_Subscript:
10781 if (Args.size() == 2)
10782 OpBuilder.addSubscriptOverloads();
10783 break;
10784
10785 case OO_ArrowStar:
10786 OpBuilder.addArrowStarOverloads();
10787 break;
10788
10789 case OO_Conditional:
10790 OpBuilder.addConditionalOperatorOverloads();
10791 OpBuilder.addGenericBinaryArithmeticOverloads();
10792 break;
10793 }
10794}
10795
10796void
10798 SourceLocation Loc,
10799 ArrayRef<Expr *> Args,
10800 TemplateArgumentListInfo *ExplicitTemplateArgs,
10801 OverloadCandidateSet& CandidateSet,
10802 bool PartialOverloading) {
10803 ADLResult Fns;
10804
10805 // FIXME: This approach for uniquing ADL results (and removing
10806 // redundant candidates from the set) relies on pointer-equality,
10807 // which means we need to key off the canonical decl. However,
10808 // always going back to the canonical decl might not get us the
10809 // right set of default arguments. What default arguments are
10810 // we supposed to consider on ADL candidates, anyway?
10811
10812 // FIXME: Pass in the explicit template arguments?
10813 ArgumentDependentLookup(Name, Loc, Args, Fns);
10814
10815 ArrayRef<Expr *> ReversedArgs;
10816
10817 // Erase all of the candidates we already knew about.
10818 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10819 CandEnd = CandidateSet.end();
10820 Cand != CandEnd; ++Cand)
10821 if (Cand->Function) {
10822 FunctionDecl *Fn = Cand->Function;
10823 Fns.erase(Fn);
10824 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10825 Fns.erase(FunTmpl);
10826 }
10827
10828 // For each of the ADL candidates we found, add it to the overload
10829 // set.
10830 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10832
10833 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10834 if (ExplicitTemplateArgs)
10835 continue;
10836
10838 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10839 PartialOverloading, /*AllowExplicit=*/true,
10840 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10841 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10843 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10844 /*SuppressUserConversions=*/false, PartialOverloading,
10845 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10846 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10847 }
10848 } else {
10849 auto *FTD = cast<FunctionTemplateDecl>(*I);
10851 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10852 /*SuppressUserConversions=*/false, PartialOverloading,
10853 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10854 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10855 *this, Args, FTD->getTemplatedDecl())) {
10856
10857 // As template candidates are not deduced immediately,
10858 // persist the array in the overload set.
10859 if (ReversedArgs.empty())
10860 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10861
10863 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10864 /*SuppressUserConversions=*/false, PartialOverloading,
10865 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10867 }
10868 }
10869 }
10870}
10871
10872namespace {
10873enum class Comparison { Equal, Better, Worse };
10874}
10875
10876/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10877/// overload resolution.
10878///
10879/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10880/// Cand1's first N enable_if attributes have precisely the same conditions as
10881/// Cand2's first N enable_if attributes (where N = the number of enable_if
10882/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10883///
10884/// Note that you can have a pair of candidates such that Cand1's enable_if
10885/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10886/// worse than Cand1's.
10887static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10888 const FunctionDecl *Cand2) {
10889 // Common case: One (or both) decls don't have enable_if attrs.
10890 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10891 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10892 if (!Cand1Attr || !Cand2Attr) {
10893 if (Cand1Attr == Cand2Attr)
10894 return Comparison::Equal;
10895 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10896 }
10897
10898 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10899 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10900
10901 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10902 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10903 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10904 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10905
10906 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10907 // has fewer enable_if attributes than Cand2, and vice versa.
10908 if (!Cand1A)
10909 return Comparison::Worse;
10910 if (!Cand2A)
10911 return Comparison::Better;
10912
10913 Cand1ID.clear();
10914 Cand2ID.clear();
10915
10916 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10917 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10918 if (Cand1ID != Cand2ID)
10919 return Comparison::Worse;
10920 }
10921
10922 return Comparison::Equal;
10923}
10924
10925static Comparison
10927 const OverloadCandidate &Cand2) {
10928 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10929 !Cand2.Function->isMultiVersion())
10930 return Comparison::Equal;
10931
10932 // If both are invalid, they are equal. If one of them is invalid, the other
10933 // is better.
10934 if (Cand1.Function->isInvalidDecl()) {
10935 if (Cand2.Function->isInvalidDecl())
10936 return Comparison::Equal;
10937 return Comparison::Worse;
10938 }
10939 if (Cand2.Function->isInvalidDecl())
10940 return Comparison::Better;
10941
10942 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10943 // cpu_dispatch, else arbitrarily based on the identifiers.
10944 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10945 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10946 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10947 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10948
10949 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10950 return Comparison::Equal;
10951
10952 if (Cand1CPUDisp && !Cand2CPUDisp)
10953 return Comparison::Better;
10954 if (Cand2CPUDisp && !Cand1CPUDisp)
10955 return Comparison::Worse;
10956
10957 if (Cand1CPUSpec && Cand2CPUSpec) {
10958 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10959 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10960 ? Comparison::Better
10961 : Comparison::Worse;
10962
10963 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10964 FirstDiff = std::mismatch(
10965 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10966 Cand2CPUSpec->cpus_begin(),
10967 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10968 return LHS->getName() == RHS->getName();
10969 });
10970
10971 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10972 "Two different cpu-specific versions should not have the same "
10973 "identifier list, otherwise they'd be the same decl!");
10974 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10975 ? Comparison::Better
10976 : Comparison::Worse;
10977 }
10978 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10979}
10980
10981/// Compute the type of the implicit object parameter for the given function,
10982/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10983/// null QualType if there is a 'matches anything' implicit object parameter.
10984static std::optional<QualType>
10987 return std::nullopt;
10988
10989 auto *M = cast<CXXMethodDecl>(F);
10990 // Static member functions' object parameters match all types.
10991 if (M->isStatic())
10992 return QualType();
10993 return M->getFunctionObjectParameterReferenceType();
10994}
10995
10996// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10997// represent the same entity.
10998static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10999 const FunctionDecl *F2) {
11000 if (declaresSameEntity(F1, F2))
11001 return true;
11002 auto PT1 = F1->getPrimaryTemplate();
11003 auto PT2 = F2->getPrimaryTemplate();
11004 if (PT1 && PT2) {
11005 if (declaresSameEntity(PT1, PT2) ||
11006 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
11007 PT2->getInstantiatedFromMemberTemplate()))
11008 return true;
11009 }
11010 // TODO: It is not clear whether comparing parameters is necessary (i.e.
11011 // different functions with same params). Consider removing this (as no test
11012 // fail w/o it).
11013 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
11014 if (First) {
11015 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
11016 return *T;
11017 }
11018 assert(I < F->getNumParams());
11019 return F->getParamDecl(I++)->getType();
11020 };
11021
11022 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
11023 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
11024
11025 if (F1NumParams != F2NumParams)
11026 return false;
11027
11028 unsigned I1 = 0, I2 = 0;
11029 for (unsigned I = 0; I != F1NumParams; ++I) {
11030 QualType T1 = NextParam(F1, I1, I == 0);
11031 QualType T2 = NextParam(F2, I2, I == 0);
11032 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
11033 if (!Context.hasSameUnqualifiedType(T1, T2))
11034 return false;
11035 }
11036 return true;
11037}
11038
11039/// We're allowed to use constraints partial ordering only if the candidates
11040/// have the same parameter types:
11041/// [over.match.best.general]p2.6
11042/// F1 and F2 are non-template functions with the same
11043/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
11045 FunctionDecl *Fn2,
11046 bool IsFn1Reversed,
11047 bool IsFn2Reversed) {
11048 assert(Fn1 && Fn2);
11049 if (Fn1->isVariadic() != Fn2->isVariadic())
11050 return false;
11051
11052 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
11053 IsFn1Reversed ^ IsFn2Reversed))
11054 return false;
11055
11056 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
11057 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
11058 if (Mem1 && Mem2) {
11059 // if they are member functions, both are direct members of the same class,
11060 // and
11061 if (Mem1->getParent() != Mem2->getParent())
11062 return false;
11063 // if both are non-static member functions, they have the same types for
11064 // their object parameters
11065 if (Mem1->isInstance() && Mem2->isInstance() &&
11067 Mem1->getFunctionObjectParameterReferenceType(),
11068 Mem2->getFunctionObjectParameterReferenceType()))
11069 return false;
11070 }
11071 return true;
11072}
11073
11074static FunctionDecl *
11076 bool IsFn1Reversed, bool IsFn2Reversed) {
11077 if (!Fn1 || !Fn2)
11078 return nullptr;
11079
11080 // C++ [temp.constr.order]:
11081 // A non-template function F1 is more partial-ordering-constrained than a
11082 // non-template function F2 if:
11083 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
11084 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
11085
11086 if (Cand1IsSpecialization || Cand2IsSpecialization)
11087 return nullptr;
11088
11089 // - they have the same non-object-parameter-type-lists, and [...]
11090 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
11091 IsFn2Reversed))
11092 return nullptr;
11093
11094 // - the declaration of F1 is more constrained than the declaration of F2.
11095 return S.getMoreConstrainedFunction(Fn1, Fn2);
11096}
11097
11098/// isBetterOverloadCandidate - Determines whether the first overload
11099/// candidate is a better candidate than the second (C++ 13.3.3p1).
11101 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
11103 bool PartialOverloading) {
11104 // Define viable functions to be better candidates than non-viable
11105 // functions.
11106 if (!Cand2.Viable)
11107 return Cand1.Viable;
11108 else if (!Cand1.Viable)
11109 return false;
11110
11111 // [CUDA] A function with 'never' preference is marked not viable, therefore
11112 // is never shown up here. The worst preference shown up here is 'wrong side',
11113 // e.g. an H function called by a HD function in device compilation. This is
11114 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11115 // function which is called only by an H function. A deferred diagnostic will
11116 // be triggered if it is emitted. However a wrong-sided function is still
11117 // a viable candidate here.
11118 //
11119 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11120 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11121 // can be emitted, Cand1 is not better than Cand2. This rule should have
11122 // precedence over other rules.
11123 //
11124 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11125 // other rules should be used to determine which is better. This is because
11126 // host/device based overloading resolution is mostly for determining
11127 // viability of a function. If two functions are both viable, other factors
11128 // should take precedence in preference, e.g. the standard-defined preferences
11129 // like argument conversion ranks or enable_if partial-ordering. The
11130 // preference for pass-object-size parameters is probably most similar to a
11131 // type-based-overloading decision and so should take priority.
11132 //
11133 // If other rules cannot determine which is better, CUDA preference will be
11134 // used again to determine which is better.
11135 //
11136 // TODO: Currently IdentifyPreference does not return correct values
11137 // for functions called in global variable initializers due to missing
11138 // correct context about device/host. Therefore we can only enforce this
11139 // rule when there is a caller. We should enforce this rule for functions
11140 // in global variable initializers once proper context is added.
11141 //
11142 // TODO: We can only enable the hostness based overloading resolution when
11143 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11144 // overloading resolution diagnostics.
11145 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11146 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11147 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11148 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11149 bool IsCand1ImplicitHD =
11151 bool IsCand2ImplicitHD =
11153 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11154 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11155 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11156 // The implicit HD function may be a function in a system header which
11157 // is forced by pragma. In device compilation, if we prefer HD candidates
11158 // over wrong-sided candidates, overloading resolution may change, which
11159 // may result in non-deferrable diagnostics. As a workaround, we let
11160 // implicit HD candidates take equal preference as wrong-sided candidates.
11161 // This will preserve the overloading resolution.
11162 // TODO: We still need special handling of implicit HD functions since
11163 // they may incur other diagnostics to be deferred. We should make all
11164 // host/device related diagnostics deferrable and remove special handling
11165 // of implicit HD functions.
11166 auto EmitThreshold =
11167 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11168 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11171 auto Cand1Emittable = P1 > EmitThreshold;
11172 auto Cand2Emittable = P2 > EmitThreshold;
11173 if (Cand1Emittable && !Cand2Emittable)
11174 return true;
11175 if (!Cand1Emittable && Cand2Emittable)
11176 return false;
11177 }
11178 }
11179
11180 // C++ [over.match.best]p1: (Changed in C++23)
11181 //
11182 // -- if F is a static member function, ICS1(F) is defined such
11183 // that ICS1(F) is neither better nor worse than ICS1(G) for
11184 // any function G, and, symmetrically, ICS1(G) is neither
11185 // better nor worse than ICS1(F).
11186 unsigned StartArg = 0;
11187 if (!Cand1.TookAddressOfOverload &&
11189 StartArg = 1;
11190
11191 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11192 // We don't allow incompatible pointer conversions in C++.
11193 if (!S.getLangOpts().CPlusPlus)
11194 return ICS.isStandard() &&
11195 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11196
11197 // The only ill-formed conversion we allow in C++ is the string literal to
11198 // char* conversion, which is only considered ill-formed after C++11.
11199 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11201 };
11202
11203 // Define functions that don't require ill-formed conversions for a given
11204 // argument to be better candidates than functions that do.
11205 unsigned NumArgs = Cand1.Conversions.size();
11206 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11207 bool HasBetterConversion = false;
11208 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11209 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11210 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11211 if (Cand1Bad != Cand2Bad) {
11212 if (Cand1Bad)
11213 return false;
11214 HasBetterConversion = true;
11215 }
11216 }
11217
11218 if (HasBetterConversion)
11219 return true;
11220
11221 // C++ [over.match.best]p1:
11222 // A viable function F1 is defined to be a better function than another
11223 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11224 // conversion sequence than ICSi(F2), and then...
11225 bool HasWorseConversion = false;
11226 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11228 Cand1.Conversions[ArgIdx],
11229 Cand2.Conversions[ArgIdx])) {
11231 // Cand1 has a better conversion sequence.
11232 HasBetterConversion = true;
11233 break;
11234
11236 if (Cand1.Function && Cand2.Function &&
11237 Cand1.isReversed() != Cand2.isReversed() &&
11238 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11239 // Work around large-scale breakage caused by considering reversed
11240 // forms of operator== in C++20:
11241 //
11242 // When comparing a function against a reversed function, if we have a
11243 // better conversion for one argument and a worse conversion for the
11244 // other, the implicit conversion sequences are treated as being equally
11245 // good.
11246 //
11247 // This prevents a comparison function from being considered ambiguous
11248 // with a reversed form that is written in the same way.
11249 //
11250 // We diagnose this as an extension from CreateOverloadedBinOp.
11251 HasWorseConversion = true;
11252 break;
11253 }
11254
11255 // Cand1 can't be better than Cand2.
11256 return false;
11257
11259 // Do nothing.
11260 break;
11261 }
11262 }
11263
11264 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11265 // ICSj(F2), or, if not that,
11266 if (HasBetterConversion && !HasWorseConversion)
11267 return true;
11268
11269 // -- the context is an initialization by user-defined conversion
11270 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11271 // from the return type of F1 to the destination type (i.e.,
11272 // the type of the entity being initialized) is a better
11273 // conversion sequence than the standard conversion sequence
11274 // from the return type of F2 to the destination type.
11276 Cand1.Function && Cand2.Function &&
11279
11280 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11281 // First check whether we prefer one of the conversion functions over the
11282 // other. This only distinguishes the results in non-standard, extension
11283 // cases such as the conversion from a lambda closure type to a function
11284 // pointer or block.
11289 Cand1.FinalConversion,
11290 Cand2.FinalConversion);
11291
11294
11295 // FIXME: Compare kind of reference binding if conversion functions
11296 // convert to a reference type used in direct reference binding, per
11297 // C++14 [over.match.best]p1 section 2 bullet 3.
11298 }
11299
11300 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11301 // as combined with the resolution to CWG issue 243.
11302 //
11303 // When the context is initialization by constructor ([over.match.ctor] or
11304 // either phase of [over.match.list]), a constructor is preferred over
11305 // a conversion function.
11306 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11307 Cand1.Function && Cand2.Function &&
11310 return isa<CXXConstructorDecl>(Cand1.Function);
11311
11312 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11313 return Cand2.StrictPackMatch;
11314
11315 // -- F1 is a non-template function and F2 is a function template
11316 // specialization, or, if not that,
11317 bool Cand1IsSpecialization = Cand1.Function &&
11319 bool Cand2IsSpecialization = Cand2.Function &&
11321 if (Cand1IsSpecialization != Cand2IsSpecialization)
11322 return Cand2IsSpecialization;
11323
11324 // -- F1 and F2 are function template specializations, and the function
11325 // template for F1 is more specialized than the template for F2
11326 // according to the partial ordering rules described in 14.5.5.2, or,
11327 // if not that,
11328 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11329 const auto *Obj1Context =
11330 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11331 const auto *Obj2Context =
11332 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11333 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11335 Cand2.Function->getPrimaryTemplate(), Loc,
11337 : TPOC_Call,
11339 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11340 : QualType{},
11341 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11342 : QualType{},
11343 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11344 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11345 }
11346 }
11347
11348 // -— F1 and F2 are non-template functions and F1 is more
11349 // partial-ordering-constrained than F2 [...],
11351 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11352 Cand2.isReversed());
11353 F && F == Cand1.Function)
11354 return true;
11355
11356 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11357 // class B of D, and for all arguments the corresponding parameters of
11358 // F1 and F2 have the same type.
11359 // FIXME: Implement the "all parameters have the same type" check.
11360 bool Cand1IsInherited =
11361 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11362 bool Cand2IsInherited =
11363 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11364 if (Cand1IsInherited != Cand2IsInherited)
11365 return Cand2IsInherited;
11366 else if (Cand1IsInherited) {
11367 assert(Cand2IsInherited);
11368 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11369 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11370 if (Cand1Class->isDerivedFrom(Cand2Class))
11371 return true;
11372 if (Cand2Class->isDerivedFrom(Cand1Class))
11373 return false;
11374 // Inherited from sibling base classes: still ambiguous.
11375 }
11376
11377 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11378 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11379 // with reversed order of parameters and F1 is not
11380 //
11381 // We rank reversed + different operator as worse than just reversed, but
11382 // that comparison can never happen, because we only consider reversing for
11383 // the maximally-rewritten operator (== or <=>).
11384 if (Cand1.RewriteKind != Cand2.RewriteKind)
11385 return Cand1.RewriteKind < Cand2.RewriteKind;
11386
11387 // Check C++17 tie-breakers for deduction guides.
11388 {
11389 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11390 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11391 if (Guide1 && Guide2) {
11392 // -- F1 is generated from a deduction-guide and F2 is not
11393 if (Guide1->isImplicit() != Guide2->isImplicit())
11394 return Guide2->isImplicit();
11395
11396 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11397 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11398 return true;
11399 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11400 return false;
11401
11402 // --F1 is generated from a non-template constructor and F2 is generated
11403 // from a constructor template
11404 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11405 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11406 if (Constructor1 && Constructor2) {
11407 bool isC1Templated = Constructor1->getTemplatedKind() !=
11409 bool isC2Templated = Constructor2->getTemplatedKind() !=
11411 if (isC1Templated != isC2Templated)
11412 return isC2Templated;
11413 }
11414 }
11415 }
11416
11417 // Check for enable_if value-based overload resolution.
11418 if (Cand1.Function && Cand2.Function) {
11420 if (Cmp != Comparison::Equal)
11421 return Cmp == Comparison::Better;
11422 }
11423
11424 bool HasPS1 = Cand1.Function != nullptr &&
11426 bool HasPS2 = Cand2.Function != nullptr &&
11428 if (HasPS1 != HasPS2 && HasPS1)
11429 return true;
11430
11431 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11432 if (MV == Comparison::Better)
11433 return true;
11434 if (MV == Comparison::Worse)
11435 return false;
11436
11437 // If other rules cannot determine which is better, CUDA preference is used
11438 // to determine which is better.
11439 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11440 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11441 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11442 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11443 }
11444
11445 // General member function overloading is handled above, so this only handles
11446 // constructors with address spaces.
11447 // This only handles address spaces since C++ has no other
11448 // qualifier that can be used with constructors.
11449 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11450 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11451 if (CD1 && CD2) {
11452 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11453 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11454 if (AS1 != AS2) {
11456 return true;
11458 return false;
11459 }
11460 }
11461
11462 return false;
11463}
11464
11465/// Determine whether two declarations are "equivalent" for the purposes of
11466/// name lookup and overload resolution. This applies when the same internal/no
11467/// linkage entity is defined by two modules (probably by textually including
11468/// the same header). In such a case, we don't consider the declarations to
11469/// declare the same entity, but we also don't want lookups with both
11470/// declarations visible to be ambiguous in some cases (this happens when using
11471/// a modularized libstdc++).
11473 const NamedDecl *B) {
11474 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11475 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11476 if (!VA || !VB)
11477 return false;
11478
11479 // The declarations must be declaring the same name as an internal linkage
11480 // entity in different modules.
11481 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11482 VB->getDeclContext()->getRedeclContext()) ||
11483 getOwningModule(VA) == getOwningModule(VB) ||
11484 VA->isExternallyVisible() || VB->isExternallyVisible())
11485 return false;
11486
11487 // Check that the declarations appear to be equivalent.
11488 //
11489 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11490 // For constants and functions, we should check the initializer or body is
11491 // the same. For non-constant variables, we shouldn't allow it at all.
11492 if (Context.hasSameType(VA->getType(), VB->getType()))
11493 return true;
11494
11495 // Enum constants within unnamed enumerations will have different types, but
11496 // may still be similar enough to be interchangeable for our purposes.
11497 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11498 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11499 // Only handle anonymous enums. If the enumerations were named and
11500 // equivalent, they would have been merged to the same type.
11501 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11502 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11503 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11504 !Context.hasSameType(EnumA->getIntegerType(),
11505 EnumB->getIntegerType()))
11506 return false;
11507 // Allow this only if the value is the same for both enumerators.
11508 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11509 }
11510 }
11511
11512 // Nothing else is sufficiently similar.
11513 return false;
11514}
11515
11518 assert(D && "Unknown declaration");
11519 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11520
11521 Module *M = getOwningModule(D);
11522 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11523 << !M << (M ? M->getFullModuleName() : "");
11524
11525 for (auto *E : Equiv) {
11526 Module *M = getOwningModule(E);
11527 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11528 << !M << (M ? M->getFullModuleName() : "");
11529 }
11530}
11531
11534 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11536 static_cast<CNSInfo *>(DeductionFailure.Data)
11537 ->Satisfaction.ContainsErrors;
11538}
11539
11542 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11543 bool PartialOverloading, bool AllowExplicit,
11545 bool AggregateCandidateDeduction) {
11546
11547 auto *C =
11548 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11549
11552 /*AllowObjCConversionOnExplicit=*/false,
11553 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11554 PartialOverloading, AggregateCandidateDeduction},
11556 FoundDecl,
11557 Args,
11558 IsADLCandidate,
11559 PO};
11560
11561 HasDeferredTemplateConstructors |=
11562 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11563}
11564
11566 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11567 CXXRecordDecl *ActingContext, QualType ObjectType,
11568 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11569 bool SuppressUserConversions, bool PartialOverloading,
11571
11572 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11573
11574 auto *C =
11575 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11576
11579 /*AllowObjCConversionOnExplicit=*/false,
11580 /*AllowResultConversion=*/false,
11581 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11582 /*AggregateCandidateDeduction=*/false},
11583 MethodTmpl,
11584 FoundDecl,
11585 Args,
11586 ActingContext,
11587 ObjectClassification,
11588 ObjectType,
11589 PO};
11590}
11591
11594 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11595 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11596 bool AllowResultConversion) {
11597
11598 auto *C =
11599 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11600
11603 AllowObjCConversionOnExplicit, AllowResultConversion,
11604 /*AllowExplicit=*/false,
11605 /*SuppressUserConversions=*/false,
11606 /*PartialOverloading*/ false,
11607 /*AggregateCandidateDeduction=*/false},
11609 FoundDecl,
11610 ActingContext,
11611 From,
11612 ToType};
11613}
11614
11615static void
11618
11620 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11621 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11622 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11623}
11624
11625static void
11629 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11630 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11631 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11632 C.AggregateCandidateDeduction);
11633}
11634
11635static void
11639 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11640 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11641 C.AllowResultConversion);
11642}
11643
11645 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11646 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11647 while (Cand) {
11648 switch (Cand->Kind) {
11651 S, *this,
11652 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11653 break;
11656 S, *this,
11657 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11658 break;
11661 S, *this,
11662 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11663 break;
11664 }
11665 Cand = Cand->Next;
11666 }
11667 FirstDeferredCandidate = nullptr;
11668 DeferredCandidatesCount = 0;
11669}
11670
11672OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11673 Best->Best = true;
11674 if (Best->Function && Best->Function->isDeleted())
11675 return OR_Deleted;
11676 return OR_Success;
11677}
11678
11679void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11681 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11682 // are accepted by both clang and NVCC. However, during a particular
11683 // compilation mode only one call variant is viable. We need to
11684 // exclude non-viable overload candidates from consideration based
11685 // only on their host/device attributes. Specifically, if one
11686 // candidate call is WrongSide and the other is SameSide, we ignore
11687 // the WrongSide candidate.
11688 // We only need to remove wrong-sided candidates here if
11689 // -fgpu-exclude-wrong-side-overloads is off. When
11690 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11691 // uniformly in isBetterOverloadCandidate.
11692 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11693 return;
11694 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11695
11696 bool ContainsSameSideCandidate =
11697 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11698 // Check viable function only.
11699 return Cand->Viable && Cand->Function &&
11700 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11702 });
11703
11704 if (!ContainsSameSideCandidate)
11705 return;
11706
11707 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11708 // Check viable function only to avoid unnecessary data copying/moving.
11709 return Cand->Viable && Cand->Function &&
11710 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11712 };
11713 llvm::erase_if(Candidates, IsWrongSideCandidate);
11714}
11715
11716/// Computes the best viable function (C++ 13.3.3)
11717/// within an overload candidate set.
11718///
11719/// \param Loc The location of the function name (or operator symbol) for
11720/// which overload resolution occurs.
11721///
11722/// \param Best If overload resolution was successful or found a deleted
11723/// function, \p Best points to the candidate function found.
11724///
11725/// \returns The result of overload resolution.
11727 SourceLocation Loc,
11728 iterator &Best) {
11729
11731 DeferredCandidatesCount == 0) &&
11732 "Unexpected deferred template candidates");
11733
11734 bool TwoPhaseResolution =
11735 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11736
11737 if (TwoPhaseResolution) {
11738 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11739 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11740 if (!(HasDeferredTemplateConstructors &&
11741 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11742 return Res;
11743 }
11744 }
11745
11747 return BestViableFunctionImpl(S, Loc, Best);
11748}
11749
11750OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11752
11754 Candidates.reserve(this->Candidates.size());
11755 std::transform(this->Candidates.begin(), this->Candidates.end(),
11756 std::back_inserter(Candidates),
11757 [](OverloadCandidate &Cand) { return &Cand; });
11758
11759 if (S.getLangOpts().CUDA)
11760 CudaExcludeWrongSideCandidates(S, Candidates);
11761
11762 Best = end();
11763 for (auto *Cand : Candidates) {
11764 Cand->Best = false;
11765 if (Cand->Viable) {
11766 if (Best == end() ||
11767 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11768 Best = Cand;
11769 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11770 // This candidate has constraint that we were unable to evaluate because
11771 // it referenced an expression that contained an error. Rather than fall
11772 // back onto a potentially unintended candidate (made worse by
11773 // subsuming constraints), treat this as 'no viable candidate'.
11774 Best = end();
11775 return OR_No_Viable_Function;
11776 }
11777 }
11778
11779 // If we didn't find any viable functions, abort.
11780 if (Best == end())
11781 return OR_No_Viable_Function;
11782
11783 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11784 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11785 PendingBest.push_back(&*Best);
11786 Best->Best = true;
11787
11788 // Make sure that this function is better than every other viable
11789 // function. If not, we have an ambiguity.
11790 while (!PendingBest.empty()) {
11791 auto *Curr = PendingBest.pop_back_val();
11792 for (auto *Cand : Candidates) {
11793 if (Cand->Viable && !Cand->Best &&
11794 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11795 PendingBest.push_back(Cand);
11796 Cand->Best = true;
11797
11799 Curr->Function))
11800 EquivalentCands.push_back(Cand->Function);
11801 else
11802 Best = end();
11803 }
11804 }
11805 }
11806
11807 if (Best == end())
11808 return OR_Ambiguous;
11809
11810 OverloadingResult R = ResultForBestCandidate(Best);
11811
11812 if (!EquivalentCands.empty())
11814 EquivalentCands);
11815 return R;
11816}
11817
11818namespace {
11819
11820enum OverloadCandidateKind {
11821 oc_function,
11822 oc_method,
11823 oc_reversed_binary_operator,
11824 oc_constructor,
11825 oc_implicit_default_constructor,
11826 oc_implicit_copy_constructor,
11827 oc_implicit_move_constructor,
11828 oc_implicit_copy_assignment,
11829 oc_implicit_move_assignment,
11830 oc_implicit_equality_comparison,
11831 oc_inherited_constructor
11832};
11833
11834enum OverloadCandidateSelect {
11835 ocs_non_template,
11836 ocs_template,
11837 ocs_described_template,
11838};
11839
11840static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11841ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11842 const FunctionDecl *Fn,
11844 std::string &Description) {
11845
11846 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11847 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11848 isTemplate = true;
11849 Description = S.getTemplateArgumentBindingsText(
11850 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11851 }
11852
11853 OverloadCandidateSelect Select = [&]() {
11854 if (!Description.empty())
11855 return ocs_described_template;
11856 return isTemplate ? ocs_template : ocs_non_template;
11857 }();
11858
11859 OverloadCandidateKind Kind = [&]() {
11860 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11861 return oc_implicit_equality_comparison;
11862
11863 if (CRK & CRK_Reversed)
11864 return oc_reversed_binary_operator;
11865
11866 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11867 if (!Ctor->isImplicit()) {
11869 return oc_inherited_constructor;
11870 else
11871 return oc_constructor;
11872 }
11873
11874 if (Ctor->isDefaultConstructor())
11875 return oc_implicit_default_constructor;
11876
11877 if (Ctor->isMoveConstructor())
11878 return oc_implicit_move_constructor;
11879
11880 assert(Ctor->isCopyConstructor() &&
11881 "unexpected sort of implicit constructor");
11882 return oc_implicit_copy_constructor;
11883 }
11884
11885 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11886 // This actually gets spelled 'candidate function' for now, but
11887 // it doesn't hurt to split it out.
11888 if (!Meth->isImplicit())
11889 return oc_method;
11890
11891 if (Meth->isMoveAssignmentOperator())
11892 return oc_implicit_move_assignment;
11893
11894 if (Meth->isCopyAssignmentOperator())
11895 return oc_implicit_copy_assignment;
11896
11897 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11898 return oc_method;
11899 }
11900
11901 return oc_function;
11902 }();
11903
11904 return std::make_pair(Kind, Select);
11905}
11906
11907void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11908 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11909 // set.
11910 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11911 S.Diag(FoundDecl->getLocation(),
11912 diag::note_ovl_candidate_inherited_constructor)
11913 << Shadow->getNominatedBaseClass();
11914}
11915
11916} // end anonymous namespace
11917
11919 const FunctionDecl *FD) {
11920 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11921 bool AlwaysTrue;
11922 if (EnableIf->getCond()->isValueDependent() ||
11923 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11924 return false;
11925 if (!AlwaysTrue)
11926 return false;
11927 }
11928 return true;
11929}
11930
11931/// Returns true if we can take the address of the function.
11932///
11933/// \param Complain - If true, we'll emit a diagnostic
11934/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11935/// we in overload resolution?
11936/// \param Loc - The location of the statement we're complaining about. Ignored
11937/// if we're not complaining, or if we're in overload resolution.
11939 bool Complain,
11940 bool InOverloadResolution,
11941 SourceLocation Loc) {
11942 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11943 if (Complain) {
11944 if (InOverloadResolution)
11945 S.Diag(FD->getBeginLoc(),
11946 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11947 else
11948 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11949 }
11950 return false;
11951 }
11952
11953 if (FD->getTrailingRequiresClause()) {
11954 ConstraintSatisfaction Satisfaction;
11955 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11956 return false;
11957 if (!Satisfaction.IsSatisfied) {
11958 if (Complain) {
11959 if (InOverloadResolution) {
11960 SmallString<128> TemplateArgString;
11961 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11962 TemplateArgString += " ";
11963 TemplateArgString += S.getTemplateArgumentBindingsText(
11964 FunTmpl->getTemplateParameters(),
11966 }
11967
11968 S.Diag(FD->getBeginLoc(),
11969 diag::note_ovl_candidate_unsatisfied_constraints)
11970 << TemplateArgString;
11971 } else
11972 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11973 << FD;
11974 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11975 }
11976 return false;
11977 }
11978 }
11979
11980 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11981 return P->hasAttr<PassObjectSizeAttr>();
11982 });
11983 if (I == FD->param_end())
11984 return true;
11985
11986 if (Complain) {
11987 // Add one to ParamNo because it's user-facing
11988 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11989 if (InOverloadResolution)
11990 S.Diag(FD->getLocation(),
11991 diag::note_ovl_candidate_has_pass_object_size_params)
11992 << ParamNo;
11993 else
11994 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11995 << FD << ParamNo;
11996 }
11997 return false;
11998}
11999
12001 const FunctionDecl *FD) {
12002 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
12003 /*InOverloadResolution=*/true,
12004 /*Loc=*/SourceLocation());
12005}
12006
12008 bool Complain,
12009 SourceLocation Loc) {
12010 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
12011 /*InOverloadResolution=*/false,
12012 Loc);
12013}
12014
12015// Don't print candidates other than the one that matches the calling
12016// convention of the call operator, since that is guaranteed to exist.
12018 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
12019
12020 if (!ConvD)
12021 return false;
12022 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
12023 if (!RD->isLambda())
12024 return false;
12025
12026 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
12027 CallingConv CallOpCC =
12028 CallOp->getType()->castAs<FunctionType>()->getCallConv();
12029 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
12030 CallingConv ConvToCC =
12031 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
12032
12033 return ConvToCC != CallOpCC;
12034}
12035
12036// Notes the location of an overload candidate.
12038 OverloadCandidateRewriteKind RewriteKind,
12039 QualType DestType, bool TakingAddress) {
12040 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
12041 return;
12042 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
12043 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
12044 return;
12045 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
12046 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
12047 return;
12049 return;
12050
12051 std::string FnDesc;
12052 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
12053 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
12054 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
12055 << (unsigned)KSPair.first << (unsigned)KSPair.second
12056 << Fn << FnDesc;
12057
12058 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
12059 Diag(Fn->getLocation(), PD);
12060 MaybeEmitInheritedConstructorNote(*this, Found);
12061}
12062
12063static void
12065 // Perhaps the ambiguity was caused by two atomic constraints that are
12066 // 'identical' but not equivalent:
12067 //
12068 // void foo() requires (sizeof(T) > 4) { } // #1
12069 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
12070 //
12071 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
12072 // #2 to subsume #1, but these constraint are not considered equivalent
12073 // according to the subsumption rules because they are not the same
12074 // source-level construct. This behavior is quite confusing and we should try
12075 // to help the user figure out what happened.
12076
12077 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
12078 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
12079 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12080 if (!I->Function)
12081 continue;
12083 if (auto *Template = I->Function->getPrimaryTemplate())
12084 Template->getAssociatedConstraints(AC);
12085 else
12086 I->Function->getAssociatedConstraints(AC);
12087 if (AC.empty())
12088 continue;
12089 if (FirstCand == nullptr) {
12090 FirstCand = I->Function;
12091 FirstAC = AC;
12092 } else if (SecondCand == nullptr) {
12093 SecondCand = I->Function;
12094 SecondAC = AC;
12095 } else {
12096 // We have more than one pair of constrained functions - this check is
12097 // expensive and we'd rather not try to diagnose it.
12098 return;
12099 }
12100 }
12101 if (!SecondCand)
12102 return;
12103 // The diagnostic can only happen if there are associated constraints on
12104 // both sides (there needs to be some identical atomic constraint).
12105 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
12106 SecondCand, SecondAC))
12107 // Just show the user one diagnostic, they'll probably figure it out
12108 // from here.
12109 return;
12110}
12111
12112// Notes the location of all overload candidates designated through
12113// OverloadedExpr
12114void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12115 bool TakingAddress) {
12116 assert(OverloadedExpr->getType() == Context.OverloadTy);
12117
12118 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
12119 OverloadExpr *OvlExpr = Ovl.Expression;
12120
12121 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12122 IEnd = OvlExpr->decls_end();
12123 I != IEnd; ++I) {
12124 if (FunctionTemplateDecl *FunTmpl =
12125 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
12126 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
12127 TakingAddress);
12128 } else if (FunctionDecl *Fun
12129 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
12130 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
12131 }
12132 }
12133}
12134
12135/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12136/// "lead" diagnostic; it will be given two arguments, the source and
12137/// target types of the conversion.
12139 Sema &S,
12140 SourceLocation CaretLoc,
12141 const PartialDiagnostic &PDiag) const {
12142 S.Diag(CaretLoc, PDiag)
12143 << Ambiguous.getFromType() << Ambiguous.getToType();
12144 unsigned CandsShown = 0;
12146 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12147 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12148 break;
12149 ++CandsShown;
12150 S.NoteOverloadCandidate(I->first, I->second);
12151 }
12152 S.Diags.overloadCandidatesShown(CandsShown);
12153 if (I != E)
12154 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12155}
12156
12158 unsigned I, bool TakingCandidateAddress) {
12159 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12160 assert(Conv.isBad());
12161 assert(Cand->Function && "for now, candidate must be a function");
12162 FunctionDecl *Fn = Cand->Function;
12163
12164 // There's a conversion slot for the object argument if this is a
12165 // non-constructor method. Note that 'I' corresponds the
12166 // conversion-slot index.
12167 bool isObjectArgument = false;
12168 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12170 if (I == 0)
12171 isObjectArgument = true;
12172 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12173 I--;
12174 }
12175
12176 std::string FnDesc;
12177 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12178 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12179 FnDesc);
12180
12181 Expr *FromExpr = Conv.Bad.FromExpr;
12182 QualType FromTy = Conv.Bad.getFromType();
12183 QualType ToTy = Conv.Bad.getToType();
12184 SourceRange ToParamRange;
12185
12186 // FIXME: In presence of parameter packs we can't determine parameter range
12187 // reliably, as we don't have access to instantiation.
12188 bool HasParamPack =
12189 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12190 return Parm->isParameterPack();
12191 });
12192 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12193 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12194
12195 if (FromTy == S.Context.OverloadTy) {
12196 assert(FromExpr && "overload set argument came from implicit argument?");
12197 Expr *E = FromExpr->IgnoreParens();
12198 if (isa<UnaryOperator>(E))
12199 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12200 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12201
12202 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12203 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12204 << ToParamRange << ToTy << Name << I + 1;
12205 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12206 return;
12207 }
12208
12209 // Do some hand-waving analysis to see if the non-viability is due
12210 // to a qualifier mismatch.
12211 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12212 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12213 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12214 CToTy = RT->getPointeeType();
12215 else {
12216 // TODO: detect and diagnose the full richness of const mismatches.
12217 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12218 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12219 CFromTy = FromPT->getPointeeType();
12220 CToTy = ToPT->getPointeeType();
12221 }
12222 }
12223
12224 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12225 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12226 Qualifiers FromQs = CFromTy.getQualifiers();
12227 Qualifiers ToQs = CToTy.getQualifiers();
12228
12229 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12230 if (isObjectArgument)
12231 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12232 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12233 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12234 else
12235 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12236 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12237 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12238 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12239 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12240 return;
12241 }
12242
12243 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12245 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12246 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12247 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12248 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12249 return;
12250 }
12251
12252 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12253 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12254 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12255 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12256 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12257 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12258 return;
12259 }
12260
12261 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12262 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12263 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12264 << FromTy << !!FromQs.getPointerAuth()
12265 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12266 << ToQs.getPointerAuth().getAsString() << I + 1
12267 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12268 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12269 return;
12270 }
12271
12272 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12273 assert(CVR && "expected qualifiers mismatch");
12274
12275 if (isObjectArgument) {
12276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12277 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12278 << FromTy << (CVR - 1);
12279 } else {
12280 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12281 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12282 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12283 }
12284 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12285 return;
12286 }
12287
12290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12291 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12292 << (unsigned)isObjectArgument << I + 1
12294 << ToParamRange;
12295 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12296 return;
12297 }
12298
12299 // Special diagnostic for failure to convert an initializer list, since
12300 // telling the user that it has type void is not useful.
12301 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12303 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12304 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12307 ? 2
12308 : 0);
12309 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12310 return;
12311 }
12312
12313 // Diagnose references or pointers to incomplete types differently,
12314 // since it's far from impossible that the incompleteness triggered
12315 // the failure.
12316 QualType TempFromTy = FromTy.getNonReferenceType();
12317 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12318 TempFromTy = PTy->getPointeeType();
12319 if (TempFromTy->isIncompleteType()) {
12320 // Emit the generic diagnostic and, optionally, add the hints to it.
12321 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12322 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12323 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12324 << (unsigned)(Cand->Fix.Kind);
12325
12326 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12327 return;
12328 }
12329
12330 // Diagnose base -> derived pointer conversions.
12331 unsigned BaseToDerivedConversion = 0;
12332 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12333 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12334 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12335 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12336 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12337 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12338 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12339 FromPtrTy->getPointeeType()))
12340 BaseToDerivedConversion = 1;
12341 }
12342 } else if (const ObjCObjectPointerType *FromPtrTy
12343 = FromTy->getAs<ObjCObjectPointerType>()) {
12344 if (const ObjCObjectPointerType *ToPtrTy
12345 = ToTy->getAs<ObjCObjectPointerType>())
12346 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12347 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12348 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12349 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12350 FromIface->isSuperClassOf(ToIface))
12351 BaseToDerivedConversion = 2;
12352 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12353 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12354 S.getASTContext()) &&
12355 !FromTy->isIncompleteType() &&
12356 !ToRefTy->getPointeeType()->isIncompleteType() &&
12357 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12358 BaseToDerivedConversion = 3;
12359 }
12360 }
12361
12362 if (BaseToDerivedConversion) {
12363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12364 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12365 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12366 << I + 1;
12367 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12368 return;
12369 }
12370
12371 if (isa<ObjCObjectPointerType>(CFromTy) &&
12372 isa<PointerType>(CToTy)) {
12373 Qualifiers FromQs = CFromTy.getQualifiers();
12374 Qualifiers ToQs = CToTy.getQualifiers();
12375 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12376 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12377 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12378 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12379 << I + 1;
12380 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12381 return;
12382 }
12383 }
12384
12385 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12386 return;
12387
12388 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12389 // although this is almost always an error and we advise against it.
12390 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12391 ToTy == S.Context.getLogicalOperationType()) {
12392 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12393 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12394 << Conv.Bad.FromExpr << ToTy;
12395 return;
12396 }
12397
12398 // Emit the generic diagnostic and, optionally, add the hints to it.
12399 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12400 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12401 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12402 << (unsigned)(Cand->Fix.Kind);
12403
12404 // Check that location of Fn is not in system header.
12405 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12406 // If we can fix the conversion, suggest the FixIts.
12407 for (const FixItHint &HI : Cand->Fix.Hints)
12408 FDiag << HI;
12409 }
12410
12411 S.Diag(Fn->getLocation(), FDiag);
12412
12413 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12414}
12415
12416/// Additional arity mismatch diagnosis specific to a function overload
12417/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12418/// over a candidate in any candidate set.
12420 unsigned NumArgs, bool IsAddressOf = false) {
12421 assert(Cand->Function && "Candidate is required to be a function.");
12422 FunctionDecl *Fn = Cand->Function;
12423 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12424 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12425
12426 // With invalid overloaded operators, it's possible that we think we
12427 // have an arity mismatch when in fact it looks like we have the
12428 // right number of arguments, because only overloaded operators have
12429 // the weird behavior of overloading member and non-member functions.
12430 // Just don't report anything.
12431 if (Fn->isInvalidDecl() &&
12432 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12433 return true;
12434
12435 if (NumArgs < MinParams) {
12436 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12438 Cand->DeductionFailure.getResult() ==
12440 } else {
12441 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12443 Cand->DeductionFailure.getResult() ==
12445 }
12446
12447 return false;
12448}
12449
12450/// General arity mismatch diagnosis over a candidate in a candidate set.
12452 unsigned NumFormalArgs,
12453 bool IsAddressOf = false) {
12454 assert(isa<FunctionDecl>(D) &&
12455 "The templated declaration should at least be a function"
12456 " when diagnosing bad template argument deduction due to too many"
12457 " or too few arguments");
12458
12460
12461 // TODO: treat calls to a missing default constructor as a special case
12462 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12463 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12464 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12465
12466 // at least / at most / exactly
12467 bool HasExplicitObjectParam =
12468 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12469
12470 unsigned ParamCount =
12471 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12472 unsigned mode, modeCount;
12473
12474 if (NumFormalArgs < MinParams) {
12475 if (MinParams != ParamCount || FnTy->isVariadic() ||
12476 FnTy->isTemplateVariadic())
12477 mode = 0; // "at least"
12478 else
12479 mode = 2; // "exactly"
12480 modeCount = MinParams;
12481 } else {
12482 if (MinParams != ParamCount)
12483 mode = 1; // "at most"
12484 else
12485 mode = 2; // "exactly"
12486 modeCount = ParamCount;
12487 }
12488
12489 std::string Description;
12490 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12491 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12492
12493 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12494 if (modeCount == 1 && !IsAddressOf &&
12495 FirstNonObjectParamIdx < Fn->getNumParams() &&
12496 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12497 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12498 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12499 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12500 << NumFormalArgs << HasExplicitObjectParam
12501 << Fn->getParametersSourceRange();
12502 else
12503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12504 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12505 << Description << mode << modeCount << NumFormalArgs
12506 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12507
12508 MaybeEmitInheritedConstructorNote(S, Found);
12509}
12510
12511/// Arity mismatch diagnosis specific to a function overload candidate.
12513 unsigned NumFormalArgs) {
12514 assert(Cand->Function && "Candidate must be a function");
12515 FunctionDecl *Fn = Cand->Function;
12516 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12517 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12518 Cand->TookAddressOfOverload);
12519}
12520
12522 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12523 return TD;
12524 llvm_unreachable("Unsupported: Getting the described template declaration"
12525 " for bad deduction diagnosis");
12526}
12527
12528/// Diagnose a failed template-argument deduction.
12529static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12530 DeductionFailureInfo &DeductionFailure,
12531 unsigned NumArgs, bool TakingCandidateAddress,
12532 TemplateSpecCandidateSetKind CandidateSetKind =
12534 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12535 NamedDecl *ParamD = dyn_cast_if_present<TemplateTypeParmDecl *>(Param);
12536 if (!ParamD)
12537 ParamD = dyn_cast_if_present<NonTypeTemplateParmDecl *>(Param);
12538 if (!ParamD)
12539 ParamD = dyn_cast_if_present<TemplateTemplateParmDecl *>(Param);
12540 switch (DeductionFailure.getResult()) {
12542 llvm_unreachable(
12543 "TemplateDeductionResult::Success while diagnosing bad deduction");
12545 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12546 "while diagnosing bad deduction");
12549 return;
12550
12552 assert(ParamD && "no parameter found for incomplete deduction result");
12553 S.Diag(Templated->getLocation(),
12554 diag::note_ovl_candidate_incomplete_deduction)
12555 << ParamD->getDeclName();
12556 MaybeEmitInheritedConstructorNote(S, Found);
12557 return;
12558 }
12559
12561 assert(ParamD && "no parameter found for incomplete deduction result");
12562 S.Diag(Templated->getLocation(),
12563 diag::note_ovl_candidate_incomplete_deduction_pack)
12564 << ParamD->getDeclName()
12565 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12566 << *DeductionFailure.getFirstArg();
12567 MaybeEmitInheritedConstructorNote(S, Found);
12568 return;
12569 }
12570
12572 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12574
12575 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12576
12577 // Param will have been canonicalized, but it should just be a
12578 // qualified version of ParamD, so move the qualifiers to that.
12580 Qs.strip(Param);
12581 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12582 assert(S.Context.hasSameType(Param, NonCanonParam));
12583
12584 // Arg has also been canonicalized, but there's nothing we can do
12585 // about that. It also doesn't matter as much, because it won't
12586 // have any template parameters in it (because deduction isn't
12587 // done on dependent types).
12588 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12589
12590 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12591 << ParamD->getDeclName() << Arg << NonCanonParam;
12592 MaybeEmitInheritedConstructorNote(S, Found);
12593 return;
12594 }
12595
12597 assert(ParamD && "no parameter found for inconsistent deduction result");
12598 int which = 0;
12599 if (isa<TemplateTypeParmDecl>(ParamD))
12600 which = 0;
12601 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12602 // Deduction might have failed because we deduced arguments of two
12603 // different types for a non-type template parameter.
12604 // FIXME: Use a different TDK value for this.
12605 QualType T1 =
12606 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12607 QualType T2 =
12608 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12609 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12610 S.Diag(Templated->getLocation(),
12611 diag::note_ovl_candidate_inconsistent_deduction_types)
12612 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12613 << *DeductionFailure.getSecondArg() << T2;
12614 MaybeEmitInheritedConstructorNote(S, Found);
12615 return;
12616 }
12617
12618 which = 1;
12619 } else {
12620 which = 2;
12621 }
12622
12623 // Tweak the diagnostic if the problem is that we deduced packs of
12624 // different arities. We'll print the actual packs anyway in case that
12625 // includes additional useful information.
12626 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12627 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12628 DeductionFailure.getFirstArg()->pack_size() !=
12629 DeductionFailure.getSecondArg()->pack_size()) {
12630 which = 3;
12631 }
12632
12633 S.Diag(Templated->getLocation(),
12634 diag::note_ovl_candidate_inconsistent_deduction)
12635 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12636 << *DeductionFailure.getSecondArg();
12637 MaybeEmitInheritedConstructorNote(S, Found);
12638 return;
12639 }
12640
12642 assert(ParamD && "no parameter found for invalid explicit arguments");
12643
12644 auto Diag = S.Diag(Templated->getLocation(),
12645 diag::note_ovl_candidate_explicit_arg_mismatch);
12646 if (ParamD->getDeclName())
12647 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12648 else
12649 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12650 << (getDepthAndIndex(ParamD).second + 1);
12651 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12652 SmallString<128> DiagContent;
12653 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12654 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12655 } else {
12656 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12657 }
12658
12659 MaybeEmitInheritedConstructorNote(S, Found);
12660 return;
12661 }
12663 // Format the template argument list into the argument string.
12664 SmallString<128> TemplateArgString;
12665 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12666 TemplateArgString = " ";
12667 TemplateArgString += S.getTemplateArgumentBindingsText(
12668 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12669 if (TemplateArgString.size() == 1)
12670 TemplateArgString.clear();
12671 S.Diag(Templated->getLocation(),
12672 diag::note_ovl_candidate_unsatisfied_constraints)
12673 << TemplateArgString;
12674
12676 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12677 return;
12678 }
12681 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12682 return;
12683
12685 S.Diag(Templated->getLocation(),
12686 diag::note_ovl_candidate_instantiation_depth);
12687 MaybeEmitInheritedConstructorNote(S, Found);
12688 return;
12689
12691 // Format the template argument list into the argument string.
12692 SmallString<128> TemplateArgString;
12693 if (TemplateArgumentList *Args =
12694 DeductionFailure.getTemplateArgumentList()) {
12695 TemplateArgString = " ";
12696 TemplateArgString += S.getTemplateArgumentBindingsText(
12697 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12698 if (TemplateArgString.size() == 1)
12699 TemplateArgString.clear();
12700 }
12701
12702 // If this candidate was disabled by enable_if, say so.
12703 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12704 if (PDiag && PDiag->second.getDiagID() ==
12705 diag::err_typename_nested_not_found_enable_if) {
12706 // FIXME: Use the source range of the condition, and the fully-qualified
12707 // name of the enable_if template. These are both present in PDiag.
12708 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12709 << "'enable_if'" << TemplateArgString;
12710 return;
12711 }
12712
12713 // We found a specific requirement that disabled the enable_if.
12714 if (PDiag && PDiag->second.getDiagID() ==
12715 diag::err_typename_nested_not_found_requirement) {
12716 S.Diag(Templated->getLocation(),
12717 diag::note_ovl_candidate_disabled_by_requirement)
12718 << PDiag->second.getStringArg(0) << TemplateArgString;
12719 return;
12720 }
12721
12722 // Format the SFINAE diagnostic into the argument string.
12723 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12724 // formatted message in another diagnostic.
12725 SmallString<128> SFINAEArgString;
12726 SourceRange R;
12727 if (PDiag) {
12728 SFINAEArgString = ": ";
12729 R = SourceRange(PDiag->first, PDiag->first);
12730 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12731 }
12732
12733 S.Diag(Templated->getLocation(),
12734 diag::note_ovl_candidate_substitution_failure)
12735 << TemplateArgString << SFINAEArgString << R;
12736 MaybeEmitInheritedConstructorNote(S, Found);
12737 return;
12738 }
12739
12742 // Format the template argument list into the argument string.
12743 SmallString<128> TemplateArgString;
12744 if (TemplateArgumentList *Args =
12745 DeductionFailure.getTemplateArgumentList()) {
12746 TemplateArgString = " ";
12747 TemplateArgString += S.getTemplateArgumentBindingsText(
12748 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12749 if (TemplateArgString.size() == 1)
12750 TemplateArgString.clear();
12751 }
12752
12753 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12754 << (*DeductionFailure.getCallArgIndex() + 1)
12755 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12756 << TemplateArgString
12757 << (DeductionFailure.getResult() ==
12759 break;
12760 }
12761
12763 // FIXME: Provide a source location to indicate what we couldn't match.
12764 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12765 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12766 if (FirstTA.getKind() == TemplateArgument::Template &&
12767 SecondTA.getKind() == TemplateArgument::Template) {
12768 TemplateName FirstTN = FirstTA.getAsTemplate();
12769 TemplateName SecondTN = SecondTA.getAsTemplate();
12770 if (FirstTN.getKind() == TemplateName::Template &&
12771 SecondTN.getKind() == TemplateName::Template) {
12772 if (FirstTN.getAsTemplateDecl()->getName() ==
12773 SecondTN.getAsTemplateDecl()->getName()) {
12774 // FIXME: This fixes a bad diagnostic where both templates are named
12775 // the same. This particular case is a bit difficult since:
12776 // 1) It is passed as a string to the diagnostic printer.
12777 // 2) The diagnostic printer only attempts to find a better
12778 // name for types, not decls.
12779 // Ideally, this should folded into the diagnostic printer.
12780 S.Diag(Templated->getLocation(),
12781 CandidateSetKind ==
12783 ? diag::note_friend_template_non_deduced_mismatch_qualified
12784 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12785 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12786 return;
12787 }
12788 }
12789 }
12790
12791 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12793 return;
12794
12795 // FIXME: For generic lambda parameters, check if the function is a lambda
12796 // call operator, and if so, emit a prettier and more informative
12797 // diagnostic that mentions 'auto' and lambda in addition to
12798 // (or instead of?) the canonical template type parameters.
12799 S.Diag(Templated->getLocation(),
12801 ? diag::note_friend_template_non_deduced_mismatch
12802 : diag::note_ovl_candidate_non_deduced_mismatch)
12803 << FirstTA << SecondTA;
12804 return;
12805 }
12806 // TODO: diagnose these individually, then kill off
12807 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12809 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12810 MaybeEmitInheritedConstructorNote(S, Found);
12811 return;
12813 S.Diag(Templated->getLocation(),
12814 diag::note_cuda_ovl_candidate_target_mismatch);
12815 return;
12816 }
12817}
12818
12819/// Diagnose a failed template-argument deduction, for function calls.
12821 unsigned NumArgs,
12822 bool TakingCandidateAddress) {
12823 assert(Cand->Function && "Candidate must be a function");
12824 FunctionDecl *Fn = Cand->Function;
12828 if (CheckArityMismatch(S, Cand, NumArgs))
12829 return;
12830 }
12831 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12832 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12833}
12834
12835/// CUDA: diagnose an invalid call across targets.
12837 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12838 assert(Cand->Function && "Candidate must be a Function.");
12839 FunctionDecl *Callee = Cand->Function;
12840
12841 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12842 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12843
12844 std::string FnDesc;
12845 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12846 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12847 Cand->getRewriteKind(), FnDesc);
12848
12849 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12850 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12851 << FnDesc /* Ignored */
12852 << CalleeTarget << CallerTarget;
12853
12854 // This could be an implicit constructor for which we could not infer the
12855 // target due to a collsion. Diagnose that case.
12856 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12857 if (Meth != nullptr && Meth->isImplicit()) {
12858 CXXRecordDecl *ParentClass = Meth->getParent();
12860
12861 switch (FnKindPair.first) {
12862 default:
12863 return;
12864 case oc_implicit_default_constructor:
12866 break;
12867 case oc_implicit_copy_constructor:
12869 break;
12870 case oc_implicit_move_constructor:
12872 break;
12873 case oc_implicit_copy_assignment:
12875 break;
12876 case oc_implicit_move_assignment:
12878 break;
12879 };
12880
12881 bool ConstRHS = false;
12882 if (Meth->getNumParams()) {
12883 if (const ReferenceType *RT =
12884 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12885 ConstRHS = RT->getPointeeType().isConstQualified();
12886 }
12887 }
12888
12889 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12890 /* ConstRHS */ ConstRHS,
12891 /* Diagnose */ true);
12892 }
12893}
12894
12896 assert(Cand->Function && "Candidate must be a function");
12897 FunctionDecl *Callee = Cand->Function;
12898 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12899
12900 S.Diag(Callee->getLocation(),
12901 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12902 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12903}
12904
12906 assert(Cand->Function && "Candidate must be a function");
12907 FunctionDecl *Fn = Cand->Function;
12909 assert(ES.isExplicit() && "not an explicit candidate");
12910
12911 unsigned Kind;
12912 switch (Fn->getDeclKind()) {
12913 case Decl::Kind::CXXConstructor:
12914 Kind = 0;
12915 break;
12916 case Decl::Kind::CXXConversion:
12917 Kind = 1;
12918 break;
12919 case Decl::Kind::CXXDeductionGuide:
12920 Kind = Fn->isImplicit() ? 0 : 2;
12921 break;
12922 default:
12923 llvm_unreachable("invalid Decl");
12924 }
12925
12926 // Note the location of the first (in-class) declaration; a redeclaration
12927 // (particularly an out-of-class definition) will typically lack the
12928 // 'explicit' specifier.
12929 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12930 FunctionDecl *First = Fn->getFirstDecl();
12931 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12932 First = Pattern->getFirstDecl();
12933
12934 S.Diag(First->getLocation(),
12935 diag::note_ovl_candidate_explicit)
12936 << Kind << (ES.getExpr() ? 1 : 0)
12937 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12938}
12939
12941 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12942 if (!DG)
12943 return;
12944 TemplateDecl *OriginTemplate =
12946 // We want to always print synthesized deduction guides for type aliases.
12947 // They would retain the explicit bit of the corresponding constructor.
12948 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12949 return;
12950 std::string FunctionProto;
12951 llvm::raw_string_ostream OS(FunctionProto);
12952 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12953 if (!Template) {
12954 // This also could be an instantiation. Find out the primary template.
12955 FunctionDecl *Pattern =
12956 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12957 if (!Pattern) {
12958 // The implicit deduction guide is built on an explicit non-template
12959 // deduction guide. Currently, this might be the case only for type
12960 // aliases.
12961 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12962 // gets merged.
12963 assert(OriginTemplate->isTypeAlias() &&
12964 "Non-template implicit deduction guides are only possible for "
12965 "type aliases");
12966 DG->print(OS);
12967 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12968 << FunctionProto;
12969 return;
12970 }
12972 assert(Template && "Cannot find the associated function template of "
12973 "CXXDeductionGuideDecl?");
12974 }
12975 Template->print(OS);
12976 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12977 << FunctionProto;
12978}
12979
12980/// Generates a 'note' diagnostic for an overload candidate. We've
12981/// already generated a primary error at the call site.
12982///
12983/// It really does need to be a single diagnostic with its caret
12984/// pointed at the candidate declaration. Yes, this creates some
12985/// major challenges of technical writing. Yes, this makes pointing
12986/// out problems with specific arguments quite awkward. It's still
12987/// better than generating twenty screens of text for every failed
12988/// overload.
12989///
12990/// It would be great to be able to express per-candidate problems
12991/// more richly for those diagnostic clients that cared, but we'd
12992/// still have to be just as careful with the default diagnostics.
12993/// \param CtorDestAS Addr space of object being constructed (for ctor
12994/// candidates only).
12996 unsigned NumArgs,
12997 bool TakingCandidateAddress,
12998 LangAS CtorDestAS = LangAS::Default) {
12999 assert(Cand->Function && "Candidate must be a function");
13000 FunctionDecl *Fn = Cand->Function;
13002 return;
13003
13004 // There is no physical candidate declaration to point to for OpenCL builtins.
13005 // Except for failed conversions, the notes are identical for each candidate,
13006 // so do not generate such notes.
13007 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
13009 return;
13010
13011 // Skip implicit member functions when trying to resolve
13012 // the address of a an overload set for a function pointer.
13013 if (Cand->TookAddressOfOverload &&
13014 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
13015 return;
13016
13017 // Note deleted candidates, but only if they're viable.
13018 if (Cand->Viable) {
13019 if (Fn->isDeleted()) {
13020 std::string FnDesc;
13021 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13022 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13023 Cand->getRewriteKind(), FnDesc);
13024
13025 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
13026 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
13027 << (Fn->isDeleted()
13028 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
13029 : 0);
13030 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13031 return;
13032 }
13033
13034 // We don't really have anything else to say about viable candidates.
13035 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13036 return;
13037 }
13038
13039 // If this is a synthesized deduction guide we're deducing against, add a note
13040 // for it. These deduction guides are not explicitly spelled in the source
13041 // code, so simply printing a deduction failure note mentioning synthesized
13042 // template parameters or pointing to the header of the surrounding RecordDecl
13043 // would be confusing.
13044 //
13045 // We prefer adding such notes at the end of the deduction failure because
13046 // duplicate code snippets appearing in the diagnostic would likely become
13047 // noisy.
13048 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
13049
13050 switch (Cand->FailureKind) {
13053 return DiagnoseArityMismatch(S, Cand, NumArgs);
13054
13056 return DiagnoseBadDeduction(S, Cand, NumArgs,
13057 TakingCandidateAddress);
13058
13060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
13061 << (Fn->getPrimaryTemplate() ? 1 : 0);
13062 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13063 return;
13064 }
13065
13067 Qualifiers QualsForPrinting;
13068 QualsForPrinting.setAddressSpace(CtorDestAS);
13069 S.Diag(Fn->getLocation(),
13070 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
13071 << QualsForPrinting;
13072 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13073 return;
13074 }
13075
13079 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13080
13082 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
13083 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
13084 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
13085 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
13086
13087 // FIXME: this currently happens when we're called from SemaInit
13088 // when user-conversion overload fails. Figure out how to handle
13089 // those conditions and diagnose them well.
13090 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13091 }
13092
13094 return DiagnoseBadTarget(S, Cand);
13095
13096 case ovl_fail_enable_if:
13097 return DiagnoseFailedEnableIfAttr(S, Cand);
13098
13099 case ovl_fail_explicit:
13100 return DiagnoseFailedExplicitSpec(S, Cand);
13101
13103 // It's generally not interesting to note copy/move constructors here.
13104 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
13105 return;
13106 S.Diag(Fn->getLocation(),
13107 diag::note_ovl_candidate_inherited_constructor_slice)
13108 << (Fn->getPrimaryTemplate() ? 1 : 0)
13109 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
13110 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13111 return;
13112
13114 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
13115 (void)Available;
13116 assert(!Available);
13117 break;
13118 }
13120 // Do nothing, these should simply be ignored.
13121 break;
13122
13124 std::string FnDesc;
13125 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13126 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13127 Cand->getRewriteKind(), FnDesc);
13128
13129 S.Diag(Fn->getLocation(),
13130 diag::note_ovl_candidate_constraints_not_satisfied)
13131 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13132 << FnDesc /* Ignored */;
13133 ConstraintSatisfaction Satisfaction;
13134 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
13135 /*ForOverloadResolution=*/true))
13136 break;
13137 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13138 }
13139 }
13140}
13141
13144 return;
13145
13146 // Desugar the type of the surrogate down to a function type,
13147 // retaining as many typedefs as possible while still showing
13148 // the function type (and, therefore, its parameter types).
13149 QualType FnType = Cand->Surrogate->getConversionType();
13150 bool isLValueReference = false;
13151 bool isRValueReference = false;
13152 bool isPointer = false;
13153 if (const LValueReferenceType *FnTypeRef =
13154 FnType->getAs<LValueReferenceType>()) {
13155 FnType = FnTypeRef->getPointeeType();
13156 isLValueReference = true;
13157 } else if (const RValueReferenceType *FnTypeRef =
13158 FnType->getAs<RValueReferenceType>()) {
13159 FnType = FnTypeRef->getPointeeType();
13160 isRValueReference = true;
13161 }
13162 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13163 FnType = FnTypePtr->getPointeeType();
13164 isPointer = true;
13165 }
13166 // Desugar down to a function type.
13167 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13168 // Reconstruct the pointer/reference as appropriate.
13169 if (isPointer) FnType = S.Context.getPointerType(FnType);
13170 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13171 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13172
13173 if (!Cand->Viable &&
13175 S.Diag(Cand->Surrogate->getLocation(),
13176 diag::note_ovl_surrogate_constraints_not_satisfied)
13177 << Cand->Surrogate;
13178 ConstraintSatisfaction Satisfaction;
13179 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13180 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13181 } else {
13182 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13183 << FnType;
13184 }
13185}
13186
13187static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13188 SourceLocation OpLoc,
13189 OverloadCandidate *Cand) {
13190 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13191 std::string TypeStr("operator");
13192 TypeStr += Opc;
13193 TypeStr += "(";
13194 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13195 if (Cand->Conversions.size() == 1) {
13196 TypeStr += ")";
13197 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13198 } else {
13199 TypeStr += ", ";
13200 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13201 TypeStr += ")";
13202 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13203 }
13204}
13205
13207 OverloadCandidate *Cand) {
13208 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13209 if (ICS.isBad()) break; // all meaningless after first invalid
13210 if (!ICS.isAmbiguous()) continue;
13211
13213 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13214 }
13215}
13216
13218 if (Cand->Function)
13219 return Cand->Function->getLocation();
13220 if (Cand->IsSurrogate)
13221 return Cand->Surrogate->getLocation();
13222 return SourceLocation();
13223}
13224
13225static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13226 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13230 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13231
13235 return 1;
13236
13239 return 2;
13240
13248 return 3;
13249
13251 return 4;
13252
13254 return 5;
13255
13258 return 6;
13259 }
13260 llvm_unreachable("Unhandled deduction result");
13261}
13262
13263namespace {
13264
13265struct CompareOverloadCandidatesForDisplay {
13266 Sema &S;
13267 SourceLocation Loc;
13268 size_t NumArgs;
13270
13271 CompareOverloadCandidatesForDisplay(
13272 Sema &S, SourceLocation Loc, size_t NArgs,
13274 : S(S), NumArgs(NArgs), CSK(CSK) {}
13275
13276 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13277 // If there are too many or too few arguments, that's the high-order bit we
13278 // want to sort by, even if the immediate failure kind was something else.
13279 if (C->FailureKind == ovl_fail_too_many_arguments ||
13280 C->FailureKind == ovl_fail_too_few_arguments)
13281 return static_cast<OverloadFailureKind>(C->FailureKind);
13282
13283 if (C->Function) {
13284 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13286 if (NumArgs < C->Function->getMinRequiredArguments())
13288 }
13289
13290 return static_cast<OverloadFailureKind>(C->FailureKind);
13291 }
13292
13293 bool operator()(const OverloadCandidate *L,
13294 const OverloadCandidate *R) {
13295 // Fast-path this check.
13296 if (L == R) return false;
13297
13298 // Order first by viability.
13299 if (L->Viable) {
13300 if (!R->Viable) return true;
13301
13302 if (int Ord = CompareConversions(*L, *R))
13303 return Ord < 0;
13304 // Use other tie breakers.
13305 } else if (R->Viable)
13306 return false;
13307
13308 assert(L->Viable == R->Viable);
13309
13310 // Criteria by which we can sort non-viable candidates:
13311 if (!L->Viable) {
13312 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13313 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13314
13315 // 1. Arity mismatches come after other candidates.
13316 if (LFailureKind == ovl_fail_too_many_arguments ||
13317 LFailureKind == ovl_fail_too_few_arguments) {
13318 if (RFailureKind == ovl_fail_too_many_arguments ||
13319 RFailureKind == ovl_fail_too_few_arguments) {
13320 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13321 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13322 if (LDist == RDist) {
13323 if (LFailureKind == RFailureKind)
13324 // Sort non-surrogates before surrogates.
13325 return !L->IsSurrogate && R->IsSurrogate;
13326 // Sort candidates requiring fewer parameters than there were
13327 // arguments given after candidates requiring more parameters
13328 // than there were arguments given.
13329 return LFailureKind == ovl_fail_too_many_arguments;
13330 }
13331 return LDist < RDist;
13332 }
13333 return false;
13334 }
13335 if (RFailureKind == ovl_fail_too_many_arguments ||
13336 RFailureKind == ovl_fail_too_few_arguments)
13337 return true;
13338
13339 // 2. Bad conversions come first and are ordered by the number
13340 // of bad conversions and quality of good conversions.
13341 if (LFailureKind == ovl_fail_bad_conversion) {
13342 if (RFailureKind != ovl_fail_bad_conversion)
13343 return true;
13344
13345 // The conversion that can be fixed with a smaller number of changes,
13346 // comes first.
13347 unsigned numLFixes = L->Fix.NumConversionsFixed;
13348 unsigned numRFixes = R->Fix.NumConversionsFixed;
13349 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13350 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13351 if (numLFixes != numRFixes) {
13352 return numLFixes < numRFixes;
13353 }
13354
13355 // If there's any ordering between the defined conversions...
13356 if (int Ord = CompareConversions(*L, *R))
13357 return Ord < 0;
13358 } else if (RFailureKind == ovl_fail_bad_conversion)
13359 return false;
13360
13361 if (LFailureKind == ovl_fail_bad_deduction) {
13362 if (RFailureKind != ovl_fail_bad_deduction)
13363 return true;
13364
13365 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13366 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13367 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13368 if (LRank != RRank)
13369 return LRank < RRank;
13370 }
13371 } else if (RFailureKind == ovl_fail_bad_deduction)
13372 return false;
13373
13374 // TODO: others?
13375 }
13376
13377 // Sort everything else by location.
13378 SourceLocation LLoc = GetLocationForCandidate(L);
13379 SourceLocation RLoc = GetLocationForCandidate(R);
13380
13381 // Put candidates without locations (e.g. builtins) at the end.
13382 if (LLoc.isValid() && RLoc.isValid())
13383 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13384 if (LLoc.isValid() && !RLoc.isValid())
13385 return true;
13386 if (RLoc.isValid() && !LLoc.isValid())
13387 return false;
13388 assert(!LLoc.isValid() && !RLoc.isValid());
13389 // For builtins and other functions without locations, fallback to the order
13390 // in which they were added into the candidate set.
13391 return L < R;
13392 }
13393
13394private:
13395 struct ConversionSignals {
13396 unsigned KindRank = 0;
13398
13399 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13400 ConversionSignals Sig;
13401 Sig.KindRank = Seq.getKindRank();
13402 if (Seq.isStandard())
13403 Sig.Rank = Seq.Standard.getRank();
13404 else if (Seq.isUserDefined())
13405 Sig.Rank = Seq.UserDefined.After.getRank();
13406 // We intend StaticObjectArgumentConversion to compare the same as
13407 // StandardConversion with ICR_ExactMatch rank.
13408 return Sig;
13409 }
13410
13411 static ConversionSignals ForObjectArgument() {
13412 // We intend StaticObjectArgumentConversion to compare the same as
13413 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13414 return {};
13415 }
13416 };
13417
13418 // Returns -1 if conversions in L are considered better.
13419 // 0 if they are considered indistinguishable.
13420 // 1 if conversions in R are better.
13421 int CompareConversions(const OverloadCandidate &L,
13422 const OverloadCandidate &R) {
13423 // We cannot use `isBetterOverloadCandidate` because it is defined
13424 // according to the C++ standard and provides a partial order, but we need
13425 // a total order as this function is used in sort.
13426 assert(L.Conversions.size() == R.Conversions.size());
13427 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13428 auto LS = L.IgnoreObjectArgument && I == 0
13429 ? ConversionSignals::ForObjectArgument()
13430 : ConversionSignals::ForSequence(L.Conversions[I]);
13431 auto RS = R.IgnoreObjectArgument
13432 ? ConversionSignals::ForObjectArgument()
13433 : ConversionSignals::ForSequence(R.Conversions[I]);
13434 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13435 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13436 ? -1
13437 : 1;
13438 }
13439 // FIXME: find a way to compare templates for being more or less
13440 // specialized that provides a strict weak ordering.
13441 return 0;
13442 }
13443};
13444}
13445
13446/// CompleteNonViableCandidate - Normally, overload resolution only
13447/// computes up to the first bad conversion. Produces the FixIt set if
13448/// possible.
13449static void
13451 ArrayRef<Expr *> Args,
13453 assert(!Cand->Viable);
13454
13455 // Don't do anything on failures other than bad conversion.
13457 return;
13458
13459 // We only want the FixIts if all the arguments can be corrected.
13460 bool Unfixable = false;
13461 // Use a implicit copy initialization to check conversion fixes.
13463
13464 // Attempt to fix the bad conversion.
13465 unsigned ConvCount = Cand->Conversions.size();
13466 for (unsigned ConvIdx =
13467 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13468 : 0);
13469 /**/; ++ConvIdx) {
13470 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13471 if (Cand->Conversions[ConvIdx].isInitialized() &&
13472 Cand->Conversions[ConvIdx].isBad()) {
13473 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13474 break;
13475 }
13476 }
13477
13478 // FIXME: this should probably be preserved from the overload
13479 // operation somehow.
13480 bool SuppressUserConversions = false;
13481
13482 unsigned ConvIdx = 0;
13483 unsigned ArgIdx = 0;
13484 ArrayRef<QualType> ParamTypes;
13485 bool Reversed = Cand->isReversed();
13486
13487 if (Cand->IsSurrogate) {
13488 QualType ConvType
13490 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13491 ConvType = ConvPtrType->getPointeeType();
13492 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13493 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13494 ConvIdx = 1;
13495 } else if (Cand->Function) {
13496 ParamTypes =
13497 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13498 if (isa<CXXMethodDecl>(Cand->Function) &&
13501 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13502 ConvIdx = 1;
13504 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13506 OO_Subscript)
13507 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13508 ArgIdx = 1;
13509 }
13510 } else {
13511 // Builtin operator.
13512 assert(ConvCount <= 3);
13513 ParamTypes = Cand->BuiltinParamTypes;
13514 }
13515
13516 // Fill in the rest of the conversions.
13517 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13518 ConvIdx != ConvCount && ArgIdx < Args.size();
13519 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13520 if (Cand->Conversions[ConvIdx].isInitialized()) {
13521 // We've already checked this conversion.
13522 } else if (ParamIdx < ParamTypes.size()) {
13523 if (ParamTypes[ParamIdx]->isDependentType())
13524 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13525 Args[ArgIdx]->getType());
13526 else {
13527 Cand->Conversions[ConvIdx] =
13528 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13529 SuppressUserConversions,
13530 /*InOverloadResolution=*/true,
13531 /*AllowObjCWritebackConversion=*/
13532 S.getLangOpts().ObjCAutoRefCount);
13533 // Store the FixIt in the candidate if it exists.
13534 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13535 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13536 }
13537 } else
13538 Cand->Conversions[ConvIdx].setEllipsis();
13539 }
13540}
13541
13544 SourceLocation OpLoc,
13545 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13546
13548
13549 // Sort the candidates by viability and position. Sorting directly would
13550 // be prohibitive, so we make a set of pointers and sort those.
13552 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13553 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13554 Cand != LastCand; ++Cand) {
13555 if (!Filter(*Cand))
13556 continue;
13557 switch (OCD) {
13558 case OCD_AllCandidates:
13559 if (!Cand->Viable) {
13560 if (!Cand->Function && !Cand->IsSurrogate) {
13561 // This a non-viable builtin candidate. We do not, in general,
13562 // want to list every possible builtin candidate.
13563 continue;
13564 }
13565 CompleteNonViableCandidate(S, Cand, Args, Kind);
13566 }
13567 break;
13568
13570 if (!Cand->Viable)
13571 continue;
13572 break;
13573
13575 if (!Cand->Best)
13576 continue;
13577 break;
13578 }
13579
13580 Cands.push_back(Cand);
13581 }
13582
13583 llvm::stable_sort(
13584 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13585
13586 return Cands;
13587}
13588
13590 SourceLocation OpLoc) {
13591 bool DeferHint = false;
13592 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13593 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13594 // host device candidates.
13595 auto WrongSidedCands =
13596 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13597 return (Cand.Viable == false &&
13599 (Cand.Function &&
13600 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13601 Cand.Function->template hasAttr<CUDADeviceAttr>());
13602 });
13603 DeferHint = !WrongSidedCands.empty();
13604 }
13605 return DeferHint;
13606}
13607
13608/// When overload resolution fails, prints diagnostic messages containing the
13609/// candidates in the candidate set.
13612 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13613 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13614
13615 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13616
13617 {
13618 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13619 S.Diag(PD.first, PD.second);
13620 }
13621
13622 // In WebAssembly we don't want to emit further diagnostics if a table is
13623 // passed as an argument to a function.
13624 bool NoteCands = true;
13625 for (const Expr *Arg : Args) {
13626 if (Arg->getType()->isWebAssemblyTableType())
13627 NoteCands = false;
13628 }
13629
13630 if (NoteCands)
13631 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13632
13633 if (OCD == OCD_AmbiguousCandidates)
13635 {Candidates.begin(), Candidates.end()});
13636}
13637
13640 StringRef Opc, SourceLocation OpLoc) {
13641 bool ReportedAmbiguousConversions = false;
13642
13643 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13644 unsigned CandsShown = 0;
13645 auto I = Cands.begin(), E = Cands.end();
13646 for (; I != E; ++I) {
13647 OverloadCandidate *Cand = *I;
13648
13649 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13650 ShowOverloads == Ovl_Best) {
13651 break;
13652 }
13653 ++CandsShown;
13654
13655 if (Cand->Function)
13656 NoteFunctionCandidate(S, Cand, Args.size(),
13657 Kind == CSK_AddressOfOverloadSet, DestAS);
13658 else if (Cand->IsSurrogate)
13659 NoteSurrogateCandidate(S, Cand);
13660 else {
13661 assert(Cand->Viable &&
13662 "Non-viable built-in candidates are not added to Cands.");
13663 // Generally we only see ambiguities including viable builtin
13664 // operators if overload resolution got screwed up by an
13665 // ambiguous user-defined conversion.
13666 //
13667 // FIXME: It's quite possible for different conversions to see
13668 // different ambiguities, though.
13669 if (!ReportedAmbiguousConversions) {
13670 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13671 ReportedAmbiguousConversions = true;
13672 }
13673
13674 // If this is a viable builtin, print it.
13675 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13676 }
13677 }
13678
13679 // Inform S.Diags that we've shown an overload set with N elements. This may
13680 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13681 S.Diags.overloadCandidatesShown(CandsShown);
13682
13683 if (I != E) {
13684 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13685 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13686 }
13687}
13688
13690 const Sema &S) const {
13691 if (S.getLangOpts().CUDA) {
13692 auto *Caller = S.getCurFunctionDecl(true);
13693 // Overloading based on __host__ and __device__ attributes takes
13694 // higher priority, HD functions may favor template candidates even when a
13695 // non-template candidate would be a perfect match.
13696 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13697 Caller->hasAttr<CUDADeviceAttr>())
13698 return false;
13699 }
13700
13701 return
13702 // For user defined conversion we need to check against different
13703 // combination of CV qualifiers and look at any explicit specifier, so
13704 // always deduce template candidates.
13706 // When doing code completion, we want to see all the
13707 // viable candidates.
13708 && Kind != CSK_CodeCompletion;
13709}
13710
13711static SourceLocation
13713 return Cand->Specialization ? Cand->Specialization->getLocation()
13714 : SourceLocation();
13715}
13716
13717namespace {
13718struct CompareTemplateSpecCandidatesForDisplay {
13719 Sema &S;
13720 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13721
13722 bool operator()(const TemplateSpecCandidate *L,
13723 const TemplateSpecCandidate *R) {
13724 // Fast-path this check.
13725 if (L == R)
13726 return false;
13727
13728 // Assuming that both candidates are not matches...
13729
13730 // Sort by the ranking of deduction failures.
13731 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13733 RankDeductionFailure(R->DeductionFailure);
13734
13735 // Sort everything else by location.
13736 SourceLocation LLoc = GetLocationForCandidate(L);
13737 SourceLocation RLoc = GetLocationForCandidate(R);
13738
13739 // Put candidates without locations (e.g. builtins) at the end.
13740 if (LLoc.isInvalid())
13741 return false;
13742 if (RLoc.isInvalid())
13743 return true;
13744
13745 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13746 }
13747};
13748}
13749
13750/// Diagnose a template argument deduction failure.
13751/// We are treating these failures as overload failures due to bad
13752/// deductions.
13754 Sema &S, bool ForTakingAddress,
13755 TemplateSpecCandidateSetKind CandidateSetKind) {
13757 DeductionFailure, /*NumArgs=*/0, ForTakingAddress,
13758 CandidateSetKind);
13759}
13760
13761void TemplateSpecCandidateSet::destroyCandidates() {
13762 for (iterator i = begin(), e = end(); i != e; ++i) {
13763 i->DeductionFailure.Destroy();
13764 }
13765}
13766
13768 destroyCandidates();
13769 Candidates.clear();
13770}
13771
13772/// NoteCandidates - When no template specialization match is found, prints
13773/// diagnostic messages containing the non-matching specializations that form
13774/// the candidate set.
13775/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13776/// OCD == OCD_AllCandidates and Cand->Viable == false.
13778 // Sort the candidates by position (assuming no candidate is a match).
13779 // Sorting directly would be prohibitive, so we make a set of pointers
13780 // and sort those.
13782 Cands.reserve(size());
13783 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13784 if (Cand->Specialization)
13785 Cands.push_back(Cand);
13786 // Otherwise, this is a non-matching builtin candidate. We do not,
13787 // in general, want to list every possible builtin candidate.
13788 }
13789
13790 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13791
13792 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13793 // for generalization purposes (?).
13794 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13795
13797 unsigned CandsShown = 0;
13798 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13799 TemplateSpecCandidate *Cand = *I;
13800
13801 // Set an arbitrary limit on the number of candidates we'll spam
13802 // the user with. FIXME: This limit should depend on details of the
13803 // candidate list.
13804 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13805 break;
13806 ++CandsShown;
13807
13808 assert(Cand->Specialization &&
13809 "Non-matching built-in candidates are not added to Cands.");
13810 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13811 }
13812
13813 if (I != E)
13814 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13815}
13816
13817// [PossiblyAFunctionType] --> [Return]
13818// NonFunctionType --> NonFunctionType
13819// R (A) --> R(A)
13820// R (*)(A) --> R (A)
13821// R (&)(A) --> R (A)
13822// R (S::*)(A) --> R (A)
13824 QualType Ret = PossiblyAFunctionType;
13825 if (const PointerType *ToTypePtr =
13826 PossiblyAFunctionType->getAs<PointerType>())
13827 Ret = ToTypePtr->getPointeeType();
13828 else if (const ReferenceType *ToTypeRef =
13829 PossiblyAFunctionType->getAs<ReferenceType>())
13830 Ret = ToTypeRef->getPointeeType();
13831 else if (const MemberPointerType *MemTypePtr =
13832 PossiblyAFunctionType->getAs<MemberPointerType>())
13833 Ret = MemTypePtr->getPointeeType();
13834 Ret =
13835 Context.getCanonicalType(Ret).getUnqualifiedType();
13836 return Ret;
13837}
13838
13840 bool Complain = true) {
13841 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13842 S.DeduceReturnType(FD, Loc, Complain))
13843 return true;
13844
13845 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13846 if (S.getLangOpts().CPlusPlus17 &&
13847 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13848 !S.ResolveExceptionSpec(Loc, FPT))
13849 return true;
13850
13851 return false;
13852}
13853
13854namespace {
13855// A helper class to help with address of function resolution
13856// - allows us to avoid passing around all those ugly parameters
13857class AddressOfFunctionResolver {
13858 Sema& S;
13859 Expr* SourceExpr;
13860 const QualType& TargetType;
13861 QualType TargetFunctionType; // Extracted function type from target type
13862
13863 bool Complain;
13864 //DeclAccessPair& ResultFunctionAccessPair;
13865 ASTContext& Context;
13866
13867 bool TargetTypeIsNonStaticMemberFunction;
13868 bool FoundNonTemplateFunction;
13869 bool StaticMemberFunctionFromBoundPointer;
13870 bool HasComplained;
13871
13872 OverloadExpr::FindResult OvlExprInfo;
13873 OverloadExpr *OvlExpr;
13874 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13875 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13876 TemplateSpecCandidateSet FailedCandidates;
13877
13878public:
13879 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13880 const QualType &TargetType, bool Complain)
13881 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13882 Complain(Complain), Context(S.getASTContext()),
13883 TargetTypeIsNonStaticMemberFunction(
13884 !!TargetType->getAs<MemberPointerType>()),
13885 FoundNonTemplateFunction(false),
13886 StaticMemberFunctionFromBoundPointer(false),
13887 HasComplained(false),
13888 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13889 OvlExpr(OvlExprInfo.Expression),
13890 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13891 ExtractUnqualifiedFunctionTypeFromTargetType();
13892
13893 if (TargetFunctionType->isFunctionType()) {
13894 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13895 if (!UME->isImplicitAccess() &&
13897 StaticMemberFunctionFromBoundPointer = true;
13898 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13899 DeclAccessPair dap;
13900 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13901 OvlExpr, false, &dap)) {
13902 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13903 if (!Method->isStatic()) {
13904 // If the target type is a non-function type and the function found
13905 // is a non-static member function, pretend as if that was the
13906 // target, it's the only possible type to end up with.
13907 TargetTypeIsNonStaticMemberFunction = true;
13908
13909 // And skip adding the function if its not in the proper form.
13910 // We'll diagnose this due to an empty set of functions.
13911 if (!OvlExprInfo.HasFormOfMemberPointer)
13912 return;
13913 }
13914
13915 Matches.push_back(std::make_pair(dap, Fn));
13916 }
13917 return;
13918 }
13919
13920 if (OvlExpr->hasExplicitTemplateArgs())
13921 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13922
13923 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13924 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13925 EliminateSuboptimalCudaMatches();
13926
13927 // C++ [over.over]p4:
13928 // If more than one function is selected, [...]
13929 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13930 if (FoundNonTemplateFunction) {
13931 EliminateAllTemplateMatches();
13932 EliminateLessPartialOrderingConstrainedMatches();
13933 } else
13934 EliminateAllExceptMostSpecializedTemplate();
13935 }
13936 }
13937 }
13938
13939 bool hasComplained() const { return HasComplained; }
13940
13941private:
13942 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13943 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13944 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13945 }
13946
13947 /// \return true if A is considered a better overload candidate for the
13948 /// desired type than B.
13949 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13950 // If A doesn't have exactly the correct type, we don't want to classify it
13951 // as "better" than anything else. This way, the user is required to
13952 // disambiguate for us if there are multiple candidates and no exact match.
13953 return candidateHasExactlyCorrectType(A) &&
13954 (!candidateHasExactlyCorrectType(B) ||
13955 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13956 }
13957
13958 /// \return true if we were able to eliminate all but one overload candidate,
13959 /// false otherwise.
13960 bool eliminiateSuboptimalOverloadCandidates() {
13961 // Same algorithm as overload resolution -- one pass to pick the "best",
13962 // another pass to be sure that nothing is better than the best.
13963 auto Best = Matches.begin();
13964 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13965 if (isBetterCandidate(I->second, Best->second))
13966 Best = I;
13967
13968 const FunctionDecl *BestFn = Best->second;
13969 auto IsBestOrInferiorToBest = [this, BestFn](
13970 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13971 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13972 };
13973
13974 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13975 // option, so we can potentially give the user a better error
13976 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13977 return false;
13978 Matches[0] = *Best;
13979 Matches.resize(1);
13980 return true;
13981 }
13982
13983 bool isTargetTypeAFunction() const {
13984 return TargetFunctionType->isFunctionType();
13985 }
13986
13987 // [ToType] [Return]
13988
13989 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13990 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13991 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13992 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13993 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13994 }
13995
13996 // return true if any matching specializations were found
13997 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13998 const DeclAccessPair& CurAccessFunPair) {
13999 if (CXXMethodDecl *Method
14000 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
14001 // Skip non-static function templates when converting to pointer, and
14002 // static when converting to member pointer.
14003 bool CanConvertToFunctionPointer =
14004 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14005 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14006 return false;
14007 }
14008 else if (TargetTypeIsNonStaticMemberFunction)
14009 return false;
14010
14011 // C++ [over.over]p2:
14012 // If the name is a function template, template argument deduction is
14013 // done (14.8.2.2), and if the argument deduction succeeds, the
14014 // resulting template argument list is used to generate a single
14015 // function template specialization, which is added to the set of
14016 // overloaded functions considered.
14017 FunctionDecl *Specialization = nullptr;
14018 TemplateDeductionInfo Info(FailedCandidates.getLocation());
14020 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
14021 Specialization, Info, /*IsAddressOfFunction*/ true);
14022 Result != TemplateDeductionResult::Success) {
14023 // Make a note of the failed deduction for diagnostics.
14024 FailedCandidates.addCandidate()
14025 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
14026 MakeDeductionFailureInfo(Context, Result, Info));
14027 return false;
14028 }
14029
14030 // Template argument deduction ensures that we have an exact match or
14031 // compatible pointer-to-function arguments that would be adjusted by ICS.
14032 // This function template specicalization works.
14034 Context.getCanonicalType(Specialization->getType()),
14035 Context.getCanonicalType(TargetFunctionType)));
14036
14038 return false;
14039
14040 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
14041 return true;
14042 }
14043
14044 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
14045 const DeclAccessPair& CurAccessFunPair) {
14046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14047 // Skip non-static functions when converting to pointer, and static
14048 // when converting to member pointer.
14049 bool CanConvertToFunctionPointer =
14050 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14051 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14052 return false;
14053 }
14054 else if (TargetTypeIsNonStaticMemberFunction)
14055 return false;
14056
14057 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
14058 if (S.getLangOpts().CUDA) {
14059 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
14060 if (!(Caller && Caller->isImplicit()) &&
14061 !S.CUDA().IsAllowedCall(Caller, FunDecl))
14062 return false;
14063 }
14064 if (FunDecl->isMultiVersion()) {
14065 const auto *TA = FunDecl->getAttr<TargetAttr>();
14066 if (TA && !TA->isDefaultVersion())
14067 return false;
14068 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
14069 if (TVA && !TVA->isDefaultVersion())
14070 return false;
14071 }
14072
14073 // If any candidate has a placeholder return type, trigger its deduction
14074 // now.
14075 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
14076 Complain)) {
14077 HasComplained |= Complain;
14078 return false;
14079 }
14080
14081 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
14082 return false;
14083
14084 // If we're in C, we need to support types that aren't exactly identical.
14085 if (!S.getLangOpts().CPlusPlus ||
14086 candidateHasExactlyCorrectType(FunDecl)) {
14087 Matches.push_back(std::make_pair(
14088 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
14089 FoundNonTemplateFunction = true;
14090 return true;
14091 }
14092 }
14093
14094 return false;
14095 }
14096
14097 bool FindAllFunctionsThatMatchTargetTypeExactly() {
14098 bool Ret = false;
14099
14100 // If the overload expression doesn't have the form of a pointer to
14101 // member, don't try to convert it to a pointer-to-member type.
14102 if (IsInvalidFormOfPointerToMemberFunction())
14103 return false;
14104
14105 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14106 E = OvlExpr->decls_end();
14107 I != E; ++I) {
14108 // Look through any using declarations to find the underlying function.
14109 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14110
14111 // C++ [over.over]p3:
14112 // Non-member functions and static member functions match
14113 // targets of type "pointer-to-function" or "reference-to-function."
14114 // Nonstatic member functions match targets of
14115 // type "pointer-to-member-function."
14116 // Note that according to DR 247, the containing class does not matter.
14117 if (FunctionTemplateDecl *FunctionTemplate
14118 = dyn_cast<FunctionTemplateDecl>(Fn)) {
14119 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
14120 Ret = true;
14121 }
14122 // If we have explicit template arguments supplied, skip non-templates.
14123 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14124 AddMatchingNonTemplateFunction(Fn, I.getPair()))
14125 Ret = true;
14126 }
14127 assert(Ret || Matches.empty());
14128 return Ret;
14129 }
14130
14131 void EliminateAllExceptMostSpecializedTemplate() {
14132 // [...] and any given function template specialization F1 is
14133 // eliminated if the set contains a second function template
14134 // specialization whose function template is more specialized
14135 // than the function template of F1 according to the partial
14136 // ordering rules of 14.5.5.2.
14137
14138 // The algorithm specified above is quadratic. We instead use a
14139 // two-pass algorithm (similar to the one used to identify the
14140 // best viable function in an overload set) that identifies the
14141 // best function template (if it exists).
14142
14143 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14144 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14145 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14146
14147 // TODO: It looks like FailedCandidates does not serve much purpose
14148 // here, since the no_viable diagnostic has index 0.
14149 UnresolvedSetIterator Result = S.getMostSpecialized(
14150 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14151 SourceExpr->getBeginLoc(), S.PDiag(),
14152 S.PDiag(diag::err_addr_ovl_ambiguous)
14153 << Matches[0].second->getDeclName(),
14154 S.PDiag(diag::note_ovl_candidate)
14155 << (unsigned)oc_function << (unsigned)ocs_described_template,
14156 Complain, TargetFunctionType);
14157
14158 if (Result != MatchesCopy.end()) {
14159 // Make it the first and only element
14160 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14161 Matches[0].second = cast<FunctionDecl>(*Result);
14162 Matches.resize(1);
14163 } else
14164 HasComplained |= Complain;
14165 }
14166
14167 void EliminateAllTemplateMatches() {
14168 // [...] any function template specializations in the set are
14169 // eliminated if the set also contains a non-template function, [...]
14170 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14171 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14172 ++I;
14173 else {
14174 Matches[I] = Matches[--N];
14175 Matches.resize(N);
14176 }
14177 }
14178 }
14179
14180 void EliminateLessPartialOrderingConstrainedMatches() {
14181 // C++ [over.over]p5:
14182 // [...] Any given non-template function F0 is eliminated if the set
14183 // contains a second non-template function that is more
14184 // partial-ordering-constrained than F0. [...]
14185 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14186 "Call EliminateAllTemplateMatches() first");
14187 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14188 Results.push_back(Matches[0]);
14189 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14190 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14191 FunctionDecl *F = getMorePartialOrderingConstrained(
14192 S, Matches[I].second, Results[0].second,
14193 /*IsFn1Reversed=*/false,
14194 /*IsFn2Reversed=*/false);
14195 if (!F) {
14196 Results.push_back(Matches[I]);
14197 continue;
14198 }
14199 if (F == Matches[I].second) {
14200 Results.clear();
14201 Results.push_back(Matches[I]);
14202 }
14203 }
14204 std::swap(Matches, Results);
14205 }
14206
14207 void EliminateSuboptimalCudaMatches() {
14208 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14209 Matches);
14210 }
14211
14212public:
14213 void ComplainNoMatchesFound() const {
14214 assert(Matches.empty());
14215 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14216 << OvlExpr->getName() << TargetFunctionType
14217 << OvlExpr->getSourceRange();
14218 if (FailedCandidates.empty())
14219 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14220 /*TakingAddress=*/true);
14221 else {
14222 // We have some deduction failure messages. Use them to diagnose
14223 // the function templates, and diagnose the non-template candidates
14224 // normally.
14225 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14226 IEnd = OvlExpr->decls_end();
14227 I != IEnd; ++I)
14228 if (FunctionDecl *Fun =
14229 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14231 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14232 /*TakingAddress=*/true);
14233 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14234 }
14235 }
14236
14237 bool IsInvalidFormOfPointerToMemberFunction() const {
14238 return TargetTypeIsNonStaticMemberFunction &&
14239 !OvlExprInfo.HasFormOfMemberPointer;
14240 }
14241
14242 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14243 // TODO: Should we condition this on whether any functions might
14244 // have matched, or is it more appropriate to do that in callers?
14245 // TODO: a fixit wouldn't hurt.
14246 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14247 << TargetType << OvlExpr->getSourceRange();
14248 }
14249
14250 bool IsStaticMemberFunctionFromBoundPointer() const {
14251 return StaticMemberFunctionFromBoundPointer;
14252 }
14253
14254 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14255 S.Diag(OvlExpr->getBeginLoc(),
14256 diag::err_invalid_form_pointer_member_function)
14257 << OvlExpr->getSourceRange();
14258 }
14259
14260 void ComplainOfInvalidConversion() const {
14261 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14262 << OvlExpr->getName() << TargetType;
14263 }
14264
14265 void ComplainMultipleMatchesFound() const {
14266 assert(Matches.size() > 1);
14267 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14268 << OvlExpr->getName() << OvlExpr->getSourceRange();
14269 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14270 /*TakingAddress=*/true);
14271 }
14272
14273 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14274
14275 int getNumMatches() const { return Matches.size(); }
14276
14277 FunctionDecl* getMatchingFunctionDecl() const {
14278 if (Matches.size() != 1) return nullptr;
14279 return Matches[0].second;
14280 }
14281
14282 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14283 if (Matches.size() != 1) return nullptr;
14284 return &Matches[0].first;
14285 }
14286};
14287}
14288
14289FunctionDecl *
14291 QualType TargetType,
14292 bool Complain,
14293 DeclAccessPair &FoundResult,
14294 bool *pHadMultipleCandidates) {
14295 assert(AddressOfExpr->getType() == Context.OverloadTy);
14296
14297 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14298 Complain);
14299 int NumMatches = Resolver.getNumMatches();
14300 FunctionDecl *Fn = nullptr;
14301 bool ShouldComplain = Complain && !Resolver.hasComplained();
14302 if (NumMatches == 0 && ShouldComplain) {
14303 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14304 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14305 else
14306 Resolver.ComplainNoMatchesFound();
14307 }
14308 else if (NumMatches > 1 && ShouldComplain)
14309 Resolver.ComplainMultipleMatchesFound();
14310 else if (NumMatches == 1) {
14311 Fn = Resolver.getMatchingFunctionDecl();
14312 assert(Fn);
14313 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14314 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14315 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14316 if (Complain) {
14317 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14318 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14319 else
14320 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14321 }
14322 }
14323
14324 if (pHadMultipleCandidates)
14325 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14326 return Fn;
14327}
14328
14332 OverloadExpr *Ovl = R.Expression;
14333 bool IsResultAmbiguous = false;
14334 FunctionDecl *Result = nullptr;
14335 DeclAccessPair DAP;
14336 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14337
14338 // Return positive for better, negative for worse, 0 for equal preference.
14339 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14340 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14341 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14342 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14343 };
14344
14345 // Don't use the AddressOfResolver because we're specifically looking for
14346 // cases where we have one overload candidate that lacks
14347 // enable_if/pass_object_size/...
14348 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14349 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14350 if (!FD)
14351 return nullptr;
14352
14354 continue;
14355
14356 // If we found a better result, update Result.
14357 auto FoundBetter = [&]() {
14358 IsResultAmbiguous = false;
14359 DAP = I.getPair();
14360 Result = FD;
14361 };
14362
14363 // We have more than one result - see if it is more
14364 // partial-ordering-constrained than the previous one.
14365 if (Result) {
14366 // Check CUDA preference first. If the candidates have differennt CUDA
14367 // preference, choose the one with higher CUDA preference. Otherwise,
14368 // choose the one with more constraints.
14369 if (getLangOpts().CUDA) {
14370 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14371 // FD has different preference than Result.
14372 if (PreferenceByCUDA != 0) {
14373 // FD is more preferable than Result.
14374 if (PreferenceByCUDA > 0)
14375 FoundBetter();
14376 continue;
14377 }
14378 }
14379 // FD has the same CUDA preference than Result. Continue to check
14380 // constraints.
14381
14382 // C++ [over.over]p5:
14383 // [...] If more than one function in the set remains, all function
14384 // template specializations in the set are eliminated if the set also
14385 // contains a function that is not a function template specialization.
14386 // [...]
14387 if (Result->isFunctionTemplateSpecialization() !=
14390 FoundBetter();
14391 continue;
14392 }
14393
14394 // C++ [over.over]p5:
14395 // [...] Any given non-template function F0 is eliminated if the set
14396 // contains a second non-template function that is more
14397 // partial-ordering-constrained than F0 [...]
14398 FunctionDecl *MoreConstrained =
14400 /*IsFn1Reversed=*/false,
14401 /*IsFn2Reversed=*/false);
14402 if (MoreConstrained != FD) {
14403 if (!MoreConstrained) {
14404 IsResultAmbiguous = true;
14405 AmbiguousDecls.push_back(FD);
14406 }
14407 continue;
14408 }
14409 // FD is more constrained - replace Result with it.
14410 }
14411 FoundBetter();
14412 }
14413
14414 if (IsResultAmbiguous)
14415 return nullptr;
14416
14417 if (Result) {
14418 // We skipped over some ambiguous declarations which might be ambiguous with
14419 // the selected result.
14420 for (FunctionDecl *Skipped : AmbiguousDecls) {
14421 // If skipped candidate has different CUDA preference than the result,
14422 // there is no ambiguity. Otherwise check whether they have different
14423 // constraints.
14424 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14425 continue;
14426 if (!getMoreConstrainedFunction(Skipped, Result))
14427 return nullptr;
14428 }
14429 Pair = DAP;
14430 }
14431 return Result;
14432}
14433
14435 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14436 Expr *E = SrcExpr.get();
14437 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14438
14439 DeclAccessPair DAP;
14441 if (!Found || Found->isCPUDispatchMultiVersion() ||
14442 Found->isCPUSpecificMultiVersion())
14443 return false;
14444
14445 // Emitting multiple diagnostics for a function that is both inaccessible and
14446 // unavailable is consistent with our behavior elsewhere. So, always check
14447 // for both.
14451 if (Res.isInvalid())
14452 return false;
14453 Expr *Fixed = Res.get();
14454 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14455 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14456 else
14457 SrcExpr = Fixed;
14458 return true;
14459}
14460
14462 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14463 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14464 // C++ [over.over]p1:
14465 // [...] [Note: any redundant set of parentheses surrounding the
14466 // overloaded function name is ignored (5.1). ]
14467 // C++ [over.over]p1:
14468 // [...] The overloaded function name can be preceded by the &
14469 // operator.
14470
14471 // If we didn't actually find any template-ids, we're done.
14472 if (!ovl->hasExplicitTemplateArgs())
14473 return nullptr;
14474
14475 TemplateArgumentListInfo ExplicitTemplateArgs;
14476 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14477
14478 // Look through all of the overloaded functions, searching for one
14479 // whose type matches exactly.
14480 FunctionDecl *Matched = nullptr;
14481 for (UnresolvedSetIterator I = ovl->decls_begin(),
14482 E = ovl->decls_end(); I != E; ++I) {
14483 // C++0x [temp.arg.explicit]p3:
14484 // [...] In contexts where deduction is done and fails, or in contexts
14485 // where deduction is not done, if a template argument list is
14486 // specified and it, along with any default template arguments,
14487 // identifies a single function template specialization, then the
14488 // template-id is an lvalue for the function template specialization.
14490 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14491 if (!FunctionTemplate)
14492 continue;
14493
14494 // C++ [over.over]p2:
14495 // If the name is a function template, template argument deduction is
14496 // done (14.8.2.2), and if the argument deduction succeeds, the
14497 // resulting template argument list is used to generate a single
14498 // function template specialization, which is added to the set of
14499 // overloaded functions considered.
14500 FunctionDecl *Specialization = nullptr;
14501 TemplateDeductionInfo Info(ovl->getNameLoc());
14503 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14504 /*IsAddressOfFunction*/ true);
14506 // Make a note of the failed deduction for diagnostics.
14507 if (FailedTSC)
14508 FailedTSC->addCandidate().set(
14509 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14511 continue;
14512 }
14513
14514 assert(Specialization && "no specialization and no error?");
14515
14516 // C++ [temp.deduct.call]p6:
14517 // [...] If all successful deductions yield the same deduced A, that
14518 // deduced A is the result of deduction; otherwise, the parameter is
14519 // treated as a non-deduced context.
14520 if (Matched) {
14521 if (ForTypeDeduction &&
14523 Specialization->getType()))
14524 continue;
14525 // Multiple matches; we can't resolve to a single declaration.
14526 if (Complain) {
14527 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14528 << ovl->getName();
14530 }
14531 return nullptr;
14532 }
14533
14534 Matched = Specialization;
14535 if (FoundResult) *FoundResult = I.getPair();
14536 }
14537
14538 if (Matched &&
14539 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14540 return nullptr;
14541
14542 return Matched;
14543}
14544
14546 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14547 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14548 unsigned DiagIDForComplaining) {
14549 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14550
14552
14553 DeclAccessPair found;
14554 ExprResult SingleFunctionExpression;
14556 ovl.Expression, /*complain*/ false, &found)) {
14557 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14558 SrcExpr = ExprError();
14559 return true;
14560 }
14561
14562 // It is only correct to resolve to an instance method if we're
14563 // resolving a form that's permitted to be a pointer to member.
14564 // Otherwise we'll end up making a bound member expression, which
14565 // is illegal in all the contexts we resolve like this.
14566 if (!ovl.HasFormOfMemberPointer &&
14567 isa<CXXMethodDecl>(fn) &&
14568 cast<CXXMethodDecl>(fn)->isInstance()) {
14569 if (!complain) return false;
14570
14571 Diag(ovl.Expression->getExprLoc(),
14572 diag::err_bound_member_function)
14573 << 0 << ovl.Expression->getSourceRange();
14574
14575 // TODO: I believe we only end up here if there's a mix of
14576 // static and non-static candidates (otherwise the expression
14577 // would have 'bound member' type, not 'overload' type).
14578 // Ideally we would note which candidate was chosen and why
14579 // the static candidates were rejected.
14580 SrcExpr = ExprError();
14581 return true;
14582 }
14583
14584 // Fix the expression to refer to 'fn'.
14585 SingleFunctionExpression =
14586 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14587
14588 // If desired, do function-to-pointer decay.
14589 if (doFunctionPointerConversion) {
14590 SingleFunctionExpression =
14591 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14592 if (SingleFunctionExpression.isInvalid()) {
14593 SrcExpr = ExprError();
14594 return true;
14595 }
14596 }
14597 }
14598
14599 if (!SingleFunctionExpression.isUsable()) {
14600 if (complain) {
14601 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14602 << ovl.Expression->getName()
14603 << DestTypeForComplaining
14604 << OpRangeForComplaining
14606 NoteAllOverloadCandidates(SrcExpr.get());
14607
14608 SrcExpr = ExprError();
14609 return true;
14610 }
14611
14612 return false;
14613 }
14614
14615 SrcExpr = SingleFunctionExpression;
14616 return true;
14617}
14618
14619/// Add a single candidate to the overload set.
14621 DeclAccessPair FoundDecl,
14622 TemplateArgumentListInfo *ExplicitTemplateArgs,
14623 ArrayRef<Expr *> Args,
14624 OverloadCandidateSet &CandidateSet,
14625 bool PartialOverloading,
14626 bool KnownValid) {
14627 NamedDecl *Callee = FoundDecl.getDecl();
14628 if (isa<UsingShadowDecl>(Callee))
14629 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14630
14631 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14632 if (ExplicitTemplateArgs) {
14633 assert(!KnownValid && "Explicit template arguments?");
14634 return;
14635 }
14636 // Prevent ill-formed function decls to be added as overload candidates.
14637 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14638 return;
14639
14640 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14641 /*SuppressUserConversions=*/false,
14642 PartialOverloading);
14643 return;
14644 }
14645
14646 if (FunctionTemplateDecl *FuncTemplate
14647 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14648 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14649 ExplicitTemplateArgs, Args, CandidateSet,
14650 /*SuppressUserConversions=*/false,
14651 PartialOverloading);
14652 return;
14653 }
14654
14655 assert(!KnownValid && "unhandled case in overloaded call candidate");
14656}
14657
14659 ArrayRef<Expr *> Args,
14660 OverloadCandidateSet &CandidateSet,
14661 bool PartialOverloading) {
14662
14663#ifndef NDEBUG
14664 // Verify that ArgumentDependentLookup is consistent with the rules
14665 // in C++0x [basic.lookup.argdep]p3:
14666 //
14667 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14668 // and let Y be the lookup set produced by argument dependent
14669 // lookup (defined as follows). If X contains
14670 //
14671 // -- a declaration of a class member, or
14672 //
14673 // -- a block-scope function declaration that is not a
14674 // using-declaration, or
14675 //
14676 // -- a declaration that is neither a function or a function
14677 // template
14678 //
14679 // then Y is empty.
14680
14681 if (ULE->requiresADL()) {
14683 E = ULE->decls_end(); I != E; ++I) {
14684 assert(!(*I)->getDeclContext()->isRecord());
14685 assert(isa<UsingShadowDecl>(*I) ||
14686 !(*I)->getDeclContext()->isFunctionOrMethod());
14687 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14688 }
14689 }
14690#endif
14691
14692 // It would be nice to avoid this copy.
14693 TemplateArgumentListInfo TABuffer;
14694 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14695 if (ULE->hasExplicitTemplateArgs()) {
14696 ULE->copyTemplateArgumentsInto(TABuffer);
14697 ExplicitTemplateArgs = &TABuffer;
14698 }
14699
14701 E = ULE->decls_end(); I != E; ++I)
14702 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14703 CandidateSet, PartialOverloading,
14704 /*KnownValid*/ true);
14705
14706 if (ULE->requiresADL())
14708 Args, ExplicitTemplateArgs,
14709 CandidateSet, PartialOverloading);
14710}
14711
14713 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14714 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14715 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14716 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14717 CandidateSet, false, /*KnownValid*/ false);
14718}
14719
14720/// Determine whether a declaration with the specified name could be moved into
14721/// a different namespace.
14723 switch (Name.getCXXOverloadedOperator()) {
14724 case OO_New: case OO_Array_New:
14725 case OO_Delete: case OO_Array_Delete:
14726 return false;
14727
14728 default:
14729 return true;
14730 }
14731}
14732
14733/// Attempt to recover from an ill-formed use of a non-dependent name in a
14734/// template, where the non-dependent name was declared after the template
14735/// was defined. This is common in code written for compilers which do not
14736/// correctly implement two-stage name lookup.
14737///
14738/// Returns true if a viable candidate was found and a diagnostic was issued.
14740 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14742 const OverloadCandidateSet &ResolvedCandidates,
14743 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14744 CXXRecordDecl **FoundInClass = nullptr) {
14745 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14746 return false;
14747
14748 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14749 if (DC->isTransparentContext())
14750 continue;
14751
14752 SemaRef.LookupQualifiedName(R, DC);
14753
14754 if (!R.empty()) {
14755 R.suppressDiagnostics();
14756
14757 OverloadCandidateSet Candidates(FnLoc, CSK);
14758 // We have performed a BestViableFunction over these candidates, so
14759 // exclude them.
14760 for (auto &Cand : ResolvedCandidates) {
14761 if (Cand.Function)
14762 Candidates.exclude(Cand.Function);
14763 else if (Cand.IsSurrogate)
14764 Candidates.exclude(Cand.Surrogate);
14765 }
14766 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14767 Candidates);
14768
14771 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14772
14773 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14774 // We either found non-function declarations or a best viable function
14775 // at class scope. A class-scope lookup result disables ADL. Don't
14776 // look past this, but let the caller know that we found something that
14777 // either is, or might be, usable in this class.
14778 if (FoundInClass) {
14779 *FoundInClass = RD;
14780 if (OR == OR_Success) {
14781 R.clear();
14782 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14783 R.resolveKind();
14784 }
14785 }
14786 return false;
14787 }
14788
14789 if (OR != OR_Success) {
14790 // There wasn't a unique best function or function template.
14791 return false;
14792 }
14793
14794 // Find the namespaces where ADL would have looked, and suggest
14795 // declaring the function there instead.
14796 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14797 Sema::AssociatedClassSet AssociatedClasses;
14798 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14799 AssociatedNamespaces,
14800 AssociatedClasses);
14801 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14802 if (canBeDeclaredInNamespace(R.getLookupName())) {
14803 DeclContext *Std = SemaRef.getStdNamespace();
14804 for (Sema::AssociatedNamespaceSet::iterator
14805 it = AssociatedNamespaces.begin(),
14806 end = AssociatedNamespaces.end(); it != end; ++it) {
14807 // Never suggest declaring a function within namespace 'std'.
14808 if (Std && Std->Encloses(*it))
14809 continue;
14810
14811 // Never suggest declaring a function within a namespace with a
14812 // reserved name, like __gnu_cxx.
14813 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14814 if (NS &&
14815 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14816 continue;
14817
14818 SuggestedNamespaces.insert(*it);
14819 }
14820 }
14821
14822 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14823 << R.getLookupName();
14824 if (SuggestedNamespaces.empty()) {
14825 SemaRef.Diag(Best->Function->getLocation(),
14826 diag::note_not_found_by_two_phase_lookup)
14827 << R.getLookupName() << 0;
14828 } else if (SuggestedNamespaces.size() == 1) {
14829 SemaRef.Diag(Best->Function->getLocation(),
14830 diag::note_not_found_by_two_phase_lookup)
14831 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14832 } else {
14833 // FIXME: It would be useful to list the associated namespaces here,
14834 // but the diagnostics infrastructure doesn't provide a way to produce
14835 // a localized representation of a list of items.
14836 SemaRef.Diag(Best->Function->getLocation(),
14837 diag::note_not_found_by_two_phase_lookup)
14838 << R.getLookupName() << 2;
14839 }
14840
14841 // Try to recover by calling this function.
14842 return true;
14843 }
14844
14845 R.clear();
14846 }
14847
14848 return false;
14849}
14850
14851/// Attempt to recover from ill-formed use of a non-dependent operator in a
14852/// template, where the non-dependent operator was declared after the template
14853/// was defined.
14854///
14855/// Returns true if a viable candidate was found and a diagnostic was issued.
14857 Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc,
14858 ArrayRef<Expr *> Args, const OverloadCandidateSet &ResolvedCandidateSet) {
14859 DeclarationName OpName =
14861 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14864 ResolvedCandidateSet,
14865 /*ExplicitTemplateArgs=*/nullptr, Args, /*FoundInClass=*/nullptr);
14866}
14867
14868namespace {
14869class BuildRecoveryCallExprRAII {
14870 Sema &SemaRef;
14871 Sema::SatisfactionStackResetRAII SatStack;
14872
14873public:
14874 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14875 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14876 SemaRef.IsBuildingRecoveryCallExpr = true;
14877 }
14878
14879 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14880};
14881}
14882
14883/// Attempts to recover from a call where no functions were found.
14884///
14885/// This function will do one of three things:
14886/// * Diagnose, recover, and return a recovery expression.
14887/// * Diagnose, fail to recover, and return ExprError().
14888/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14889/// expected to diagnose as appropriate.
14890static ExprResult
14892 UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
14894 const OverloadCandidateSet &ResolvedCandidateSet,
14895 bool AllowTypoCorrection) {
14896 // Do not try to recover if it is already building a recovery call.
14897 // This stops infinite loops for template instantiations like
14898 //
14899 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14900 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14901 if (SemaRef.IsBuildingRecoveryCallExpr)
14902 return ExprResult();
14903 BuildRecoveryCallExprRAII RCE(SemaRef);
14904
14905 CXXScopeSpec SS;
14906 SS.Adopt(ULE->getQualifierLoc());
14907 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14908
14909 TemplateArgumentListInfo TABuffer;
14910 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14911 if (ULE->hasExplicitTemplateArgs()) {
14912 ULE->copyTemplateArgumentsInto(TABuffer);
14913 ExplicitTemplateArgs = &TABuffer;
14914 }
14915
14916 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14918 CXXRecordDecl *FoundInClass = nullptr;
14920 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
14921 ResolvedCandidateSet, ExplicitTemplateArgs, Args, &FoundInClass)) {
14922 // OK, diagnosed a two-phase lookup issue.
14923 } else if (ResolvedCandidateSet.empty()) {
14924 // Try to recover from an empty lookup with typo correction.
14925 R.clear();
14926 NoTypoCorrectionCCC NoTypoValidator{};
14927 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14928 ExplicitTemplateArgs != nullptr,
14929 dyn_cast<MemberExpr>(Fn));
14930 CorrectionCandidateCallback &Validator =
14931 AllowTypoCorrection
14932 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14933 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14934 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14935 Args))
14936 return ExprError();
14937 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14938 // We found a usable declaration of the name in a dependent base of some
14939 // enclosing class.
14940 // FIXME: We should also explain why the candidates found by name lookup
14941 // were not viable.
14942 if (SemaRef.DiagnoseDependentMemberLookup(R))
14943 return ExprError();
14944 } else {
14945 // We had viable candidates and couldn't recover; let the caller diagnose
14946 // this.
14947 return ExprResult();
14948 }
14949
14950 // If we get here, we should have issued a diagnostic and formed a recovery
14951 // lookup result.
14952 assert(!R.empty() && "lookup results empty despite recovery");
14953
14954 // If recovery created an ambiguity, just bail out.
14955 if (R.isAmbiguous()) {
14956 R.suppressDiagnostics();
14957 return ExprError();
14958 }
14959
14960 // Build an implicit member call if appropriate. Just drop the
14961 // casts and such from the call, we don't really care.
14962 ExprResult NewFn = ExprError();
14963 if ((*R.begin())->isCXXClassMember())
14964 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14965 ExplicitTemplateArgs, S);
14966 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14967 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14968 ExplicitTemplateArgs);
14969 else
14970 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14971
14972 if (NewFn.isInvalid())
14973 return ExprError();
14974
14975 // This shouldn't cause an infinite loop because we're giving it
14976 // an expression with viable lookup results, which should never
14977 // end up here.
14978 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14979 MultiExprArg(Args.data(), Args.size()),
14980 RParenLoc);
14981}
14982
14985 MultiExprArg Args,
14986 SourceLocation RParenLoc,
14987 OverloadCandidateSet *CandidateSet,
14988 ExprResult *Result) {
14989#ifndef NDEBUG
14990 if (ULE->requiresADL()) {
14991 // To do ADL, we must have found an unqualified name.
14992 assert(!ULE->getQualifier() && "qualified name with ADL");
14993
14994 // We don't perform ADL for implicit declarations of builtins.
14995 // Verify that this was correctly set up.
14996 FunctionDecl *F;
14997 if (ULE->decls_begin() != ULE->decls_end() &&
14998 ULE->decls_begin() + 1 == ULE->decls_end() &&
14999 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
15000 F->getBuiltinID() && F->isImplicit())
15001 llvm_unreachable("performing ADL for builtin");
15002
15003 // We don't perform ADL in C.
15004 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
15005 }
15006#endif
15007
15008 UnbridgedCastsSet UnbridgedCasts;
15009 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15010 *Result = ExprError();
15011 return true;
15012 }
15013
15014 // Add the functions denoted by the callee to the set of candidate
15015 // functions, including those from argument-dependent lookup.
15016 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
15017
15018 if (getLangOpts().MSVCCompat &&
15019 CurContext->isDependentContext() && !isSFINAEContext() &&
15021
15023 if (CandidateSet->empty() ||
15024 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
15026 // In Microsoft mode, if we are inside a template class member function
15027 // then create a type dependent CallExpr. The goal is to postpone name
15028 // lookup to instantiation time to be able to search into type dependent
15029 // base classes.
15030 CallExpr *CE =
15031 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
15032 RParenLoc, CurFPFeatureOverrides());
15034 *Result = CE;
15035 return true;
15036 }
15037 }
15038
15039 if (CandidateSet->empty())
15040 return false;
15041
15042 UnbridgedCasts.restore();
15043 return false;
15044}
15045
15046// Guess at what the return type for an unresolvable overload should be.
15049 std::optional<QualType> Result;
15050 // Adjust Type after seeing a candidate.
15051 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
15052 if (!Candidate.Function)
15053 return;
15054 if (Candidate.Function->isInvalidDecl())
15055 return;
15056 QualType T = Candidate.Function->getReturnType();
15057 if (T.isNull())
15058 return;
15059 if (!Result)
15060 Result = T;
15061 else if (Result != T)
15062 Result = QualType();
15063 };
15064
15065 // Look for an unambiguous type from a progressively larger subset.
15066 // e.g. if types disagree, but all *viable* overloads return int, choose int.
15067 //
15068 // First, consider only the best candidate.
15069 if (Best && *Best != CS.end())
15070 ConsiderCandidate(**Best);
15071 // Next, consider only viable candidates.
15072 if (!Result)
15073 for (const auto &C : CS)
15074 if (C.Viable)
15075 ConsiderCandidate(C);
15076 // Finally, consider all candidates.
15077 if (!Result)
15078 for (const auto &C : CS)
15079 ConsiderCandidate(C);
15080
15081 if (!Result)
15082 return QualType();
15083 auto Value = *Result;
15084 if (Value.isNull() || Value->isUndeducedType())
15085 return QualType();
15086 return Value;
15087}
15088
15089/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
15090/// the completed call expression. If overload resolution fails, emits
15091/// diagnostics and returns ExprError()
15094 SourceLocation LParenLoc,
15095 MultiExprArg Args,
15096 SourceLocation RParenLoc,
15097 Expr *ExecConfig,
15098 OverloadCandidateSet *CandidateSet,
15100 OverloadingResult OverloadResult,
15101 bool AllowTypoCorrection) {
15102 switch (OverloadResult) {
15103 case OR_Success: {
15104 FunctionDecl *FDecl = (*Best)->Function;
15105 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
15106 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
15107 return ExprError();
15108 ExprResult Res =
15109 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15110 if (Res.isInvalid())
15111 return ExprError();
15112 return SemaRef.BuildResolvedCallExpr(
15113 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15114 /*IsExecConfig=*/false,
15115 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15116 }
15117
15118 case OR_No_Viable_Function: {
15119 if (*Best != CandidateSet->end() &&
15120 CandidateSet->getKind() ==
15122 if (CXXMethodDecl *M =
15123 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
15125 CandidateSet->NoteCandidates(
15127 Fn->getBeginLoc(),
15128 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
15129 SemaRef, OCD_AmbiguousCandidates, Args);
15130 return ExprError();
15131 }
15132 }
15133
15134 // Try to recover by looking for viable functions which the user might
15135 // have meant to call.
15136 ExprResult Recovery =
15137 BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15138 *CandidateSet, AllowTypoCorrection);
15139 if (Recovery.isInvalid() || Recovery.isUsable())
15140 return Recovery;
15141
15142 // If the user passes in a function that we can't take the address of, we
15143 // generally end up emitting really bad error messages. Here, we attempt to
15144 // emit better ones.
15145 for (const Expr *Arg : Args) {
15146 if (!Arg->getType()->isFunctionType())
15147 continue;
15148 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
15149 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15150 if (FD &&
15151 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15152 Arg->getExprLoc()))
15153 return ExprError();
15154 }
15155 }
15156
15157 CandidateSet->NoteCandidates(
15159 Fn->getBeginLoc(),
15160 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15161 << ULE->getName() << Fn->getSourceRange()),
15162 SemaRef, OCD_AllCandidates, Args);
15163 break;
15164 }
15165
15166 case OR_Ambiguous:
15167 CandidateSet->NoteCandidates(
15168 PartialDiagnosticAt(Fn->getBeginLoc(),
15169 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15170 << ULE->getName() << Fn->getSourceRange()),
15171 SemaRef, OCD_AmbiguousCandidates, Args);
15172 break;
15173
15174 case OR_Deleted: {
15175 FunctionDecl *FDecl = (*Best)->Function;
15176 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15177 Fn->getSourceRange(), ULE->getName(),
15178 *CandidateSet, FDecl, Args);
15179
15180 // We emitted an error for the unavailable/deleted function call but keep
15181 // the call in the AST.
15182 ExprResult Res =
15183 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15184 if (Res.isInvalid())
15185 return ExprError();
15186 return SemaRef.BuildResolvedCallExpr(
15187 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15188 /*IsExecConfig=*/false,
15189 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15190 }
15191 }
15192
15193 // Overload resolution failed, try to recover.
15194 SmallVector<Expr *, 8> SubExprs = {Fn};
15195 SubExprs.append(Args.begin(), Args.end());
15196 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15197 chooseRecoveryType(*CandidateSet, Best));
15198}
15199
15202 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15203 if (I->Viable &&
15204 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15205 I->Viable = false;
15206 I->FailureKind = ovl_fail_addr_not_available;
15207 }
15208 }
15209}
15210
15213 SourceLocation LParenLoc,
15214 MultiExprArg Args,
15215 SourceLocation RParenLoc,
15216 Expr *ExecConfig,
15217 bool AllowTypoCorrection,
15218 bool CalleesAddressIsTaken) {
15219
15223
15224 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15225 ExprResult result;
15226
15227 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15228 &result))
15229 return result;
15230
15231 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15232 // functions that aren't addressible are considered unviable.
15233 if (CalleesAddressIsTaken)
15234 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15235
15237 OverloadingResult OverloadResult =
15238 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15239
15240 // [C++23][over.call.func]
15241 // if overload resolution selects a non-static member function,
15242 // the call is ill-formed;
15244 Best != CandidateSet.end()) {
15245 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15246 M && M->isImplicitObjectMemberFunction()) {
15247 OverloadResult = OR_No_Viable_Function;
15248 }
15249 }
15250
15251 // Model the case with a call to a templated function whose definition
15252 // encloses the call and whose return type contains a placeholder type as if
15253 // the UnresolvedLookupExpr was type-dependent.
15254 if (OverloadResult == OR_Success) {
15255 const FunctionDecl *FDecl = Best->Function;
15256 if (LangOpts.CUDA)
15257 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15258 if (FDecl && FDecl->isTemplateInstantiation() &&
15259 FDecl->getReturnType()->isUndeducedType()) {
15260
15261 // Creating dependent CallExpr is not okay if the enclosing context itself
15262 // is not dependent. This situation notably arises if a non-dependent
15263 // member function calls the later-defined overloaded static function.
15264 //
15265 // For example, in
15266 // class A {
15267 // void c() { callee(1); }
15268 // static auto callee(auto x) { }
15269 // };
15270 //
15271 // Here callee(1) is unresolved at the call site, but is not inside a
15272 // dependent context. There will be no further attempt to resolve this
15273 // call if it is made dependent.
15274
15275 if (const auto *TP =
15276 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15277 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15278 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15279 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15280 }
15281 }
15282 }
15283
15284 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15285 ExecConfig, &CandidateSet, &Best,
15286 OverloadResult, AllowTypoCorrection);
15287}
15288
15292 const UnresolvedSetImpl &Fns,
15293 bool PerformADL) {
15295 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15296 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15297}
15298
15301 bool HadMultipleCandidates) {
15302 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15303 // the FoundDecl as it impedes TransformMemberExpr.
15304 // We go a bit further here: if there's no difference in UnderlyingDecl,
15305 // then using FoundDecl vs Method shouldn't make a difference either.
15306 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15307 FoundDecl = Method;
15308 // Convert the expression to match the conversion function's implicit object
15309 // parameter.
15310 ExprResult Exp;
15311 if (Method->isExplicitObjectMemberFunction())
15313 else
15315 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15316 if (Exp.isInvalid())
15317 return true;
15318
15319 if (Method->getParent()->isLambda() &&
15320 Method->getConversionType()->isBlockPointerType()) {
15321 // This is a lambda conversion to block pointer; check if the argument
15322 // was a LambdaExpr.
15323 Expr *SubE = E;
15324 auto *CE = dyn_cast<CastExpr>(SubE);
15325 if (CE && CE->getCastKind() == CK_NoOp)
15326 SubE = CE->getSubExpr();
15327 SubE = SubE->IgnoreParens();
15328 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15329 SubE = BE->getSubExpr();
15330 if (isa<LambdaExpr>(SubE)) {
15331 // For the conversion to block pointer on a lambda expression, we
15332 // construct a special BlockLiteral instead; this doesn't really make
15333 // a difference in ARC, but outside of ARC the resulting block literal
15334 // follows the normal lifetime rules for block literals instead of being
15335 // autoreleased.
15339 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15341
15342 // FIXME: This note should be produced by a CodeSynthesisContext.
15343 if (BlockExp.isInvalid())
15344 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15345 return BlockExp;
15346 }
15347 }
15348 CallExpr *CE;
15349 QualType ResultType = Method->getReturnType();
15351 ResultType = ResultType.getNonLValueExprType(Context);
15352 if (Method->isExplicitObjectMemberFunction()) {
15353 ExprResult FnExpr =
15354 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15355 HadMultipleCandidates, E->getBeginLoc());
15356 if (FnExpr.isInvalid())
15357 return ExprError();
15358 Expr *ObjectParam = Exp.get();
15359 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15360 ResultType, VK, Exp.get()->getEndLoc(),
15362 CE->setUsesMemberSyntax(true);
15363 } else {
15364 MemberExpr *ME =
15365 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15367 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15368 HadMultipleCandidates, DeclarationNameInfo(),
15369 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15370
15371 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15372 Exp.get()->getEndLoc(),
15374 }
15375
15376 if (CheckFunctionCall(Method, CE,
15377 Method->getType()->castAs<FunctionProtoType>()))
15378 return ExprError();
15379
15381}
15382
15385 const UnresolvedSetImpl &Fns,
15386 ArrayRef<Expr *> Args, bool PerformADL) {
15387 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15388
15389 SourceLocation OpLoc = CandidateSet.getLocation();
15390 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15391
15392 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15393 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15394 if (PerformADL)
15395 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15396 /*ExplicitTemplateArgs*/ nullptr,
15397 CandidateSet);
15398 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15399}
15400
15403 const UnresolvedSetImpl &Fns,
15404 Expr *Input, bool PerformADL) {
15406 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15407 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15408 // TODO: provide better source location info.
15409 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15410
15411 if (checkPlaceholderForOverload(*this, Input))
15412 return ExprError();
15413
15414 Expr *Args[2] = { Input, nullptr };
15415 unsigned NumArgs = 1;
15416
15417 // For post-increment and post-decrement, add the implicit '0' as
15418 // the second argument, so that we know this is a post-increment or
15419 // post-decrement.
15420 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15421 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15422 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15423 SourceLocation());
15424 NumArgs = 2;
15425 }
15426
15427 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15428
15429 if (Input->isTypeDependent()) {
15431 // [C++26][expr.unary.op][expr.pre.incr]
15432 // The * operator yields an lvalue of type
15433 // The pre/post increment operators yied an lvalue.
15434 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15435 VK = VK_LValue;
15436
15437 if (Fns.empty())
15438 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15439 OK_Ordinary, OpLoc, false,
15441
15442 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15444 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15445 if (Fn.isInvalid())
15446 return ExprError();
15447 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15448 Context.DependentTy, VK_PRValue, OpLoc,
15450 }
15451
15452 // Build an empty overload set.
15454 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, ArgsArray, PerformADL);
15455
15456 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15457
15458 // Perform overload resolution.
15460 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15461 case OR_Success: {
15462 // We found a built-in operator or an overloaded operator.
15463 FunctionDecl *FnDecl = Best->Function;
15464
15465 if (FnDecl) {
15466 Expr *Base = nullptr;
15467 // We matched an overloaded operator. Build a call to that
15468 // operator.
15469
15470 // Convert the arguments.
15471 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15472 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15473
15474 ExprResult InputInit;
15475 if (Method->isExplicitObjectMemberFunction())
15476 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15477 else
15479 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15480 if (InputInit.isInvalid())
15481 return ExprError();
15482 Base = Input = InputInit.get();
15483 } else {
15484 // Convert the arguments.
15485 ExprResult InputInit
15487 Context,
15488 FnDecl->getParamDecl(0)),
15490 Input);
15491 if (InputInit.isInvalid())
15492 return ExprError();
15493 Input = InputInit.get();
15494 }
15495
15496 // Build the actual expression node.
15497 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15498 Base, HadMultipleCandidates,
15499 OpLoc);
15500 if (FnExpr.isInvalid())
15501 return ExprError();
15502
15503 // Determine the result type.
15504 QualType ResultTy = FnDecl->getReturnType();
15506 ResultTy = ResultTy.getNonLValueExprType(Context);
15507
15508 Args[0] = Input;
15510 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15512 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15513
15514 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15515 return ExprError();
15516
15517 if (CheckFunctionCall(FnDecl, TheCall,
15518 FnDecl->getType()->castAs<FunctionProtoType>()))
15519 return ExprError();
15520 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15521 } else {
15522 // We matched a built-in operator. Convert the arguments, then
15523 // break out so that we will build the appropriate built-in
15524 // operator node.
15526 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15529 if (InputRes.isInvalid())
15530 return ExprError();
15531 Input = InputRes.get();
15532 break;
15533 }
15534 }
15535
15537 // This is an erroneous use of an operator which can be overloaded by
15538 // a non-member function. Check for non-member operators which were
15539 // defined too late to be candidates.
15540 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray,
15541 CandidateSet))
15542 // FIXME: Recover by calling the found function.
15543 return ExprError();
15544
15545 // No viable function; fall through to handling this as a
15546 // built-in operator, which will produce an error message for us.
15547 break;
15548
15549 case OR_Ambiguous:
15550 CandidateSet.NoteCandidates(
15551 PartialDiagnosticAt(OpLoc,
15552 PDiag(diag::err_ovl_ambiguous_oper_unary)
15554 << Input->getType() << Input->getSourceRange()),
15555 *this, OCD_AmbiguousCandidates, ArgsArray,
15556 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15557 return ExprError();
15558
15559 case OR_Deleted: {
15560 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15561 // object whose method was called. Later in NoteCandidates size of ArgsArray
15562 // is passed further and it eventually ends up compared to number of
15563 // function candidate parameters which never includes the object parameter,
15564 // so slice ArgsArray to make sure apples are compared to apples.
15565 StringLiteral *Msg = Best->Function->getDeletedMessage();
15566 CandidateSet.NoteCandidates(
15567 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15569 << (Msg != nullptr)
15570 << (Msg ? Msg->getString() : StringRef())
15571 << Input->getSourceRange()),
15572 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15573 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15574 return ExprError();
15575 }
15576 }
15577
15578 // Either we found no viable overloaded operator or we matched a
15579 // built-in operator. In either case, fall through to trying to
15580 // build a built-in operation.
15581 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15582}
15583
15586 const UnresolvedSetImpl &Fns,
15587 ArrayRef<Expr *> Args, bool PerformADL) {
15588 SourceLocation OpLoc = CandidateSet.getLocation();
15589
15590 OverloadedOperatorKind ExtraOp =
15593 : OO_None;
15594
15595 // Add the candidates from the given function set. This also adds the
15596 // rewritten candidates using these functions if necessary.
15597 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15598
15599 // As template candidates are not deduced immediately,
15600 // persist the array in the overload set.
15601 ArrayRef<Expr *> ReversedArgs;
15602 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15603 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15604 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15605
15606 // Add operator candidates that are member functions.
15607 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15608 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15609 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15611
15612 // In C++20, also add any rewritten member candidates.
15613 if (ExtraOp) {
15614 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15615 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15616 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15618 }
15619
15620 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15621 // performed for an assignment operator (nor for operator[] nor operator->,
15622 // which don't get here).
15623 if (Op != OO_Equal && PerformADL) {
15624 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15625 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15626 /*ExplicitTemplateArgs*/ nullptr,
15627 CandidateSet);
15628 if (ExtraOp) {
15629 DeclarationName ExtraOpName =
15630 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15631 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15632 /*ExplicitTemplateArgs*/ nullptr,
15633 CandidateSet);
15634 }
15635 }
15636
15637 // Add builtin operator candidates.
15638 //
15639 // FIXME: We don't add any rewritten candidates here. This is strictly
15640 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15641 // resulting in our selecting a rewritten builtin candidate. For example:
15642 //
15643 // enum class E { e };
15644 // bool operator!=(E, E) requires false;
15645 // bool k = E::e != E::e;
15646 //
15647 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15648 // it seems unreasonable to consider rewritten builtin candidates. A core
15649 // issue has been filed proposing to removed this requirement.
15650 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15651}
15652
15655 const UnresolvedSetImpl &Fns, Expr *LHS,
15656 Expr *RHS, bool PerformADL,
15657 bool AllowRewrittenCandidates,
15658 FunctionDecl *DefaultedFn) {
15659 Expr *Args[2] = { LHS, RHS };
15660 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15661
15662 if (!getLangOpts().CPlusPlus20)
15663 AllowRewrittenCandidates = false;
15664
15666
15667 // If either side is type-dependent, create an appropriate dependent
15668 // expression.
15669 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15670 if (Fns.empty()) {
15671 // If there are no functions to store, just build a dependent
15672 // BinaryOperator or CompoundAssignment.
15675 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15676 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15677 Context.DependentTy);
15679 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15681 }
15682
15683 // FIXME: save results of ADL from here?
15684 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15685 // TODO: provide better source location info in DNLoc component.
15686 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15687 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15689 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15690 if (Fn.isInvalid())
15691 return ExprError();
15692 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15693 Context.DependentTy, VK_PRValue, OpLoc,
15695 }
15696
15697 // If this is the .* operator, which is not overloadable, just
15698 // create a built-in binary operator.
15699 if (Opc == BO_PtrMemD) {
15700 auto CheckPlaceholder = [&](Expr *&Arg) {
15702 if (Res.isUsable())
15703 Arg = Res.get();
15704 return !Res.isUsable();
15705 };
15706
15707 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15708 // expression that contains placeholders (in either the LHS or RHS).
15709 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15710 return ExprError();
15711 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15712 }
15713
15714 // Always do placeholder-like conversions on the RHS.
15715 if (checkPlaceholderForOverload(*this, Args[1]))
15716 return ExprError();
15717
15718 // Do placeholder-like conversion on the LHS; note that we should
15719 // not get here with a PseudoObject LHS.
15720 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15721 if (checkPlaceholderForOverload(*this, Args[0]))
15722 return ExprError();
15723
15724 // If this is the assignment operator, we only perform overload resolution
15725 // if the left-hand side is a class or enumeration type. This is actually
15726 // a hack. The standard requires that we do overload resolution between the
15727 // various built-in candidates, but as DR507 points out, this can lead to
15728 // problems. So we do it this way, which pretty much follows what GCC does.
15729 // Note that we go the traditional code path for compound assignment forms.
15730 // In HLSL, user-defined structs/classes do not have constructors or
15731 // overloadable assignment operators, so we can take this shortcut too.
15732 const Type *LHSTy = Args[0]->getType().getTypePtr();
15733 if (Opc == BO_Assign &&
15734 (!LHSTy->isOverloadableType() ||
15735 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15737 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15738
15739 // Build the overload set.
15742 Op, OpLoc, AllowRewrittenCandidates));
15743 if (DefaultedFn)
15744 CandidateSet.exclude(DefaultedFn);
15745 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15746
15747 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15748
15749 // Perform overload resolution.
15751 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15752 case OR_Success: {
15753 // We found a built-in operator or an overloaded operator.
15754 FunctionDecl *FnDecl = Best->Function;
15755
15756 bool IsReversed = Best->isReversed();
15757 if (IsReversed)
15758 std::swap(Args[0], Args[1]);
15759
15760 if (FnDecl) {
15761
15762 if (FnDecl->isInvalidDecl())
15763 return ExprError();
15764
15765 Expr *Base = nullptr;
15766 // We matched an overloaded operator. Build a call to that
15767 // operator.
15768
15769 OverloadedOperatorKind ChosenOp =
15771
15772 // C++2a [over.match.oper]p9:
15773 // If a rewritten operator== candidate is selected by overload
15774 // resolution for an operator@, its return type shall be cv bool
15775 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15776 !FnDecl->getReturnType()->isBooleanType()) {
15777 bool IsExtension =
15779 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15780 : diag::err_ovl_rewrite_equalequal_not_bool)
15781 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15782 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15783 Diag(FnDecl->getLocation(), diag::note_declared_at);
15784 if (!IsExtension)
15785 return ExprError();
15786 }
15787
15788 if (AllowRewrittenCandidates && !IsReversed &&
15789 CandidateSet.getRewriteInfo().isReversible()) {
15790 // We could have reversed this operator, but didn't. Check if some
15791 // reversed form was a viable candidate, and if so, if it had a
15792 // better conversion for either parameter. If so, this call is
15793 // formally ambiguous, and allowing it is an extension.
15795 for (OverloadCandidate &Cand : CandidateSet) {
15796 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15797 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15798 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15800 *this, OpLoc, Cand.Conversions[ArgIdx],
15801 Best->Conversions[ArgIdx]) ==
15803 AmbiguousWith.push_back(Cand.Function);
15804 break;
15805 }
15806 }
15807 }
15808 }
15809
15810 if (!AmbiguousWith.empty()) {
15811 bool AmbiguousWithSelf =
15812 AmbiguousWith.size() == 1 &&
15813 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15814 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15816 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15817 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15818 if (AmbiguousWithSelf) {
15819 Diag(FnDecl->getLocation(),
15820 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15821 // Mark member== const or provide matching != to disallow reversed
15822 // args. Eg.
15823 // struct S { bool operator==(const S&); };
15824 // S()==S();
15825 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15826 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15827 !MD->isConst() &&
15828 !MD->hasCXXExplicitFunctionObjectParameter() &&
15829 Context.hasSameUnqualifiedType(
15830 MD->getFunctionObjectParameterType(),
15831 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15832 Context.hasSameUnqualifiedType(
15833 MD->getFunctionObjectParameterType(),
15834 Args[0]->getType()) &&
15835 Context.hasSameUnqualifiedType(
15836 MD->getFunctionObjectParameterType(),
15837 Args[1]->getType()))
15838 Diag(FnDecl->getLocation(),
15839 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15840 } else {
15841 Diag(FnDecl->getLocation(),
15842 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15843 for (auto *F : AmbiguousWith)
15844 Diag(F->getLocation(),
15845 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15846 }
15847 }
15848 }
15849
15850 // Check for nonnull = nullable.
15851 // This won't be caught in the arg's initialization: the parameter to
15852 // the assignment operator is not marked nonnull.
15853 if (Op == OO_Equal)
15855 Args[1]->getType(), OpLoc);
15856
15857 // Convert the arguments.
15858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15859 // Best->Access is only meaningful for class members.
15860 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15861
15862 ExprResult Arg0, Arg1;
15863 unsigned ParamIdx = 0;
15864 if (Method->isExplicitObjectMemberFunction()) {
15865 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15866 ParamIdx = 1;
15867 } else {
15869 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15870 }
15873 Context, FnDecl->getParamDecl(ParamIdx)),
15874 SourceLocation(), Args[1]);
15875 if (Arg0.isInvalid() || Arg1.isInvalid())
15876 return ExprError();
15877
15878 Base = Args[0] = Arg0.getAs<Expr>();
15879 Args[1] = RHS = Arg1.getAs<Expr>();
15880 } else {
15881 // Convert the arguments.
15884 FnDecl->getParamDecl(0)),
15885 SourceLocation(), Args[0]);
15886 if (Arg0.isInvalid())
15887 return ExprError();
15888
15889 ExprResult Arg1 =
15892 FnDecl->getParamDecl(1)),
15893 SourceLocation(), Args[1]);
15894 if (Arg1.isInvalid())
15895 return ExprError();
15896 Args[0] = LHS = Arg0.getAs<Expr>();
15897 Args[1] = RHS = Arg1.getAs<Expr>();
15898 }
15899
15900 // Build the actual expression node.
15901 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15902 Best->FoundDecl, Base,
15903 HadMultipleCandidates, OpLoc);
15904 if (FnExpr.isInvalid())
15905 return ExprError();
15906
15907 if (auto *Pattern = FnDecl->getInstantiatedFromMemberFunction();
15908 Pattern && Pattern->getOverloadedOperator() == OO_Spaceship)
15909 Pattern->setIsUsed();
15910
15911 // Determine the result type.
15912 QualType ResultTy = FnDecl->getReturnType();
15914 ResultTy = ResultTy.getNonLValueExprType(Context);
15915
15916 CallExpr *TheCall;
15917 ArrayRef<const Expr *> ArgsArray(Args, 2);
15918 const Expr *ImplicitThis = nullptr;
15919
15920 // We always create a CXXOperatorCallExpr, even for explicit object
15921 // members; CodeGen should take care not to emit the this pointer.
15923 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15925 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15926 IsReversed);
15927
15928 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15929 Method && Method->isImplicitObjectMemberFunction()) {
15930 // Cut off the implicit 'this'.
15931 ImplicitThis = ArgsArray[0];
15932 ArgsArray = ArgsArray.slice(1);
15933 }
15934
15935 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15936 FnDecl))
15937 return ExprError();
15938
15939 if (Op == OO_Equal) {
15940 // Check for a self move.
15941 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15942 // lifetime check.
15944 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15945 Args[1]);
15946 }
15947 if (ImplicitThis) {
15948 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15949 QualType ThisTypeFromDecl = Context.getPointerType(
15950 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15951
15952 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15953 ThisTypeFromDecl);
15954 }
15955
15956 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15957 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15959
15960 ExprResult R = MaybeBindToTemporary(TheCall);
15961 if (R.isInvalid())
15962 return ExprError();
15963
15964 R = CheckForImmediateInvocation(R, FnDecl);
15965 if (R.isInvalid())
15966 return ExprError();
15967
15968 // For a rewritten candidate, we've already reversed the arguments
15969 // if needed. Perform the rest of the rewrite now.
15970 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15971 (Op == OO_Spaceship && IsReversed)) {
15972 if (Op == OO_ExclaimEqual) {
15973 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15974 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15975 } else {
15976 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15977 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15978 Expr *ZeroLiteral =
15980
15983 Ctx.Entity = FnDecl;
15985
15987 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15988 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15989 /*AllowRewrittenCandidates=*/false);
15990
15992 }
15993 if (R.isInvalid())
15994 return ExprError();
15995 } else {
15996 assert(ChosenOp == Op && "unexpected operator name");
15997 }
15998
15999 // Make a note in the AST if we did any rewriting.
16000 if (Best->RewriteKind != CRK_None)
16001 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
16002
16003 return R;
16004 } else {
16005 // We matched a built-in operator. Convert the arguments, then
16006 // break out so that we will build the appropriate built-in
16007 // operator node.
16009 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16012 if (ArgsRes0.isInvalid())
16013 return ExprError();
16014 Args[0] = ArgsRes0.get();
16015
16017 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16020 if (ArgsRes1.isInvalid())
16021 return ExprError();
16022 Args[1] = ArgsRes1.get();
16023 break;
16024 }
16025 }
16026
16027 case OR_No_Viable_Function: {
16028 // C++ [over.match.oper]p9:
16029 // If the operator is the operator , [...] and there are no
16030 // viable functions, then the operator is assumed to be the
16031 // built-in operator and interpreted according to clause 5.
16032 if (Opc == BO_Comma)
16033 break;
16034
16035 // When defaulting an 'operator<=>', we can try to synthesize a three-way
16036 // compare result using '==' and '<'.
16037 if (DefaultedFn && Opc == BO_Cmp) {
16038 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
16039 Args[1], DefaultedFn);
16040 if (E.isInvalid() || E.isUsable())
16041 return E;
16042 }
16043
16044 // For class as left operand for assignment or compound assignment
16045 // operator do not fall through to handling in built-in, but report that
16046 // no overloaded assignment operator found
16048 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
16049 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
16050 Args, OpLoc);
16051 DeferDiagsRAII DDR(*this,
16052 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
16053 if (Args[0]->getType()->isRecordType() &&
16054 Opc >= BO_Assign && Opc <= BO_OrAssign) {
16055 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16057 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16058 if (Args[0]->getType()->isIncompleteType()) {
16059 Diag(OpLoc, diag::note_assign_lhs_incomplete)
16060 << Args[0]->getType()
16061 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16062 }
16063 } else {
16064 // This is an erroneous use of an operator which can be overloaded by
16065 // a non-member function. Check for non-member operators which were
16066 // defined too late to be candidates.
16067 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args,
16068 CandidateSet))
16069 // FIXME: Recover by calling the found function.
16070 return ExprError();
16071
16072 // No viable function; try to create a built-in operation, which will
16073 // produce an error. Then, show the non-viable candidates.
16074 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
16075 }
16076 assert(Result.isInvalid() &&
16077 "C++ binary operator overloading is missing candidates!");
16078 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
16079 return Result;
16080 }
16081
16082 case OR_Ambiguous:
16083 CandidateSet.NoteCandidates(
16084 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16086 << Args[0]->getType()
16087 << Args[1]->getType()
16088 << Args[0]->getSourceRange()
16089 << Args[1]->getSourceRange()),
16091 OpLoc);
16092 return ExprError();
16093
16094 case OR_Deleted: {
16095 if (isImplicitlyDeleted(Best->Function)) {
16096 FunctionDecl *DeletedFD = Best->Function;
16098 DeletedFD->getDefaultedFunctionKind();
16099 if (DFK.isSpecialMember()) {
16100 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
16101 << Args[0]->getType() << DFK.asSpecialMember();
16102 } else {
16103 assert(DFK.isComparison());
16104 Diag(OpLoc, diag::err_ovl_deleted_comparison)
16105 << Args[0]->getType() << DeletedFD;
16106 }
16107
16108 // The user probably meant to call this special member. Just
16109 // explain why it's deleted.
16110 NoteDeletedFunction(DeletedFD);
16111 return ExprError();
16112 }
16113
16114 StringLiteral *Msg = Best->Function->getDeletedMessage();
16115 CandidateSet.NoteCandidates(
16117 OpLoc,
16118 PDiag(diag::err_ovl_deleted_oper)
16119 << getOperatorSpelling(Best->Function->getDeclName()
16120 .getCXXOverloadedOperator())
16121 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
16122 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
16124 OpLoc);
16125 return ExprError();
16126 }
16127 }
16128
16129 // We matched a built-in operator; build it.
16130 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
16131}
16132
16134 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16135 FunctionDecl *DefaultedFn) {
16136 const ComparisonCategoryInfo *Info =
16137 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
16138 // If we're not producing a known comparison category type, we can't
16139 // synthesize a three-way comparison. Let the caller diagnose this.
16140 if (!Info)
16141 return ExprResult((Expr*)nullptr);
16142
16143 // If we ever want to perform this synthesis more generally, we will need to
16144 // apply the temporary materialization conversion to the operands.
16145 assert(LHS->isGLValue() && RHS->isGLValue() &&
16146 "cannot use prvalue expressions more than once");
16147 Expr *OrigLHS = LHS;
16148 Expr *OrigRHS = RHS;
16149
16150 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16151 // each of them multiple times below.
16152 LHS = new (Context)
16153 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16154 LHS->getObjectKind(), LHS);
16155 RHS = new (Context)
16156 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16157 RHS->getObjectKind(), RHS);
16158
16159 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
16160 DefaultedFn);
16161 if (Eq.isInvalid())
16162 return ExprError();
16163
16164 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
16165 true, DefaultedFn);
16166 if (Less.isInvalid())
16167 return ExprError();
16168
16170 if (Info->isPartial()) {
16171 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16172 DefaultedFn);
16173 if (Greater.isInvalid())
16174 return ExprError();
16175 }
16176
16177 // Form the list of comparisons we're going to perform.
16178 struct Comparison {
16181 } Comparisons[4] =
16187 };
16188
16189 int I = Info->isPartial() ? 3 : 2;
16190
16191 // Combine the comparisons with suitable conditional expressions.
16193 for (; I >= 0; --I) {
16194 // Build a reference to the comparison category constant.
16195 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16196 // FIXME: Missing a constant for a comparison category. Diagnose this?
16197 if (!VI)
16198 return ExprResult((Expr*)nullptr);
16199 ExprResult ThisResult =
16201 if (ThisResult.isInvalid())
16202 return ExprError();
16203
16204 // Build a conditional unless this is the final case.
16205 if (Result.get()) {
16206 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16207 ThisResult.get(), Result.get());
16208 if (Result.isInvalid())
16209 return ExprError();
16210 } else {
16211 Result = ThisResult;
16212 }
16213 }
16214
16215 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16216 // bind the OpaqueValueExprs before they're (repeatedly) used.
16217 Expr *SyntacticForm = BinaryOperator::Create(
16218 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16219 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16221 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16222 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16223}
16224
16226 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16227 MultiExprArg Args, SourceLocation LParenLoc) {
16228
16229 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16230 unsigned NumParams = Proto->getNumParams();
16231 unsigned NumArgsSlots =
16232 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16233 // Build the full argument list for the method call (the implicit object
16234 // parameter is placed at the beginning of the list).
16235 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16236 bool IsError = false;
16237 // Initialize the implicit object parameter.
16238 // Check the argument types.
16239 for (unsigned i = 0; i != NumParams; i++) {
16240 Expr *Arg;
16241 if (i < Args.size()) {
16242 Arg = Args[i];
16243 ExprResult InputInit =
16245 S.Context, Method->getParamDecl(i)),
16246 SourceLocation(), Arg);
16247 IsError |= InputInit.isInvalid();
16248 Arg = InputInit.getAs<Expr>();
16249 } else {
16250 ExprResult DefArg =
16251 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16252 if (DefArg.isInvalid()) {
16253 IsError = true;
16254 break;
16255 }
16256 Arg = DefArg.getAs<Expr>();
16257 }
16258
16259 MethodArgs.push_back(Arg);
16260 }
16261 return IsError;
16262}
16263
16265 SourceLocation RLoc,
16266 Expr *Base,
16267 MultiExprArg ArgExpr) {
16269 Args.push_back(Base);
16270 for (auto *e : ArgExpr) {
16271 Args.push_back(e);
16272 }
16273 DeclarationName OpName =
16274 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16275
16276 SourceRange Range = ArgExpr.empty()
16277 ? SourceRange{}
16278 : SourceRange(ArgExpr.front()->getBeginLoc(),
16279 ArgExpr.back()->getEndLoc());
16280
16281 // If either side is type-dependent, create an appropriate dependent
16282 // expression.
16284
16285 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16286 // CHECKME: no 'operator' keyword?
16287 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16288 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16290 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16291 if (Fn.isInvalid())
16292 return ExprError();
16293 // Can't add any actual overloads yet
16294
16295 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16296 Context.DependentTy, VK_PRValue, RLoc,
16298 }
16299
16300 // Handle placeholders
16301 UnbridgedCastsSet UnbridgedCasts;
16302 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16303 return ExprError();
16304 }
16305 // Build an empty overload set.
16307
16308 // Subscript can only be overloaded as a member function.
16309
16310 // Add operator candidates that are member functions.
16311 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16312
16313 // Add builtin operator candidates.
16314 if (Args.size() == 2)
16315 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16316
16317 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16318
16319 // Perform overload resolution.
16321 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16322 case OR_Success: {
16323 // We found a built-in operator or an overloaded operator.
16324 FunctionDecl *FnDecl = Best->Function;
16325
16326 if (FnDecl) {
16327 // We matched an overloaded operator. Build a call to that
16328 // operator.
16329
16330 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16331
16332 // Convert the arguments.
16334 SmallVector<Expr *, 2> MethodArgs;
16335
16336 // Initialize the object parameter.
16337 if (Method->isExplicitObjectMemberFunction()) {
16338 ExprResult Res =
16340 if (Res.isInvalid())
16341 return ExprError();
16342 Args[0] = Res.get();
16343 ArgExpr = Args;
16344 } else {
16346 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16347 if (Arg0.isInvalid())
16348 return ExprError();
16349
16350 MethodArgs.push_back(Arg0.get());
16351 }
16352
16354 *this, MethodArgs, Method, ArgExpr, LLoc);
16355 if (IsError)
16356 return ExprError();
16357
16358 // Build the actual expression node.
16359 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16360 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16361 ExprResult FnExpr =
16362 CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, Base,
16363 HadMultipleCandidates, OpLocInfo);
16364 if (FnExpr.isInvalid())
16365 return ExprError();
16366
16367 // Determine the result type
16368 QualType ResultTy = FnDecl->getReturnType();
16370 ResultTy = ResultTy.getNonLValueExprType(Context);
16371
16373 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16375
16376 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16377 return ExprError();
16378
16379 if (CheckFunctionCall(Method, TheCall,
16380 Method->getType()->castAs<FunctionProtoType>()))
16381 return ExprError();
16382
16384 FnDecl);
16385 } else {
16386 // We matched a built-in operator. Convert the arguments, then
16387 // break out so that we will build the appropriate built-in
16388 // operator node.
16390 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16393 if (ArgsRes0.isInvalid())
16394 return ExprError();
16395 Args[0] = ArgsRes0.get();
16396
16398 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16401 if (ArgsRes1.isInvalid())
16402 return ExprError();
16403 Args[1] = ArgsRes1.get();
16404
16405 break;
16406 }
16407 }
16408
16409 case OR_No_Viable_Function: {
16411 CandidateSet.empty()
16412 ? (PDiag(diag::err_ovl_no_oper)
16413 << Args[0]->getType() << /*subscript*/ 0
16414 << Args[0]->getSourceRange() << Range)
16415 : (PDiag(diag::err_ovl_no_viable_subscript)
16416 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16417 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16418 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16419 return ExprError();
16420 }
16421
16422 case OR_Ambiguous:
16423 if (Args.size() == 2) {
16424 CandidateSet.NoteCandidates(
16426 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16427 << "[]" << Args[0]->getType() << Args[1]->getType()
16428 << Args[0]->getSourceRange() << Range),
16429 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16430 } else {
16431 CandidateSet.NoteCandidates(
16433 PDiag(diag::err_ovl_ambiguous_subscript_call)
16434 << Args[0]->getType()
16435 << Args[0]->getSourceRange() << Range),
16436 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16437 }
16438 return ExprError();
16439
16440 case OR_Deleted: {
16441 StringLiteral *Msg = Best->Function->getDeletedMessage();
16442 CandidateSet.NoteCandidates(
16444 PDiag(diag::err_ovl_deleted_oper)
16445 << "[]" << (Msg != nullptr)
16446 << (Msg ? Msg->getString() : StringRef())
16447 << Args[0]->getSourceRange() << Range),
16448 *this, OCD_AllCandidates, Args, "[]", LLoc);
16449 return ExprError();
16450 }
16451 }
16452
16453 // We matched a built-in operator; build it.
16454 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16455}
16456
16458 SourceLocation LParenLoc,
16459 MultiExprArg Args,
16460 SourceLocation RParenLoc,
16461 Expr *ExecConfig, bool IsExecConfig,
16462 bool AllowRecovery) {
16463 assert(MemExprE->getType() == Context.BoundMemberTy ||
16464 MemExprE->getType() == Context.OverloadTy);
16465
16466 // Dig out the member expression. This holds both the object
16467 // argument and the member function we're referring to.
16468 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16469
16470 // Determine whether this is a call to a pointer-to-member function.
16471 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16472 assert(op->getType() == Context.BoundMemberTy);
16473 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16474
16475 QualType fnType =
16476 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16477
16478 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16479 QualType resultType = proto->getCallResultType(Context);
16481
16482 // Check that the object type isn't more qualified than the
16483 // member function we're calling.
16484 Qualifiers funcQuals = proto->getMethodQuals();
16485
16486 QualType objectType = op->getLHS()->getType();
16487 if (op->getOpcode() == BO_PtrMemI)
16488 objectType = objectType->castAs<PointerType>()->getPointeeType();
16489 Qualifiers objectQuals = objectType.getQualifiers();
16490
16491 Qualifiers difference = objectQuals - funcQuals;
16492 difference.removeObjCGCAttr();
16493 difference.removeAddressSpace();
16494 if (difference) {
16495 std::string qualsString = difference.getAsString();
16496 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16497 << fnType.getUnqualifiedType()
16498 << qualsString
16499 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16500 }
16501
16503 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16505
16506 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16507 call, nullptr))
16508 return ExprError();
16509
16510 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16511 return ExprError();
16512
16513 if (CheckOtherCall(call, proto))
16514 return ExprError();
16515
16516 return MaybeBindToTemporary(call);
16517 }
16518
16519 // We only try to build a recovery expr at this level if we can preserve
16520 // the return type, otherwise we return ExprError() and let the caller
16521 // recover.
16522 auto BuildRecoveryExpr = [&](QualType Type) {
16523 if (!AllowRecovery)
16524 return ExprError();
16525 std::vector<Expr *> SubExprs = {MemExprE};
16526 llvm::append_range(SubExprs, Args);
16527 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16528 Type);
16529 };
16530 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16531 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16532 RParenLoc, CurFPFeatureOverrides());
16533
16534 UnbridgedCastsSet UnbridgedCasts;
16535 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16536 return ExprError();
16537
16538 MemberExpr *MemExpr;
16539 CXXMethodDecl *Method = nullptr;
16540 bool HadMultipleCandidates = false;
16541 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16542 NestedNameSpecifier Qualifier = std::nullopt;
16543 if (isa<MemberExpr>(NakedMemExpr)) {
16544 MemExpr = cast<MemberExpr>(NakedMemExpr);
16546 FoundDecl = MemExpr->getFoundDecl();
16547 Qualifier = MemExpr->getQualifier();
16548 UnbridgedCasts.restore();
16549 } else {
16550 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16551 Qualifier = UnresExpr->getQualifier();
16552
16553 QualType ObjectType = UnresExpr->getBaseType();
16554 Expr::Classification ObjectClassification
16556 : UnresExpr->getBase()->Classify(Context);
16557
16558 // Add overload candidates
16559 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16561
16562 // FIXME: avoid copy.
16563 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16564 if (UnresExpr->hasExplicitTemplateArgs()) {
16565 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16566 TemplateArgs = &TemplateArgsBuffer;
16567 }
16568
16570 E = UnresExpr->decls_end(); I != E; ++I) {
16571
16572 QualType ExplicitObjectType = ObjectType;
16573
16574 NamedDecl *Func = *I;
16575 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16577 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16578
16579 bool HasExplicitParameter = false;
16580 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16581 M && M->hasCXXExplicitFunctionObjectParameter())
16582 HasExplicitParameter = true;
16583 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16584 M &&
16585 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16586 HasExplicitParameter = true;
16587
16588 if (HasExplicitParameter)
16589 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16590
16591 // Microsoft supports direct constructor calls.
16592 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16594 CandidateSet,
16595 /*SuppressUserConversions*/ false);
16596 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16597 // If explicit template arguments were provided, we can't call a
16598 // non-template member function.
16599 if (TemplateArgs)
16600 continue;
16601
16602 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16603 ObjectClassification, Args, CandidateSet,
16604 /*SuppressUserConversions=*/false);
16605 } else {
16607 I.getPair(), ActingDC, TemplateArgs,
16608 ExplicitObjectType, ObjectClassification,
16609 Args, CandidateSet,
16610 /*SuppressUserConversions=*/false);
16611 }
16612 }
16613
16614 HadMultipleCandidates = (CandidateSet.size() > 1);
16615
16616 DeclarationName DeclName = UnresExpr->getMemberName();
16617
16618 UnbridgedCasts.restore();
16619
16621 bool Succeeded = false;
16622 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16623 Best)) {
16624 case OR_Success:
16625 Method = cast<CXXMethodDecl>(Best->Function);
16626 FoundDecl = Best->FoundDecl;
16627 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16628 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16629 break;
16630 // If FoundDecl is different from Method (such as if one is a template
16631 // and the other a specialization), make sure DiagnoseUseOfDecl is
16632 // called on both.
16633 // FIXME: This would be more comprehensively addressed by modifying
16634 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16635 // being used.
16636 if (Method != FoundDecl.getDecl() &&
16638 break;
16639 Succeeded = true;
16640 break;
16641
16643 CandidateSet.NoteCandidates(
16645 UnresExpr->getMemberLoc(),
16646 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16647 << DeclName << MemExprE->getSourceRange()),
16648 *this, OCD_AllCandidates, Args);
16649 break;
16650 case OR_Ambiguous:
16651 CandidateSet.NoteCandidates(
16652 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16653 PDiag(diag::err_ovl_ambiguous_member_call)
16654 << DeclName << MemExprE->getSourceRange()),
16655 *this, OCD_AmbiguousCandidates, Args);
16656 break;
16657 case OR_Deleted:
16659 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16660 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16661 break;
16662 }
16663 // Overload resolution fails, try to recover.
16664 if (!Succeeded)
16665 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16666
16667 ExprResult Res =
16668 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16669 if (Res.isInvalid())
16670 return ExprError();
16671 MemExprE = Res.get();
16672
16673 // If overload resolution picked a static member
16674 // build a non-member call based on that function.
16675 if (Method->isStatic()) {
16676 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16677 ExecConfig, IsExecConfig);
16678 }
16679
16680 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16681 }
16682
16683 QualType ResultType = Method->getReturnType();
16685 ResultType = ResultType.getNonLValueExprType(Context);
16686
16687 assert(Method && "Member call to something that isn't a method?");
16688 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16689
16690 CallExpr *TheCall = nullptr;
16692 if (Method->isExplicitObjectMemberFunction()) {
16693 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16694 NewArgs))
16695 return ExprError();
16696
16697 // FIXME: avoid copy.
16698 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16699 if (MemExpr->hasExplicitTemplateArgs()) {
16700 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16701 TemplateArgs = &TemplateArgsBuffer;
16702 }
16703
16704 // Build the actual expression node.
16706 *this, MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(),
16707 Method, FoundDecl, MemExpr, HadMultipleCandidates,
16708 MemExpr->getMemberNameInfo(), TemplateArgs);
16709 if (FnExpr.isInvalid())
16710 return ExprError();
16711
16712 TheCall =
16713 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16714 CurFPFeatureOverrides(), Proto->getNumParams());
16715 TheCall->setUsesMemberSyntax(true);
16716 } else {
16717 // Convert the object argument (for a non-static member function call).
16719 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16720 if (ObjectArg.isInvalid())
16721 return ExprError();
16722 MemExpr->setBase(ObjectArg.get());
16723 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16724 RParenLoc, CurFPFeatureOverrides(),
16725 Proto->getNumParams());
16726 }
16727
16728 // Check for a valid return type.
16729 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16730 TheCall, Method))
16731 return BuildRecoveryExpr(ResultType);
16732
16733 // Convert the rest of the arguments
16734 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16735 RParenLoc))
16736 return BuildRecoveryExpr(ResultType);
16737
16738 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16739
16740 if (CheckFunctionCall(Method, TheCall, Proto))
16741 return ExprError();
16742
16743 // In the case the method to call was not selected by the overloading
16744 // resolution process, we still need to handle the enable_if attribute. Do
16745 // that here, so it will not hide previous -- and more relevant -- errors.
16746 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16747 if (const EnableIfAttr *Attr =
16748 CheckEnableIf(Method, LParenLoc, Args, true)) {
16749 Diag(MemE->getMemberLoc(),
16750 diag::err_ovl_no_viable_member_function_in_call)
16751 << Method << Method->getSourceRange();
16752 Diag(Method->getLocation(),
16753 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16754 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16755 return ExprError();
16756 }
16757 }
16758
16760 TheCall->getDirectCallee()->isPureVirtual()) {
16761 const FunctionDecl *MD = TheCall->getDirectCallee();
16762
16763 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16765 Diag(MemExpr->getBeginLoc(),
16766 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16768 << MD->getParent();
16769
16770 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16771 if (getLangOpts().AppleKext)
16772 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16773 << MD->getParent() << MD->getDeclName();
16774 }
16775 }
16776
16777 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16778 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16779 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16780 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16781 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16782 MemExpr->getMemberLoc());
16783 }
16784
16786 TheCall->getDirectCallee());
16787}
16788
16791 SourceLocation LParenLoc,
16792 MultiExprArg Args,
16793 SourceLocation RParenLoc) {
16794 if (checkPlaceholderForOverload(*this, Obj))
16795 return ExprError();
16796 ExprResult Object = Obj;
16797
16798 UnbridgedCastsSet UnbridgedCasts;
16799 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16800 return ExprError();
16801
16802 assert(Object.get()->getType()->isRecordType() &&
16803 "Requires object type argument");
16804
16805 // C++ [over.call.object]p1:
16806 // If the primary-expression E in the function call syntax
16807 // evaluates to a class object of type "cv T", then the set of
16808 // candidate functions includes at least the function call
16809 // operators of T. The function call operators of T are obtained by
16810 // ordinary lookup of the name operator() in the context of
16811 // (E).operator().
16812 OverloadCandidateSet CandidateSet(LParenLoc,
16814 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16815
16816 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16817 diag::err_incomplete_object_call, Object.get()))
16818 return true;
16819
16820 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16821 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16823 R.suppressAccessDiagnostics();
16824
16825 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16826 Oper != OperEnd; ++Oper) {
16827 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16828 Object.get()->Classify(Context), Args, CandidateSet,
16829 /*SuppressUserConversion=*/false);
16830 }
16831
16832 // When calling a lambda, both the call operator, and
16833 // the conversion operator to function pointer
16834 // are considered. But when constraint checking
16835 // on the call operator fails, it will also fail on the
16836 // conversion operator as the constraints are always the same.
16837 // As the user probably does not intend to perform a surrogate call,
16838 // we filter them out to produce better error diagnostics, ie to avoid
16839 // showing 2 failed overloads instead of one.
16840 bool IgnoreSurrogateFunctions = false;
16841 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16842 const OverloadCandidate &Candidate = *CandidateSet.begin();
16843 if (!Candidate.Viable &&
16845 IgnoreSurrogateFunctions = true;
16846 }
16847
16848 // C++ [over.call.object]p2:
16849 // In addition, for each (non-explicit in C++0x) conversion function
16850 // declared in T of the form
16851 //
16852 // operator conversion-type-id () cv-qualifier;
16853 //
16854 // where cv-qualifier is the same cv-qualification as, or a
16855 // greater cv-qualification than, cv, and where conversion-type-id
16856 // denotes the type "pointer to function of (P1,...,Pn) returning
16857 // R", or the type "reference to pointer to function of
16858 // (P1,...,Pn) returning R", or the type "reference to function
16859 // of (P1,...,Pn) returning R", a surrogate call function [...]
16860 // is also considered as a candidate function. Similarly,
16861 // surrogate call functions are added to the set of candidate
16862 // functions for each conversion function declared in an
16863 // accessible base class provided the function is not hidden
16864 // within T by another intervening declaration.
16865 const auto &Conversions = Record->getVisibleConversionFunctions();
16866 for (auto I = Conversions.begin(), E = Conversions.end();
16867 !IgnoreSurrogateFunctions && I != E; ++I) {
16868 NamedDecl *D = *I;
16869 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16870 if (isa<UsingShadowDecl>(D))
16871 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16872
16873 // Skip over templated conversion functions; they aren't
16874 // surrogates.
16876 continue;
16877
16879 if (!Conv->isExplicit()) {
16880 // Strip the reference type (if any) and then the pointer type (if
16881 // any) to get down to what might be a function type.
16882 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16883 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16884 ConvType = ConvPtrType->getPointeeType();
16885
16886 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16887 {
16888 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16889 Object.get(), Args, CandidateSet);
16890 }
16891 }
16892 }
16893
16894 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16895
16896 // Perform overload resolution.
16898 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16899 Best)) {
16900 case OR_Success:
16901 // Overload resolution succeeded; we'll build the appropriate call
16902 // below.
16903 break;
16904
16905 case OR_No_Viable_Function: {
16907 CandidateSet.empty()
16908 ? (PDiag(diag::err_ovl_no_oper)
16909 << Object.get()->getType() << /*call*/ 1
16910 << Object.get()->getSourceRange())
16911 : (PDiag(diag::err_ovl_no_viable_object_call)
16912 << Object.get()->getType() << Object.get()->getSourceRange());
16913 CandidateSet.NoteCandidates(
16914 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16915 OCD_AllCandidates, Args);
16916 break;
16917 }
16918 case OR_Ambiguous:
16919 if (!R.isAmbiguous())
16920 CandidateSet.NoteCandidates(
16921 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16922 PDiag(diag::err_ovl_ambiguous_object_call)
16923 << Object.get()->getType()
16924 << Object.get()->getSourceRange()),
16925 *this, OCD_AmbiguousCandidates, Args);
16926 break;
16927
16928 case OR_Deleted: {
16929 // FIXME: Is this diagnostic here really necessary? It seems that
16930 // 1. we don't have any tests for this diagnostic, and
16931 // 2. we already issue err_deleted_function_use for this later on anyway.
16932 StringLiteral *Msg = Best->Function->getDeletedMessage();
16933 CandidateSet.NoteCandidates(
16934 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16935 PDiag(diag::err_ovl_deleted_object_call)
16936 << Object.get()->getType() << (Msg != nullptr)
16937 << (Msg ? Msg->getString() : StringRef())
16938 << Object.get()->getSourceRange()),
16939 *this, OCD_AllCandidates, Args);
16940 break;
16941 }
16942 }
16943
16944 if (Best == CandidateSet.end())
16945 return true;
16946
16947 UnbridgedCasts.restore();
16948
16949 if (Best->Function == nullptr) {
16950 // Since there is no function declaration, this is one of the
16951 // surrogate candidates. Dig out the conversion function.
16952 CXXConversionDecl *Conv
16954 Best->Conversions[0].UserDefined.ConversionFunction);
16955
16956 // FoundDecl may be a UsingShadowDecl naming the conversion function.
16957 assert(Conv == Best->FoundDecl.getDecl()->getUnderlyingDecl() &&
16958 "Found Decl & conversion-to-functionptr should be same, right?!");
16959 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16960 Best->FoundDecl);
16961 if (DiagnoseUseOfDecl(Conv, LParenLoc))
16962 return ExprError();
16963 // We selected one of the surrogate functions that converts the
16964 // object parameter to a function pointer. Perform the conversion
16965 // on the object argument, then let BuildCallExpr finish the job.
16966
16967 // Create an implicit member expr to refer to the conversion operator.
16968 // and then call it.
16969 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16970 Conv, HadMultipleCandidates);
16971 if (Call.isInvalid())
16972 return ExprError();
16973 // Record usage of conversion in an implicit cast.
16975 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16976 nullptr, VK_PRValue, CurFPFeatureOverrides());
16977
16978 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16979 }
16980
16981 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16982
16983 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16984 // that calls this method, using Object for the implicit object
16985 // parameter and passing along the remaining arguments.
16986 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16987
16988 // An error diagnostic has already been printed when parsing the declaration.
16989 if (Method->isInvalidDecl())
16990 return ExprError();
16991
16992 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16993 unsigned NumParams = Proto->getNumParams();
16994
16995 DeclarationNameInfo OpLocInfo(
16996 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16997 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16998 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, Obj,
16999 HadMultipleCandidates, OpLocInfo);
17000 if (NewFn.isInvalid())
17001 return true;
17002
17003 SmallVector<Expr *, 8> MethodArgs;
17004 MethodArgs.reserve(NumParams + 1);
17005
17006 bool IsError = false;
17007
17008 // Initialize the object parameter.
17010 if (Method->isExplicitObjectMemberFunction()) {
17011 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
17012 } else {
17014 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17015 if (ObjRes.isInvalid())
17016 IsError = true;
17017 else
17018 Object = ObjRes;
17019 MethodArgs.push_back(Object.get());
17020 }
17021
17023 *this, MethodArgs, Method, Args, LParenLoc);
17024
17025 // If this is a variadic call, handle args passed through "...".
17026 if (Proto->isVariadic()) {
17027 // Promote the arguments (C99 6.5.2.2p7).
17028 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
17030 Args[i], VariadicCallType::Method, nullptr);
17031 IsError |= Arg.isInvalid();
17032 MethodArgs.push_back(Arg.get());
17033 }
17034 }
17035
17036 if (IsError)
17037 return true;
17038
17039 DiagnoseSentinelCalls(Method, LParenLoc, Args);
17040
17041 // Once we've built TheCall, all of the expressions are properly owned.
17042 QualType ResultTy = Method->getReturnType();
17044 ResultTy = ResultTy.getNonLValueExprType(Context);
17045
17047 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
17049
17050 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
17051 return true;
17052
17053 if (CheckFunctionCall(Method, TheCall, Proto))
17054 return true;
17055
17057}
17058
17060 SourceLocation OpLoc,
17061 bool *NoArrowOperatorFound) {
17062 assert(Base->getType()->isRecordType() &&
17063 "left-hand side must have class type");
17064
17066 return ExprError();
17067
17068 SourceLocation Loc = Base->getExprLoc();
17069
17070 // C++ [over.ref]p1:
17071 //
17072 // [...] An expression x->m is interpreted as (x.operator->())->m
17073 // for a class object x of type T if T::operator->() exists and if
17074 // the operator is selected as the best match function by the
17075 // overload resolution mechanism (13.3).
17076 DeclarationName OpName =
17077 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
17079
17080 if (RequireCompleteType(Loc, Base->getType(),
17081 diag::err_typecheck_incomplete_tag, Base))
17082 return ExprError();
17083
17084 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
17085 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
17086 R.suppressAccessDiagnostics();
17087
17088 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
17089 Oper != OperEnd; ++Oper) {
17090 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
17091 {}, CandidateSet,
17092 /*SuppressUserConversion=*/false);
17093 }
17094
17095 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17096
17097 // Perform overload resolution.
17099 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
17100 case OR_Success:
17101 // Overload resolution succeeded; we'll build the call below.
17102 break;
17103
17104 case OR_No_Viable_Function: {
17105 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
17106 if (CandidateSet.empty()) {
17107 QualType BaseType = Base->getType();
17108 if (NoArrowOperatorFound) {
17109 // Report this specific error to the caller instead of emitting a
17110 // diagnostic, as requested.
17111 *NoArrowOperatorFound = true;
17112 return ExprError();
17113 }
17114 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
17115 << BaseType << Base->getSourceRange();
17116 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
17117 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
17118 << FixItHint::CreateReplacement(OpLoc, ".");
17119 }
17120 } else
17121 Diag(OpLoc, diag::err_ovl_no_viable_oper)
17122 << "operator->" << Base->getSourceRange();
17123 CandidateSet.NoteCandidates(*this, Base, Cands);
17124 return ExprError();
17125 }
17126 case OR_Ambiguous:
17127 if (!R.isAmbiguous())
17128 CandidateSet.NoteCandidates(
17129 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
17130 << "->" << Base->getType()
17131 << Base->getSourceRange()),
17133 return ExprError();
17134
17135 case OR_Deleted: {
17136 StringLiteral *Msg = Best->Function->getDeletedMessage();
17137 CandidateSet.NoteCandidates(
17138 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
17139 << "->" << (Msg != nullptr)
17140 << (Msg ? Msg->getString() : StringRef())
17141 << Base->getSourceRange()),
17142 *this, OCD_AllCandidates, Base);
17143 return ExprError();
17144 }
17145 }
17146
17147 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
17148
17149 // Convert the object parameter.
17150 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
17151
17152 if (Method->isExplicitObjectMemberFunction()) {
17154 if (R.isInvalid())
17155 return ExprError();
17156 Base = R.get();
17157 } else {
17159 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17160 if (BaseResult.isInvalid())
17161 return ExprError();
17162 Base = BaseResult.get();
17163 }
17164
17165 // Build the operator call.
17166 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
17167 Base, HadMultipleCandidates, OpLoc);
17168 if (FnExpr.isInvalid())
17169 return ExprError();
17170
17171 QualType ResultTy = Method->getReturnType();
17173 ResultTy = ResultTy.getNonLValueExprType(Context);
17174
17175 CallExpr *TheCall =
17176 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17177 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17178
17179 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17180 return ExprError();
17181
17182 if (CheckFunctionCall(Method, TheCall,
17183 Method->getType()->castAs<FunctionProtoType>()))
17184 return ExprError();
17185
17187}
17188
17190 DeclarationNameInfo &SuffixInfo,
17191 ArrayRef<Expr*> Args,
17192 SourceLocation LitEndLoc,
17193 TemplateArgumentListInfo *TemplateArgs) {
17194 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17195
17196 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17198 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17199 TemplateArgs);
17200
17201 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17202
17203 // Perform overload resolution. This will usually be trivial, but might need
17204 // to perform substitutions for a literal operator template.
17206 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17207 case OR_Success:
17208 case OR_Deleted:
17209 break;
17210
17212 CandidateSet.NoteCandidates(
17213 PartialDiagnosticAt(UDSuffixLoc,
17214 PDiag(diag::err_ovl_no_viable_function_in_call)
17215 << R.getLookupName()),
17216 *this, OCD_AllCandidates, Args);
17217 return ExprError();
17218
17219 case OR_Ambiguous:
17220 CandidateSet.NoteCandidates(
17221 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17222 << R.getLookupName()),
17223 *this, OCD_AmbiguousCandidates, Args);
17224 return ExprError();
17225 }
17226
17227 FunctionDecl *FD = Best->Function;
17228 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, nullptr,
17229 HadMultipleCandidates, SuffixInfo);
17230 if (Fn.isInvalid())
17231 return true;
17232
17233 // Check the argument types. This should almost always be a no-op, except
17234 // that array-to-pointer decay is applied to string literals.
17235 Expr *ConvArgs[2];
17236 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17239 SourceLocation(), Args[ArgIdx]);
17240 if (InputInit.isInvalid())
17241 return true;
17242 ConvArgs[ArgIdx] = InputInit.get();
17243 }
17244
17245 QualType ResultTy = FD->getReturnType();
17247 ResultTy = ResultTy.getNonLValueExprType(Context);
17248
17250 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17251 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17252
17253 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17254 return ExprError();
17255
17256 if (CheckFunctionCall(FD, UDL, nullptr))
17257 return ExprError();
17258
17260}
17261
17264 SourceLocation RangeLoc,
17265 const DeclarationNameInfo &NameInfo,
17266 LookupResult &MemberLookup,
17267 OverloadCandidateSet *CandidateSet,
17268 Expr *Range, ExprResult *CallExpr) {
17269 Scope *S = nullptr;
17270
17272 if (!MemberLookup.empty()) {
17273 ExprResult MemberRef =
17274 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17275 /*IsPtr=*/false, CXXScopeSpec(),
17276 /*TemplateKWLoc=*/SourceLocation(),
17277 /*FirstQualifierInScope=*/nullptr,
17278 MemberLookup,
17279 /*TemplateArgs=*/nullptr, S);
17280 if (MemberRef.isInvalid()) {
17281 *CallExpr = ExprError();
17282 return FRS_DiagnosticIssued;
17283 }
17284 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17285 if (CallExpr->isInvalid()) {
17286 *CallExpr = ExprError();
17287 return FRS_DiagnosticIssued;
17288 }
17289 } else {
17290 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17292 NameInfo, UnresolvedSet<0>());
17293 if (FnR.isInvalid())
17294 return FRS_DiagnosticIssued;
17296
17297 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17298 CandidateSet, CallExpr);
17299 if (CandidateSet->empty() || CandidateSetError) {
17300 *CallExpr = ExprError();
17301 return FRS_NoViableFunction;
17302 }
17304 OverloadingResult OverloadResult =
17305 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17306
17307 if (OverloadResult == OR_No_Viable_Function) {
17308 *CallExpr = ExprError();
17309 return FRS_NoViableFunction;
17310 }
17311 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17312 Loc, nullptr, CandidateSet, &Best,
17313 OverloadResult,
17314 /*AllowTypoCorrection=*/false);
17315 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17316 *CallExpr = ExprError();
17317 return FRS_DiagnosticIssued;
17318 }
17319 }
17320 return FRS_Success;
17321}
17322
17324 FunctionDecl *Fn) {
17325 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17326 ExprResult SubExpr =
17327 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17328 if (SubExpr.isInvalid())
17329 return ExprError();
17330 if (SubExpr.get() == PE->getSubExpr())
17331 return PE;
17332
17333 return new (Context)
17334 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17335 }
17336
17337 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17338 ExprResult SubExpr =
17339 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17340 if (SubExpr.isInvalid())
17341 return ExprError();
17342 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17343 SubExpr.get()->getType()) &&
17344 "Implicit cast type cannot be determined from overload");
17345 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17346 if (SubExpr.get() == ICE->getSubExpr())
17347 return ICE;
17348
17349 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17350 SubExpr.get(), nullptr, ICE->getValueKind(),
17352 }
17353
17354 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17355 if (!GSE->isResultDependent()) {
17356 ExprResult SubExpr =
17357 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17358 if (SubExpr.isInvalid())
17359 return ExprError();
17360 if (SubExpr.get() == GSE->getResultExpr())
17361 return GSE;
17362
17363 // Replace the resulting type information before rebuilding the generic
17364 // selection expression.
17365 ArrayRef<Expr *> A = GSE->getAssocExprs();
17366 SmallVector<Expr *, 4> AssocExprs(A);
17367 unsigned ResultIdx = GSE->getResultIndex();
17368 AssocExprs[ResultIdx] = SubExpr.get();
17369
17370 if (GSE->isExprPredicate())
17372 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17373 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17374 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17375 ResultIdx);
17377 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17378 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17379 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17380 ResultIdx);
17381 }
17382 // Rather than fall through to the unreachable, return the original generic
17383 // selection expression.
17384 return GSE;
17385 }
17386
17387 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17388 assert(UnOp->getOpcode() == UO_AddrOf &&
17389 "Can only take the address of an overloaded function");
17390 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17391 if (!Method->isImplicitObjectMemberFunction()) {
17392 // Do nothing: the address of static and
17393 // explicit object member functions is a (non-member) function pointer.
17394 } else {
17395 // Fix the subexpression, which really has to be an
17396 // UnresolvedLookupExpr holding an overloaded member function
17397 // or template.
17398 ExprResult SubExpr =
17399 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17400 if (SubExpr.isInvalid())
17401 return ExprError();
17402 if (SubExpr.get() == UnOp->getSubExpr())
17403 return UnOp;
17404
17405 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17406 SubExpr.get(), Method))
17407 return ExprError();
17408
17409 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17410 "fixed to something other than a decl ref");
17411 NestedNameSpecifier Qualifier =
17412 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17413 assert(Qualifier &&
17414 "fixed to a member ref with no nested name qualifier");
17415
17416 // We have taken the address of a pointer to member
17417 // function. Perform the computation here so that we get the
17418 // appropriate pointer to member type.
17419 QualType MemPtrType = Context.getMemberPointerType(
17420 Fn->getType(), Qualifier,
17421 cast<CXXRecordDecl>(Method->getDeclContext()));
17422 // Under the MS ABI, lock down the inheritance model now.
17423 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17424 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17425
17426 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17427 MemPtrType, VK_PRValue, OK_Ordinary,
17428 UnOp->getOperatorLoc(), false,
17430 }
17431 }
17432 ExprResult SubExpr =
17433 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17434 if (SubExpr.isInvalid())
17435 return ExprError();
17436 if (SubExpr.get() == UnOp->getSubExpr())
17437 return UnOp;
17438
17439 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17440 SubExpr.get());
17441 }
17442
17443 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17444 if (Found.getAccess() == AS_none) {
17446 }
17447 // FIXME: avoid copy.
17448 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17449 if (ULE->hasExplicitTemplateArgs()) {
17450 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17451 TemplateArgs = &TemplateArgsBuffer;
17452 }
17453
17454 QualType Type = Fn->getType();
17455 ExprValueKind ValueKind =
17456 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17457 ? VK_LValue
17458 : VK_PRValue;
17459
17460 // FIXME: Duplicated from BuildDeclarationNameExpr.
17461 if (unsigned BID = Fn->getBuiltinID()) {
17462 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17463 Type = Context.BuiltinFnTy;
17464 ValueKind = VK_PRValue;
17465 }
17466 }
17467
17469 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17470 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17471 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17472 return DRE;
17473 }
17474
17475 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17476 // FIXME: avoid copy.
17477 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17478 if (MemExpr->hasExplicitTemplateArgs()) {
17479 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17480 TemplateArgs = &TemplateArgsBuffer;
17481 }
17482
17483 Expr *Base;
17484
17485 // If we're filling in a static method where we used to have an
17486 // implicit member access, rewrite to a simple decl ref.
17487 if (MemExpr->isImplicitAccess()) {
17488 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17490 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17491 MemExpr->getQualifierLoc(), Found.getDecl(),
17492 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17493 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17494 return DRE;
17495 } else {
17496 SourceLocation Loc = MemExpr->getMemberLoc();
17497 if (MemExpr->getQualifier())
17498 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17499 Base =
17500 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17501 }
17502 } else
17503 Base = MemExpr->getBase();
17504
17505 ExprValueKind valueKind;
17506 QualType type;
17507 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17508 valueKind = VK_LValue;
17509 type = Fn->getType();
17510 } else {
17511 valueKind = VK_PRValue;
17512 type = Context.BoundMemberTy;
17513 }
17514
17515 return BuildMemberExpr(
17516 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17517 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17518 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17519 type, valueKind, OK_Ordinary, TemplateArgs);
17520 }
17521
17522 llvm_unreachable("Invalid reference to overloaded function");
17523}
17524
17530
17531bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17533 if (!PartialOverloading || !Function)
17534 return true;
17535 if (Function->isVariadic())
17536 return false;
17537 if (const auto *Proto =
17538 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17539 if (Proto->isTemplateVariadic())
17540 return false;
17541 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17542 if (const auto *Proto =
17543 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17544 if (Proto->isTemplateVariadic())
17545 return false;
17546 return true;
17547}
17548
17550 DeclarationName Name,
17551 OverloadCandidateSet &CandidateSet,
17552 FunctionDecl *Fn, MultiExprArg Args,
17553 bool IsMember) {
17554 StringLiteral *Msg = Fn->getDeletedMessage();
17555 CandidateSet.NoteCandidates(
17556 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17557 << IsMember << Name << (Msg != nullptr)
17558 << (Msg ? Msg->getString() : StringRef())
17559 << Range),
17560 *this, OCD_AllCandidates, Args);
17561}
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 AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:33
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:51
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
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 void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress, TemplateSpecCandidateSetKind CandidateSetKind=TemplateSpecCandidateSetKind::Normal)
Diagnose a failed template-argument deduction.
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 IsHLSLPackedTypeConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &DimensionICK, Expr *From)
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 bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, const OverloadCandidateSet &ResolvedCandidateSet)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
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 ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, const OverloadCandidateSet &ResolvedCandidateSet, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
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 bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, const OverloadCandidateSet &ResolvedCandidates, 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 void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
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 ExprResult CreateFunctionRefExpr(Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
A convenience routine for creating a decayed reference to a function.
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 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 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 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)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool isAbsent() const
Definition APValue.h:545
bool isFloat() const
Definition APValue.h:550
bool isInt() const
Definition APValue.h:549
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
APFloat & getFloat()
Definition APValue.h:587
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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:856
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
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
CanQualType MetaInfoTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:972
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:971
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:3990
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:401
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8394
Attr - This represents one attribute.
Definition Attr.h:47
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2217
StringRef getOpcodeStr() const
Definition Expr.h:4173
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2170
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:5144
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
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:2645
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3106
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2985
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3017
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3021
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
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:724
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
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:654
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:1028
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1989
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1569
bool hasDefinition() const
Definition DeclCXX.h:562
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:291
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
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:3012
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:1549
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3176
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3394
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:3362
QualType getElementType() const
Definition TypeBase.h:3372
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:5166
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4644
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4641
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:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
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:1315
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:1508
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
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:582
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
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:597
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
AccessSpecifier getAccess() const
Definition DeclBase.h:516
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:578
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:573
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
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:833
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:857
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:818
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:803
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:794
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:630
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4162
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4380
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4278
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1973
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1957
const Expr * getExpr() const
Definition DeclCXX.h:1958
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2370
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1496
The return type of classify().
Definition Expr.h:341
bool isLValue() const
Definition Expr.h:392
bool isPRValue() const
Definition Expr.h:395
bool isXValue() const
Definition Expr.h:393
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:400
bool isRValue() const
Definition Expr.h:396
This represents one expression.
Definition Expr.h:114
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:289
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool EvaluateAsMandatedConstantExpr(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required by the language to be a constant expression.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3378
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:876
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:880
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:456
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:856
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:4110
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:417
QualType getType() const
Definition Expr.h:146
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:528
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:439
ExtVectorType - Extended vector type.
Definition TypeBase.h:4497
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3311
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:140
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:103
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2135
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2164
Represents a function declaration or definition.
Definition Decl.h:2071
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2832
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2944
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4267
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4255
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3822
param_iterator param_end()
Definition Decl.h:2930
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3726
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3930
QualType getReturnType() const
Definition Decl.h:2992
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2917
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:4326
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4375
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3807
param_iterator param_begin()
Definition Decl.h:2929
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3137
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4391
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4319
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3934
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2609
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4192
bool isConsteval() const
Definition Decl.h:2621
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3770
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3304
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:3009
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:3775
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4227
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3886
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2828
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:6052
unsigned getNumParams() const
Definition TypeBase.h:5826
Qualifiers getMethodQuals() const
Definition TypeBase.h:5974
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5988
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:4855
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4926
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4783
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
ExtInfo getExtInfo() const
Definition TypeBase.h:5100
CallingConv getCallConv() const
Definition TypeBase.h:5099
QualType getReturnType() const
Definition TypeBase.h:5084
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:5112
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:4765
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:3922
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:626
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:677
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:774
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:681
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:831
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:685
bool hasInitializerListContainerType() const
Definition Overload.h:813
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:738
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:820
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:689
QualType getInitializerListContainerType() const
Definition Overload.h:823
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5377
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5504
bool hasOneInit() const
Whether getNumInitsWithEmbedExpanded() is 1, without walking the list.
Definition Expr.h:5425
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2535
bool hasZeroInits() const
Definition Expr.h:5422
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5414
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2553
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
Describes an entity that is being initialized.
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
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:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
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:4586
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3622
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3544
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding the member name, if any.
Definition Expr.h:3550
NestedNameSpecifierLoc getQualifierLoc() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name,...
Definition Expr.h:3535
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
bool hasExplicitTemplateArgs() const
Determines whether the member name was followed by an explicit template argument list.
Definition Expr.h:3577
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3530
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:3581
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3651
Expr * getBase() const
Definition Expr.h:3510
void setBase(Expr *E)
Definition Expr.h:3509
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1830
DeclarationNameInfo getMemberNameInfo() const
Retrieve the member declaration name info.
Definition Expr.h:3610
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3520
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3783
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5845
QualType getPointeeType() const
Definition TypeBase.h:3769
Describes a module or submodule.
Definition Module.h:340
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:242
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1209
Represent a C++ namespace.
Definition Decl.h:594
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>::".
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8163
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8219
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8308
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8277
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8231
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8271
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2011
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8283
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1164
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:1364
bool shouldDeferTemplateArgumentDeduction(const Sema &S) const
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1466
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1400
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:1416
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1354
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1189
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1185
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1180
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1175
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1194
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
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:1372
SourceLocation getLocation() const
Definition Overload.h:1352
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1431
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1353
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1391
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:3143
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3295
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3204
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3259
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3256
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3234
decls_iterator decls_begin() const
Definition ExprCXX.h:3236
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3247
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3269
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3265
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3325
decls_iterator decls_end() const
Definition ExprCXX.h:3239
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3253
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
Represents a parameter to a function.
Definition Decl.h:1832
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3064
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5238
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8656
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8667
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3825
QualType withConst() const
Definition TypeBase.h:1175
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
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:8763
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8732
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8699
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8624
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8743
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8610
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8518
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8525
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4982
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:854
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:861
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
GC getObjCGCAttr() const
Definition TypeBase.h:520
bool hasOnlyConst() const
Definition TypeBase.h:459
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasConst() const
Definition TypeBase.h:458
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasRestrict() const
Definition TypeBase.h:478
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
void removeObjCGCAttr()
Definition TypeBase.h:524
void removeUnaligned()
Definition TypeBase.h:516
void removeAddressSpace()
Definition TypeBase.h:597
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
bool hasVolatile() const
Definition TypeBase.h:468
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
void removeVolatile()
Definition TypeBase.h:470
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:572
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:751
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
Represents a struct/union/class.
Definition Decl.h:4476
field_range fields() const
Definition Decl.h:4679
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4664
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
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:1710
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1762
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
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:196
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
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:463
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:400
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:410
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:312
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:10498
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.
RAII class to control scope of DeferDiags.
Definition Sema.h:10221
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1411
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1446
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:12686
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12720
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
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:1473
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:10239
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:9507
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9534
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9519
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9515
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:419
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:169
ExprResult 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:1498
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:10581
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10584
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10590
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10588
@ AR_dependent
Definition Sema.h:1717
@ AR_accessible
Definition Sema.h:1715
@ AR_inaccessible
Definition Sema.h:1716
@ AR_delayed
Definition Sema.h:1718
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:2106
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:1779
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:1331
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:698
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:229
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:931
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:1543
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:769
ASTContext & getASTContext() const
Definition Sema.h:934
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:774
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
@ FRS_Success
Definition Sema.h:10969
@ FRS_DiagnosticIssued
Definition Sema.h:10971
@ FRS_NoViableFunction
Definition Sema.h:10970
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9500
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:10290
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:1235
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:3756
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:12384
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:278
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:927
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:1329
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:1508
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9499
MemberPointerConversionDirection
Definition Sema.h:10422
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:10609
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:649
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:15810
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:10035
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:7130
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:1471
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:8343
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:14219
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:7627
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:13940
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:15765
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:128
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:6893
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6862
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.
MultiExprArg getInitsWithEmbedExpanded(InitListExpr *ILE, SmallVectorImpl< Expr * > &Storage)
The initializers of ILE with each multi-element EmbedExpr split into one EmbedExpr per embedded eleme...
MemberPointerConversionResult
Definition Sema.h:10414
SourceManager & SourceMgr
Definition Sema.h:1334
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1333
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:525
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:6570
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:1478
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:8823
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:301
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:395
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:360
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:312
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:306
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:365
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:342
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:327
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:394
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:337
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:370
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:321
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false, bool AllowRelaxedEval=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:332
void setToType(unsigned Idx, QualType T)
Definition Overload.h:399
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:387
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:352
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:317
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:356
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:347
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:377
QualType getToType(unsigned Idx) const
Definition Overload.h:414
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:1844
StringRef getString() const
Definition Expr.h:1912
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:686
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:728
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:713
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.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3689
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isObjCBuiltinType() const
Definition TypeBase.h:9045
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
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:2122
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:920
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isFloat16Type() const
Definition TypeBase.h:9213
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:857
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
bool isRValueReferenceType() const
Definition TypeBase.h:8847
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:8918
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9371
bool isArrayType() const
Definition TypeBase.h:8914
bool isCharType() const
Definition Type.cpp:2319
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9276
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2550
bool isPointerType() const
Definition TypeBase.h:8815
bool isArrayParameterType() const
Definition TypeBase.h:8930
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2795
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2282
bool isObjCQualifiedIdType() const
Definition TypeBase.h:9015
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2355
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:9002
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2871
bool isLValueReferenceType() const
Definition TypeBase.h:8843
bool isBitIntType() const
Definition TypeBase.h:9090
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2631
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9264
bool isHalfType() const
Definition TypeBase.h:9208
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9182
bool isQueueT() const
Definition TypeBase.h:9071
bool isMemberPointerType() const
Definition TypeBase.h:8896
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9354
bool isObjCIdType() const
Definition TypeBase.h:9027
bool isMatrixType() const
Definition TypeBase.h:8978
bool isOverflowBehaviorType() const
Definition TypeBase.h:8986
bool isHLSLBuiltinPackedType() const
Definition TypeBase.h:9145
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:9063
bool isMetaInfoType() const
Definition TypeBase.h:9204
bool isBFloat16Type() const
Definition TypeBase.h:9225
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
bool isVectorType() const
Definition TypeBase.h:8954
bool isObjCClassType() const
Definition TypeBase.h:9033
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2816
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9157
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:2460
bool isAnyPointerType() const
Definition TypeBase.h:8823
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:9059
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:868
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1462
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:5201
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1438
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3373
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3442
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:464
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4180
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4288
QualType getBaseType() const
Definition ExprCXX.h:4262
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4272
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4253
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4298
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4292
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:645
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:998
QualType getType() const
Definition Decl.h:725
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:276
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...
Top level wrappers for InstallAPI frontend operations.
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:816
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:827
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:823
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:819
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:65
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
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:863
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:891
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:900
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:883
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:887
@ 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:928
@ ovl_fail_too_few_arguments
Definition Overload.h:865
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:907
@ ovl_fail_too_many_arguments
Definition Overload.h:864
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:915
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:924
@ ovl_fail_bad_conversion
Definition Overload.h:866
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:896
@ ovl_fail_bad_deduction
Definition Overload.h:867
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:911
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:920
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:904
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:872
@ Comparison
A comparison.
Definition Sema.h:660
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:224
@ ICR_Conversion
Conversion.
Definition Overload.h:238
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:250
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:260
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:266
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:229
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:253
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:241
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:247
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:244
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:263
@ ICR_Promotion
Promotion.
Definition Overload.h:232
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:226
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:257
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:235
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:165
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1087
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:128
@ AS_none
Definition Specifiers.h:131
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:933
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:217
@ ICK_HLSL_Packed_Type_Conversion
HLSL packed type conversion to and from uint.
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
TemplateSpecCandidateSetKind
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:682
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:705
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:726
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:684
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:722
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:580
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 Decl.h:2031
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:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:277
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:279
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:285
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:293
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:282
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:289
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:316
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:373
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:423
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:418
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:421
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:394
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:380
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:416
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:425
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:413
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:383
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:377
@ Success
Template argument deduction was successful.
Definition Sema.h:375
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:397
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:386
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:400
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:389
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:410
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:427
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:404
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:407
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
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:1527
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:831
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:834
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:839
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:837
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:835
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:844
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:838
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:6160
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:441
__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:526
ConversionSet::const_iterator const_iterator
Definition Overload.h:562
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:527
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:553
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:90
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:91
QualType getToType() const
Definition Overload.h:611
QualType getFromType() const
Definition Overload.h:610
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).
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:1106
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
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:651
SmallVectorImpl< PartialDiagnosticAt > * ExtendedDiag
Location where we spot ptr to int cast or null subobject while evaluating constant expression in MS c...
Definition Expr.h:655
Extra information about a function prototype.
Definition TypeBase.h:5633
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5638
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1199
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:1221
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1248
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1210
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1212
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1238
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:937
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:1002
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:993
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1067
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1041
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1006
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:983
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:951
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:947
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:942
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1014
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:963
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:977
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1032
unsigned getNumParams() const
Definition Overload.h:1080
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1010
unsigned TookAddressOfOverload
Definition Overload.h:996
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1019
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1023
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:960
DeductionFailureInfo DeductionFailure
Definition Overload.h:1026
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:967
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:955
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1037
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10701
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10708
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13351
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13436
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13485
Abstract class used to diagnose incomplete types.
Definition Sema.h:8420
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
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)
void NoteDeductionFailure(Sema &S, bool ForTakingAddress, TemplateSpecCandidateSetKind CandidateSetKind)
Diagnose a template argument deduction failure.
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:481
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:493
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:515
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:506
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:510
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:501
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:520
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.