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));
6213 return TryCopyInitialization(S, &TmpExpr, ExplicitParameterType,
6214 SuppressUserConversion,
6215 /*InOverloadResolution=*/true, false);
6216 }
6217
6218 assert(FromType->isRecordType());
6219
6220 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6221 // C++98 [class.dtor]p2:
6222 // A destructor can be invoked for a const, volatile or const volatile
6223 // object.
6224 // C++98 [over.match.funcs]p4:
6225 // For static member functions, the implicit object parameter is considered
6226 // to match any object (since if the function is selected, the object is
6227 // discarded).
6228 Qualifiers Quals = Method->getMethodQualifiers();
6229 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6230 Quals.addConst();
6231 Quals.addVolatile();
6232 }
6233
6234 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6235
6236 // Set up the conversion sequence as a "bad" conversion, to allow us
6237 // to exit early.
6239
6240 // C++0x [over.match.funcs]p4:
6241 // For non-static member functions, the type of the implicit object
6242 // parameter is
6243 //
6244 // - "lvalue reference to cv X" for functions declared without a
6245 // ref-qualifier or with the & ref-qualifier
6246 // - "rvalue reference to cv X" for functions declared with the &&
6247 // ref-qualifier
6248 //
6249 // where X is the class of which the function is a member and cv is the
6250 // cv-qualification on the member function declaration.
6251 //
6252 // However, when finding an implicit conversion sequence for the argument, we
6253 // are not allowed to perform user-defined conversions
6254 // (C++ [over.match.funcs]p5). We perform a simplified version of
6255 // reference binding here, that allows class rvalues to bind to
6256 // non-constant references.
6257
6258 // First check the qualifiers.
6259 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6260 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6261 if (ImplicitParamType.getCVRQualifiers() !=
6262 FromTypeCanon.getLocalCVRQualifiers() &&
6263 !ImplicitParamType.isAtLeastAsQualifiedAs(
6264 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6266 FromType, ImplicitParamType);
6267 return ICS;
6268 }
6269
6270 if (FromTypeCanon.hasAddressSpace()) {
6271 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6272 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6273 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6274 S.getASTContext())) {
6276 FromType, ImplicitParamType);
6277 return ICS;
6278 }
6279 }
6280
6281 // Check that we have either the same type or a derived type. It
6282 // affects the conversion rank.
6283 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6284 ImplicitConversionKind SecondKind;
6285 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6286 SecondKind = ICK_Identity;
6287 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6288 SecondKind = ICK_Derived_To_Base;
6289 } else if (!Method->isExplicitObjectMemberFunction()) {
6291 FromType, ImplicitParamType);
6292 return ICS;
6293 }
6294
6295 // Check the ref-qualifier.
6296 switch (Method->getRefQualifier()) {
6297 case RQ_None:
6298 // Do nothing; we don't care about lvalueness or rvalueness.
6299 break;
6300
6301 case RQ_LValue:
6302 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6303 // non-const lvalue reference cannot bind to an rvalue
6305 ImplicitParamType);
6306 return ICS;
6307 }
6308 break;
6309
6310 case RQ_RValue:
6311 if (!FromClassification.isRValue()) {
6312 // rvalue reference cannot bind to an lvalue
6314 ImplicitParamType);
6315 return ICS;
6316 }
6317 break;
6318 }
6319
6320 // Success. Mark this as a reference binding.
6321 ICS.setStandard();
6323 ICS.Standard.Second = SecondKind;
6324 ICS.Standard.setFromType(FromType);
6325 ICS.Standard.setAllToTypes(ImplicitParamType);
6326 ICS.Standard.ReferenceBinding = true;
6327 ICS.Standard.DirectBinding = true;
6328 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6329 ICS.Standard.BindsToFunctionLvalue = false;
6330 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6331 ICS.Standard.FromBracedInitList = false;
6333 = (Method->getRefQualifier() == RQ_None);
6334 return ICS;
6335}
6336
6337/// PerformObjectArgumentInitialization - Perform initialization of
6338/// the implicit object parameter for the given Method with the given
6339/// expression.
6341 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6343 QualType FromRecordType, DestType;
6344 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6345
6346 LangAS FromAS = From->getType().getAddressSpace();
6347 if (getLangOpts().HLSL &&
6348 (FromAS == LangAS::hlsl_constant ||
6349 (FromAS == LangAS::hlsl_groupshared && Method->isConst()))) {
6351 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6352 /*BasePath=*/nullptr, VK_PRValue,
6354 } else if (getLangOpts().HLSL && FromAS == LangAS::hlsl_groupshared) {
6355 ASTContext &Ctx = SemaRef.getASTContext();
6357 InitializedEntity TempEntity =
6359 ExprResult Res = SemaRef.HLSL().CreateOutArgExpr(
6360 From, Ty, Ty, TempEntity, From->getBeginLoc(), /*IsInOut=*/true);
6361 if (Res.isInvalid())
6362 return ExprError();
6363 From = Res.get();
6364 }
6365
6366 Expr::Classification FromClassification;
6367 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6368 FromRecordType = PT->getPointeeType();
6369 DestType = Method->getThisType();
6370 FromClassification = Expr::Classification::makeSimpleLValue();
6371 } else {
6372 FromRecordType = From->getType();
6373 DestType = ImplicitParamRecordType;
6374 FromClassification = From->Classify(Context);
6375
6376 // CWG2813 [expr.call]p6:
6377 // If the function is an implicit object member function, the object
6378 // expression of the class member access shall be a glvalue [...]
6379 if (From->isPRValue()) {
6380 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6381 Method->getRefQualifier() !=
6383 }
6384 }
6385
6386 // Note that we always use the true parent context when performing
6387 // the actual argument initialization.
6389 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6390 Method->getParent());
6391 if (ICS.isBad()) {
6392 switch (ICS.Bad.Kind) {
6394 Qualifiers FromQs = FromRecordType.getQualifiers();
6395 Qualifiers ToQs = DestType.getQualifiers();
6396 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6397 if (CVR) {
6398 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6399 << Method->getDeclName() << FromRecordType << (CVR - 1)
6400 << From->getSourceRange();
6401 Diag(Method->getLocation(), diag::note_previous_decl)
6402 << Method->getDeclName();
6403 return ExprError();
6404 }
6405 break;
6406 }
6407
6410 bool IsRValueQualified =
6411 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6412 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6413 << Method->getDeclName() << FromClassification.isRValue()
6414 << IsRValueQualified;
6415 Diag(Method->getLocation(), diag::note_previous_decl)
6416 << Method->getDeclName();
6417 return ExprError();
6418 }
6419
6422 break;
6423
6426 llvm_unreachable("Lists are not objects");
6427 }
6428
6429 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6430 << ImplicitParamRecordType << FromRecordType
6431 << From->getSourceRange();
6432 }
6433
6434 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6435 ExprResult FromRes =
6436 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6437 if (FromRes.isInvalid())
6438 return ExprError();
6439 From = FromRes.get();
6440 }
6441
6442 if (!Context.hasSameType(From->getType(), DestType)) {
6443 CastKind CK;
6444 QualType PteeTy = DestType->getPointeeType();
6445 LangAS DestAS =
6446 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6447 if (FromRecordType.getAddressSpace() != DestAS)
6448 CK = CK_AddressSpaceConversion;
6449 else
6450 CK = CK_NoOp;
6451 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6452 }
6453 return From;
6454}
6455
6456/// TryContextuallyConvertToBool - Attempt to contextually convert the
6457/// expression From to bool (C++0x [conv]p3).
6460 // C++ [dcl.init]/17.8:
6461 // - Otherwise, if the initialization is direct-initialization, the source
6462 // type is std::nullptr_t, and the destination type is bool, the initial
6463 // value of the object being initialized is false.
6464 if (From->getType()->isNullPtrType())
6466 S.Context.BoolTy,
6467 From->isGLValue());
6468
6469 // All other direct-initialization of bool is equivalent to an implicit
6470 // conversion to bool in which explicit conversions are permitted.
6471 return TryImplicitConversion(S, From, S.Context.BoolTy,
6472 /*SuppressUserConversions=*/false,
6473 AllowedExplicit::Conversions,
6474 /*InOverloadResolution=*/false,
6475 /*CStyle=*/false,
6476 /*AllowObjCWritebackConversion=*/false,
6477 /*AllowObjCConversionOnExplicit=*/false);
6478}
6479
6481 if (checkPlaceholderForOverload(*this, From))
6482 return ExprError();
6483 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6484 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6485
6487 if (!ICS.isBad())
6488 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6491 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6492 << From->getType() << From->getSourceRange();
6493 return ExprError();
6494}
6495
6496/// Check that the specified conversion is permitted in a converted constant
6497/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6498/// is acceptable.
6501 // Since we know that the target type is an integral or unscoped enumeration
6502 // type, most conversion kinds are impossible. All possible First and Third
6503 // conversions are fine.
6504 switch (SCS.Second) {
6505 case ICK_Identity:
6507 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6509 return true;
6510
6512 // Conversion from an integral or unscoped enumeration type to bool is
6513 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6514 // conversion, so we allow it in a converted constant expression.
6515 //
6516 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6517 // a lot of popular code. We should at least add a warning for this
6518 // (non-conforming) extension.
6520 SCS.getToType(2)->isBooleanType();
6521
6523 case ICK_Pointer_Member:
6524 // C++1z: null pointer conversions and null member pointer conversions are
6525 // only permitted if the source type is std::nullptr_t.
6526 return SCS.getFromType()->isNullPtrType();
6527
6540 case ICK_Vector_Splat:
6541 case ICK_Complex_Real:
6552 return false;
6553
6558 llvm_unreachable("found a first conversion kind in Second");
6559
6561 case ICK_Qualification:
6562 llvm_unreachable("found a third conversion kind in Second");
6563
6565 break;
6566 }
6567
6568 llvm_unreachable("unknown conversion kind");
6569}
6570
6571/// BuildConvertedConstantExpression - Check that the expression From is a
6572/// converted constant expression of type T, perform the conversion but
6573/// does not evaluate the expression
6575 QualType T, CCEKind CCE,
6576 NamedDecl *Dest,
6577 APValue &PreNarrowingValue) {
6578 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6580 CCE == CCEKind::PackIndex);
6581 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6582 "converted constant expression outside C++11 or TTP matching");
6583
6584 if (checkPlaceholderForOverload(S, From))
6585 return ExprError();
6586
6587 // C++1z [expr.const]p3:
6588 // A converted constant expression of type T is an expression,
6589 // implicitly converted to type T, where the converted
6590 // expression is a constant expression and the implicit conversion
6591 // sequence contains only [... list of conversions ...].
6593 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6595 : TryCopyInitialization(S, From, T,
6596 /*SuppressUserConversions=*/false,
6597 /*InOverloadResolution=*/false,
6598 /*AllowObjCWritebackConversion=*/false,
6599 /*AllowExplicit=*/false);
6600 StandardConversionSequence *SCS = nullptr;
6601 switch (ICS.getKind()) {
6603 SCS = &ICS.Standard;
6604 break;
6606 if (T->isRecordType())
6607 SCS = &ICS.UserDefined.Before;
6608 else
6609 SCS = &ICS.UserDefined.After;
6610 break;
6614 return S.Diag(From->getBeginLoc(),
6615 diag::err_typecheck_converted_constant_expression)
6616 << From->getType() << From->getSourceRange() << T;
6617 return ExprError();
6618
6621 llvm_unreachable("bad conversion in converted constant expression");
6622 }
6623
6624 // Check that we would only use permitted conversions.
6625 if (!CheckConvertedConstantConversions(S, *SCS)) {
6626 return S.Diag(From->getBeginLoc(),
6627 diag::err_typecheck_converted_constant_expression_disallowed)
6628 << From->getType() << From->getSourceRange() << T;
6629 }
6630 // [...] and where the reference binding (if any) binds directly.
6631 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6632 return S.Diag(From->getBeginLoc(),
6633 diag::err_typecheck_converted_constant_expression_indirect)
6634 << From->getType() << From->getSourceRange() << T;
6635 }
6636 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6637 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6638 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6639 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6640 // case explicitly.
6641 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6642 return S.Diag(From->getBeginLoc(),
6643 diag::err_reference_bind_to_bitfield_in_cce)
6644 << From->getSourceRange();
6645 }
6646
6647 // Usually we can simply apply the ImplicitConversionSequence we formed
6648 // earlier, but that's not guaranteed to work when initializing an object of
6649 // class type.
6651 bool IsTemplateArgument =
6653 if (T->isRecordType()) {
6654 assert(IsTemplateArgument &&
6655 "unexpected class type converted constant expr");
6659 SourceLocation(), From);
6660 } else {
6661 Result =
6663 }
6664 if (Result.isInvalid())
6665 return Result;
6666
6667 // C++2a [intro.execution]p5:
6668 // A full-expression is [...] a constant-expression [...]
6669 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6670 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6671 IsTemplateArgument);
6672 if (Result.isInvalid())
6673 return Result;
6674
6675 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6676
6677 // Check for a narrowing implicit conversion.
6678 bool ReturnPreNarrowingValue = false;
6679 QualType PreNarrowingType;
6680 switch (SCS->getNarrowingKind(
6681 S.Context, Result.get(), PreNarrowingValue, PreNarrowingType,
6682 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6684 // Implicit conversion to a narrower type, and the value is not a constant
6685 // expression. We'll diagnose this in a moment.
6686 case NK_Not_Narrowing:
6687 break;
6688
6690 if (CCE == CCEKind::ArrayBound &&
6691 PreNarrowingType->isIntegralOrEnumerationType() &&
6692 PreNarrowingValue.isInt()) {
6693 // Don't diagnose array bound narrowing here; we produce more precise
6694 // errors by allowing the un-narrowed value through.
6695 ReturnPreNarrowingValue = true;
6696 break;
6697 }
6698 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6699 << CCE << /*Constant*/ 1
6700 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6701 // If this is an SFINAE Context, treat the result as invalid so it stops
6702 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6703 // FIXME: Should do this whenever the above diagnostic is an error, but
6704 // without further changes this would degrade some other diagnostics.
6705 if (S.isSFINAEContext())
6706 return ExprError();
6707 break;
6708
6710 // Implicit conversion to a narrower type, but the expression is
6711 // value-dependent so we can't tell whether it's actually narrowing.
6712 // For matching the parameters of a TTP, the conversion is ill-formed
6713 // if it may narrow.
6714 if (CCE != CCEKind::TempArgStrict)
6715 break;
6716 [[fallthrough]];
6717 case NK_Type_Narrowing:
6718 // FIXME: It would be better to diagnose that the expression is not a
6719 // constant expression.
6720 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6721 << CCE << /*Constant*/ 0 << From->getType() << T;
6722 if (S.isSFINAEContext())
6723 return ExprError();
6724 break;
6725 }
6726 if (!ReturnPreNarrowingValue)
6727 PreNarrowingValue = {};
6728
6729 return Result;
6730}
6731
6732/// CheckConvertedConstantExpression - Check that the expression From is a
6733/// converted constant expression of type T, perform the conversion and produce
6734/// the converted expression, per C++11 [expr.const]p3.
6737 CCEKind CCE, bool RequireInt,
6738 NamedDecl *Dest) {
6739
6740 APValue PreNarrowingValue;
6742 PreNarrowingValue);
6743 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6744 Value = APValue();
6745 return Result;
6746 }
6747 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6748 RequireInt, PreNarrowingValue);
6749}
6750
6752 CCEKind CCE,
6753 NamedDecl *Dest) {
6754 APValue PreNarrowingValue;
6755 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6756 PreNarrowingValue);
6757}
6758
6760 APValue &Value, CCEKind CCE,
6761 NamedDecl *Dest) {
6762 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6763 Dest);
6764}
6765
6767 llvm::APSInt &Value,
6768 CCEKind CCE) {
6769 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6770
6771 APValue V;
6772 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6773 /*Dest=*/nullptr);
6774 if (!R.isInvalid() && !R.get()->isValueDependent())
6775 Value = V.getInt();
6776 return R;
6777}
6778
6781 CCEKind CCE, bool RequireInt,
6782 const APValue &PreNarrowingValue) {
6783
6784 ExprResult Result = E;
6785 // Check the expression is a constant expression.
6788 Expr::EvalResult Eval;
6789 Eval.Diag = &Notes;
6790 Eval.ExtendedDiag = &MSWarning;
6791
6792 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6793
6794 ConstantExprKind Kind;
6795 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6796 Kind = ConstantExprKind::ClassTemplateArgument;
6797 else if (CCE == CCEKind::TemplateArg)
6798 Kind = ConstantExprKind::NonClassTemplateArgument;
6799 else
6800 Kind = ConstantExprKind::Normal;
6801
6802 EvalProxy SProxy(*this);
6803 if (!E->EvaluateAsMandatedConstantExpr(Eval, Context, SProxy, Kind) ||
6804 (RequireInt && !Eval.Val.isInt())) {
6805 // The expression can't be folded, so we can't keep it at this position in
6806 // the AST.
6807 Result = ExprError();
6808 } else {
6809 Value = Eval.Val;
6810 // For -fms-compatibility mode we relax some requirements
6811 // for constant folding in non-SFINAE contexts
6812 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6813 if (Notes.empty() && !CantFold) {
6814 for (auto &Info : MSWarning)
6815 Diag(Info.first, Info.second);
6816 // It's a constant expression.
6817 Expr *E = Result.get();
6818 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6819 // We expect a ConstantExpr to have a value associated with it
6820 // by this point.
6821 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6822 "ConstantExpr has no value associated with it");
6823 (void)CE;
6824 } else {
6826 }
6827 if (!PreNarrowingValue.isAbsent())
6828 Value = std::move(PreNarrowingValue);
6829 return E;
6830 }
6831 }
6832
6833 // It's not a constant expression. Produce an appropriate diagnostic.
6834 if (Notes.size() == 1 &&
6835 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6836 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6837 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6838 diag::note_constexpr_invalid_template_arg) {
6839 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6840 for (unsigned I = 0; I < Notes.size(); ++I)
6841 Diag(Notes[I].first, Notes[I].second);
6842 } else {
6843 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6844 << CCE << E->getSourceRange();
6845 for (unsigned I = 0; I < Notes.size(); ++I)
6846 Diag(Notes[I].first, Notes[I].second);
6847 }
6848 return ExprError();
6849}
6850
6851/// dropPointerConversions - If the given standard conversion sequence
6852/// involves any pointer conversions, remove them. This may change
6853/// the result type of the conversion sequence.
6855 if (SCS.Second == ICK_Pointer_Conversion) {
6856 SCS.Second = ICK_Identity;
6857 SCS.Dimension = ICK_Identity;
6858 SCS.Third = ICK_Identity;
6859 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6860 }
6861}
6862
6863/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6864/// convert the expression From to an Objective-C pointer type.
6865static ImplicitConversionSequence
6867 // Do an implicit conversion to 'id'.
6870 = TryImplicitConversion(S, From, Ty,
6871 // FIXME: Are these flags correct?
6872 /*SuppressUserConversions=*/false,
6873 AllowedExplicit::Conversions,
6874 /*InOverloadResolution=*/false,
6875 /*CStyle=*/false,
6876 /*AllowObjCWritebackConversion=*/false,
6877 /*AllowObjCConversionOnExplicit=*/true);
6878
6879 // Strip off any final conversions to 'id'.
6880 switch (ICS.getKind()) {
6885 break;
6886
6889 break;
6890
6893 break;
6894 }
6895
6896 return ICS;
6897}
6898
6900 if (checkPlaceholderForOverload(*this, From))
6901 return ExprError();
6902
6903 QualType Ty = Context.getObjCIdType();
6906 if (!ICS.isBad())
6907 return PerformImplicitConversion(From, Ty, ICS,
6909 return ExprResult();
6910}
6911
6912static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6913 const Expr *Base = nullptr;
6914 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6915 "expected a member expression");
6916
6917 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6918 M && !M->isImplicitAccess())
6919 Base = M->getBase();
6920 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6921 M && !M->isImplicitAccess())
6922 Base = M->getBase();
6923
6924 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6925
6926 if (T->isPointerType())
6927 T = T->getPointeeType();
6928
6929 return T;
6930}
6931
6933 const FunctionDecl *Fun) {
6934 QualType ObjType = Obj->getType();
6935 if (ObjType->isPointerType()) {
6936 ObjType = ObjType->getPointeeType();
6937 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6939 /*CanOverflow=*/false, FPOptionsOverride());
6940 }
6941 return Obj;
6942}
6943
6951
6953 Expr *Object, MultiExprArg &Args,
6954 SmallVectorImpl<Expr *> &NewArgs) {
6955 assert(Method->isExplicitObjectMemberFunction() &&
6956 "Method is not an explicit member function");
6957 assert(NewArgs.empty() && "NewArgs should be empty");
6958
6959 NewArgs.reserve(Args.size() + 1);
6960 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6961 NewArgs.push_back(This);
6962 NewArgs.append(Args.begin(), Args.end());
6963 Args = NewArgs;
6965 Method, Object->getBeginLoc());
6966}
6967
6968/// Determine whether the provided type is an integral type, or an enumeration
6969/// type of a permitted flavor.
6971 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6972 : T->isIntegralOrUnscopedEnumerationType();
6973}
6974
6975static ExprResult
6978 QualType T, UnresolvedSetImpl &ViableConversions) {
6979
6980 if (Converter.Suppress)
6981 return ExprError();
6982
6983 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6984 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6985 CXXConversionDecl *Conv =
6986 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6988 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6989 }
6990 return From;
6991}
6992
6993static bool
6996 QualType T, bool HadMultipleCandidates,
6997 UnresolvedSetImpl &ExplicitConversions) {
6998 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6999 DeclAccessPair Found = ExplicitConversions[0];
7000 CXXConversionDecl *Conversion =
7001 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
7002
7003 // The user probably meant to invoke the given explicit
7004 // conversion; use it.
7005 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
7006 std::string TypeStr;
7007 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
7008
7009 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
7011 "static_cast<" + TypeStr + ">(")
7013 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
7014 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
7015
7016 // If we aren't in a SFINAE context, build a call to the
7017 // explicit conversion function.
7018 if (SemaRef.isSFINAEContext())
7019 return true;
7020
7021 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
7022 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
7023 HadMultipleCandidates);
7024 if (Result.isInvalid())
7025 return true;
7026
7027 // Replace the conversion with a RecoveryExpr, so we don't try to
7028 // instantiate it later, but can further diagnose here.
7029 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
7030 From, Result.get()->getType());
7031 if (Result.isInvalid())
7032 return true;
7033 From = Result.get();
7034 }
7035 return false;
7036}
7037
7038static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
7040 QualType T, bool HadMultipleCandidates,
7042 CXXConversionDecl *Conversion =
7043 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
7044 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
7045
7046 QualType ToType = Conversion->getConversionType().getNonReferenceType();
7047 if (!Converter.SuppressConversion) {
7048 if (SemaRef.isSFINAEContext())
7049 return true;
7050
7051 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
7052 << From->getSourceRange();
7053 }
7054
7055 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
7056 HadMultipleCandidates);
7057 if (Result.isInvalid())
7058 return true;
7059 // Record usage of conversion in an implicit cast.
7060 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
7061 CK_UserDefinedConversion, Result.get(),
7062 nullptr, Result.get()->getValueKind(),
7063 SemaRef.CurFPFeatureOverrides());
7064 return false;
7065}
7066
7068 Sema &SemaRef, SourceLocation Loc, Expr *From,
7070 if (!Converter.match(From->getType()) && !Converter.Suppress)
7071 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
7072 << From->getSourceRange();
7073
7074 return SemaRef.DefaultLvalueConversion(From);
7075}
7076
7077static void
7079 UnresolvedSetImpl &ViableConversions,
7080 OverloadCandidateSet &CandidateSet) {
7081 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7082 NamedDecl *D = FoundDecl.getDecl();
7083 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7084 if (isa<UsingShadowDecl>(D))
7085 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7086
7087 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7089 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7090 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7091 continue;
7092 }
7094 SemaRef.AddConversionCandidate(
7095 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7096 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7097 }
7098}
7099
7100/// Attempt to convert the given expression to a type which is accepted
7101/// by the given converter.
7102///
7103/// This routine will attempt to convert an expression of class type to a
7104/// type accepted by the specified converter. In C++11 and before, the class
7105/// must have a single non-explicit conversion function converting to a matching
7106/// type. In C++1y, there can be multiple such conversion functions, but only
7107/// one target type.
7108///
7109/// \param Loc The source location of the construct that requires the
7110/// conversion.
7111///
7112/// \param From The expression we're converting from.
7113///
7114/// \param Converter Used to control and diagnose the conversion process.
7115///
7116/// \returns The expression, converted to an integral or enumeration type if
7117/// successful.
7119 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7120 // We can't perform any more checking for type-dependent expressions.
7121 if (From->isTypeDependent())
7122 return From;
7123
7124 // Process placeholders immediately.
7125 if (From->hasPlaceholderType()) {
7126 ExprResult result = CheckPlaceholderExpr(From);
7127 if (result.isInvalid())
7128 return result;
7129 From = result.get();
7130 }
7131
7132 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7133 ExprResult Converted = DefaultLvalueConversion(From);
7134 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7135 From = Converted.isUsable() ? Converted.get() : nullptr;
7136 // If the expression already has a matching type, we're golden.
7137 if (Converter.match(T))
7138 return Converted;
7139
7140 // FIXME: Check for missing '()' if T is a function type?
7141
7142 // We can only perform contextual implicit conversions on objects of class
7143 // type.
7144 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7145 if (!RecordTy || !getLangOpts().CPlusPlus) {
7146 if (!Converter.Suppress)
7147 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7148 return From;
7149 }
7150
7151 // We must have a complete class type.
7152 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7153 ContextualImplicitConverter &Converter;
7154 Expr *From;
7155
7156 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7157 : Converter(Converter), From(From) {}
7158
7159 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7160 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7161 }
7162 } IncompleteDiagnoser(Converter, From);
7163
7164 if (Converter.Suppress ? !isCompleteType(Loc, T)
7165 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7166 return From;
7167
7168 // Look for a conversion to an integral or enumeration type.
7170 ViableConversions; // These are *potentially* viable in C++1y.
7171 UnresolvedSet<4> ExplicitConversions;
7172 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7173 ->getDefinitionOrSelf()
7174 ->getVisibleConversionFunctions();
7175
7176 bool HadMultipleCandidates =
7177 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7178
7179 // To check that there is only one target type, in C++1y:
7180 QualType ToType;
7181 bool HasUniqueTargetType = true;
7182
7183 // Collect explicit or viable (potentially in C++1y) conversions.
7184 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7185 NamedDecl *D = (*I)->getUnderlyingDecl();
7186 CXXConversionDecl *Conversion;
7187 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7188 if (ConvTemplate) {
7190 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7191 else
7192 continue; // C++11 does not consider conversion operator templates(?).
7193 } else
7194 Conversion = cast<CXXConversionDecl>(D);
7195
7196 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7197 "Conversion operator templates are considered potentially "
7198 "viable in C++1y");
7199
7200 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7201 if (Converter.match(CurToType) || ConvTemplate) {
7202
7203 if (Conversion->isExplicit()) {
7204 // FIXME: For C++1y, do we need this restriction?
7205 // cf. diagnoseNoViableConversion()
7206 if (!ConvTemplate)
7207 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7208 } else {
7209 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7210 if (ToType.isNull())
7211 ToType = CurToType.getUnqualifiedType();
7212 else if (HasUniqueTargetType &&
7213 (CurToType.getUnqualifiedType() != ToType))
7214 HasUniqueTargetType = false;
7215 }
7216 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7217 }
7218 }
7219 }
7220
7221 if (getLangOpts().CPlusPlus14) {
7222 // C++1y [conv]p6:
7223 // ... An expression e of class type E appearing in such a context
7224 // is said to be contextually implicitly converted to a specified
7225 // type T and is well-formed if and only if e can be implicitly
7226 // converted to a type T that is determined as follows: E is searched
7227 // for conversion functions whose return type is cv T or reference to
7228 // cv T such that T is allowed by the context. There shall be
7229 // exactly one such T.
7230
7231 // If no unique T is found:
7232 if (ToType.isNull()) {
7233 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7234 HadMultipleCandidates,
7235 ExplicitConversions))
7236 return ExprError();
7237 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7238 }
7239
7240 // If more than one unique Ts are found:
7241 if (!HasUniqueTargetType)
7242 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7243 ViableConversions);
7244
7245 // If one unique T is found:
7246 // First, build a candidate set from the previously recorded
7247 // potentially viable conversions.
7249 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7250 CandidateSet);
7251
7252 // Then, perform overload resolution over the candidate set.
7254 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7255 case OR_Success: {
7256 // Apply this conversion.
7258 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7259 if (recordConversion(*this, Loc, From, Converter, T,
7260 HadMultipleCandidates, Found))
7261 return ExprError();
7262 break;
7263 }
7264 case OR_Ambiguous:
7265 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7266 ViableConversions);
7268 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7269 HadMultipleCandidates,
7270 ExplicitConversions))
7271 return ExprError();
7272 [[fallthrough]];
7273 case OR_Deleted:
7274 // We'll complain below about a non-integral condition type.
7275 break;
7276 }
7277 } else {
7278 switch (ViableConversions.size()) {
7279 case 0: {
7280 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7281 HadMultipleCandidates,
7282 ExplicitConversions))
7283 return ExprError();
7284
7285 // We'll complain below about a non-integral condition type.
7286 break;
7287 }
7288 case 1: {
7289 // Apply this conversion.
7290 DeclAccessPair Found = ViableConversions[0];
7291 if (recordConversion(*this, Loc, From, Converter, T,
7292 HadMultipleCandidates, Found))
7293 return ExprError();
7294 break;
7295 }
7296 default:
7297 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7298 ViableConversions);
7299 }
7300 }
7301
7302 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7303}
7304
7305/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7306/// an acceptable non-member overloaded operator for a call whose
7307/// arguments have types T1 (and, if non-empty, T2). This routine
7308/// implements the check in C++ [over.match.oper]p3b2 concerning
7309/// enumeration types.
7311 FunctionDecl *Fn,
7312 ArrayRef<Expr *> Args) {
7313 QualType T1 = Args[0]->getType();
7314 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7315
7316 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7317 return true;
7318
7319 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7320 return true;
7321
7322 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7323 if (Proto->getNumParams() < 1)
7324 return false;
7325
7326 if (T1->isEnumeralType()) {
7327 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7328 if (Context.hasSameUnqualifiedType(T1, ArgType))
7329 return true;
7330 }
7331
7332 if (Proto->getNumParams() < 2)
7333 return false;
7334
7335 if (!T2.isNull() && T2->isEnumeralType()) {
7336 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7337 if (Context.hasSameUnqualifiedType(T2, ArgType))
7338 return true;
7339 }
7340
7341 return false;
7342}
7343
7346 return false;
7347
7348 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7349 return FD->isTargetMultiVersion();
7350
7351 if (!FD->isMultiVersion())
7352 return false;
7353
7354 // Among multiple target versions consider either the default,
7355 // or the first non-default in the absence of default version.
7356 unsigned SeenAt = 0;
7357 unsigned I = 0;
7358 bool HasDefault = false;
7360 FD, [&](const FunctionDecl *CurFD) {
7361 if (FD == CurFD)
7362 SeenAt = I;
7363 else if (CurFD->isTargetMultiVersionDefault())
7364 HasDefault = true;
7365 ++I;
7366 });
7367 return HasDefault || SeenAt != 0;
7368}
7369
7372 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7373 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7374 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7375 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7376 bool StrictPackMatch) {
7377 const FunctionProtoType *Proto
7378 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7379 assert(Proto && "Functions without a prototype cannot be overloaded");
7380 assert(!Function->getDescribedFunctionTemplate() &&
7381 "Use AddTemplateOverloadCandidate for function templates");
7382
7383 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7385 // If we get here, it's because we're calling a member function
7386 // that is named without a member access expression (e.g.,
7387 // "this->f") that was either written explicitly or created
7388 // implicitly. This can happen with a qualified call to a member
7389 // function, e.g., X::f(). We use an empty type for the implied
7390 // object argument (C++ [over.call.func]p3), and the acting context
7391 // is irrelevant.
7392 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7394 CandidateSet, SuppressUserConversions,
7395 PartialOverloading, EarlyConversions, PO,
7396 StrictPackMatch);
7397 return;
7398 }
7399 // We treat a constructor like a non-member function, since its object
7400 // argument doesn't participate in overload resolution.
7401 }
7402
7403 if (!CandidateSet.isNewCandidate(Function, PO))
7404 return;
7405
7406 // C++11 [class.copy]p11: [DR1402]
7407 // A defaulted move constructor that is defined as deleted is ignored by
7408 // overload resolution.
7409 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7410 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7411 Constructor->isMoveConstructor())
7412 return;
7413
7414 // Overload resolution is always an unevaluated context.
7417
7418 // C++ [over.match.oper]p3:
7419 // if no operand has a class type, only those non-member functions in the
7420 // lookup set that have a first parameter of type T1 or "reference to
7421 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7422 // is a right operand) a second parameter of type T2 or "reference to
7423 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7424 // candidate functions.
7425 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7427 return;
7428
7429 // Add this candidate
7430 OverloadCandidate &Candidate =
7431 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7432 Candidate.FoundDecl = FoundDecl;
7433 Candidate.Function = Function;
7434 Candidate.Viable = true;
7435 Candidate.RewriteKind =
7436 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7437 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7438 Candidate.ExplicitCallArguments = Args.size();
7439 Candidate.StrictPackMatch = StrictPackMatch;
7440
7441 // Explicit functions are not actually candidates at all if we're not
7442 // allowing them in this context, but keep them around so we can point
7443 // to them in diagnostics.
7444 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7445 Candidate.Viable = false;
7446 Candidate.FailureKind = ovl_fail_explicit;
7447 return;
7448 }
7449
7450 // Functions with internal linkage are only viable in the same module unit.
7451 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7452 /// FIXME: Currently, the semantics of linkage in clang is slightly
7453 /// different from the semantics in C++ spec. In C++ spec, only names
7454 /// have linkage. So that all entities of the same should share one
7455 /// linkage. But in clang, different entities of the same could have
7456 /// different linkage.
7457 const NamedDecl *ND = Function;
7458 bool IsImplicitlyInstantiated = false;
7459 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7460 ND = SpecInfo->getTemplate();
7461 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7463 }
7464
7465 /// Don't remove inline functions with internal linkage from the overload
7466 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7467 /// However:
7468 /// - Inline functions with internal linkage are a common pattern in
7469 /// headers to avoid ODR issues.
7470 /// - The global module is meant to be a transition mechanism for C and C++
7471 /// headers, and the current rules as written work against that goal.
7472 const bool IsInlineFunctionInGMF =
7473 Function->isFromGlobalModule() &&
7474 (IsImplicitlyInstantiated || Function->isInlined());
7475
7476 // Don't exclude internal-linkage entities from the current TU's global
7477 // module fragment.
7478 const Module *CurrentModule = getCurrentModule();
7479 const bool IsCurrentUnitGMFDecl =
7480 Function->isFromGlobalModule() && CurrentModule &&
7481 Function->getOwningModule()->getTopLevelModule() ==
7482 CurrentModule->getTopLevelModule();
7483
7484 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7485 !IsCurrentUnitGMFDecl) {
7486 Candidate.Viable = false;
7488 return;
7489 }
7490 }
7491
7493 Candidate.Viable = false;
7495 return;
7496 }
7497
7498 if (Constructor) {
7499 // C++ [class.copy]p3:
7500 // A member function template is never instantiated to perform the copy
7501 // of a class object to an object of its class type.
7502 CanQualType ClassType =
7503 Context.getCanonicalTagType(Constructor->getParent());
7504 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7505 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7506 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7507 ClassType))) {
7508 Candidate.Viable = false;
7510 return;
7511 }
7512
7513 // C++ [over.match.funcs]p8: (proposed DR resolution)
7514 // A constructor inherited from class type C that has a first parameter
7515 // of type "reference to P" (including such a constructor instantiated
7516 // from a template) is excluded from the set of candidate functions when
7517 // constructing an object of type cv D if the argument list has exactly
7518 // one argument and D is reference-related to P and P is reference-related
7519 // to C.
7520 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7521 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7522 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7523 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7524 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7525 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7526 SourceLocation Loc = Args.front()->getExprLoc();
7527 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7528 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7529 Candidate.Viable = false;
7531 return;
7532 }
7533 }
7534
7535 // Check that the constructor is capable of constructing an object in the
7536 // destination address space.
7538 Constructor->getMethodQualifiers().getAddressSpace(),
7539 CandidateSet.getDestAS(), getASTContext())) {
7540 Candidate.Viable = false;
7542 }
7543 }
7544
7545 unsigned NumParams = Proto->getNumParams();
7546
7547 // (C++ 13.3.2p2): A candidate function having fewer than m
7548 // parameters is viable only if it has an ellipsis in its parameter
7549 // list (8.3.5).
7550 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7551 !Proto->isVariadic() &&
7552 shouldEnforceArgLimit(PartialOverloading, Function)) {
7553 Candidate.Viable = false;
7555 return;
7556 }
7557
7558 // (C++ 13.3.2p2): A candidate function having more than m parameters
7559 // is viable only if the (m+1)st parameter has a default argument
7560 // (8.3.6). For the purposes of overload resolution, the
7561 // parameter list is truncated on the right, so that there are
7562 // exactly m parameters.
7563 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7564 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7565 !PartialOverloading) {
7566 // Not enough arguments.
7567 Candidate.Viable = false;
7569 return;
7570 }
7571
7572 // (CUDA B.1): Check for invalid calls between targets.
7573 if (getLangOpts().CUDA) {
7574 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7575 // Skip the check for callers that are implicit members, because in this
7576 // case we may not yet know what the member's target is; the target is
7577 // inferred for the member automatically, based on the bases and fields of
7578 // the class.
7579 if (!(Caller && Caller->isImplicit()) &&
7580 !CUDA().IsAllowedCall(Caller, Function)) {
7581 Candidate.Viable = false;
7582 Candidate.FailureKind = ovl_fail_bad_target;
7583 return;
7584 }
7585 }
7586
7587 if (Function->getTrailingRequiresClause()) {
7588 ConstraintSatisfaction Satisfaction;
7589 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7590 /*ForOverloadResolution*/ true) ||
7591 !Satisfaction.IsSatisfied) {
7592 Candidate.Viable = false;
7594 return;
7595 }
7596 }
7597
7598 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7599 // Determine the implicit conversion sequences for each of the
7600 // arguments.
7601 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7602 unsigned ConvIdx =
7603 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7604 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7605 // We already formed a conversion sequence for this parameter during
7606 // template argument deduction.
7607 } else if (ArgIdx < NumParams) {
7608 // (C++ 13.3.2p3): for F to be a viable function, there shall
7609 // exist for each argument an implicit conversion sequence
7610 // (13.3.3.1) that converts that argument to the corresponding
7611 // parameter of F.
7612 QualType ParamType = Proto->getParamType(ArgIdx);
7613 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7614 if (ParamABI == ParameterABI::HLSLOut ||
7615 ParamABI == ParameterABI::HLSLInOut) {
7616 ParamType = ParamType.getNonReferenceType();
7617 if (ParamABI == ParameterABI::HLSLInOut &&
7618 Args[ArgIdx]->getType().getAddressSpace() ==
7620 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7621 }
7622 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7623 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7624 /*InOverloadResolution=*/true,
7625 /*AllowObjCWritebackConversion=*/
7626 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7627 if (Candidate.Conversions[ConvIdx].isBad()) {
7628 Candidate.Viable = false;
7630 return;
7631 }
7632 } else {
7633 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7634 // argument for which there is no corresponding parameter is
7635 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7636 Candidate.Conversions[ConvIdx].setEllipsis();
7637 }
7638 }
7639
7640 if (EnableIfAttr *FailedAttr =
7641 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7642 Candidate.Viable = false;
7643 Candidate.FailureKind = ovl_fail_enable_if;
7644 Candidate.DeductionFailure.Data = FailedAttr;
7645 return;
7646 }
7647}
7648
7652 if (Methods.size() <= 1)
7653 return nullptr;
7654
7655 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7656 bool Match = true;
7657 ObjCMethodDecl *Method = Methods[b];
7658 unsigned NumNamedArgs = Sel.getNumArgs();
7659 // Method might have more arguments than selector indicates. This is due
7660 // to addition of c-style arguments in method.
7661 if (Method->param_size() > NumNamedArgs)
7662 NumNamedArgs = Method->param_size();
7663 if (Args.size() < NumNamedArgs)
7664 continue;
7665
7666 for (unsigned i = 0; i < NumNamedArgs; i++) {
7667 // We can't do any type-checking on a type-dependent argument.
7668 if (Args[i]->isTypeDependent()) {
7669 Match = false;
7670 break;
7671 }
7672
7673 ParmVarDecl *param = Method->parameters()[i];
7674 Expr *argExpr = Args[i];
7675 assert(argExpr && "SelectBestMethod(): missing expression");
7676
7677 // Strip the unbridged-cast placeholder expression off unless it's
7678 // a consumed argument.
7679 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7680 !param->hasAttr<CFConsumedAttr>())
7681 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7682
7683 // If the parameter is __unknown_anytype, move on to the next method.
7684 if (param->getType() == Context.UnknownAnyTy) {
7685 Match = false;
7686 break;
7687 }
7688
7689 ImplicitConversionSequence ConversionState
7690 = TryCopyInitialization(*this, argExpr, param->getType(),
7691 /*SuppressUserConversions*/false,
7692 /*InOverloadResolution=*/true,
7693 /*AllowObjCWritebackConversion=*/
7694 getLangOpts().ObjCAutoRefCount,
7695 /*AllowExplicit*/false);
7696 // This function looks for a reasonably-exact match, so we consider
7697 // incompatible pointer conversions to be a failure here.
7698 if (ConversionState.isBad() ||
7699 (ConversionState.isStandard() &&
7700 ConversionState.Standard.Second ==
7702 Match = false;
7703 break;
7704 }
7705 }
7706 // Promote additional arguments to variadic methods.
7707 if (Match && Method->isVariadic()) {
7708 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7709 if (Args[i]->isTypeDependent()) {
7710 Match = false;
7711 break;
7712 }
7714 Args[i], VariadicCallType::Method, nullptr);
7715 if (Arg.isInvalid()) {
7716 Match = false;
7717 break;
7718 }
7719 }
7720 } else {
7721 // Check for extra arguments to non-variadic methods.
7722 if (Args.size() != NumNamedArgs)
7723 Match = false;
7724 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7725 // Special case when selectors have no argument. In this case, select
7726 // one with the most general result type of 'id'.
7727 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7728 QualType ReturnT = Methods[b]->getReturnType();
7729 if (ReturnT->isObjCIdType())
7730 return Methods[b];
7731 }
7732 }
7733 }
7734
7735 if (Match)
7736 return Method;
7737 }
7738 return nullptr;
7739}
7740
7742 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7743 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7744 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7745 if (ThisArg) {
7746 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7747 assert(!isa<CXXConstructorDecl>(Method) &&
7748 "Shouldn't have `this` for ctors!");
7749 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7751 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7752 if (R.isInvalid())
7753 return false;
7754 ConvertedThis = R.get();
7755 } else {
7756 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7757 (void)MD;
7758 assert((MissingImplicitThis || MD->isStatic() ||
7760 "Expected `this` for non-ctor instance methods");
7761 }
7762 ConvertedThis = nullptr;
7763 }
7764
7765 // Ignore any variadic arguments. Converting them is pointless, since the
7766 // user can't refer to them in the function condition.
7767 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7768
7769 // Convert the arguments.
7770 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7771 ExprResult R;
7773 S.Context, Function->getParamDecl(I)),
7774 SourceLocation(), Args[I]);
7775
7776 if (R.isInvalid())
7777 return false;
7778
7779 ConvertedArgs.push_back(R.get());
7780 }
7781
7782 if (Trap.hasErrorOccurred())
7783 return false;
7784
7785 // Push default arguments if needed.
7786 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7787 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7788 ParmVarDecl *P = Function->getParamDecl(i);
7789 if (!P->hasDefaultArg())
7790 return false;
7791 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7792 if (R.isInvalid())
7793 return false;
7794 ConvertedArgs.push_back(R.get());
7795 }
7796
7797 if (Trap.hasErrorOccurred())
7798 return false;
7799 }
7800 return true;
7801}
7802
7804 SourceLocation CallLoc,
7805 ArrayRef<Expr *> Args,
7806 bool MissingImplicitThis) {
7807 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7808 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7809 return nullptr;
7810
7811 SFINAETrap Trap(*this);
7812 // Perform the access checking immediately so any access diagnostics are
7813 // caught by the SFINAE trap.
7814 llvm::scope_exit UndelayDiags(
7815 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7816 DelayedDiagnostics.popUndelayed(CurrentState);
7817 });
7818 SmallVector<Expr *, 16> ConvertedArgs;
7819 // FIXME: We should look into making enable_if late-parsed.
7820 Expr *DiscardedThis;
7822 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7823 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7824 return *EnableIfAttrs.begin();
7825
7826 for (auto *EIA : EnableIfAttrs) {
7828 // FIXME: This doesn't consider value-dependent cases, because doing so is
7829 // very difficult. Ideally, we should handle them more gracefully.
7830 if (EIA->getCond()->isValueDependent() ||
7831 !EIA->getCond()->EvaluateWithSubstitution(
7832 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7833 return EIA;
7834
7835 if (!Result.isInt() || !Result.getInt().getBoolValue())
7836 return EIA;
7837 }
7838 return nullptr;
7839}
7840
7841template <typename CheckFn>
7843 bool ArgDependent, SourceLocation Loc,
7844 CheckFn &&IsSuccessful) {
7846 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7847 if (ArgDependent == DIA->getArgDependent())
7848 Attrs.push_back(DIA);
7849 }
7850
7851 // Common case: No diagnose_if attributes, so we can quit early.
7852 if (Attrs.empty())
7853 return false;
7854
7855 auto WarningBegin = std::stable_partition(
7856 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7857 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7858 DIA->getWarningGroup().empty();
7859 });
7860
7861 // Note that diagnose_if attributes are late-parsed, so they appear in the
7862 // correct order (unlike enable_if attributes).
7863 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7864 IsSuccessful);
7865 if (ErrAttr != WarningBegin) {
7866 const DiagnoseIfAttr *DIA = *ErrAttr;
7867 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7868 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7869 << DIA->getParent() << DIA->getCond()->getSourceRange();
7870 return true;
7871 }
7872
7873 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7874 switch (Sev) {
7875 case DiagnoseIfAttr::DS_warning:
7877 case DiagnoseIfAttr::DS_error:
7878 return diag::Severity::Error;
7879 }
7880 llvm_unreachable("Fully covered switch above!");
7881 };
7882
7883 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7884 if (IsSuccessful(DIA)) {
7885 if (DIA->getWarningGroup().empty() &&
7886 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7887 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7888 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7889 << DIA->getParent() << DIA->getCond()->getSourceRange();
7890 } else {
7891 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7892 DIA->getWarningGroup());
7893 assert(DiagGroup);
7894 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7895 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7896 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7897 S.Diag(Loc, DiagID) << DIA->getMessage();
7898 }
7899 }
7900
7901 return false;
7902}
7903
7905 const Expr *ThisArg,
7907 SourceLocation Loc) {
7909 *this, Function, /*ArgDependent=*/true, Loc,
7910 [&](const DiagnoseIfAttr *DIA) {
7912 // It's sane to use the same Args for any redecl of this function, since
7913 // EvaluateWithSubstitution only cares about the position of each
7914 // argument in the arg list, not the ParmVarDecl* it maps to.
7915 if (!DIA->getCond()->EvaluateWithSubstitution(
7916 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7917 return false;
7918 return Result.isInt() && Result.getInt().getBoolValue();
7919 });
7920}
7921
7923 SourceLocation Loc) {
7925 *this, ND, /*ArgDependent=*/false, Loc,
7926 [&](const DiagnoseIfAttr *DIA) {
7927 bool Result;
7928 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7929 Result;
7930 });
7931}
7932
7934 ArrayRef<Expr *> Args,
7935 OverloadCandidateSet &CandidateSet,
7936 TemplateArgumentListInfo *ExplicitTemplateArgs,
7937 bool SuppressUserConversions,
7938 bool PartialOverloading,
7939 bool FirstArgumentIsBase) {
7940 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7941 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7942 ArrayRef<Expr *> FunctionArgs = Args;
7943
7944 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7945 FunctionDecl *FD =
7946 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7947
7948 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7949 QualType ObjectType;
7950 Expr::Classification ObjectClassification;
7951 if (Args.size() > 0) {
7952 if (Expr *E = Args[0]) {
7953 // Use the explicit base to restrict the lookup:
7954 ObjectType = E->getType();
7955 // Pointers in the object arguments are implicitly dereferenced, so we
7956 // always classify them as l-values.
7957 if (!ObjectType.isNull() && ObjectType->isPointerType())
7958 ObjectClassification = Expr::Classification::makeSimpleLValue();
7959 else
7960 ObjectClassification = E->Classify(Context);
7961 } // .. else there is an implicit base.
7962 FunctionArgs = Args.slice(1);
7963 }
7964 if (FunTmpl) {
7966 FunTmpl, F.getPair(),
7968 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7969 FunctionArgs, CandidateSet, SuppressUserConversions,
7970 PartialOverloading);
7971 } else {
7972 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7973 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7974 ObjectClassification, FunctionArgs, CandidateSet,
7975 SuppressUserConversions, PartialOverloading);
7976 }
7977 } else {
7978 // This branch handles both standalone functions and static methods.
7979
7980 // Slice the first argument (which is the base) when we access
7981 // static method as non-static.
7982 if (Args.size() > 0 &&
7983 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7984 !isa<CXXConstructorDecl>(FD)))) {
7985 assert(cast<CXXMethodDecl>(FD)->isStatic());
7986 FunctionArgs = Args.slice(1);
7987 }
7988 if (FunTmpl) {
7989 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7990 ExplicitTemplateArgs, FunctionArgs,
7991 CandidateSet, SuppressUserConversions,
7992 PartialOverloading);
7993 } else {
7994 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7995 SuppressUserConversions, PartialOverloading);
7996 }
7997 }
7998 }
7999}
8000
8002 Expr::Classification ObjectClassification,
8003 ArrayRef<Expr *> Args,
8004 OverloadCandidateSet &CandidateSet,
8005 bool SuppressUserConversions,
8007 NamedDecl *Decl = FoundDecl.getDecl();
8009
8011 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
8012
8013 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
8014 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
8015 "Expected a member function template");
8016 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
8017 /*ExplicitArgs*/ nullptr, ObjectType,
8018 ObjectClassification, Args, CandidateSet,
8019 SuppressUserConversions, false, PO);
8020 } else {
8021 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
8022 ObjectType, ObjectClassification, Args, CandidateSet,
8023 SuppressUserConversions, false, {}, PO);
8024 }
8025}
8026
8029 CXXRecordDecl *ActingContext, QualType ObjectType,
8030 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8031 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8032 bool PartialOverloading, ConversionSequenceList EarlyConversions,
8033 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
8034 const FunctionProtoType *Proto
8035 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
8036 assert(Proto && "Methods without a prototype cannot be overloaded");
8038 "Use AddOverloadCandidate for constructors");
8039
8040 if (!CandidateSet.isNewCandidate(Method, PO))
8041 return;
8042
8043 // C++11 [class.copy]p23: [DR1402]
8044 // A defaulted move assignment operator that is defined as deleted is
8045 // ignored by overload resolution.
8046 if (Method->isDefaulted() && Method->isDeleted() &&
8047 Method->isMoveAssignmentOperator())
8048 return;
8049
8050 // Overload resolution is always an unevaluated context.
8053
8054 bool IgnoreExplicitObject =
8055 (Method->isExplicitObjectMemberFunction() &&
8056 CandidateSet.getKind() ==
8058 bool ImplicitObjectMethodTreatedAsStatic =
8059 CandidateSet.getKind() ==
8061 Method->isImplicitObjectMemberFunction();
8062
8063 unsigned ExplicitOffset =
8064 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
8065
8066 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
8067 int(ImplicitObjectMethodTreatedAsStatic);
8068
8069 unsigned ExtraArgs =
8071 ? 0
8072 : 1;
8073
8074 // Add this candidate
8075 OverloadCandidate &Candidate =
8076 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
8077 Candidate.FoundDecl = FoundDecl;
8078 Candidate.Function = Method;
8079 Candidate.RewriteKind =
8080 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
8081 Candidate.TookAddressOfOverload =
8083 Candidate.ExplicitCallArguments = Args.size();
8084 Candidate.StrictPackMatch = StrictPackMatch;
8085
8086 // (C++ 13.3.2p2): A candidate function having fewer than m
8087 // parameters is viable only if it has an ellipsis in its parameter
8088 // list (8.3.5).
8089 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
8090 !Proto->isVariadic() &&
8091 shouldEnforceArgLimit(PartialOverloading, Method)) {
8092 Candidate.Viable = false;
8094 return;
8095 }
8096
8097 // (C++ 13.3.2p2): A candidate function having more than m parameters
8098 // is viable only if the (m+1)st parameter has a default argument
8099 // (8.3.6). For the purposes of overload resolution, the
8100 // parameter list is truncated on the right, so that there are
8101 // exactly m parameters.
8102 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8103 ExplicitOffset +
8104 int(ImplicitObjectMethodTreatedAsStatic);
8105
8106 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8107 // Not enough arguments.
8108 Candidate.Viable = false;
8110 return;
8111 }
8112
8113 Candidate.Viable = true;
8114
8115 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8116 if (!IgnoreExplicitObject) {
8117 if (ObjectType.isNull())
8118 Candidate.IgnoreObjectArgument = true;
8119 else if (Method->isStatic()) {
8120 // [over.best.ics.general]p8
8121 // When the parameter is the implicit object parameter of a static member
8122 // function, the implicit conversion sequence is a standard conversion
8123 // sequence that is neither better nor worse than any other standard
8124 // conversion sequence.
8125 //
8126 // This is a rule that was introduced in C++23 to support static lambdas.
8127 // We apply it retroactively because we want to support static lambdas as
8128 // an extension and it doesn't hurt previous code.
8129 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8130 } else {
8131 // Determine the implicit conversion sequence for the object
8132 // parameter.
8133 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8134 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8135 Method, ActingContext, /*InOverloadResolution=*/true);
8136 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8137 Candidate.Viable = false;
8139 return;
8140 }
8141 }
8142 }
8143
8144 // (CUDA B.1): Check for invalid calls between targets.
8145 if (getLangOpts().CUDA)
8146 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8147 Method)) {
8148 Candidate.Viable = false;
8149 Candidate.FailureKind = ovl_fail_bad_target;
8150 return;
8151 }
8152
8153 if (Method->getTrailingRequiresClause()) {
8154 ConstraintSatisfaction Satisfaction;
8155 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8156 /*ForOverloadResolution*/ true) ||
8157 !Satisfaction.IsSatisfied) {
8158 Candidate.Viable = false;
8160 return;
8161 }
8162 }
8163
8164 // Determine the implicit conversion sequences for each of the
8165 // arguments.
8166 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8167 unsigned ConvIdx =
8168 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8169 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8170 // We already formed a conversion sequence for this parameter during
8171 // template argument deduction.
8172 } else if (ArgIdx < NumParams) {
8173 // (C++ 13.3.2p3): for F to be a viable function, there shall
8174 // exist for each argument an implicit conversion sequence
8175 // (13.3.3.1) that converts that argument to the corresponding
8176 // parameter of F.
8177 QualType ParamType;
8178 if (ImplicitObjectMethodTreatedAsStatic) {
8179 ParamType = ArgIdx == 0
8180 ? Method->getFunctionObjectParameterReferenceType()
8181 : Proto->getParamType(ArgIdx - 1);
8182 } else {
8183 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8184 }
8185 Candidate.Conversions[ConvIdx]
8186 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8187 SuppressUserConversions,
8188 /*InOverloadResolution=*/true,
8189 /*AllowObjCWritebackConversion=*/
8190 getLangOpts().ObjCAutoRefCount);
8191 if (Candidate.Conversions[ConvIdx].isBad()) {
8192 Candidate.Viable = false;
8194 return;
8195 }
8196 } else {
8197 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8198 // argument for which there is no corresponding parameter is
8199 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8200 Candidate.Conversions[ConvIdx].setEllipsis();
8201 }
8202 }
8203
8204 if (EnableIfAttr *FailedAttr =
8205 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8206 Candidate.Viable = false;
8207 Candidate.FailureKind = ovl_fail_enable_if;
8208 Candidate.DeductionFailure.Data = FailedAttr;
8209 return;
8210 }
8211
8213 Candidate.Viable = false;
8215 }
8216}
8217
8219 Sema &S, OverloadCandidateSet &CandidateSet,
8220 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8221 CXXRecordDecl *ActingContext,
8222 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8223 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8224 bool SuppressUserConversions, bool PartialOverloading,
8226
8227 // C++ [over.match.funcs]p7:
8228 // In each case where a candidate is a function template, candidate
8229 // function template specializations are generated using template argument
8230 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8231 // candidate functions in the usual way.113) A given name can refer to one
8232 // or more function templates and also to a set of overloaded non-template
8233 // functions. In such a case, the candidate functions generated from each
8234 // function template are combined with the set of non-template candidate
8235 // functions.
8236 TemplateDeductionInfo Info(CandidateSet.getLocation());
8237 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8238 FunctionDecl *Specialization = nullptr;
8239 ConversionSequenceList Conversions;
8241 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8242 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8243 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8244 CandidateSet.getKind() ==
8246 [&](ArrayRef<QualType> ParamTypes,
8247 bool OnlyInitializeNonUserDefinedConversions) {
8248 return S.CheckNonDependentConversions(
8249 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8250 Sema::CheckNonDependentConversionsFlag(
8251 SuppressUserConversions,
8252 OnlyInitializeNonUserDefinedConversions),
8253 ActingContext, ObjectType, ObjectClassification, PO);
8254 });
8256 OverloadCandidate &Candidate =
8257 CandidateSet.addCandidate(Conversions.size(), Conversions);
8258 Candidate.FoundDecl = FoundDecl;
8259 Candidate.Function = Method;
8260 Candidate.Viable = false;
8261 Candidate.RewriteKind =
8262 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8263 Candidate.IsSurrogate = false;
8264 Candidate.TookAddressOfOverload =
8265 CandidateSet.getKind() ==
8267
8268 Candidate.IgnoreObjectArgument =
8269 Method->isStatic() ||
8270 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8271 Candidate.ExplicitCallArguments = Args.size();
8274 else {
8276 Candidate.DeductionFailure =
8278 }
8279 return;
8280 }
8281
8282 // Add the function template specialization produced by template argument
8283 // deduction as a candidate.
8284 assert(Specialization && "Missing member function template specialization?");
8286 "Specialization is not a member function?");
8288 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8289 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8290 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8291}
8292
8294 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8295 CXXRecordDecl *ActingContext,
8296 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8297 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8298 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8299 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8300 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8301 return;
8302
8303 if (ExplicitTemplateArgs ||
8304 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8306 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8307 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8308 SuppressUserConversions, PartialOverloading, PO);
8309 return;
8310 }
8311
8313 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8314 Args, SuppressUserConversions, PartialOverloading, PO);
8315}
8316
8317/// Determine whether a given function template has a simple explicit specifier
8318/// or a non-value-dependent explicit-specification that evaluates to true.
8322
8327
8329 Sema &S, OverloadCandidateSet &CandidateSet,
8331 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8332 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8334 bool AggregateCandidateDeduction) {
8335
8336 // If the function template has a non-dependent explicit specification,
8337 // exclude it now if appropriate; we are not permitted to perform deduction
8338 // and substitution in this case.
8339 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8340 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8341 Candidate.FoundDecl = FoundDecl;
8342 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8343 Candidate.Viable = false;
8344 Candidate.FailureKind = ovl_fail_explicit;
8345 return;
8346 }
8347
8348 // C++ [over.match.funcs]p7:
8349 // In each case where a candidate is a function template, candidate
8350 // function template specializations are generated using template argument
8351 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8352 // candidate functions in the usual way.113) A given name can refer to one
8353 // or more function templates and also to a set of overloaded non-template
8354 // functions. In such a case, the candidate functions generated from each
8355 // function template are combined with the set of non-template candidate
8356 // functions.
8357 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8358 FunctionTemplate->getTemplateDepth());
8359 FunctionDecl *Specialization = nullptr;
8360 ConversionSequenceList Conversions;
8362 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8363 PartialOverloading, AggregateCandidateDeduction,
8364 /*PartialOrdering=*/false,
8365 /*ObjectType=*/QualType(),
8366 /*ObjectClassification=*/Expr::Classification(),
8367 CandidateSet.getKind() ==
8369 [&](ArrayRef<QualType> ParamTypes,
8370 bool OnlyInitializeNonUserDefinedConversions) {
8371 return S.CheckNonDependentConversions(
8372 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8373 Sema::CheckNonDependentConversionsFlag(
8374 SuppressUserConversions,
8375 OnlyInitializeNonUserDefinedConversions),
8376 nullptr, QualType(), {}, PO);
8377 });
8379 OverloadCandidate &Candidate =
8380 CandidateSet.addCandidate(Conversions.size(), Conversions);
8381 Candidate.FoundDecl = FoundDecl;
8382 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8383 Candidate.Viable = false;
8384 Candidate.RewriteKind =
8385 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8386 Candidate.IsSurrogate = false;
8387 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8388 // Ignore the object argument if there is one, since we don't have an object
8389 // type.
8390 Candidate.TookAddressOfOverload =
8391 CandidateSet.getKind() ==
8393
8394 Candidate.IgnoreObjectArgument =
8395 isa<CXXMethodDecl>(Candidate.Function) &&
8396 !cast<CXXMethodDecl>(Candidate.Function)
8397 ->isExplicitObjectMemberFunction() &&
8399
8400 Candidate.ExplicitCallArguments = Args.size();
8403 else {
8405 Candidate.DeductionFailure =
8407 }
8408 return;
8409 }
8410
8411 // Add the function template specialization produced by template argument
8412 // deduction as a candidate.
8413 assert(Specialization && "Missing function template specialization?");
8415 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8416 PartialOverloading, AllowExplicit,
8417 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8418 Info.AggregateDeductionCandidateHasMismatchedArity,
8419 Info.hasStrictPackMatch());
8420}
8421
8424 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8425 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8426 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8427 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8428 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8429 return;
8430
8431 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8432
8433 if (ExplicitTemplateArgs ||
8434 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8435 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8436 DependentExplicitSpecifier)) {
8437
8439 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8440 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8441 IsADLCandidate, PO, AggregateCandidateDeduction);
8442
8443 if (DependentExplicitSpecifier)
8445 return;
8446 }
8447
8448 CandidateSet.AddDeferredTemplateCandidate(
8449 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8450 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8451 AggregateCandidateDeduction);
8452}
8453
8456 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8458 CheckNonDependentConversionsFlag UserConversionFlag,
8459 CXXRecordDecl *ActingContext, QualType ObjectType,
8460 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8461 // FIXME: The cases in which we allow explicit conversions for constructor
8462 // arguments never consider calling a constructor template. It's not clear
8463 // that is correct.
8464 const bool AllowExplicit = false;
8465
8466 bool ForOverloadSetAddressResolution =
8468 auto *FD = FunctionTemplate->getTemplatedDecl();
8469 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8470 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8472 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8473
8474 if (Conversions.empty())
8475 Conversions =
8476 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8477
8478 // Overload resolution is always an unevaluated context.
8481
8482 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8483 // require that, but this check should never result in a hard error, and
8484 // overload resolution is permitted to sidestep instantiations.
8485 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8486 !ObjectType.isNull()) {
8487 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8488 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8489 !ParamTypes[0]->isDependentType()) {
8491 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8492 Method, ActingContext, /*InOverloadResolution=*/true,
8493 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8494 : QualType());
8495 if (Conversions[ConvIdx].isBad())
8496 return true;
8497 }
8498 }
8499
8500 // A speculative workaround for self-dependent constraint bugs that manifest
8501 // after CWG2369.
8502 // FIXME: Add references to the standard once P3606 is adopted.
8503 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8504 QualType ArgType) {
8505 ParamType = ParamType.getNonReferenceType();
8506 ArgType = ArgType.getNonReferenceType();
8507 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8508 if (PointerConv) {
8509 ParamType = ParamType->getPointeeType();
8510 ArgType = ArgType->getPointeeType();
8511 }
8512
8513 if (auto *RD = ParamType->getAsCXXRecordDecl();
8514 RD && RD->hasDefinition() &&
8515 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8516 auto Info = getConstructorInfo(ND);
8517 if (!Info)
8518 return false;
8519 CXXConstructorDecl *Ctor = Info.Constructor;
8520 /// isConvertingConstructor takes copy/move constructors into
8521 /// account!
8522 return !Ctor->isCopyOrMoveConstructor() &&
8524 /*AllowExplicit=*/true);
8525 }))
8526 return true;
8527 if (auto *RD = ArgType->getAsCXXRecordDecl();
8528 RD && RD->hasDefinition() &&
8529 !RD->getVisibleConversionFunctions().empty())
8530 return true;
8531
8532 return false;
8533 };
8534
8535 unsigned Offset =
8536 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8537 : 0;
8538
8539 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8540 I != N; ++I) {
8541 QualType ParamType = ParamTypes[I + Offset];
8542 if (!ParamType->isDependentType()) {
8543 unsigned ConvIdx;
8545 ConvIdx = Args.size() - 1 - I;
8546 assert(Args.size() + ThisConversions == 2 &&
8547 "number of args (including 'this') must be exactly 2 for "
8548 "reversed order");
8549 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8550 // would also be 0. 'this' got ConvIdx = 1 previously.
8551 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8552 } else {
8553 // For members, 'this' got ConvIdx = 0 previously.
8554 ConvIdx = ThisConversions + I;
8555 }
8556 if (Conversions[ConvIdx].isInitialized())
8557 continue;
8558 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8559 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8560 continue;
8562 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8563 /*InOverloadResolution=*/true,
8564 /*AllowObjCWritebackConversion=*/
8565 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8566 if (Conversions[ConvIdx].isBad())
8567 return true;
8568 }
8569 }
8570
8571 return false;
8572}
8573
8574/// Determine whether this is an allowable conversion from the result
8575/// of an explicit conversion operator to the expected type, per C++
8576/// [over.match.conv]p1 and [over.match.ref]p1.
8577///
8578/// \param ConvType The return type of the conversion function.
8579///
8580/// \param ToType The type we are converting to.
8581///
8582/// \param AllowObjCPointerConversion Allow a conversion from one
8583/// Objective-C pointer to another.
8584///
8585/// \returns true if the conversion is allowable, false otherwise.
8587 QualType ConvType, QualType ToType,
8588 bool AllowObjCPointerConversion) {
8589 QualType ToNonRefType = ToType.getNonReferenceType();
8590
8591 // Easy case: the types are the same.
8592 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8593 return true;
8594
8595 // Allow qualification conversions.
8596 bool ObjCLifetimeConversion;
8597 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8598 ObjCLifetimeConversion))
8599 return true;
8600
8601 // If we're not allowed to consider Objective-C pointer conversions,
8602 // we're done.
8603 if (!AllowObjCPointerConversion)
8604 return false;
8605
8606 // Is this an Objective-C pointer conversion?
8607 bool IncompatibleObjC = false;
8608 QualType ConvertedType;
8609 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8610 IncompatibleObjC);
8611}
8612
8614 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8615 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8616 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8617 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8618 assert(!Conversion->getDescribedFunctionTemplate() &&
8619 "Conversion function templates use AddTemplateConversionCandidate");
8620 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8621 if (!CandidateSet.isNewCandidate(Conversion))
8622 return;
8623
8624 // If the conversion function has an undeduced return type, trigger its
8625 // deduction now.
8626 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8627 if (DeduceReturnType(Conversion, From->getExprLoc()))
8628 return;
8629 ConvType = Conversion->getConversionType().getNonReferenceType();
8630 }
8631
8632 // If we don't allow any conversion of the result type, ignore conversion
8633 // functions that don't convert to exactly (possibly cv-qualified) T.
8634 if (!AllowResultConversion &&
8635 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8636 return;
8637
8638 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8639 // operator is only a candidate if its return type is the target type or
8640 // can be converted to the target type with a qualification conversion.
8641 //
8642 // FIXME: Include such functions in the candidate list and explain why we
8643 // can't select them.
8644 if (Conversion->isExplicit() &&
8645 !isAllowableExplicitConversion(*this, ConvType, ToType,
8646 AllowObjCConversionOnExplicit))
8647 return;
8648
8649 // Overload resolution is always an unevaluated context.
8652
8653 // Add this candidate
8654 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8655 Candidate.FoundDecl = FoundDecl;
8656 Candidate.Function = Conversion;
8658 Candidate.FinalConversion.setFromType(ConvType);
8659 Candidate.FinalConversion.setAllToTypes(ToType);
8660 Candidate.HasFinalConversion = true;
8661 Candidate.Viable = true;
8662 Candidate.ExplicitCallArguments = 1;
8663 Candidate.StrictPackMatch = StrictPackMatch;
8664
8665 // Explicit functions are not actually candidates at all if we're not
8666 // allowing them in this context, but keep them around so we can point
8667 // to them in diagnostics.
8668 if (!AllowExplicit && Conversion->isExplicit()) {
8669 Candidate.Viable = false;
8670 Candidate.FailureKind = ovl_fail_explicit;
8671 return;
8672 }
8673
8674 // C++ [over.match.funcs]p4:
8675 // For conversion functions, the function is considered to be a member of
8676 // the class of the implicit implied object argument for the purpose of
8677 // defining the type of the implicit object parameter.
8678 //
8679 // Determine the implicit conversion sequence for the implicit
8680 // object parameter.
8681 QualType ObjectType = From->getType();
8682 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8683 ObjectType = FromPtrType->getPointeeType();
8684 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8685 // C++23 [over.best.ics.general]
8686 // However, if the target is [...]
8687 // - the object parameter of a user-defined conversion function
8688 // [...] user-defined conversion sequences are not considered.
8690 *this, CandidateSet.getLocation(), From->getType(),
8691 From->Classify(Context), Conversion, ConversionContext,
8692 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8693 /*SuppressUserConversion*/ true);
8694
8695 if (Candidate.Conversions[0].isBad()) {
8696 Candidate.Viable = false;
8698 return;
8699 }
8700
8701 if (Conversion->getTrailingRequiresClause()) {
8702 ConstraintSatisfaction Satisfaction;
8703 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8704 !Satisfaction.IsSatisfied) {
8705 Candidate.Viable = false;
8707 return;
8708 }
8709 }
8710
8711 // We won't go through a user-defined type conversion function to convert a
8712 // derived to base as such conversions are given Conversion Rank. They only
8713 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8714 QualType FromCanon
8715 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8716 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8717 if (FromCanon == ToCanon ||
8718 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8719 Candidate.Viable = false;
8721 return;
8722 }
8723
8724 // To determine what the conversion from the result of calling the
8725 // conversion function to the type we're eventually trying to
8726 // convert to (ToType), we need to synthesize a call to the
8727 // conversion function and attempt copy initialization from it. This
8728 // makes sure that we get the right semantics with respect to
8729 // lvalues/rvalues and the type. Fortunately, we can allocate this
8730 // call on the stack and we don't need its arguments to be
8731 // well-formed.
8732 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8733 VK_LValue, From->getBeginLoc());
8735 Context.getPointerType(Conversion->getType()),
8736 CK_FunctionToPointerDecay, &ConversionRef,
8738
8739 QualType ConversionType = Conversion->getConversionType();
8740 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8741 Candidate.Viable = false;
8743 return;
8744 }
8745
8746 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8747
8748 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8749
8750 // Introduce a temporary expression with the right type and value category
8751 // that we can use for deduction purposes.
8752 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8753
8755 TryCopyInitialization(*this, &FakeCall, ToType,
8756 /*SuppressUserConversions=*/true,
8757 /*InOverloadResolution=*/false,
8758 /*AllowObjCWritebackConversion=*/false);
8759
8760 switch (ICS.getKind()) {
8762 Candidate.FinalConversion = ICS.Standard;
8763 Candidate.HasFinalConversion = true;
8764
8765 // C++ [over.ics.user]p3:
8766 // If the user-defined conversion is specified by a specialization of a
8767 // conversion function template, the second standard conversion sequence
8768 // shall have exact match rank.
8769 if (Conversion->getPrimaryTemplate() &&
8771 Candidate.Viable = false;
8773 return;
8774 }
8775
8776 // C++0x [dcl.init.ref]p5:
8777 // In the second case, if the reference is an rvalue reference and
8778 // the second standard conversion sequence of the user-defined
8779 // conversion sequence includes an lvalue-to-rvalue conversion, the
8780 // program is ill-formed.
8781 if (ToType->isRValueReferenceType() &&
8783 Candidate.Viable = false;
8785 return;
8786 }
8787 break;
8788
8790 Candidate.Viable = false;
8792 return;
8793
8794 default:
8795 llvm_unreachable(
8796 "Can only end up with a standard conversion sequence or failure");
8797 }
8798
8799 if (EnableIfAttr *FailedAttr =
8800 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8801 Candidate.Viable = false;
8802 Candidate.FailureKind = ovl_fail_enable_if;
8803 Candidate.DeductionFailure.Data = FailedAttr;
8804 return;
8805 }
8806
8807 if (isNonViableMultiVersionOverload(Conversion)) {
8808 Candidate.Viable = false;
8810 }
8811}
8812
8814 Sema &S, OverloadCandidateSet &CandidateSet,
8816 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8817 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8818 bool AllowResultConversion) {
8819
8820 // If the function template has a non-dependent explicit specification,
8821 // exclude it now if appropriate; we are not permitted to perform deduction
8822 // and substitution in this case.
8823 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8824 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8825 Candidate.FoundDecl = FoundDecl;
8826 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8827 Candidate.Viable = false;
8828 Candidate.FailureKind = ovl_fail_explicit;
8829 return;
8830 }
8831
8832 QualType ObjectType = From->getType();
8833 Expr::Classification ObjectClassification = From->Classify(S.Context);
8834
8835 TemplateDeductionInfo Info(CandidateSet.getLocation());
8838 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8839 Specialization, Info);
8841 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8842 Candidate.FoundDecl = FoundDecl;
8843 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8844 Candidate.Viable = false;
8846 Candidate.ExplicitCallArguments = 1;
8847 Candidate.DeductionFailure =
8849 return;
8850 }
8851
8852 // Add the conversion function template specialization produced by
8853 // template argument deduction as a candidate.
8854 assert(Specialization && "Missing function template specialization?");
8855 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8856 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8857 AllowExplicit, AllowResultConversion,
8858 Info.hasStrictPackMatch());
8859}
8860
8863 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8864 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8865 bool AllowExplicit, bool AllowResultConversion) {
8866 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8867 "Only conversion function templates permitted here");
8868
8869 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8870 return;
8871
8872 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8873 CandidateSet.getKind() ==
8877 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8878 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8879 AllowResultConversion);
8880
8882 return;
8883 }
8884
8886 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8887 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8888}
8889
8891 DeclAccessPair FoundDecl,
8892 CXXRecordDecl *ActingContext,
8893 const FunctionProtoType *Proto,
8894 Expr *Object,
8895 ArrayRef<Expr *> Args,
8896 OverloadCandidateSet& CandidateSet) {
8897 if (!CandidateSet.isNewCandidate(Conversion))
8898 return;
8899
8900 // Overload resolution is always an unevaluated context.
8903
8904 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8905 Candidate.FoundDecl = FoundDecl;
8906 Candidate.Function = nullptr;
8907 Candidate.Surrogate = Conversion;
8908 Candidate.IsSurrogate = true;
8909 Candidate.Viable = true;
8910 Candidate.ExplicitCallArguments = Args.size();
8911
8912 // Determine the implicit conversion sequence for the implicit
8913 // object parameter.
8914 ImplicitConversionSequence ObjectInit;
8915 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8916 ObjectInit = TryCopyInitialization(*this, Object,
8917 Conversion->getParamDecl(0)->getType(),
8918 /*SuppressUserConversions=*/false,
8919 /*InOverloadResolution=*/true, false);
8920 } else {
8922 *this, CandidateSet.getLocation(), Object->getType(),
8923 Object->Classify(Context), Conversion, ActingContext);
8924 }
8925
8926 if (ObjectInit.isBad()) {
8927 Candidate.Viable = false;
8929 Candidate.Conversions[0] = ObjectInit;
8930 return;
8931 }
8932
8933 // The first conversion is actually a user-defined conversion whose
8934 // first conversion is ObjectInit's standard conversion (which is
8935 // effectively a reference binding). Record it as such.
8936 Candidate.Conversions[0].setUserDefined();
8937 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8938 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8939 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8940 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8941 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8942 Candidate.Conversions[0].UserDefined.After
8943 = Candidate.Conversions[0].UserDefined.Before;
8944 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8945
8946 // Find the
8947 unsigned NumParams = Proto->getNumParams();
8948
8949 // (C++ 13.3.2p2): A candidate function having fewer than m
8950 // parameters is viable only if it has an ellipsis in its parameter
8951 // list (8.3.5).
8952 if (Args.size() > NumParams && !Proto->isVariadic()) {
8953 Candidate.Viable = false;
8955 return;
8956 }
8957
8958 // Function types don't have any default arguments, so just check if
8959 // we have enough arguments.
8960 if (Args.size() < NumParams) {
8961 // Not enough arguments.
8962 Candidate.Viable = false;
8964 return;
8965 }
8966
8967 // Determine the implicit conversion sequences for each of the
8968 // arguments.
8969 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8970 if (ArgIdx < NumParams) {
8971 // (C++ 13.3.2p3): for F to be a viable function, there shall
8972 // exist for each argument an implicit conversion sequence
8973 // (13.3.3.1) that converts that argument to the corresponding
8974 // parameter of F.
8975 QualType ParamType = Proto->getParamType(ArgIdx);
8976 Candidate.Conversions[ArgIdx + 1]
8977 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8978 /*SuppressUserConversions=*/false,
8979 /*InOverloadResolution=*/false,
8980 /*AllowObjCWritebackConversion=*/
8981 getLangOpts().ObjCAutoRefCount);
8982 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8983 Candidate.Viable = false;
8985 return;
8986 }
8987 } else {
8988 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8989 // argument for which there is no corresponding parameter is
8990 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8991 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8992 }
8993 }
8994
8995 if (Conversion->getTrailingRequiresClause()) {
8996 ConstraintSatisfaction Satisfaction;
8997 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8998 /*ForOverloadResolution*/ true) ||
8999 !Satisfaction.IsSatisfied) {
9000 Candidate.Viable = false;
9002 return;
9003 }
9004 }
9005
9006 if (EnableIfAttr *FailedAttr =
9007 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
9008 Candidate.Viable = false;
9009 Candidate.FailureKind = ovl_fail_enable_if;
9010 Candidate.DeductionFailure.Data = FailedAttr;
9011 return;
9012 }
9013}
9014
9016 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
9017 OverloadCandidateSet &CandidateSet,
9018 TemplateArgumentListInfo *ExplicitTemplateArgs) {
9019 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
9020 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
9021 ArrayRef<Expr *> FunctionArgs = Args;
9022
9023 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
9024 FunctionDecl *FD =
9025 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
9026
9027 // Don't consider rewritten functions if we're not rewriting.
9028 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
9029 continue;
9030
9031 assert(!isa<CXXMethodDecl>(FD) &&
9032 "unqualified operator lookup found a member function");
9033
9034 if (FunTmpl) {
9035 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
9036 FunctionArgs, CandidateSet);
9037 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9038
9039 // As template candidates are not deduced immediately,
9040 // persist the array in the overload set.
9042 FunctionArgs[1], FunctionArgs[0]);
9043 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
9044 Reversed, CandidateSet, false, false, true,
9045 ADLCallKind::NotADL,
9047 }
9048 } else {
9049 if (ExplicitTemplateArgs)
9050 continue;
9051 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
9052 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
9053 AddOverloadCandidate(FD, F.getPair(),
9054 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
9055 false, false, true, false, ADLCallKind::NotADL, {},
9057 }
9058 }
9059}
9060
9062 SourceLocation OpLoc,
9063 ArrayRef<Expr *> Args,
9064 OverloadCandidateSet &CandidateSet,
9066 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9067
9068 // C++ [over.match.oper]p3:
9069 // For a unary operator @ with an operand of a type whose
9070 // cv-unqualified version is T1, and for a binary operator @ with
9071 // a left operand of a type whose cv-unqualified version is T1 and
9072 // a right operand of a type whose cv-unqualified version is T2,
9073 // three sets of candidate functions, designated member
9074 // candidates, non-member candidates and built-in candidates, are
9075 // constructed as follows:
9076 QualType T1 = Args[0]->getType();
9077
9078 // -- If T1 is a complete class type or a class currently being
9079 // defined, the set of member candidates is the result of the
9080 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9081 // the set of member candidates is empty.
9082 if (T1->isRecordType()) {
9083 bool IsComplete = isCompleteType(OpLoc, T1);
9084 auto *T1RD = T1->getAsCXXRecordDecl();
9085 // Complete the type if it can be completed.
9086 // If the type is neither complete nor being defined, bail out now.
9087 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9088 return;
9089
9090 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9091 LookupQualifiedName(Operators, T1RD);
9092 Operators.suppressAccessDiagnostics();
9093
9094 for (LookupResult::iterator Oper = Operators.begin(),
9095 OperEnd = Operators.end();
9096 Oper != OperEnd; ++Oper) {
9097 if (Oper->getAsFunction() &&
9099 !CandidateSet.getRewriteInfo().shouldAddReversed(
9100 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9101 continue;
9102 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9103 Args[0]->Classify(Context), Args.slice(1),
9104 CandidateSet, /*SuppressUserConversion=*/false, PO);
9105 }
9106 }
9107}
9108
9110 OverloadCandidateSet& CandidateSet,
9111 bool IsAssignmentOperator,
9112 unsigned NumContextualBoolArguments) {
9113 // Overload resolution is always an unevaluated context.
9116
9117 // Add this candidate
9118 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9119 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9120 Candidate.Function = nullptr;
9121 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9122
9123 // Determine the implicit conversion sequences for each of the
9124 // arguments.
9125 Candidate.Viable = true;
9126 Candidate.ExplicitCallArguments = Args.size();
9127 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9128 // C++ [over.match.oper]p4:
9129 // For the built-in assignment operators, conversions of the
9130 // left operand are restricted as follows:
9131 // -- no temporaries are introduced to hold the left operand, and
9132 // -- no user-defined conversions are applied to the left
9133 // operand to achieve a type match with the left-most
9134 // parameter of a built-in candidate.
9135 //
9136 // We block these conversions by turning off user-defined
9137 // conversions, since that is the only way that initialization of
9138 // a reference to a non-class type can occur from something that
9139 // is not of the same type.
9140 if (ArgIdx < NumContextualBoolArguments) {
9141 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9142 "Contextual conversion to bool requires bool type");
9143 Candidate.Conversions[ArgIdx]
9144 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9145 } else {
9146 Candidate.Conversions[ArgIdx]
9147 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9148 ArgIdx == 0 && IsAssignmentOperator,
9149 /*InOverloadResolution=*/false,
9150 /*AllowObjCWritebackConversion=*/
9151 getLangOpts().ObjCAutoRefCount);
9152 }
9153 if (Candidate.Conversions[ArgIdx].isBad()) {
9154 Candidate.Viable = false;
9156 break;
9157 }
9158 }
9159}
9160
9161namespace {
9162
9163/// BuiltinCandidateTypeSet - A set of types that will be used for the
9164/// candidate operator functions for built-in operators (C++
9165/// [over.built]). The types are separated into pointer types and
9166/// enumeration types.
9167class BuiltinCandidateTypeSet {
9168 /// TypeSet - A set of types.
9169 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9170
9171 /// PointerTypes - The set of pointer types that will be used in the
9172 /// built-in candidates.
9173 TypeSet PointerTypes;
9174
9175 /// MemberPointerTypes - The set of member pointer types that will be
9176 /// used in the built-in candidates.
9177 TypeSet MemberPointerTypes;
9178
9179 /// EnumerationTypes - The set of enumeration types that will be
9180 /// used in the built-in candidates.
9181 TypeSet EnumerationTypes;
9182
9183 /// The set of vector types that will be used in the built-in
9184 /// candidates.
9185 TypeSet VectorTypes;
9186
9187 /// The set of matrix types that will be used in the built-in
9188 /// candidates.
9189 TypeSet MatrixTypes;
9190
9191 /// The set of _BitInt types that will be used in the built-in candidates.
9192 TypeSet BitIntTypes;
9193
9194 /// A flag indicating non-record types are viable candidates
9195 bool HasNonRecordTypes;
9196
9197 /// A flag indicating whether either arithmetic or enumeration types
9198 /// were present in the candidate set.
9199 bool HasArithmeticOrEnumeralTypes;
9200
9201 /// A flag indicating whether the candidate set has a type that might
9202 /// convert to a promoted arithmetic type or to a vector type. This is
9203 /// conservative: only scoped enumerations, pointers, member pointers,
9204 /// nullptr_t, and classes that convert to nothing else are known not to.
9205 bool MayConvertToArithmetic;
9206
9207 /// A flag indicating whether the nullptr type was present in the
9208 /// candidate set.
9209 bool HasNullPtrType;
9210
9211 /// A flag indicating whether the reflection type was present in the
9212 /// candidate set.
9213 bool HasReflectionType;
9214
9215 /// Sema - The semantic analysis instance where we are building the
9216 /// candidate type set.
9217 Sema &SemaRef;
9218
9219 /// Context - The AST context in which we will build the type sets.
9220 ASTContext &Context;
9221
9222 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9223 const Qualifiers &VisibleQuals);
9224 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9225
9226public:
9227 /// iterator - Iterates through the types that are part of the set.
9228 typedef TypeSet::iterator iterator;
9229
9230 BuiltinCandidateTypeSet(Sema &SemaRef)
9231 : HasNonRecordTypes(false), HasArithmeticOrEnumeralTypes(false),
9232 MayConvertToArithmetic(false), HasNullPtrType(false),
9233 HasReflectionType(false), SemaRef(SemaRef), Context(SemaRef.Context) {}
9234
9235 void AddTypesConvertedFrom(QualType Ty,
9236 SourceLocation Loc,
9237 bool AllowUserConversions,
9238 bool AllowExplicitConversions,
9239 const Qualifiers &VisibleTypeConversionsQuals);
9240
9241 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9242 llvm::iterator_range<iterator> member_pointer_types() {
9243 return MemberPointerTypes;
9244 }
9245 llvm::iterator_range<iterator> enumeration_types() {
9246 return EnumerationTypes;
9247 }
9248 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9249 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9250 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9251
9252 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9253 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9254 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9255 bool mayConvertToArithmetic() const { return MayConvertToArithmetic; }
9256 bool hasNullPtrType() const { return HasNullPtrType; }
9257 bool hasReflectionType() const { return HasReflectionType; }
9258};
9259
9260} // end anonymous namespace
9261
9262/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9263/// the set of pointer types along with any more-qualified variants of
9264/// that type. For example, if @p Ty is "int const *", this routine
9265/// will add "int const *", "int const volatile *", "int const
9266/// restrict *", and "int const volatile restrict *" to the set of
9267/// pointer types. Returns true if the add of @p Ty itself succeeded,
9268/// false otherwise.
9269///
9270/// FIXME: what to do about extended qualifiers?
9271bool
9272BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9273 const Qualifiers &VisibleQuals) {
9274
9275 // Insert this type.
9276 if (!PointerTypes.insert(Ty))
9277 return false;
9278
9279 QualType PointeeTy;
9280 const PointerType *PointerTy = Ty->getAs<PointerType>();
9281 bool buildObjCPtr = false;
9282 if (!PointerTy) {
9283 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9284 PointeeTy = PTy->getPointeeType();
9285 buildObjCPtr = true;
9286 } else {
9287 PointeeTy = PointerTy->getPointeeType();
9288 }
9289
9290 // Don't add qualified variants of arrays. For one, they're not allowed
9291 // (the qualifier would sink to the element type), and for another, the
9292 // only overload situation where it matters is subscript or pointer +- int,
9293 // and those shouldn't have qualifier variants anyway.
9294 if (PointeeTy->isArrayType())
9295 return true;
9296
9297 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9298 bool hasVolatile = VisibleQuals.hasVolatile();
9299 bool hasRestrict = VisibleQuals.hasRestrict();
9300
9301 // Iterate through all strict supersets of BaseCVR.
9302 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9303 if ((CVR | BaseCVR) != CVR) continue;
9304 // Skip over volatile if no volatile found anywhere in the types.
9305 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9306
9307 // Skip over restrict if no restrict found anywhere in the types, or if
9308 // the type cannot be restrict-qualified.
9309 if ((CVR & Qualifiers::Restrict) &&
9310 (!hasRestrict ||
9311 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9312 continue;
9313
9314 // Build qualified pointee type.
9315 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9316
9317 // Build qualified pointer type.
9318 QualType QPointerTy;
9319 if (!buildObjCPtr)
9320 QPointerTy = Context.getPointerType(QPointeeTy);
9321 else
9322 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9323
9324 // Insert qualified pointer type.
9325 PointerTypes.insert(QPointerTy);
9326 }
9327
9328 return true;
9329}
9330
9331/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9332/// to the set of pointer types along with any more-qualified variants of
9333/// that type. For example, if @p Ty is "int const *", this routine
9334/// will add "int const *", "int const volatile *", "int const
9335/// restrict *", and "int const volatile restrict *" to the set of
9336/// pointer types. Returns true if the add of @p Ty itself succeeded,
9337/// false otherwise.
9338///
9339/// FIXME: what to do about extended qualifiers?
9340bool
9341BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9342 QualType Ty) {
9343 // Insert this type.
9344 if (!MemberPointerTypes.insert(Ty))
9345 return false;
9346
9347 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9348 assert(PointerTy && "type was not a member pointer type!");
9349
9350 QualType PointeeTy = PointerTy->getPointeeType();
9351 // Don't add qualified variants of arrays. For one, they're not allowed
9352 // (the qualifier would sink to the element type), and for another, the
9353 // only overload situation where it matters is subscript or pointer +- int,
9354 // and those shouldn't have qualifier variants anyway.
9355 if (PointeeTy->isArrayType())
9356 return true;
9357 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9358
9359 // Iterate through all strict supersets of the pointee type's CVR
9360 // qualifiers.
9361 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9362 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9363 if ((CVR | BaseCVR) != CVR) continue;
9364
9365 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9366 MemberPointerTypes.insert(Context.getMemberPointerType(
9367 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9368 }
9369
9370 return true;
9371}
9372
9373/// AddTypesConvertedFrom - Add each of the types to which the type @p
9374/// Ty can be implicit converted to the given set of @p Types. We're
9375/// primarily interested in pointer types and enumeration types. We also
9376/// take member pointer types, for the conditional operator.
9377/// AllowUserConversions is true if we should look at the conversion
9378/// functions of a class type, and AllowExplicitConversions if we
9379/// should also include the explicit conversion functions of a class
9380/// type.
9381void
9382BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9383 SourceLocation Loc,
9384 bool AllowUserConversions,
9385 bool AllowExplicitConversions,
9386 const Qualifiers &VisibleQuals) {
9387 // Only deal with canonical types.
9388 Ty = Context.getCanonicalType(Ty);
9389
9390 // Look through reference types; they aren't part of the type of an
9391 // expression for the purposes of conversions.
9392 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9393 Ty = RefTy->getPointeeType();
9394
9395 // If we're dealing with an array type, decay to the pointer.
9396 if (Ty->isArrayType())
9397 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9398
9399 // Otherwise, we don't care about qualifiers on the type.
9400 Ty = Ty.getLocalUnqualifiedType();
9401
9402 // Flag if we ever add a non-record type.
9403 bool TyIsRec = Ty->isRecordType();
9404 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9405
9406 // Flag if we encounter an arithmetic type.
9407 HasArithmeticOrEnumeralTypes =
9408 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9409
9410 // Flag if the type might convert to a promoted arithmetic or vector type.
9411 // For records, this is set below when visiting their conversion functions.
9412 MayConvertToArithmetic =
9413 MayConvertToArithmetic ||
9414 !(TyIsRec || Ty->isScopedEnumeralType() || Ty->isAnyPointerType() ||
9415 Ty->isMemberPointerType() || Ty->isNullPtrType());
9416
9417 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9418 PointerTypes.insert(Ty);
9419 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9420 // Insert our type, and its more-qualified variants, into the set
9421 // of types.
9422 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9423 return;
9424 } else if (Ty->isMemberPointerType()) {
9425 // Member pointers are far easier, since the pointee can't be converted.
9426 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9427 return;
9428 } else if (Ty->isEnumeralType()) {
9429 HasArithmeticOrEnumeralTypes = true;
9430 EnumerationTypes.insert(Ty);
9431 } else if (Ty->isBitIntType()) {
9432 HasArithmeticOrEnumeralTypes = true;
9433 BitIntTypes.insert(Ty);
9434 } else if (Ty->isVectorType()) {
9435 // We treat vector types as arithmetic types in many contexts as an
9436 // extension.
9437 HasArithmeticOrEnumeralTypes = true;
9438 VectorTypes.insert(Ty);
9439 } else if (Ty->isMatrixType()) {
9440 // Similar to vector types, we treat vector types as arithmetic types in
9441 // many contexts as an extension.
9442 HasArithmeticOrEnumeralTypes = true;
9443 MatrixTypes.insert(Ty);
9444 } else if (Ty->isNullPtrType()) {
9445 HasNullPtrType = true;
9446 } else if (Ty->isMetaInfoType()) {
9447 HasReflectionType = true;
9448 } else if (AllowUserConversions && TyIsRec) {
9449 // No conversion functions in incomplete types.
9450 if (!SemaRef.isCompleteType(Loc, Ty))
9451 return;
9452
9453 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9454 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9455 if (isa<UsingShadowDecl>(D))
9456 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9457
9458 // Skip conversion function templates; they don't tell us anything
9459 // about which builtin types we can convert to.
9461 MayConvertToArithmetic = true;
9462 continue;
9463 }
9464
9465 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9466 if (AllowExplicitConversions || !Conv->isExplicit()) {
9467 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9468 VisibleQuals);
9469 }
9470 }
9471 }
9472}
9473/// Helper function for adjusting address spaces for the pointer or reference
9474/// operands of builtin operators depending on the argument.
9479
9480/// Helper function for AddBuiltinOperatorCandidates() that adds
9481/// the volatile- and non-volatile-qualified assignment operators for the
9482/// given type to the candidate set.
9484 QualType T,
9485 ArrayRef<Expr *> Args,
9486 OverloadCandidateSet &CandidateSet) {
9487 QualType ParamTypes[2];
9488
9489 // T& operator=(T&, T)
9490 ParamTypes[0] = S.Context.getLValueReferenceType(
9492 ParamTypes[1] = T;
9493 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9494 /*IsAssignmentOperator=*/true);
9495
9497 // volatile T& operator=(volatile T&, T)
9498 ParamTypes[0] = S.Context.getLValueReferenceType(
9500 Args[0]));
9501 ParamTypes[1] = T;
9502 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9503 /*IsAssignmentOperator=*/true);
9504 }
9505}
9506
9507/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9508/// if any, found in visible type conversion functions found in ArgExpr's type.
9509static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9510 Qualifiers VRQuals;
9511 CXXRecordDecl *ClassDecl;
9512 if (const MemberPointerType *RHSMPType =
9513 ArgExpr->getType()->getAs<MemberPointerType>())
9514 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9515 else
9516 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9517 if (!ClassDecl) {
9518 // Just to be safe, assume the worst case.
9519 VRQuals.addVolatile();
9520 VRQuals.addRestrict();
9521 return VRQuals;
9522 }
9523 if (!ClassDecl->hasDefinition())
9524 return VRQuals;
9525
9526 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9527 if (isa<UsingShadowDecl>(D))
9528 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9529 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9530 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9531 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9532 CanTy = ResTypeRef->getPointeeType();
9533 // Need to go down the pointer/mempointer chain and add qualifiers
9534 // as see them.
9535 bool done = false;
9536 while (!done) {
9537 if (CanTy.isRestrictQualified())
9538 VRQuals.addRestrict();
9539 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9540 CanTy = ResTypePtr->getPointeeType();
9541 else if (const MemberPointerType *ResTypeMPtr =
9542 CanTy->getAs<MemberPointerType>())
9543 CanTy = ResTypeMPtr->getPointeeType();
9544 else
9545 done = true;
9546 if (CanTy.isVolatileQualified())
9547 VRQuals.addVolatile();
9548 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9549 return VRQuals;
9550 }
9551 }
9552 }
9553 return VRQuals;
9554}
9555
9556// Note: We're currently only handling qualifiers that are meaningful for the
9557// LHS of compound assignment overloading.
9559 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9560 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9561 // _Atomic
9562 if (Available.hasAtomic()) {
9563 Available.removeAtomic();
9564 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9565 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9566 return;
9567 }
9568
9569 // volatile
9570 if (Available.hasVolatile()) {
9571 Available.removeVolatile();
9572 assert(!Applied.hasVolatile());
9573 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9574 Callback);
9575 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9576 return;
9577 }
9578
9579 Callback(Applied);
9580}
9581
9583 QualifiersAndAtomic Quals,
9584 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9586 Callback);
9587}
9588
9590 QualifiersAndAtomic Quals,
9591 Sema &S) {
9592 if (Quals.hasAtomic())
9594 if (Quals.hasVolatile())
9597}
9598
9599namespace {
9600
9601/// Helper class to manage the addition of builtin operator overload
9602/// candidates. It provides shared state and utility methods used throughout
9603/// the process, as well as a helper method to add each group of builtin
9604/// operator overloads from the standard to a candidate set.
9605class BuiltinOperatorOverloadBuilder {
9606 // Common instance state available to all overload candidate addition methods.
9607 Sema &S;
9608 ArrayRef<Expr *> Args;
9609 QualifiersAndAtomic VisibleTypeConversionsQuals;
9610 // Whether a candidate whose parameters are all arithmetic, vector or matrix
9611 // types can be viable. It is viable if there is an arithmetic or enumeral
9612 // candidate type, and every argument might convert to such a type.
9613 bool ArithmeticCandidatesMayBeViable;
9614 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9615 OverloadCandidateSet &CandidateSet;
9616
9617 static constexpr int ArithmeticTypesCap = 26;
9618 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9619
9620 // Define some indices used to iterate over the arithmetic types in
9621 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9622 // types are that preserved by promotion (C++ [over.built]p2).
9623 unsigned FirstIntegralType,
9624 LastIntegralType;
9625 unsigned FirstPromotedIntegralType,
9626 LastPromotedIntegralType;
9627 unsigned FirstPromotedArithmeticType,
9628 LastPromotedArithmeticType;
9629 unsigned NumArithmeticTypes;
9630
9631 void InitArithmeticTypes() {
9632 // Start of promoted types.
9633 FirstPromotedArithmeticType = 0;
9634 ArithmeticTypes.push_back(S.Context.FloatTy);
9635 ArithmeticTypes.push_back(S.Context.DoubleTy);
9636 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9638 ArithmeticTypes.push_back(S.Context.Float128Ty);
9640 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9641
9642 // Start of integral types.
9643 FirstIntegralType = ArithmeticTypes.size();
9644 FirstPromotedIntegralType = ArithmeticTypes.size();
9645 ArithmeticTypes.push_back(S.Context.IntTy);
9646 ArithmeticTypes.push_back(S.Context.LongTy);
9647 ArithmeticTypes.push_back(S.Context.LongLongTy);
9651 ArithmeticTypes.push_back(S.Context.Int128Ty);
9652 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9653 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9654 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9658 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9659
9660 /// We add candidates for the unique, unqualified _BitInt types present in
9661 /// the candidate type set. The candidate set already handled ensuring the
9662 /// type is unqualified and canonical, but because we're adding from N
9663 /// different sets, we need to do some extra work to unique things. Insert
9664 /// the candidates into a unique set, then move from that set into the list
9665 /// of arithmetic types.
9666 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9667 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9668 for (QualType BitTy : Candidate.bitint_types())
9669 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9670 }
9671 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9672 LastPromotedIntegralType = ArithmeticTypes.size();
9673 LastPromotedArithmeticType = ArithmeticTypes.size();
9674 // End of promoted types.
9675
9676 ArithmeticTypes.push_back(S.Context.BoolTy);
9677 ArithmeticTypes.push_back(S.Context.CharTy);
9678 ArithmeticTypes.push_back(S.Context.WCharTy);
9679 if (S.Context.getLangOpts().Char8)
9680 ArithmeticTypes.push_back(S.Context.Char8Ty);
9681 ArithmeticTypes.push_back(S.Context.Char16Ty);
9682 ArithmeticTypes.push_back(S.Context.Char32Ty);
9683 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9684 ArithmeticTypes.push_back(S.Context.ShortTy);
9685 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9686 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9687 LastIntegralType = ArithmeticTypes.size();
9688 NumArithmeticTypes = ArithmeticTypes.size();
9689 // End of integral types.
9690 // FIXME: What about complex? What about half?
9691
9692 // We don't know for sure how many bit-precise candidates were involved, so
9693 // we subtract those from the total when testing whether we're under the
9694 // cap or not.
9695 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9696 ArithmeticTypesCap &&
9697 "Enough inline storage for all arithmetic types.");
9698 }
9699
9700 /// Helper method to factor out the common pattern of adding overloads
9701 /// for '++' and '--' builtin operators.
9702 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9703 bool HasVolatile,
9704 bool HasRestrict) {
9705 QualType ParamTypes[2] = {
9706 S.Context.getLValueReferenceType(CandidateTy),
9707 S.Context.IntTy
9708 };
9709
9710 // Non-volatile version.
9711 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9712
9713 // Use a heuristic to reduce number of builtin candidates in the set:
9714 // add volatile version only if there are conversions to a volatile type.
9715 if (HasVolatile) {
9716 ParamTypes[0] =
9718 S.Context.getVolatileType(CandidateTy));
9719 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9720 }
9721
9722 // Add restrict version only if there are conversions to a restrict type
9723 // and our candidate type is a non-restrict-qualified pointer.
9724 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9725 !CandidateTy.isRestrictQualified()) {
9726 ParamTypes[0]
9729 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9730
9731 if (HasVolatile) {
9732 ParamTypes[0]
9734 S.Context.getCVRQualifiedType(CandidateTy,
9737 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9738 }
9739 }
9740
9741 }
9742
9743 /// Helper to add an overload candidate for a binary builtin with types \p L
9744 /// and \p R.
9745 void AddCandidate(QualType L, QualType R) {
9746 QualType LandR[2] = {L, R};
9747 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9748 }
9749
9750public:
9751 BuiltinOperatorOverloadBuilder(
9752 Sema &S, ArrayRef<Expr *> Args,
9753 QualifiersAndAtomic VisibleTypeConversionsQuals,
9754 bool HasArithmeticOrEnumeralCandidateType,
9755 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9756 OverloadCandidateSet &CandidateSet)
9757 : S(S), Args(Args),
9758 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9759 ArithmeticCandidatesMayBeViable(
9760 HasArithmeticOrEnumeralCandidateType &&
9761 llvm::all_of(CandidateTypes,
9762 [](const BuiltinCandidateTypeSet &Types) {
9763 return Types.mayConvertToArithmetic();
9764 })),
9765 CandidateTypes(CandidateTypes), CandidateSet(CandidateSet) {
9766 InitArithmeticTypes();
9767 }
9768
9769 // Increment is deprecated for bool since C++17.
9770 //
9771 // C++ [over.built]p3:
9772 //
9773 // For every pair (T, VQ), where T is an arithmetic type other
9774 // than bool, and VQ is either volatile or empty, there exist
9775 // candidate operator functions of the form
9776 //
9777 // VQ T& operator++(VQ T&);
9778 // T operator++(VQ T&, int);
9779 //
9780 // C++ [over.built]p4:
9781 //
9782 // For every pair (T, VQ), where T is an arithmetic type other
9783 // than bool, and VQ is either volatile or empty, there exist
9784 // candidate operator functions of the form
9785 //
9786 // VQ T& operator--(VQ T&);
9787 // T operator--(VQ T&, int);
9788 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9789 if (!ArithmeticCandidatesMayBeViable)
9790 return;
9791
9792 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9793 const auto TypeOfT = ArithmeticTypes[Arith];
9794 if (TypeOfT == S.Context.BoolTy) {
9795 if (Op == OO_MinusMinus)
9796 continue;
9797 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9798 continue;
9799 }
9800 addPlusPlusMinusMinusStyleOverloads(
9801 TypeOfT,
9802 VisibleTypeConversionsQuals.hasVolatile(),
9803 VisibleTypeConversionsQuals.hasRestrict());
9804 }
9805 }
9806
9807 // C++ [over.built]p5:
9808 //
9809 // For every pair (T, VQ), where T is a cv-qualified or
9810 // cv-unqualified object type, and VQ is either volatile or
9811 // empty, there exist candidate operator functions of the form
9812 //
9813 // T*VQ& operator++(T*VQ&);
9814 // T*VQ& operator--(T*VQ&);
9815 // T* operator++(T*VQ&, int);
9816 // T* operator--(T*VQ&, int);
9817 void addPlusPlusMinusMinusPointerOverloads() {
9818 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9819 // Skip pointer types that aren't pointers to object types.
9820 if (!PtrTy->getPointeeType()->isObjectType())
9821 continue;
9822
9823 addPlusPlusMinusMinusStyleOverloads(
9824 PtrTy,
9825 (!PtrTy.isVolatileQualified() &&
9826 VisibleTypeConversionsQuals.hasVolatile()),
9827 (!PtrTy.isRestrictQualified() &&
9828 VisibleTypeConversionsQuals.hasRestrict()));
9829 }
9830 }
9831
9832 // C++ [over.built]p6:
9833 // For every cv-qualified or cv-unqualified object type T, there
9834 // exist candidate operator functions of the form
9835 //
9836 // T& operator*(T*);
9837 //
9838 // C++ [over.built]p7:
9839 // For every function type T that does not have cv-qualifiers or a
9840 // ref-qualifier, there exist candidate operator functions of the form
9841 // T& operator*(T*);
9842 void addUnaryStarPointerOverloads() {
9843 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9844 QualType PointeeTy = ParamTy->getPointeeType();
9845 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9846 continue;
9847
9848 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9849 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9850 continue;
9851
9852 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9853 }
9854 }
9855
9856 // C++ [over.built]p9:
9857 // For every promoted arithmetic type T, there exist candidate
9858 // operator functions of the form
9859 //
9860 // T operator+(T);
9861 // T operator-(T);
9862 void addUnaryPlusOrMinusArithmeticOverloads() {
9863 if (!ArithmeticCandidatesMayBeViable)
9864 return;
9865
9866 for (unsigned Arith = FirstPromotedArithmeticType;
9867 Arith < LastPromotedArithmeticType; ++Arith) {
9868 QualType ArithTy = ArithmeticTypes[Arith];
9869 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9870 }
9871
9872 // Extension: We also add these operators for vector types.
9873 for (QualType VecTy : CandidateTypes[0].vector_types())
9874 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9875 }
9876
9877 // C++ [over.built]p8:
9878 // For every type T, there exist candidate operator functions of
9879 // the form
9880 //
9881 // T* operator+(T*);
9882 void addUnaryPlusPointerOverloads() {
9883 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9884 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9885 }
9886
9887 // C++ [over.built]p10:
9888 // For every promoted integral type T, there exist candidate
9889 // operator functions of the form
9890 //
9891 // T operator~(T);
9892 void addUnaryTildePromotedIntegralOverloads() {
9893 if (!ArithmeticCandidatesMayBeViable)
9894 return;
9895
9896 for (unsigned Int = FirstPromotedIntegralType;
9897 Int < LastPromotedIntegralType; ++Int) {
9898 QualType IntTy = ArithmeticTypes[Int];
9899 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9900 }
9901
9902 // Extension: We also add this operator for vector types.
9903 for (QualType VecTy : CandidateTypes[0].vector_types())
9904 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9905 }
9906
9907 // C++ [over.match.oper]p16:
9908 // For every pointer to member type T or type std::nullptr_t, there
9909 // exist candidate operator functions of the form
9910 //
9911 // bool operator==(T,T);
9912 // bool operator!=(T,T);
9913 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9914 /// Set of (canonical) types that we've already handled.
9915 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9916
9917 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9918 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9919 // Don't add the same builtin candidate twice.
9920 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9921 continue;
9922
9923 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9924 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9925 }
9926
9927 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9929 if (AddedTypes.insert(NullPtrTy).second) {
9930 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9931 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9932 }
9933 }
9934
9935 if (CandidateTypes[ArgIdx].hasReflectionType()) {
9936 CanQualType MetaInfoTy = S.Context.MetaInfoTy;
9937 if (AddedTypes.insert(MetaInfoTy).second) {
9938 QualType ParamTypes[2] = {MetaInfoTy, MetaInfoTy};
9939 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9940 }
9941 }
9942 }
9943 }
9944
9945 // C++ [over.built]p15:
9946 //
9947 // For every T, where T is an enumeration type or a pointer type,
9948 // there exist candidate operator functions of the form
9949 //
9950 // bool operator<(T, T);
9951 // bool operator>(T, T);
9952 // bool operator<=(T, T);
9953 // bool operator>=(T, T);
9954 // bool operator==(T, T);
9955 // bool operator!=(T, T);
9956 // R operator<=>(T, T)
9957 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9958 // C++ [over.match.oper]p3:
9959 // [...]the built-in candidates include all of the candidate operator
9960 // functions defined in 13.6 that, compared to the given operator, [...]
9961 // do not have the same parameter-type-list as any non-template non-member
9962 // candidate.
9963 //
9964 // Note that in practice, this only affects enumeration types because there
9965 // aren't any built-in candidates of record type, and a user-defined operator
9966 // must have an operand of record or enumeration type. Also, the only other
9967 // overloaded operator with enumeration arguments, operator=,
9968 // cannot be overloaded for enumeration types, so this is the only place
9969 // where we must suppress candidates like this.
9970 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9971 UserDefinedBinaryOperators;
9972
9973 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9974 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9975 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9976 CEnd = CandidateSet.end();
9977 C != CEnd; ++C) {
9978 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9979 continue;
9980
9981 if (C->Function->isFunctionTemplateSpecialization())
9982 continue;
9983
9984 // We interpret "same parameter-type-list" as applying to the
9985 // "synthesized candidate, with the order of the two parameters
9986 // reversed", not to the original function.
9987 bool Reversed = C->isReversed();
9988 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9989 ->getType()
9990 .getUnqualifiedType();
9991 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9992 ->getType()
9993 .getUnqualifiedType();
9994
9995 // Skip if either parameter isn't of enumeral type.
9996 if (!FirstParamType->isEnumeralType() ||
9997 !SecondParamType->isEnumeralType())
9998 continue;
9999
10000 // Add this operator to the set of known user-defined operators.
10001 UserDefinedBinaryOperators.insert(
10002 std::make_pair(S.Context.getCanonicalType(FirstParamType),
10003 S.Context.getCanonicalType(SecondParamType)));
10004 }
10005 }
10006 }
10007
10008 /// Set of (canonical) types that we've already handled.
10009 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10010
10011 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10012 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10013 // Don't add the same builtin candidate twice.
10014 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10015 continue;
10016 if (IsSpaceship && PtrTy->isFunctionPointerType())
10017 continue;
10018
10019 QualType ParamTypes[2] = {PtrTy, PtrTy};
10020 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10021 }
10022 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10023 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
10024
10025 // Don't add the same builtin candidate twice, or if a user defined
10026 // candidate exists.
10027 if (!AddedTypes.insert(CanonType).second ||
10028 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
10029 CanonType)))
10030 continue;
10031 QualType ParamTypes[2] = {EnumTy, EnumTy};
10032 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10033 }
10034 }
10035 }
10036
10037 // C++ [over.built]p13:
10038 //
10039 // For every cv-qualified or cv-unqualified object type T
10040 // there exist candidate operator functions of the form
10041 //
10042 // T* operator+(T*, ptrdiff_t);
10043 // T& operator[](T*, ptrdiff_t); [BELOW]
10044 // T* operator-(T*, ptrdiff_t);
10045 // T* operator+(ptrdiff_t, T*);
10046 // T& operator[](ptrdiff_t, T*); [BELOW]
10047 //
10048 // C++ [over.built]p14:
10049 //
10050 // For every T, where T is a pointer to object type, there
10051 // exist candidate operator functions of the form
10052 //
10053 // ptrdiff_t operator-(T, T);
10054 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
10055 /// Set of (canonical) types that we've already handled.
10056 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10057
10058 for (int Arg = 0; Arg < 2; ++Arg) {
10059 QualType AsymmetricParamTypes[2] = {
10062 };
10063 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
10064 QualType PointeeTy = PtrTy->getPointeeType();
10065 if (!PointeeTy->isObjectType())
10066 continue;
10067
10068 AsymmetricParamTypes[Arg] = PtrTy;
10069 if (Arg == 0 || Op == OO_Plus) {
10070 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
10071 // T* operator+(ptrdiff_t, T*);
10072 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
10073 }
10074 if (Op == OO_Minus) {
10075 // ptrdiff_t operator-(T, T);
10076 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10077 continue;
10078
10079 QualType ParamTypes[2] = {PtrTy, PtrTy};
10080 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10081 }
10082 }
10083 }
10084 }
10085
10086 // C++ [over.built]p12:
10087 //
10088 // For every pair of promoted arithmetic types L and R, there
10089 // exist candidate operator functions of the form
10090 //
10091 // LR operator*(L, R);
10092 // LR operator/(L, R);
10093 // LR operator+(L, R);
10094 // LR operator-(L, R);
10095 // bool operator<(L, R);
10096 // bool operator>(L, R);
10097 // bool operator<=(L, R);
10098 // bool operator>=(L, R);
10099 // bool operator==(L, R);
10100 // bool operator!=(L, R);
10101 //
10102 // where LR is the result of the usual arithmetic conversions
10103 // between types L and R.
10104 //
10105 // C++ [over.built]p24:
10106 //
10107 // For every pair of promoted arithmetic types L and R, there exist
10108 // candidate operator functions of the form
10109 //
10110 // LR operator?(bool, L, R);
10111 //
10112 // where LR is the result of the usual arithmetic conversions
10113 // between types L and R.
10114 // Our candidates ignore the first parameter.
10115 void addGenericBinaryArithmeticOverloads() {
10116 if (!ArithmeticCandidatesMayBeViable)
10117 return;
10118
10119 for (unsigned Left = FirstPromotedArithmeticType;
10120 Left < LastPromotedArithmeticType; ++Left) {
10121 for (unsigned Right = FirstPromotedArithmeticType;
10122 Right < LastPromotedArithmeticType; ++Right) {
10123 QualType LandR[2] = { ArithmeticTypes[Left],
10124 ArithmeticTypes[Right] };
10125 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10126 }
10127 }
10128
10129 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10130 // conditional operator for vector types.
10131 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10132 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10133 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10134 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10135 }
10136 }
10137
10138 /// Add binary operator overloads for each candidate matrix type M1, M2:
10139 /// * (M1, M1) -> M1
10140 /// * (M1, M1.getElementType()) -> M1
10141 /// * (M2.getElementType(), M2) -> M2
10142 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10143 void addMatrixBinaryArithmeticOverloads() {
10144 if (!ArithmeticCandidatesMayBeViable)
10145 return;
10146
10147 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10148 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10149 AddCandidate(M1, M1);
10150 }
10151
10152 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10153 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10154 if (!CandidateTypes[0].containsMatrixType(M2))
10155 AddCandidate(M2, M2);
10156 }
10157 }
10158
10159 // C++2a [over.built]p14:
10160 //
10161 // For every integral type T there exists a candidate operator function
10162 // of the form
10163 //
10164 // std::strong_ordering operator<=>(T, T)
10165 //
10166 // C++2a [over.built]p15:
10167 //
10168 // For every pair of floating-point types L and R, there exists a candidate
10169 // operator function of the form
10170 //
10171 // std::partial_ordering operator<=>(L, R);
10172 //
10173 // FIXME: The current specification for integral types doesn't play nice with
10174 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10175 // comparisons. Under the current spec this can lead to ambiguity during
10176 // overload resolution. For example:
10177 //
10178 // enum A : int {a};
10179 // auto x = (a <=> (long)42);
10180 //
10181 // error: call is ambiguous for arguments 'A' and 'long'.
10182 // note: candidate operator<=>(int, int)
10183 // note: candidate operator<=>(long, long)
10184 //
10185 // To avoid this error, this function deviates from the specification and adds
10186 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10187 // arithmetic types (the same as the generic relational overloads).
10188 //
10189 // For now this function acts as a placeholder.
10190 void addThreeWayArithmeticOverloads() {
10191 addGenericBinaryArithmeticOverloads();
10192 }
10193
10194 // C++ [over.built]p17:
10195 //
10196 // For every pair of promoted integral types L and R, there
10197 // exist candidate operator functions of the form
10198 //
10199 // LR operator%(L, R);
10200 // LR operator&(L, R);
10201 // LR operator^(L, R);
10202 // LR operator|(L, R);
10203 // L operator<<(L, R);
10204 // L operator>>(L, R);
10205 //
10206 // where LR is the result of the usual arithmetic conversions
10207 // between types L and R.
10208 void addBinaryBitwiseArithmeticOverloads() {
10209 if (!ArithmeticCandidatesMayBeViable)
10210 return;
10211
10212 for (unsigned Left = FirstPromotedIntegralType;
10213 Left < LastPromotedIntegralType; ++Left) {
10214 for (unsigned Right = FirstPromotedIntegralType;
10215 Right < LastPromotedIntegralType; ++Right) {
10216 QualType LandR[2] = { ArithmeticTypes[Left],
10217 ArithmeticTypes[Right] };
10218 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10219 }
10220 }
10221 }
10222
10223 // C++ [over.built]p20:
10224 //
10225 // For every pair (T, VQ), where T is an enumeration or
10226 // pointer to member type and VQ is either volatile or
10227 // empty, there exist candidate operator functions of the form
10228 //
10229 // VQ T& operator=(VQ T&, T);
10230 void addAssignmentMemberPointerOrEnumeralOverloads() {
10231 /// Set of (canonical) types that we've already handled.
10232 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10233
10234 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10235 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10236 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10237 continue;
10238
10239 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10240 }
10241
10242 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10243 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10244 continue;
10245
10246 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10247 }
10248 }
10249 }
10250
10251 // C++ [over.built]p19:
10252 //
10253 // For every pair (T, VQ), where T is any type and VQ is either
10254 // volatile or empty, there exist candidate operator functions
10255 // of the form
10256 //
10257 // T*VQ& operator=(T*VQ&, T*);
10258 //
10259 // C++ [over.built]p21:
10260 //
10261 // For every pair (T, VQ), where T is a cv-qualified or
10262 // cv-unqualified object type and VQ is either volatile or
10263 // empty, there exist candidate operator functions of the form
10264 //
10265 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10266 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10267 void addAssignmentPointerOverloads(bool isEqualOp) {
10268 /// Set of (canonical) types that we've already handled.
10269 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10270
10271 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10272 // If this is operator=, keep track of the builtin candidates we added.
10273 if (isEqualOp)
10274 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10275 else if (!PtrTy->getPointeeType()->isObjectType())
10276 continue;
10277
10278 // non-volatile version
10279 QualType ParamTypes[2] = {
10281 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10282 };
10283 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10284 /*IsAssignmentOperator=*/ isEqualOp);
10285
10286 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10287 VisibleTypeConversionsQuals.hasVolatile();
10288 if (NeedVolatile) {
10289 // volatile version
10290 ParamTypes[0] =
10292 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10293 /*IsAssignmentOperator=*/isEqualOp);
10294 }
10295
10296 if (!PtrTy.isRestrictQualified() &&
10297 VisibleTypeConversionsQuals.hasRestrict()) {
10298 // restrict version
10299 ParamTypes[0] =
10301 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10302 /*IsAssignmentOperator=*/isEqualOp);
10303
10304 if (NeedVolatile) {
10305 // volatile restrict version
10306 ParamTypes[0] =
10309 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10310 /*IsAssignmentOperator=*/isEqualOp);
10311 }
10312 }
10313 }
10314
10315 if (isEqualOp) {
10316 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10317 // Make sure we don't add the same candidate twice.
10318 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10319 continue;
10320
10321 QualType ParamTypes[2] = {
10323 PtrTy,
10324 };
10325
10326 // non-volatile version
10327 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10328 /*IsAssignmentOperator=*/true);
10329
10330 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10331 VisibleTypeConversionsQuals.hasVolatile();
10332 if (NeedVolatile) {
10333 // volatile version
10334 ParamTypes[0] = S.Context.getLValueReferenceType(
10335 S.Context.getVolatileType(PtrTy));
10336 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10337 /*IsAssignmentOperator=*/true);
10338 }
10339
10340 if (!PtrTy.isRestrictQualified() &&
10341 VisibleTypeConversionsQuals.hasRestrict()) {
10342 // restrict version
10343 ParamTypes[0] = S.Context.getLValueReferenceType(
10344 S.Context.getRestrictType(PtrTy));
10345 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10346 /*IsAssignmentOperator=*/true);
10347
10348 if (NeedVolatile) {
10349 // volatile restrict version
10350 ParamTypes[0] =
10353 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10354 /*IsAssignmentOperator=*/true);
10355 }
10356 }
10357 }
10358 }
10359 }
10360
10361 // C++ [over.built]p18:
10362 //
10363 // For every triple (L, VQ, R), where L is an arithmetic type,
10364 // VQ is either volatile or empty, and R is a promoted
10365 // arithmetic type, there exist candidate operator functions of
10366 // the form
10367 //
10368 // VQ L& operator=(VQ L&, R);
10369 // VQ L& operator*=(VQ L&, R);
10370 // VQ L& operator/=(VQ L&, R);
10371 // VQ L& operator+=(VQ L&, R);
10372 // VQ L& operator-=(VQ L&, R);
10373 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10374 if (!ArithmeticCandidatesMayBeViable)
10375 return;
10376
10377 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10378 for (unsigned Right = FirstPromotedArithmeticType;
10379 Right < LastPromotedArithmeticType; ++Right) {
10380 QualType ParamTypes[2];
10381 ParamTypes[1] = ArithmeticTypes[Right];
10383 S, ArithmeticTypes[Left], Args[0]);
10384
10386 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10387 ParamTypes[0] =
10388 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10389 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10390 /*IsAssignmentOperator=*/isEqualOp);
10391 });
10392 }
10393 }
10394
10395 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10396 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10397 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10398 QualType ParamTypes[2];
10399 ParamTypes[1] = Vec2Ty;
10400 // Add this built-in operator as a candidate (VQ is empty).
10401 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10402 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10403 /*IsAssignmentOperator=*/isEqualOp);
10404
10405 // Add this built-in operator as a candidate (VQ is 'volatile').
10406 if (VisibleTypeConversionsQuals.hasVolatile()) {
10407 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10408 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10409 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10410 /*IsAssignmentOperator=*/isEqualOp);
10411 }
10412 }
10413 }
10414
10415 // C++ [over.built]p22:
10416 //
10417 // For every triple (L, VQ, R), where L is an integral type, VQ
10418 // is either volatile or empty, and R is a promoted integral
10419 // type, there exist candidate operator functions of the form
10420 //
10421 // VQ L& operator%=(VQ L&, R);
10422 // VQ L& operator<<=(VQ L&, R);
10423 // VQ L& operator>>=(VQ L&, R);
10424 // VQ L& operator&=(VQ L&, R);
10425 // VQ L& operator^=(VQ L&, R);
10426 // VQ L& operator|=(VQ L&, R);
10427 void addAssignmentIntegralOverloads() {
10428 if (!ArithmeticCandidatesMayBeViable)
10429 return;
10430
10431 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10432 for (unsigned Right = FirstPromotedIntegralType;
10433 Right < LastPromotedIntegralType; ++Right) {
10434 QualType ParamTypes[2];
10435 ParamTypes[1] = ArithmeticTypes[Right];
10437 S, ArithmeticTypes[Left], Args[0]);
10438
10440 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10441 ParamTypes[0] =
10442 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10443 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10444 });
10445 }
10446 }
10447 }
10448
10449 // C++ [over.operator]p23:
10450 //
10451 // There also exist candidate operator functions of the form
10452 //
10453 // bool operator!(bool);
10454 // bool operator&&(bool, bool);
10455 // bool operator||(bool, bool);
10456 void addExclaimOverload() {
10457 QualType ParamTy = S.Context.BoolTy;
10458 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10459 /*IsAssignmentOperator=*/false,
10460 /*NumContextualBoolArguments=*/1);
10461 }
10462 void addAmpAmpOrPipePipeOverload() {
10463 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10464 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10465 /*IsAssignmentOperator=*/false,
10466 /*NumContextualBoolArguments=*/2);
10467 }
10468
10469 // C++ [over.built]p13:
10470 //
10471 // For every cv-qualified or cv-unqualified object type T there
10472 // exist candidate operator functions of the form
10473 //
10474 // T* operator+(T*, ptrdiff_t); [ABOVE]
10475 // T& operator[](T*, ptrdiff_t);
10476 // T* operator-(T*, ptrdiff_t); [ABOVE]
10477 // T* operator+(ptrdiff_t, T*); [ABOVE]
10478 // T& operator[](ptrdiff_t, T*);
10479 void addSubscriptOverloads() {
10480 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10481 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10482 QualType PointeeType = PtrTy->getPointeeType();
10483 if (!PointeeType->isObjectType())
10484 continue;
10485
10486 // T& operator[](T*, ptrdiff_t)
10487 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10488 }
10489
10490 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10491 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10492 QualType PointeeType = PtrTy->getPointeeType();
10493 if (!PointeeType->isObjectType())
10494 continue;
10495
10496 // T& operator[](ptrdiff_t, T*)
10497 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10498 }
10499 }
10500
10501 // C++ [over.built]p11:
10502 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10503 // C1 is the same type as C2 or is a derived class of C2, T is an object
10504 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10505 // there exist candidate operator functions of the form
10506 //
10507 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10508 //
10509 // where CV12 is the union of CV1 and CV2.
10510 void addArrowStarOverloads() {
10511 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10512 QualType C1Ty = PtrTy;
10513 QualType C1;
10514 QualifierCollector Q1;
10515 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10516 if (!isa<RecordType>(C1))
10517 continue;
10518 // heuristic to reduce number of builtin candidates in the set.
10519 // Add volatile/restrict version only if there are conversions to a
10520 // volatile/restrict type.
10521 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10522 continue;
10523 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10524 continue;
10525 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10526 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10527 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10528 *D2 = mptr->getMostRecentCXXRecordDecl();
10529 if (!declaresSameEntity(D1, D2) &&
10530 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10531 break;
10532 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10533 // build CV12 T&
10534 QualType T = mptr->getPointeeType();
10535 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10536 T.isVolatileQualified())
10537 continue;
10538 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10539 T.isRestrictQualified())
10540 continue;
10541 T = Q1.apply(S.Context, T);
10542 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10543 }
10544 }
10545 }
10546
10547 // Note that we don't consider the first argument, since it has been
10548 // contextually converted to bool long ago. The candidates below are
10549 // therefore added as binary.
10550 //
10551 // C++ [over.built]p25:
10552 // For every type T, where T is a pointer, pointer-to-member, or scoped
10553 // enumeration type, there exist candidate operator functions of the form
10554 //
10555 // T operator?(bool, T, T);
10556 //
10557 void addConditionalOperatorOverloads() {
10558 /// Set of (canonical) types that we've already handled.
10559 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10560
10561 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10562 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10563 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10564 continue;
10565
10566 QualType ParamTypes[2] = {PtrTy, PtrTy};
10567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10568 }
10569
10570 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10571 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10572 continue;
10573
10574 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10575 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10576 }
10577
10578 if (S.getLangOpts().CPlusPlus11) {
10579 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10580 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10581 continue;
10582
10583 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10584 continue;
10585
10586 QualType ParamTypes[2] = {EnumTy, EnumTy};
10587 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10588 }
10589 }
10590 }
10591 }
10592};
10593
10594} // end anonymous namespace
10595
10597 SourceLocation OpLoc,
10598 ArrayRef<Expr *> Args,
10599 OverloadCandidateSet &CandidateSet) {
10600 // Find all of the types that the arguments can convert to, but only
10601 // if the operator we're looking at has built-in operator candidates
10602 // that make use of these types. Also record whether we encounter non-record
10603 // candidate types or either arithmetic or enumeral candidate types.
10604 QualifiersAndAtomic VisibleTypeConversionsQuals;
10605 VisibleTypeConversionsQuals.addConst();
10606 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10607 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10608 if (Args[ArgIdx]->getType()->isAtomicType())
10609 VisibleTypeConversionsQuals.addAtomic();
10610 }
10611
10612 bool HasNonRecordCandidateType = false;
10613 bool HasArithmeticOrEnumeralCandidateType = false;
10615 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10616 CandidateTypes.emplace_back(*this);
10617 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10618 OpLoc,
10619 true,
10620 (Op == OO_Exclaim ||
10621 Op == OO_AmpAmp ||
10622 Op == OO_PipePipe),
10623 VisibleTypeConversionsQuals);
10624 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10625 CandidateTypes[ArgIdx].hasNonRecordTypes();
10626 HasArithmeticOrEnumeralCandidateType =
10627 HasArithmeticOrEnumeralCandidateType ||
10628 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10629 }
10630
10631 // Exit early when no non-record types have been added to the candidate set
10632 // for any of the arguments to the operator.
10633 //
10634 // We can't exit early for !, ||, or &&, since there we have always have
10635 // 'bool' overloads.
10636 if (!HasNonRecordCandidateType &&
10637 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10638 return;
10639
10640 // Setup an object to manage the common state for building overloads.
10641 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10642 VisibleTypeConversionsQuals,
10643 HasArithmeticOrEnumeralCandidateType,
10644 CandidateTypes, CandidateSet);
10645
10646 // Dispatch over the operation to add in only those overloads which apply.
10647 switch (Op) {
10648 case OO_None:
10650 llvm_unreachable("Expected an overloaded operator");
10651
10652 case OO_New:
10653 case OO_Delete:
10654 case OO_Array_New:
10655 case OO_Array_Delete:
10656 case OO_Call:
10657 llvm_unreachable(
10658 "Special operators don't use AddBuiltinOperatorCandidates");
10659
10660 case OO_Comma:
10661 case OO_Arrow:
10662 case OO_Coawait:
10663 // C++ [over.match.oper]p3:
10664 // -- For the operator ',', the unary operator '&', the
10665 // operator '->', or the operator 'co_await', the
10666 // built-in candidates set is empty.
10667 break;
10668
10669 case OO_Plus: // '+' is either unary or binary
10670 if (Args.size() == 1)
10671 OpBuilder.addUnaryPlusPointerOverloads();
10672 [[fallthrough]];
10673
10674 case OO_Minus: // '-' is either unary or binary
10675 if (Args.size() == 1) {
10676 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10677 } else {
10678 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10679 OpBuilder.addGenericBinaryArithmeticOverloads();
10680 OpBuilder.addMatrixBinaryArithmeticOverloads();
10681 }
10682 break;
10683
10684 case OO_Star: // '*' is either unary or binary
10685 if (Args.size() == 1)
10686 OpBuilder.addUnaryStarPointerOverloads();
10687 else {
10688 OpBuilder.addGenericBinaryArithmeticOverloads();
10689 OpBuilder.addMatrixBinaryArithmeticOverloads();
10690 }
10691 break;
10692
10693 case OO_Slash:
10694 OpBuilder.addGenericBinaryArithmeticOverloads();
10695 break;
10696
10697 case OO_PlusPlus:
10698 case OO_MinusMinus:
10699 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10700 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10701 break;
10702
10703 case OO_EqualEqual:
10704 case OO_ExclaimEqual:
10705 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10706 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10707 OpBuilder.addGenericBinaryArithmeticOverloads();
10708 break;
10709
10710 case OO_Less:
10711 case OO_Greater:
10712 case OO_LessEqual:
10713 case OO_GreaterEqual:
10714 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10715 OpBuilder.addGenericBinaryArithmeticOverloads();
10716 break;
10717
10718 case OO_Spaceship:
10719 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10720 OpBuilder.addThreeWayArithmeticOverloads();
10721 break;
10722
10723 case OO_Percent:
10724 case OO_Caret:
10725 case OO_Pipe:
10726 case OO_LessLess:
10727 case OO_GreaterGreater:
10728 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10729 break;
10730
10731 case OO_Amp: // '&' is either unary or binary
10732 if (Args.size() == 1)
10733 // C++ [over.match.oper]p3:
10734 // -- For the operator ',', the unary operator '&', or the
10735 // operator '->', the built-in candidates set is empty.
10736 break;
10737
10738 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10739 break;
10740
10741 case OO_Tilde:
10742 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10743 break;
10744
10745 case OO_Equal:
10746 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10747 [[fallthrough]];
10748
10749 case OO_PlusEqual:
10750 case OO_MinusEqual:
10751 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10752 [[fallthrough]];
10753
10754 case OO_StarEqual:
10755 case OO_SlashEqual:
10756 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10757 break;
10758
10759 case OO_PercentEqual:
10760 case OO_LessLessEqual:
10761 case OO_GreaterGreaterEqual:
10762 case OO_AmpEqual:
10763 case OO_CaretEqual:
10764 case OO_PipeEqual:
10765 OpBuilder.addAssignmentIntegralOverloads();
10766 break;
10767
10768 case OO_Exclaim:
10769 OpBuilder.addExclaimOverload();
10770 break;
10771
10772 case OO_AmpAmp:
10773 case OO_PipePipe:
10774 OpBuilder.addAmpAmpOrPipePipeOverload();
10775 break;
10776
10777 case OO_Subscript:
10778 if (Args.size() == 2)
10779 OpBuilder.addSubscriptOverloads();
10780 break;
10781
10782 case OO_ArrowStar:
10783 OpBuilder.addArrowStarOverloads();
10784 break;
10785
10786 case OO_Conditional:
10787 OpBuilder.addConditionalOperatorOverloads();
10788 OpBuilder.addGenericBinaryArithmeticOverloads();
10789 break;
10790 }
10791}
10792
10793void
10795 SourceLocation Loc,
10796 ArrayRef<Expr *> Args,
10797 TemplateArgumentListInfo *ExplicitTemplateArgs,
10798 OverloadCandidateSet& CandidateSet,
10799 bool PartialOverloading) {
10800 ADLResult Fns;
10801
10802 // FIXME: This approach for uniquing ADL results (and removing
10803 // redundant candidates from the set) relies on pointer-equality,
10804 // which means we need to key off the canonical decl. However,
10805 // always going back to the canonical decl might not get us the
10806 // right set of default arguments. What default arguments are
10807 // we supposed to consider on ADL candidates, anyway?
10808
10809 // FIXME: Pass in the explicit template arguments?
10810 ArgumentDependentLookup(Name, Loc, Args, Fns);
10811
10812 ArrayRef<Expr *> ReversedArgs;
10813
10814 // Erase all of the candidates we already knew about.
10815 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10816 CandEnd = CandidateSet.end();
10817 Cand != CandEnd; ++Cand)
10818 if (Cand->Function) {
10819 FunctionDecl *Fn = Cand->Function;
10820 Fns.erase(Fn);
10821 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10822 Fns.erase(FunTmpl);
10823 }
10824
10825 // For each of the ADL candidates we found, add it to the overload
10826 // set.
10827 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10829
10830 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10831 if (ExplicitTemplateArgs)
10832 continue;
10833
10835 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10836 PartialOverloading, /*AllowExplicit=*/true,
10837 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10838 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10840 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10841 /*SuppressUserConversions=*/false, PartialOverloading,
10842 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10843 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10844 }
10845 } else {
10846 auto *FTD = cast<FunctionTemplateDecl>(*I);
10848 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10849 /*SuppressUserConversions=*/false, PartialOverloading,
10850 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10851 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10852 *this, Args, FTD->getTemplatedDecl())) {
10853
10854 // As template candidates are not deduced immediately,
10855 // persist the array in the overload set.
10856 if (ReversedArgs.empty())
10857 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10858
10860 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10861 /*SuppressUserConversions=*/false, PartialOverloading,
10862 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10864 }
10865 }
10866 }
10867}
10868
10869namespace {
10870enum class Comparison { Equal, Better, Worse };
10871}
10872
10873/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10874/// overload resolution.
10875///
10876/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10877/// Cand1's first N enable_if attributes have precisely the same conditions as
10878/// Cand2's first N enable_if attributes (where N = the number of enable_if
10879/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10880///
10881/// Note that you can have a pair of candidates such that Cand1's enable_if
10882/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10883/// worse than Cand1's.
10884static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10885 const FunctionDecl *Cand2) {
10886 // Common case: One (or both) decls don't have enable_if attrs.
10887 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10888 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10889 if (!Cand1Attr || !Cand2Attr) {
10890 if (Cand1Attr == Cand2Attr)
10891 return Comparison::Equal;
10892 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10893 }
10894
10895 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10896 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10897
10898 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10899 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10900 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10901 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10902
10903 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10904 // has fewer enable_if attributes than Cand2, and vice versa.
10905 if (!Cand1A)
10906 return Comparison::Worse;
10907 if (!Cand2A)
10908 return Comparison::Better;
10909
10910 Cand1ID.clear();
10911 Cand2ID.clear();
10912
10913 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10914 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10915 if (Cand1ID != Cand2ID)
10916 return Comparison::Worse;
10917 }
10918
10919 return Comparison::Equal;
10920}
10921
10922static Comparison
10924 const OverloadCandidate &Cand2) {
10925 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10926 !Cand2.Function->isMultiVersion())
10927 return Comparison::Equal;
10928
10929 // If both are invalid, they are equal. If one of them is invalid, the other
10930 // is better.
10931 if (Cand1.Function->isInvalidDecl()) {
10932 if (Cand2.Function->isInvalidDecl())
10933 return Comparison::Equal;
10934 return Comparison::Worse;
10935 }
10936 if (Cand2.Function->isInvalidDecl())
10937 return Comparison::Better;
10938
10939 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10940 // cpu_dispatch, else arbitrarily based on the identifiers.
10941 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10942 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10943 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10944 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10945
10946 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10947 return Comparison::Equal;
10948
10949 if (Cand1CPUDisp && !Cand2CPUDisp)
10950 return Comparison::Better;
10951 if (Cand2CPUDisp && !Cand1CPUDisp)
10952 return Comparison::Worse;
10953
10954 if (Cand1CPUSpec && Cand2CPUSpec) {
10955 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10956 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10957 ? Comparison::Better
10958 : Comparison::Worse;
10959
10960 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10961 FirstDiff = std::mismatch(
10962 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10963 Cand2CPUSpec->cpus_begin(),
10964 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10965 return LHS->getName() == RHS->getName();
10966 });
10967
10968 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10969 "Two different cpu-specific versions should not have the same "
10970 "identifier list, otherwise they'd be the same decl!");
10971 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10972 ? Comparison::Better
10973 : Comparison::Worse;
10974 }
10975 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10976}
10977
10978/// Compute the type of the implicit object parameter for the given function,
10979/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10980/// null QualType if there is a 'matches anything' implicit object parameter.
10981static std::optional<QualType>
10984 return std::nullopt;
10985
10986 auto *M = cast<CXXMethodDecl>(F);
10987 // Static member functions' object parameters match all types.
10988 if (M->isStatic())
10989 return QualType();
10990 return M->getFunctionObjectParameterReferenceType();
10991}
10992
10993// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10994// represent the same entity.
10995static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10996 const FunctionDecl *F2) {
10997 if (declaresSameEntity(F1, F2))
10998 return true;
10999 auto PT1 = F1->getPrimaryTemplate();
11000 auto PT2 = F2->getPrimaryTemplate();
11001 if (PT1 && PT2) {
11002 if (declaresSameEntity(PT1, PT2) ||
11003 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
11004 PT2->getInstantiatedFromMemberTemplate()))
11005 return true;
11006 }
11007 // TODO: It is not clear whether comparing parameters is necessary (i.e.
11008 // different functions with same params). Consider removing this (as no test
11009 // fail w/o it).
11010 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
11011 if (First) {
11012 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
11013 return *T;
11014 }
11015 assert(I < F->getNumParams());
11016 return F->getParamDecl(I++)->getType();
11017 };
11018
11019 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
11020 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
11021
11022 if (F1NumParams != F2NumParams)
11023 return false;
11024
11025 unsigned I1 = 0, I2 = 0;
11026 for (unsigned I = 0; I != F1NumParams; ++I) {
11027 QualType T1 = NextParam(F1, I1, I == 0);
11028 QualType T2 = NextParam(F2, I2, I == 0);
11029 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
11030 if (!Context.hasSameUnqualifiedType(T1, T2))
11031 return false;
11032 }
11033 return true;
11034}
11035
11036/// We're allowed to use constraints partial ordering only if the candidates
11037/// have the same parameter types:
11038/// [over.match.best.general]p2.6
11039/// F1 and F2 are non-template functions with the same
11040/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
11042 FunctionDecl *Fn2,
11043 bool IsFn1Reversed,
11044 bool IsFn2Reversed) {
11045 assert(Fn1 && Fn2);
11046 if (Fn1->isVariadic() != Fn2->isVariadic())
11047 return false;
11048
11049 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
11050 IsFn1Reversed ^ IsFn2Reversed))
11051 return false;
11052
11053 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
11054 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
11055 if (Mem1 && Mem2) {
11056 // if they are member functions, both are direct members of the same class,
11057 // and
11058 if (Mem1->getParent() != Mem2->getParent())
11059 return false;
11060 // if both are non-static member functions, they have the same types for
11061 // their object parameters
11062 if (Mem1->isInstance() && Mem2->isInstance() &&
11064 Mem1->getFunctionObjectParameterReferenceType(),
11065 Mem2->getFunctionObjectParameterReferenceType()))
11066 return false;
11067 }
11068 return true;
11069}
11070
11071static FunctionDecl *
11073 bool IsFn1Reversed, bool IsFn2Reversed) {
11074 if (!Fn1 || !Fn2)
11075 return nullptr;
11076
11077 // C++ [temp.constr.order]:
11078 // A non-template function F1 is more partial-ordering-constrained than a
11079 // non-template function F2 if:
11080 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
11081 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
11082
11083 if (Cand1IsSpecialization || Cand2IsSpecialization)
11084 return nullptr;
11085
11086 // - they have the same non-object-parameter-type-lists, and [...]
11087 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
11088 IsFn2Reversed))
11089 return nullptr;
11090
11091 // - the declaration of F1 is more constrained than the declaration of F2.
11092 return S.getMoreConstrainedFunction(Fn1, Fn2);
11093}
11094
11095/// isBetterOverloadCandidate - Determines whether the first overload
11096/// candidate is a better candidate than the second (C++ 13.3.3p1).
11098 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
11100 bool PartialOverloading) {
11101 // Define viable functions to be better candidates than non-viable
11102 // functions.
11103 if (!Cand2.Viable)
11104 return Cand1.Viable;
11105 else if (!Cand1.Viable)
11106 return false;
11107
11108 // [CUDA] A function with 'never' preference is marked not viable, therefore
11109 // is never shown up here. The worst preference shown up here is 'wrong side',
11110 // e.g. an H function called by a HD function in device compilation. This is
11111 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11112 // function which is called only by an H function. A deferred diagnostic will
11113 // be triggered if it is emitted. However a wrong-sided function is still
11114 // a viable candidate here.
11115 //
11116 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11117 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11118 // can be emitted, Cand1 is not better than Cand2. This rule should have
11119 // precedence over other rules.
11120 //
11121 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11122 // other rules should be used to determine which is better. This is because
11123 // host/device based overloading resolution is mostly for determining
11124 // viability of a function. If two functions are both viable, other factors
11125 // should take precedence in preference, e.g. the standard-defined preferences
11126 // like argument conversion ranks or enable_if partial-ordering. The
11127 // preference for pass-object-size parameters is probably most similar to a
11128 // type-based-overloading decision and so should take priority.
11129 //
11130 // If other rules cannot determine which is better, CUDA preference will be
11131 // used again to determine which is better.
11132 //
11133 // TODO: Currently IdentifyPreference does not return correct values
11134 // for functions called in global variable initializers due to missing
11135 // correct context about device/host. Therefore we can only enforce this
11136 // rule when there is a caller. We should enforce this rule for functions
11137 // in global variable initializers once proper context is added.
11138 //
11139 // TODO: We can only enable the hostness based overloading resolution when
11140 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11141 // overloading resolution diagnostics.
11142 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11143 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11144 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11145 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11146 bool IsCand1ImplicitHD =
11148 bool IsCand2ImplicitHD =
11150 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11151 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11152 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11153 // The implicit HD function may be a function in a system header which
11154 // is forced by pragma. In device compilation, if we prefer HD candidates
11155 // over wrong-sided candidates, overloading resolution may change, which
11156 // may result in non-deferrable diagnostics. As a workaround, we let
11157 // implicit HD candidates take equal preference as wrong-sided candidates.
11158 // This will preserve the overloading resolution.
11159 // TODO: We still need special handling of implicit HD functions since
11160 // they may incur other diagnostics to be deferred. We should make all
11161 // host/device related diagnostics deferrable and remove special handling
11162 // of implicit HD functions.
11163 auto EmitThreshold =
11164 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11165 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11168 auto Cand1Emittable = P1 > EmitThreshold;
11169 auto Cand2Emittable = P2 > EmitThreshold;
11170 if (Cand1Emittable && !Cand2Emittable)
11171 return true;
11172 if (!Cand1Emittable && Cand2Emittable)
11173 return false;
11174 }
11175 }
11176
11177 // C++ [over.match.best]p1: (Changed in C++23)
11178 //
11179 // -- if F is a static member function, ICS1(F) is defined such
11180 // that ICS1(F) is neither better nor worse than ICS1(G) for
11181 // any function G, and, symmetrically, ICS1(G) is neither
11182 // better nor worse than ICS1(F).
11183 unsigned StartArg = 0;
11184 if (!Cand1.TookAddressOfOverload &&
11186 StartArg = 1;
11187
11188 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11189 // We don't allow incompatible pointer conversions in C++.
11190 if (!S.getLangOpts().CPlusPlus)
11191 return ICS.isStandard() &&
11192 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11193
11194 // The only ill-formed conversion we allow in C++ is the string literal to
11195 // char* conversion, which is only considered ill-formed after C++11.
11196 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11198 };
11199
11200 // Define functions that don't require ill-formed conversions for a given
11201 // argument to be better candidates than functions that do.
11202 unsigned NumArgs = Cand1.Conversions.size();
11203 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11204 bool HasBetterConversion = false;
11205 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11206 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11207 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11208 if (Cand1Bad != Cand2Bad) {
11209 if (Cand1Bad)
11210 return false;
11211 HasBetterConversion = true;
11212 }
11213 }
11214
11215 if (HasBetterConversion)
11216 return true;
11217
11218 // C++ [over.match.best]p1:
11219 // A viable function F1 is defined to be a better function than another
11220 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11221 // conversion sequence than ICSi(F2), and then...
11222 bool HasWorseConversion = false;
11223 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11225 Cand1.Conversions[ArgIdx],
11226 Cand2.Conversions[ArgIdx])) {
11228 // Cand1 has a better conversion sequence.
11229 HasBetterConversion = true;
11230 break;
11231
11233 if (Cand1.Function && Cand2.Function &&
11234 Cand1.isReversed() != Cand2.isReversed() &&
11235 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11236 // Work around large-scale breakage caused by considering reversed
11237 // forms of operator== in C++20:
11238 //
11239 // When comparing a function against a reversed function, if we have a
11240 // better conversion for one argument and a worse conversion for the
11241 // other, the implicit conversion sequences are treated as being equally
11242 // good.
11243 //
11244 // This prevents a comparison function from being considered ambiguous
11245 // with a reversed form that is written in the same way.
11246 //
11247 // We diagnose this as an extension from CreateOverloadedBinOp.
11248 HasWorseConversion = true;
11249 break;
11250 }
11251
11252 // Cand1 can't be better than Cand2.
11253 return false;
11254
11256 // Do nothing.
11257 break;
11258 }
11259 }
11260
11261 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11262 // ICSj(F2), or, if not that,
11263 if (HasBetterConversion && !HasWorseConversion)
11264 return true;
11265
11266 // -- the context is an initialization by user-defined conversion
11267 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11268 // from the return type of F1 to the destination type (i.e.,
11269 // the type of the entity being initialized) is a better
11270 // conversion sequence than the standard conversion sequence
11271 // from the return type of F2 to the destination type.
11273 Cand1.Function && Cand2.Function &&
11276
11277 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11278 // First check whether we prefer one of the conversion functions over the
11279 // other. This only distinguishes the results in non-standard, extension
11280 // cases such as the conversion from a lambda closure type to a function
11281 // pointer or block.
11286 Cand1.FinalConversion,
11287 Cand2.FinalConversion);
11288
11291
11292 // FIXME: Compare kind of reference binding if conversion functions
11293 // convert to a reference type used in direct reference binding, per
11294 // C++14 [over.match.best]p1 section 2 bullet 3.
11295 }
11296
11297 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11298 // as combined with the resolution to CWG issue 243.
11299 //
11300 // When the context is initialization by constructor ([over.match.ctor] or
11301 // either phase of [over.match.list]), a constructor is preferred over
11302 // a conversion function.
11303 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11304 Cand1.Function && Cand2.Function &&
11307 return isa<CXXConstructorDecl>(Cand1.Function);
11308
11309 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11310 return Cand2.StrictPackMatch;
11311
11312 // -- F1 is a non-template function and F2 is a function template
11313 // specialization, or, if not that,
11314 bool Cand1IsSpecialization = Cand1.Function &&
11316 bool Cand2IsSpecialization = Cand2.Function &&
11318 if (Cand1IsSpecialization != Cand2IsSpecialization)
11319 return Cand2IsSpecialization;
11320
11321 // -- F1 and F2 are function template specializations, and the function
11322 // template for F1 is more specialized than the template for F2
11323 // according to the partial ordering rules described in 14.5.5.2, or,
11324 // if not that,
11325 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11326 const auto *Obj1Context =
11327 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11328 const auto *Obj2Context =
11329 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11330 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11332 Cand2.Function->getPrimaryTemplate(), Loc,
11334 : TPOC_Call,
11336 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11337 : QualType{},
11338 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11339 : QualType{},
11340 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11341 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11342 }
11343 }
11344
11345 // -— F1 and F2 are non-template functions and F1 is more
11346 // partial-ordering-constrained than F2 [...],
11348 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11349 Cand2.isReversed());
11350 F && F == Cand1.Function)
11351 return true;
11352
11353 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11354 // class B of D, and for all arguments the corresponding parameters of
11355 // F1 and F2 have the same type.
11356 // FIXME: Implement the "all parameters have the same type" check.
11357 bool Cand1IsInherited =
11358 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11359 bool Cand2IsInherited =
11360 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11361 if (Cand1IsInherited != Cand2IsInherited)
11362 return Cand2IsInherited;
11363 else if (Cand1IsInherited) {
11364 assert(Cand2IsInherited);
11365 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11366 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11367 if (Cand1Class->isDerivedFrom(Cand2Class))
11368 return true;
11369 if (Cand2Class->isDerivedFrom(Cand1Class))
11370 return false;
11371 // Inherited from sibling base classes: still ambiguous.
11372 }
11373
11374 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11375 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11376 // with reversed order of parameters and F1 is not
11377 //
11378 // We rank reversed + different operator as worse than just reversed, but
11379 // that comparison can never happen, because we only consider reversing for
11380 // the maximally-rewritten operator (== or <=>).
11381 if (Cand1.RewriteKind != Cand2.RewriteKind)
11382 return Cand1.RewriteKind < Cand2.RewriteKind;
11383
11384 // Check C++17 tie-breakers for deduction guides.
11385 {
11386 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11387 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11388 if (Guide1 && Guide2) {
11389 // -- F1 is generated from a deduction-guide and F2 is not
11390 if (Guide1->isImplicit() != Guide2->isImplicit())
11391 return Guide2->isImplicit();
11392
11393 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11394 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11395 return true;
11396 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11397 return false;
11398
11399 // --F1 is generated from a non-template constructor and F2 is generated
11400 // from a constructor template
11401 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11402 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11403 if (Constructor1 && Constructor2) {
11404 bool isC1Templated = Constructor1->getTemplatedKind() !=
11406 bool isC2Templated = Constructor2->getTemplatedKind() !=
11408 if (isC1Templated != isC2Templated)
11409 return isC2Templated;
11410 }
11411 }
11412 }
11413
11414 // Check for enable_if value-based overload resolution.
11415 if (Cand1.Function && Cand2.Function) {
11417 if (Cmp != Comparison::Equal)
11418 return Cmp == Comparison::Better;
11419 }
11420
11421 bool HasPS1 = Cand1.Function != nullptr &&
11423 bool HasPS2 = Cand2.Function != nullptr &&
11425 if (HasPS1 != HasPS2 && HasPS1)
11426 return true;
11427
11428 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11429 if (MV == Comparison::Better)
11430 return true;
11431 if (MV == Comparison::Worse)
11432 return false;
11433
11434 // If other rules cannot determine which is better, CUDA preference is used
11435 // to determine which is better.
11436 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11437 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11438 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11439 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11440 }
11441
11442 // General member function overloading is handled above, so this only handles
11443 // constructors with address spaces.
11444 // This only handles address spaces since C++ has no other
11445 // qualifier that can be used with constructors.
11446 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11447 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11448 if (CD1 && CD2) {
11449 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11450 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11451 if (AS1 != AS2) {
11453 return true;
11455 return false;
11456 }
11457 }
11458
11459 return false;
11460}
11461
11462/// Determine whether two declarations are "equivalent" for the purposes of
11463/// name lookup and overload resolution. This applies when the same internal/no
11464/// linkage entity is defined by two modules (probably by textually including
11465/// the same header). In such a case, we don't consider the declarations to
11466/// declare the same entity, but we also don't want lookups with both
11467/// declarations visible to be ambiguous in some cases (this happens when using
11468/// a modularized libstdc++).
11470 const NamedDecl *B) {
11471 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11472 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11473 if (!VA || !VB)
11474 return false;
11475
11476 // The declarations must be declaring the same name as an internal linkage
11477 // entity in different modules.
11478 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11479 VB->getDeclContext()->getRedeclContext()) ||
11480 getOwningModule(VA) == getOwningModule(VB) ||
11481 VA->isExternallyVisible() || VB->isExternallyVisible())
11482 return false;
11483
11484 // Check that the declarations appear to be equivalent.
11485 //
11486 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11487 // For constants and functions, we should check the initializer or body is
11488 // the same. For non-constant variables, we shouldn't allow it at all.
11489 if (Context.hasSameType(VA->getType(), VB->getType()))
11490 return true;
11491
11492 // Enum constants within unnamed enumerations will have different types, but
11493 // may still be similar enough to be interchangeable for our purposes.
11494 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11495 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11496 // Only handle anonymous enums. If the enumerations were named and
11497 // equivalent, they would have been merged to the same type.
11498 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11499 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11500 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11501 !Context.hasSameType(EnumA->getIntegerType(),
11502 EnumB->getIntegerType()))
11503 return false;
11504 // Allow this only if the value is the same for both enumerators.
11505 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11506 }
11507 }
11508
11509 // Nothing else is sufficiently similar.
11510 return false;
11511}
11512
11515 assert(D && "Unknown declaration");
11516 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11517
11518 Module *M = getOwningModule(D);
11519 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11520 << !M << (M ? M->getFullModuleName() : "");
11521
11522 for (auto *E : Equiv) {
11523 Module *M = getOwningModule(E);
11524 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11525 << !M << (M ? M->getFullModuleName() : "");
11526 }
11527}
11528
11531 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11533 static_cast<CNSInfo *>(DeductionFailure.Data)
11534 ->Satisfaction.ContainsErrors;
11535}
11536
11539 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11540 bool PartialOverloading, bool AllowExplicit,
11542 bool AggregateCandidateDeduction) {
11543
11544 auto *C =
11545 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11546
11549 /*AllowObjCConversionOnExplicit=*/false,
11550 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11551 PartialOverloading, AggregateCandidateDeduction},
11553 FoundDecl,
11554 Args,
11555 IsADLCandidate,
11556 PO};
11557
11558 HasDeferredTemplateConstructors |=
11559 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11560}
11561
11563 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11564 CXXRecordDecl *ActingContext, QualType ObjectType,
11565 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11566 bool SuppressUserConversions, bool PartialOverloading,
11568
11569 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11570
11571 auto *C =
11572 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11573
11576 /*AllowObjCConversionOnExplicit=*/false,
11577 /*AllowResultConversion=*/false,
11578 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11579 /*AggregateCandidateDeduction=*/false},
11580 MethodTmpl,
11581 FoundDecl,
11582 Args,
11583 ActingContext,
11584 ObjectClassification,
11585 ObjectType,
11586 PO};
11587}
11588
11591 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11592 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11593 bool AllowResultConversion) {
11594
11595 auto *C =
11596 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11597
11600 AllowObjCConversionOnExplicit, AllowResultConversion,
11601 /*AllowExplicit=*/false,
11602 /*SuppressUserConversions=*/false,
11603 /*PartialOverloading*/ false,
11604 /*AggregateCandidateDeduction=*/false},
11606 FoundDecl,
11607 ActingContext,
11608 From,
11609 ToType};
11610}
11611
11612static void
11615
11617 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11618 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11619 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11620}
11621
11622static void
11626 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11627 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11628 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11629 C.AggregateCandidateDeduction);
11630}
11631
11632static void
11636 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11637 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11638 C.AllowResultConversion);
11639}
11640
11642 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11643 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11644 while (Cand) {
11645 switch (Cand->Kind) {
11648 S, *this,
11649 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11650 break;
11653 S, *this,
11654 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11655 break;
11658 S, *this,
11659 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11660 break;
11661 }
11662 Cand = Cand->Next;
11663 }
11664 FirstDeferredCandidate = nullptr;
11665 DeferredCandidatesCount = 0;
11666}
11667
11669OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11670 Best->Best = true;
11671 if (Best->Function && Best->Function->isDeleted())
11672 return OR_Deleted;
11673 return OR_Success;
11674}
11675
11676void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11678 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11679 // are accepted by both clang and NVCC. However, during a particular
11680 // compilation mode only one call variant is viable. We need to
11681 // exclude non-viable overload candidates from consideration based
11682 // only on their host/device attributes. Specifically, if one
11683 // candidate call is WrongSide and the other is SameSide, we ignore
11684 // the WrongSide candidate.
11685 // We only need to remove wrong-sided candidates here if
11686 // -fgpu-exclude-wrong-side-overloads is off. When
11687 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11688 // uniformly in isBetterOverloadCandidate.
11689 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11690 return;
11691 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11692
11693 bool ContainsSameSideCandidate =
11694 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11695 // Check viable function only.
11696 return Cand->Viable && Cand->Function &&
11697 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11699 });
11700
11701 if (!ContainsSameSideCandidate)
11702 return;
11703
11704 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11705 // Check viable function only to avoid unnecessary data copying/moving.
11706 return Cand->Viable && Cand->Function &&
11707 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11709 };
11710 llvm::erase_if(Candidates, IsWrongSideCandidate);
11711}
11712
11713/// Computes the best viable function (C++ 13.3.3)
11714/// within an overload candidate set.
11715///
11716/// \param Loc The location of the function name (or operator symbol) for
11717/// which overload resolution occurs.
11718///
11719/// \param Best If overload resolution was successful or found a deleted
11720/// function, \p Best points to the candidate function found.
11721///
11722/// \returns The result of overload resolution.
11724 SourceLocation Loc,
11725 iterator &Best) {
11726
11728 DeferredCandidatesCount == 0) &&
11729 "Unexpected deferred template candidates");
11730
11731 bool TwoPhaseResolution =
11732 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11733
11734 if (TwoPhaseResolution) {
11735 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11736 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11737 if (!(HasDeferredTemplateConstructors &&
11738 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11739 return Res;
11740 }
11741 }
11742
11744 return BestViableFunctionImpl(S, Loc, Best);
11745}
11746
11747OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11749
11751 Candidates.reserve(this->Candidates.size());
11752 std::transform(this->Candidates.begin(), this->Candidates.end(),
11753 std::back_inserter(Candidates),
11754 [](OverloadCandidate &Cand) { return &Cand; });
11755
11756 if (S.getLangOpts().CUDA)
11757 CudaExcludeWrongSideCandidates(S, Candidates);
11758
11759 Best = end();
11760 for (auto *Cand : Candidates) {
11761 Cand->Best = false;
11762 if (Cand->Viable) {
11763 if (Best == end() ||
11764 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11765 Best = Cand;
11766 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11767 // This candidate has constraint that we were unable to evaluate because
11768 // it referenced an expression that contained an error. Rather than fall
11769 // back onto a potentially unintended candidate (made worse by
11770 // subsuming constraints), treat this as 'no viable candidate'.
11771 Best = end();
11772 return OR_No_Viable_Function;
11773 }
11774 }
11775
11776 // If we didn't find any viable functions, abort.
11777 if (Best == end())
11778 return OR_No_Viable_Function;
11779
11780 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11781 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11782 PendingBest.push_back(&*Best);
11783 Best->Best = true;
11784
11785 // Make sure that this function is better than every other viable
11786 // function. If not, we have an ambiguity.
11787 while (!PendingBest.empty()) {
11788 auto *Curr = PendingBest.pop_back_val();
11789 for (auto *Cand : Candidates) {
11790 if (Cand->Viable && !Cand->Best &&
11791 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11792 PendingBest.push_back(Cand);
11793 Cand->Best = true;
11794
11796 Curr->Function))
11797 EquivalentCands.push_back(Cand->Function);
11798 else
11799 Best = end();
11800 }
11801 }
11802 }
11803
11804 if (Best == end())
11805 return OR_Ambiguous;
11806
11807 OverloadingResult R = ResultForBestCandidate(Best);
11808
11809 if (!EquivalentCands.empty())
11811 EquivalentCands);
11812 return R;
11813}
11814
11815namespace {
11816
11817enum OverloadCandidateKind {
11818 oc_function,
11819 oc_method,
11820 oc_reversed_binary_operator,
11821 oc_constructor,
11822 oc_implicit_default_constructor,
11823 oc_implicit_copy_constructor,
11824 oc_implicit_move_constructor,
11825 oc_implicit_copy_assignment,
11826 oc_implicit_move_assignment,
11827 oc_implicit_equality_comparison,
11828 oc_inherited_constructor
11829};
11830
11831enum OverloadCandidateSelect {
11832 ocs_non_template,
11833 ocs_template,
11834 ocs_described_template,
11835};
11836
11837static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11838ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11839 const FunctionDecl *Fn,
11841 std::string &Description) {
11842
11843 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11844 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11845 isTemplate = true;
11846 Description = S.getTemplateArgumentBindingsText(
11847 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11848 }
11849
11850 OverloadCandidateSelect Select = [&]() {
11851 if (!Description.empty())
11852 return ocs_described_template;
11853 return isTemplate ? ocs_template : ocs_non_template;
11854 }();
11855
11856 OverloadCandidateKind Kind = [&]() {
11857 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11858 return oc_implicit_equality_comparison;
11859
11860 if (CRK & CRK_Reversed)
11861 return oc_reversed_binary_operator;
11862
11863 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11864 if (!Ctor->isImplicit()) {
11866 return oc_inherited_constructor;
11867 else
11868 return oc_constructor;
11869 }
11870
11871 if (Ctor->isDefaultConstructor())
11872 return oc_implicit_default_constructor;
11873
11874 if (Ctor->isMoveConstructor())
11875 return oc_implicit_move_constructor;
11876
11877 assert(Ctor->isCopyConstructor() &&
11878 "unexpected sort of implicit constructor");
11879 return oc_implicit_copy_constructor;
11880 }
11881
11882 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11883 // This actually gets spelled 'candidate function' for now, but
11884 // it doesn't hurt to split it out.
11885 if (!Meth->isImplicit())
11886 return oc_method;
11887
11888 if (Meth->isMoveAssignmentOperator())
11889 return oc_implicit_move_assignment;
11890
11891 if (Meth->isCopyAssignmentOperator())
11892 return oc_implicit_copy_assignment;
11893
11894 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11895 return oc_method;
11896 }
11897
11898 return oc_function;
11899 }();
11900
11901 return std::make_pair(Kind, Select);
11902}
11903
11904void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11905 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11906 // set.
11907 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11908 S.Diag(FoundDecl->getLocation(),
11909 diag::note_ovl_candidate_inherited_constructor)
11910 << Shadow->getNominatedBaseClass();
11911}
11912
11913} // end anonymous namespace
11914
11916 const FunctionDecl *FD) {
11917 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11918 bool AlwaysTrue;
11919 if (EnableIf->getCond()->isValueDependent() ||
11920 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11921 return false;
11922 if (!AlwaysTrue)
11923 return false;
11924 }
11925 return true;
11926}
11927
11928/// Returns true if we can take the address of the function.
11929///
11930/// \param Complain - If true, we'll emit a diagnostic
11931/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11932/// we in overload resolution?
11933/// \param Loc - The location of the statement we're complaining about. Ignored
11934/// if we're not complaining, or if we're in overload resolution.
11936 bool Complain,
11937 bool InOverloadResolution,
11938 SourceLocation Loc) {
11939 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11940 if (Complain) {
11941 if (InOverloadResolution)
11942 S.Diag(FD->getBeginLoc(),
11943 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11944 else
11945 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11946 }
11947 return false;
11948 }
11949
11950 if (FD->getTrailingRequiresClause()) {
11951 ConstraintSatisfaction Satisfaction;
11952 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11953 return false;
11954 if (!Satisfaction.IsSatisfied) {
11955 if (Complain) {
11956 if (InOverloadResolution) {
11957 SmallString<128> TemplateArgString;
11958 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11959 TemplateArgString += " ";
11960 TemplateArgString += S.getTemplateArgumentBindingsText(
11961 FunTmpl->getTemplateParameters(),
11963 }
11964
11965 S.Diag(FD->getBeginLoc(),
11966 diag::note_ovl_candidate_unsatisfied_constraints)
11967 << TemplateArgString;
11968 } else
11969 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11970 << FD;
11971 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11972 }
11973 return false;
11974 }
11975 }
11976
11977 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11978 return P->hasAttr<PassObjectSizeAttr>();
11979 });
11980 if (I == FD->param_end())
11981 return true;
11982
11983 if (Complain) {
11984 // Add one to ParamNo because it's user-facing
11985 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11986 if (InOverloadResolution)
11987 S.Diag(FD->getLocation(),
11988 diag::note_ovl_candidate_has_pass_object_size_params)
11989 << ParamNo;
11990 else
11991 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11992 << FD << ParamNo;
11993 }
11994 return false;
11995}
11996
11998 const FunctionDecl *FD) {
11999 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
12000 /*InOverloadResolution=*/true,
12001 /*Loc=*/SourceLocation());
12002}
12003
12005 bool Complain,
12006 SourceLocation Loc) {
12007 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
12008 /*InOverloadResolution=*/false,
12009 Loc);
12010}
12011
12012// Don't print candidates other than the one that matches the calling
12013// convention of the call operator, since that is guaranteed to exist.
12015 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
12016
12017 if (!ConvD)
12018 return false;
12019 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
12020 if (!RD->isLambda())
12021 return false;
12022
12023 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
12024 CallingConv CallOpCC =
12025 CallOp->getType()->castAs<FunctionType>()->getCallConv();
12026 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
12027 CallingConv ConvToCC =
12028 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
12029
12030 return ConvToCC != CallOpCC;
12031}
12032
12033// Notes the location of an overload candidate.
12035 OverloadCandidateRewriteKind RewriteKind,
12036 QualType DestType, bool TakingAddress) {
12037 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
12038 return;
12039 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
12040 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
12041 return;
12042 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
12043 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
12044 return;
12046 return;
12047
12048 std::string FnDesc;
12049 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
12050 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
12051 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
12052 << (unsigned)KSPair.first << (unsigned)KSPair.second
12053 << Fn << FnDesc;
12054
12055 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
12056 Diag(Fn->getLocation(), PD);
12057 MaybeEmitInheritedConstructorNote(*this, Found);
12058}
12059
12060static void
12062 // Perhaps the ambiguity was caused by two atomic constraints that are
12063 // 'identical' but not equivalent:
12064 //
12065 // void foo() requires (sizeof(T) > 4) { } // #1
12066 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
12067 //
12068 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
12069 // #2 to subsume #1, but these constraint are not considered equivalent
12070 // according to the subsumption rules because they are not the same
12071 // source-level construct. This behavior is quite confusing and we should try
12072 // to help the user figure out what happened.
12073
12074 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
12075 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
12076 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12077 if (!I->Function)
12078 continue;
12080 if (auto *Template = I->Function->getPrimaryTemplate())
12081 Template->getAssociatedConstraints(AC);
12082 else
12083 I->Function->getAssociatedConstraints(AC);
12084 if (AC.empty())
12085 continue;
12086 if (FirstCand == nullptr) {
12087 FirstCand = I->Function;
12088 FirstAC = AC;
12089 } else if (SecondCand == nullptr) {
12090 SecondCand = I->Function;
12091 SecondAC = AC;
12092 } else {
12093 // We have more than one pair of constrained functions - this check is
12094 // expensive and we'd rather not try to diagnose it.
12095 return;
12096 }
12097 }
12098 if (!SecondCand)
12099 return;
12100 // The diagnostic can only happen if there are associated constraints on
12101 // both sides (there needs to be some identical atomic constraint).
12102 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
12103 SecondCand, SecondAC))
12104 // Just show the user one diagnostic, they'll probably figure it out
12105 // from here.
12106 return;
12107}
12108
12109// Notes the location of all overload candidates designated through
12110// OverloadedExpr
12111void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12112 bool TakingAddress) {
12113 assert(OverloadedExpr->getType() == Context.OverloadTy);
12114
12115 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
12116 OverloadExpr *OvlExpr = Ovl.Expression;
12117
12118 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12119 IEnd = OvlExpr->decls_end();
12120 I != IEnd; ++I) {
12121 if (FunctionTemplateDecl *FunTmpl =
12122 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
12123 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
12124 TakingAddress);
12125 } else if (FunctionDecl *Fun
12126 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
12127 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
12128 }
12129 }
12130}
12131
12132/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12133/// "lead" diagnostic; it will be given two arguments, the source and
12134/// target types of the conversion.
12136 Sema &S,
12137 SourceLocation CaretLoc,
12138 const PartialDiagnostic &PDiag) const {
12139 S.Diag(CaretLoc, PDiag)
12140 << Ambiguous.getFromType() << Ambiguous.getToType();
12141 unsigned CandsShown = 0;
12143 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12144 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12145 break;
12146 ++CandsShown;
12147 S.NoteOverloadCandidate(I->first, I->second);
12148 }
12149 S.Diags.overloadCandidatesShown(CandsShown);
12150 if (I != E)
12151 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12152}
12153
12155 unsigned I, bool TakingCandidateAddress) {
12156 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12157 assert(Conv.isBad());
12158 assert(Cand->Function && "for now, candidate must be a function");
12159 FunctionDecl *Fn = Cand->Function;
12160
12161 // There's a conversion slot for the object argument if this is a
12162 // non-constructor method. Note that 'I' corresponds the
12163 // conversion-slot index.
12164 bool isObjectArgument = false;
12165 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12167 if (I == 0)
12168 isObjectArgument = true;
12169 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12170 I--;
12171 }
12172
12173 std::string FnDesc;
12174 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12175 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12176 FnDesc);
12177
12178 Expr *FromExpr = Conv.Bad.FromExpr;
12179 QualType FromTy = Conv.Bad.getFromType();
12180 QualType ToTy = Conv.Bad.getToType();
12181 SourceRange ToParamRange;
12182
12183 // FIXME: In presence of parameter packs we can't determine parameter range
12184 // reliably, as we don't have access to instantiation.
12185 bool HasParamPack =
12186 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12187 return Parm->isParameterPack();
12188 });
12189 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12190 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12191
12192 if (FromTy == S.Context.OverloadTy) {
12193 assert(FromExpr && "overload set argument came from implicit argument?");
12194 Expr *E = FromExpr->IgnoreParens();
12195 if (isa<UnaryOperator>(E))
12196 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12197 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12198
12199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12200 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12201 << ToParamRange << ToTy << Name << I + 1;
12202 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12203 return;
12204 }
12205
12206 // Do some hand-waving analysis to see if the non-viability is due
12207 // to a qualifier mismatch.
12208 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12209 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12210 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12211 CToTy = RT->getPointeeType();
12212 else {
12213 // TODO: detect and diagnose the full richness of const mismatches.
12214 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12215 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12216 CFromTy = FromPT->getPointeeType();
12217 CToTy = ToPT->getPointeeType();
12218 }
12219 }
12220
12221 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12222 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12223 Qualifiers FromQs = CFromTy.getQualifiers();
12224 Qualifiers ToQs = CToTy.getQualifiers();
12225
12226 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12227 if (isObjectArgument)
12228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12229 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12230 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12231 else
12232 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12233 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12234 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12235 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12236 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12237 return;
12238 }
12239
12240 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12241 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12242 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12243 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12244 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12245 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12246 return;
12247 }
12248
12249 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12251 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12252 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12253 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12254 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12255 return;
12256 }
12257
12258 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12259 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12260 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12261 << FromTy << !!FromQs.getPointerAuth()
12262 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12263 << ToQs.getPointerAuth().getAsString() << I + 1
12264 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12265 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12266 return;
12267 }
12268
12269 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12270 assert(CVR && "expected qualifiers mismatch");
12271
12272 if (isObjectArgument) {
12273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12274 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12275 << FromTy << (CVR - 1);
12276 } else {
12277 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12278 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12279 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12280 }
12281 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12282 return;
12283 }
12284
12287 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12288 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12289 << (unsigned)isObjectArgument << I + 1
12291 << ToParamRange;
12292 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12293 return;
12294 }
12295
12296 // Special diagnostic for failure to convert an initializer list, since
12297 // telling the user that it has type void is not useful.
12298 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12300 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12301 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12304 ? 2
12305 : 0);
12306 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12307 return;
12308 }
12309
12310 // Diagnose references or pointers to incomplete types differently,
12311 // since it's far from impossible that the incompleteness triggered
12312 // the failure.
12313 QualType TempFromTy = FromTy.getNonReferenceType();
12314 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12315 TempFromTy = PTy->getPointeeType();
12316 if (TempFromTy->isIncompleteType()) {
12317 // Emit the generic diagnostic and, optionally, add the hints to it.
12318 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12319 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12320 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12321 << (unsigned)(Cand->Fix.Kind);
12322
12323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12324 return;
12325 }
12326
12327 // Diagnose base -> derived pointer conversions.
12328 unsigned BaseToDerivedConversion = 0;
12329 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12330 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12331 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12332 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12333 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12334 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12335 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12336 FromPtrTy->getPointeeType()))
12337 BaseToDerivedConversion = 1;
12338 }
12339 } else if (const ObjCObjectPointerType *FromPtrTy
12340 = FromTy->getAs<ObjCObjectPointerType>()) {
12341 if (const ObjCObjectPointerType *ToPtrTy
12342 = ToTy->getAs<ObjCObjectPointerType>())
12343 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12344 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12345 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12346 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12347 FromIface->isSuperClassOf(ToIface))
12348 BaseToDerivedConversion = 2;
12349 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12350 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12351 S.getASTContext()) &&
12352 !FromTy->isIncompleteType() &&
12353 !ToRefTy->getPointeeType()->isIncompleteType() &&
12354 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12355 BaseToDerivedConversion = 3;
12356 }
12357 }
12358
12359 if (BaseToDerivedConversion) {
12360 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12361 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12362 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12363 << I + 1;
12364 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12365 return;
12366 }
12367
12368 if (isa<ObjCObjectPointerType>(CFromTy) &&
12369 isa<PointerType>(CToTy)) {
12370 Qualifiers FromQs = CFromTy.getQualifiers();
12371 Qualifiers ToQs = CToTy.getQualifiers();
12372 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12374 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12375 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12376 << I + 1;
12377 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12378 return;
12379 }
12380 }
12381
12382 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12383 return;
12384
12385 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12386 // although this is almost always an error and we advise against it.
12387 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12388 ToTy == S.Context.getLogicalOperationType()) {
12389 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12390 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12391 << Conv.Bad.FromExpr << ToTy;
12392 return;
12393 }
12394
12395 // Emit the generic diagnostic and, optionally, add the hints to it.
12396 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12397 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12398 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12399 << (unsigned)(Cand->Fix.Kind);
12400
12401 // Check that location of Fn is not in system header.
12402 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12403 // If we can fix the conversion, suggest the FixIts.
12404 for (const FixItHint &HI : Cand->Fix.Hints)
12405 FDiag << HI;
12406 }
12407
12408 S.Diag(Fn->getLocation(), FDiag);
12409
12410 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12411}
12412
12413/// Additional arity mismatch diagnosis specific to a function overload
12414/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12415/// over a candidate in any candidate set.
12417 unsigned NumArgs, bool IsAddressOf = false) {
12418 assert(Cand->Function && "Candidate is required to be a function.");
12419 FunctionDecl *Fn = Cand->Function;
12420 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12421 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12422
12423 // With invalid overloaded operators, it's possible that we think we
12424 // have an arity mismatch when in fact it looks like we have the
12425 // right number of arguments, because only overloaded operators have
12426 // the weird behavior of overloading member and non-member functions.
12427 // Just don't report anything.
12428 if (Fn->isInvalidDecl() &&
12429 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12430 return true;
12431
12432 if (NumArgs < MinParams) {
12433 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12435 Cand->DeductionFailure.getResult() ==
12437 } else {
12438 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12440 Cand->DeductionFailure.getResult() ==
12442 }
12443
12444 return false;
12445}
12446
12447/// General arity mismatch diagnosis over a candidate in a candidate set.
12449 unsigned NumFormalArgs,
12450 bool IsAddressOf = false) {
12451 assert(isa<FunctionDecl>(D) &&
12452 "The templated declaration should at least be a function"
12453 " when diagnosing bad template argument deduction due to too many"
12454 " or too few arguments");
12455
12457
12458 // TODO: treat calls to a missing default constructor as a special case
12459 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12460 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12461 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12462
12463 // at least / at most / exactly
12464 bool HasExplicitObjectParam =
12465 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12466
12467 unsigned ParamCount =
12468 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12469 unsigned mode, modeCount;
12470
12471 if (NumFormalArgs < MinParams) {
12472 if (MinParams != ParamCount || FnTy->isVariadic() ||
12473 FnTy->isTemplateVariadic())
12474 mode = 0; // "at least"
12475 else
12476 mode = 2; // "exactly"
12477 modeCount = MinParams;
12478 } else {
12479 if (MinParams != ParamCount)
12480 mode = 1; // "at most"
12481 else
12482 mode = 2; // "exactly"
12483 modeCount = ParamCount;
12484 }
12485
12486 std::string Description;
12487 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12488 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12489
12490 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12491 if (modeCount == 1 && !IsAddressOf &&
12492 FirstNonObjectParamIdx < Fn->getNumParams() &&
12493 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12494 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12495 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12496 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12497 << NumFormalArgs << HasExplicitObjectParam
12498 << Fn->getParametersSourceRange();
12499 else
12500 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12501 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12502 << Description << mode << modeCount << NumFormalArgs
12503 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12504
12505 MaybeEmitInheritedConstructorNote(S, Found);
12506}
12507
12508/// Arity mismatch diagnosis specific to a function overload candidate.
12510 unsigned NumFormalArgs) {
12511 assert(Cand->Function && "Candidate must be a function");
12512 FunctionDecl *Fn = Cand->Function;
12513 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12514 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12515 Cand->TookAddressOfOverload);
12516}
12517
12519 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12520 return TD;
12521 llvm_unreachable("Unsupported: Getting the described template declaration"
12522 " for bad deduction diagnosis");
12523}
12524
12525/// Diagnose a failed template-argument deduction.
12526static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12527 DeductionFailureInfo &DeductionFailure,
12528 unsigned NumArgs, bool TakingCandidateAddress,
12529 TemplateSpecCandidateSetKind CandidateSetKind =
12531 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12532 NamedDecl *ParamD = dyn_cast_if_present<TemplateTypeParmDecl *>(Param);
12533 if (!ParamD)
12534 ParamD = dyn_cast_if_present<NonTypeTemplateParmDecl *>(Param);
12535 if (!ParamD)
12536 ParamD = dyn_cast_if_present<TemplateTemplateParmDecl *>(Param);
12537 switch (DeductionFailure.getResult()) {
12539 llvm_unreachable(
12540 "TemplateDeductionResult::Success while diagnosing bad deduction");
12542 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12543 "while diagnosing bad deduction");
12546 return;
12547
12549 assert(ParamD && "no parameter found for incomplete deduction result");
12550 S.Diag(Templated->getLocation(),
12551 diag::note_ovl_candidate_incomplete_deduction)
12552 << ParamD->getDeclName();
12553 MaybeEmitInheritedConstructorNote(S, Found);
12554 return;
12555 }
12556
12558 assert(ParamD && "no parameter found for incomplete deduction result");
12559 S.Diag(Templated->getLocation(),
12560 diag::note_ovl_candidate_incomplete_deduction_pack)
12561 << ParamD->getDeclName()
12562 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12563 << *DeductionFailure.getFirstArg();
12564 MaybeEmitInheritedConstructorNote(S, Found);
12565 return;
12566 }
12567
12569 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12571
12572 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12573
12574 // Param will have been canonicalized, but it should just be a
12575 // qualified version of ParamD, so move the qualifiers to that.
12577 Qs.strip(Param);
12578 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12579 assert(S.Context.hasSameType(Param, NonCanonParam));
12580
12581 // Arg has also been canonicalized, but there's nothing we can do
12582 // about that. It also doesn't matter as much, because it won't
12583 // have any template parameters in it (because deduction isn't
12584 // done on dependent types).
12585 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12586
12587 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12588 << ParamD->getDeclName() << Arg << NonCanonParam;
12589 MaybeEmitInheritedConstructorNote(S, Found);
12590 return;
12591 }
12592
12594 assert(ParamD && "no parameter found for inconsistent deduction result");
12595 int which = 0;
12596 if (isa<TemplateTypeParmDecl>(ParamD))
12597 which = 0;
12598 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12599 // Deduction might have failed because we deduced arguments of two
12600 // different types for a non-type template parameter.
12601 // FIXME: Use a different TDK value for this.
12602 QualType T1 =
12603 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12604 QualType T2 =
12605 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12606 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12607 S.Diag(Templated->getLocation(),
12608 diag::note_ovl_candidate_inconsistent_deduction_types)
12609 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12610 << *DeductionFailure.getSecondArg() << T2;
12611 MaybeEmitInheritedConstructorNote(S, Found);
12612 return;
12613 }
12614
12615 which = 1;
12616 } else {
12617 which = 2;
12618 }
12619
12620 // Tweak the diagnostic if the problem is that we deduced packs of
12621 // different arities. We'll print the actual packs anyway in case that
12622 // includes additional useful information.
12623 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12624 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12625 DeductionFailure.getFirstArg()->pack_size() !=
12626 DeductionFailure.getSecondArg()->pack_size()) {
12627 which = 3;
12628 }
12629
12630 S.Diag(Templated->getLocation(),
12631 diag::note_ovl_candidate_inconsistent_deduction)
12632 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12633 << *DeductionFailure.getSecondArg();
12634 MaybeEmitInheritedConstructorNote(S, Found);
12635 return;
12636 }
12637
12639 assert(ParamD && "no parameter found for invalid explicit arguments");
12640
12641 auto Diag = S.Diag(Templated->getLocation(),
12642 diag::note_ovl_candidate_explicit_arg_mismatch);
12643 if (ParamD->getDeclName())
12644 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12645 else
12646 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12647 << (getDepthAndIndex(ParamD).second + 1);
12648 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12649 SmallString<128> DiagContent;
12650 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12651 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12652 } else {
12653 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12654 }
12655
12656 MaybeEmitInheritedConstructorNote(S, Found);
12657 return;
12658 }
12660 // Format the template argument list into the argument string.
12661 SmallString<128> TemplateArgString;
12662 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12663 TemplateArgString = " ";
12664 TemplateArgString += S.getTemplateArgumentBindingsText(
12665 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12666 if (TemplateArgString.size() == 1)
12667 TemplateArgString.clear();
12668 S.Diag(Templated->getLocation(),
12669 diag::note_ovl_candidate_unsatisfied_constraints)
12670 << TemplateArgString;
12671
12673 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12674 return;
12675 }
12678 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12679 return;
12680
12682 S.Diag(Templated->getLocation(),
12683 diag::note_ovl_candidate_instantiation_depth);
12684 MaybeEmitInheritedConstructorNote(S, Found);
12685 return;
12686
12688 // Format the template argument list into the argument string.
12689 SmallString<128> TemplateArgString;
12690 if (TemplateArgumentList *Args =
12691 DeductionFailure.getTemplateArgumentList()) {
12692 TemplateArgString = " ";
12693 TemplateArgString += S.getTemplateArgumentBindingsText(
12694 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12695 if (TemplateArgString.size() == 1)
12696 TemplateArgString.clear();
12697 }
12698
12699 // If this candidate was disabled by enable_if, say so.
12700 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12701 if (PDiag && PDiag->second.getDiagID() ==
12702 diag::err_typename_nested_not_found_enable_if) {
12703 // FIXME: Use the source range of the condition, and the fully-qualified
12704 // name of the enable_if template. These are both present in PDiag.
12705 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12706 << "'enable_if'" << TemplateArgString;
12707 return;
12708 }
12709
12710 // We found a specific requirement that disabled the enable_if.
12711 if (PDiag && PDiag->second.getDiagID() ==
12712 diag::err_typename_nested_not_found_requirement) {
12713 S.Diag(Templated->getLocation(),
12714 diag::note_ovl_candidate_disabled_by_requirement)
12715 << PDiag->second.getStringArg(0) << TemplateArgString;
12716 return;
12717 }
12718
12719 // Format the SFINAE diagnostic into the argument string.
12720 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12721 // formatted message in another diagnostic.
12722 SmallString<128> SFINAEArgString;
12723 SourceRange R;
12724 if (PDiag) {
12725 SFINAEArgString = ": ";
12726 R = SourceRange(PDiag->first, PDiag->first);
12727 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12728 }
12729
12730 S.Diag(Templated->getLocation(),
12731 diag::note_ovl_candidate_substitution_failure)
12732 << TemplateArgString << SFINAEArgString << R;
12733 MaybeEmitInheritedConstructorNote(S, Found);
12734 return;
12735 }
12736
12739 // Format the template argument list into the argument string.
12740 SmallString<128> TemplateArgString;
12741 if (TemplateArgumentList *Args =
12742 DeductionFailure.getTemplateArgumentList()) {
12743 TemplateArgString = " ";
12744 TemplateArgString += S.getTemplateArgumentBindingsText(
12745 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12746 if (TemplateArgString.size() == 1)
12747 TemplateArgString.clear();
12748 }
12749
12750 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12751 << (*DeductionFailure.getCallArgIndex() + 1)
12752 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12753 << TemplateArgString
12754 << (DeductionFailure.getResult() ==
12756 break;
12757 }
12758
12760 // FIXME: Provide a source location to indicate what we couldn't match.
12761 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12762 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12763 if (FirstTA.getKind() == TemplateArgument::Template &&
12764 SecondTA.getKind() == TemplateArgument::Template) {
12765 TemplateName FirstTN = FirstTA.getAsTemplate();
12766 TemplateName SecondTN = SecondTA.getAsTemplate();
12767 if (FirstTN.getKind() == TemplateName::Template &&
12768 SecondTN.getKind() == TemplateName::Template) {
12769 if (FirstTN.getAsTemplateDecl()->getName() ==
12770 SecondTN.getAsTemplateDecl()->getName()) {
12771 // FIXME: This fixes a bad diagnostic where both templates are named
12772 // the same. This particular case is a bit difficult since:
12773 // 1) It is passed as a string to the diagnostic printer.
12774 // 2) The diagnostic printer only attempts to find a better
12775 // name for types, not decls.
12776 // Ideally, this should folded into the diagnostic printer.
12777 S.Diag(Templated->getLocation(),
12778 CandidateSetKind ==
12780 ? diag::note_friend_template_non_deduced_mismatch_qualified
12781 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12782 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12783 return;
12784 }
12785 }
12786 }
12787
12788 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12790 return;
12791
12792 // FIXME: For generic lambda parameters, check if the function is a lambda
12793 // call operator, and if so, emit a prettier and more informative
12794 // diagnostic that mentions 'auto' and lambda in addition to
12795 // (or instead of?) the canonical template type parameters.
12796 S.Diag(Templated->getLocation(),
12798 ? diag::note_friend_template_non_deduced_mismatch
12799 : diag::note_ovl_candidate_non_deduced_mismatch)
12800 << FirstTA << SecondTA;
12801 return;
12802 }
12803 // TODO: diagnose these individually, then kill off
12804 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12806 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12807 MaybeEmitInheritedConstructorNote(S, Found);
12808 return;
12810 S.Diag(Templated->getLocation(),
12811 diag::note_cuda_ovl_candidate_target_mismatch);
12812 return;
12813 }
12814}
12815
12816/// Diagnose a failed template-argument deduction, for function calls.
12818 unsigned NumArgs,
12819 bool TakingCandidateAddress) {
12820 assert(Cand->Function && "Candidate must be a function");
12821 FunctionDecl *Fn = Cand->Function;
12825 if (CheckArityMismatch(S, Cand, NumArgs))
12826 return;
12827 }
12828 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12829 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12830}
12831
12832/// CUDA: diagnose an invalid call across targets.
12834 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12835 assert(Cand->Function && "Candidate must be a Function.");
12836 FunctionDecl *Callee = Cand->Function;
12837
12838 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12839 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12840
12841 std::string FnDesc;
12842 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12843 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12844 Cand->getRewriteKind(), FnDesc);
12845
12846 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12847 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12848 << FnDesc /* Ignored */
12849 << CalleeTarget << CallerTarget;
12850
12851 // This could be an implicit constructor for which we could not infer the
12852 // target due to a collsion. Diagnose that case.
12853 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12854 if (Meth != nullptr && Meth->isImplicit()) {
12855 CXXRecordDecl *ParentClass = Meth->getParent();
12857
12858 switch (FnKindPair.first) {
12859 default:
12860 return;
12861 case oc_implicit_default_constructor:
12863 break;
12864 case oc_implicit_copy_constructor:
12866 break;
12867 case oc_implicit_move_constructor:
12869 break;
12870 case oc_implicit_copy_assignment:
12872 break;
12873 case oc_implicit_move_assignment:
12875 break;
12876 };
12877
12878 bool ConstRHS = false;
12879 if (Meth->getNumParams()) {
12880 if (const ReferenceType *RT =
12881 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12882 ConstRHS = RT->getPointeeType().isConstQualified();
12883 }
12884 }
12885
12886 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12887 /* ConstRHS */ ConstRHS,
12888 /* Diagnose */ true);
12889 }
12890}
12891
12893 assert(Cand->Function && "Candidate must be a function");
12894 FunctionDecl *Callee = Cand->Function;
12895 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12896
12897 S.Diag(Callee->getLocation(),
12898 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12899 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12900}
12901
12903 assert(Cand->Function && "Candidate must be a function");
12904 FunctionDecl *Fn = Cand->Function;
12906 assert(ES.isExplicit() && "not an explicit candidate");
12907
12908 unsigned Kind;
12909 switch (Fn->getDeclKind()) {
12910 case Decl::Kind::CXXConstructor:
12911 Kind = 0;
12912 break;
12913 case Decl::Kind::CXXConversion:
12914 Kind = 1;
12915 break;
12916 case Decl::Kind::CXXDeductionGuide:
12917 Kind = Fn->isImplicit() ? 0 : 2;
12918 break;
12919 default:
12920 llvm_unreachable("invalid Decl");
12921 }
12922
12923 // Note the location of the first (in-class) declaration; a redeclaration
12924 // (particularly an out-of-class definition) will typically lack the
12925 // 'explicit' specifier.
12926 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12927 FunctionDecl *First = Fn->getFirstDecl();
12928 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12929 First = Pattern->getFirstDecl();
12930
12931 S.Diag(First->getLocation(),
12932 diag::note_ovl_candidate_explicit)
12933 << Kind << (ES.getExpr() ? 1 : 0)
12934 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12935}
12936
12938 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12939 if (!DG)
12940 return;
12941 TemplateDecl *OriginTemplate =
12943 // We want to always print synthesized deduction guides for type aliases.
12944 // They would retain the explicit bit of the corresponding constructor.
12945 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12946 return;
12947 std::string FunctionProto;
12948 llvm::raw_string_ostream OS(FunctionProto);
12949 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12950 if (!Template) {
12951 // This also could be an instantiation. Find out the primary template.
12952 FunctionDecl *Pattern =
12953 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12954 if (!Pattern) {
12955 // The implicit deduction guide is built on an explicit non-template
12956 // deduction guide. Currently, this might be the case only for type
12957 // aliases.
12958 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12959 // gets merged.
12960 assert(OriginTemplate->isTypeAlias() &&
12961 "Non-template implicit deduction guides are only possible for "
12962 "type aliases");
12963 DG->print(OS);
12964 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12965 << FunctionProto;
12966 return;
12967 }
12969 assert(Template && "Cannot find the associated function template of "
12970 "CXXDeductionGuideDecl?");
12971 }
12972 Template->print(OS);
12973 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12974 << FunctionProto;
12975}
12976
12977/// Generates a 'note' diagnostic for an overload candidate. We've
12978/// already generated a primary error at the call site.
12979///
12980/// It really does need to be a single diagnostic with its caret
12981/// pointed at the candidate declaration. Yes, this creates some
12982/// major challenges of technical writing. Yes, this makes pointing
12983/// out problems with specific arguments quite awkward. It's still
12984/// better than generating twenty screens of text for every failed
12985/// overload.
12986///
12987/// It would be great to be able to express per-candidate problems
12988/// more richly for those diagnostic clients that cared, but we'd
12989/// still have to be just as careful with the default diagnostics.
12990/// \param CtorDestAS Addr space of object being constructed (for ctor
12991/// candidates only).
12993 unsigned NumArgs,
12994 bool TakingCandidateAddress,
12995 LangAS CtorDestAS = LangAS::Default) {
12996 assert(Cand->Function && "Candidate must be a function");
12997 FunctionDecl *Fn = Cand->Function;
12999 return;
13000
13001 // There is no physical candidate declaration to point to for OpenCL builtins.
13002 // Except for failed conversions, the notes are identical for each candidate,
13003 // so do not generate such notes.
13004 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
13006 return;
13007
13008 // Skip implicit member functions when trying to resolve
13009 // the address of a an overload set for a function pointer.
13010 if (Cand->TookAddressOfOverload &&
13011 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
13012 return;
13013
13014 // Note deleted candidates, but only if they're viable.
13015 if (Cand->Viable) {
13016 if (Fn->isDeleted()) {
13017 std::string FnDesc;
13018 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13019 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13020 Cand->getRewriteKind(), FnDesc);
13021
13022 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
13023 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
13024 << (Fn->isDeleted()
13025 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
13026 : 0);
13027 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13028 return;
13029 }
13030
13031 // We don't really have anything else to say about viable candidates.
13032 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13033 return;
13034 }
13035
13036 // If this is a synthesized deduction guide we're deducing against, add a note
13037 // for it. These deduction guides are not explicitly spelled in the source
13038 // code, so simply printing a deduction failure note mentioning synthesized
13039 // template parameters or pointing to the header of the surrounding RecordDecl
13040 // would be confusing.
13041 //
13042 // We prefer adding such notes at the end of the deduction failure because
13043 // duplicate code snippets appearing in the diagnostic would likely become
13044 // noisy.
13045 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
13046
13047 switch (Cand->FailureKind) {
13050 return DiagnoseArityMismatch(S, Cand, NumArgs);
13051
13053 return DiagnoseBadDeduction(S, Cand, NumArgs,
13054 TakingCandidateAddress);
13055
13057 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
13058 << (Fn->getPrimaryTemplate() ? 1 : 0);
13059 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13060 return;
13061 }
13062
13064 Qualifiers QualsForPrinting;
13065 QualsForPrinting.setAddressSpace(CtorDestAS);
13066 S.Diag(Fn->getLocation(),
13067 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
13068 << QualsForPrinting;
13069 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13070 return;
13071 }
13072
13076 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13077
13079 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
13080 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
13081 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
13082 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
13083
13084 // FIXME: this currently happens when we're called from SemaInit
13085 // when user-conversion overload fails. Figure out how to handle
13086 // those conditions and diagnose them well.
13087 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13088 }
13089
13091 return DiagnoseBadTarget(S, Cand);
13092
13093 case ovl_fail_enable_if:
13094 return DiagnoseFailedEnableIfAttr(S, Cand);
13095
13096 case ovl_fail_explicit:
13097 return DiagnoseFailedExplicitSpec(S, Cand);
13098
13100 // It's generally not interesting to note copy/move constructors here.
13101 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
13102 return;
13103 S.Diag(Fn->getLocation(),
13104 diag::note_ovl_candidate_inherited_constructor_slice)
13105 << (Fn->getPrimaryTemplate() ? 1 : 0)
13106 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
13107 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13108 return;
13109
13111 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
13112 (void)Available;
13113 assert(!Available);
13114 break;
13115 }
13117 // Do nothing, these should simply be ignored.
13118 break;
13119
13121 std::string FnDesc;
13122 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13123 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13124 Cand->getRewriteKind(), FnDesc);
13125
13126 S.Diag(Fn->getLocation(),
13127 diag::note_ovl_candidate_constraints_not_satisfied)
13128 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13129 << FnDesc /* Ignored */;
13130 ConstraintSatisfaction Satisfaction;
13131 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
13132 /*ForOverloadResolution=*/true))
13133 break;
13134 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13135 }
13136 }
13137}
13138
13141 return;
13142
13143 // Desugar the type of the surrogate down to a function type,
13144 // retaining as many typedefs as possible while still showing
13145 // the function type (and, therefore, its parameter types).
13146 QualType FnType = Cand->Surrogate->getConversionType();
13147 bool isLValueReference = false;
13148 bool isRValueReference = false;
13149 bool isPointer = false;
13150 if (const LValueReferenceType *FnTypeRef =
13151 FnType->getAs<LValueReferenceType>()) {
13152 FnType = FnTypeRef->getPointeeType();
13153 isLValueReference = true;
13154 } else if (const RValueReferenceType *FnTypeRef =
13155 FnType->getAs<RValueReferenceType>()) {
13156 FnType = FnTypeRef->getPointeeType();
13157 isRValueReference = true;
13158 }
13159 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13160 FnType = FnTypePtr->getPointeeType();
13161 isPointer = true;
13162 }
13163 // Desugar down to a function type.
13164 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13165 // Reconstruct the pointer/reference as appropriate.
13166 if (isPointer) FnType = S.Context.getPointerType(FnType);
13167 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13168 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13169
13170 if (!Cand->Viable &&
13172 S.Diag(Cand->Surrogate->getLocation(),
13173 diag::note_ovl_surrogate_constraints_not_satisfied)
13174 << Cand->Surrogate;
13175 ConstraintSatisfaction Satisfaction;
13176 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13177 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13178 } else {
13179 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13180 << FnType;
13181 }
13182}
13183
13184static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13185 SourceLocation OpLoc,
13186 OverloadCandidate *Cand) {
13187 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13188 std::string TypeStr("operator");
13189 TypeStr += Opc;
13190 TypeStr += "(";
13191 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13192 if (Cand->Conversions.size() == 1) {
13193 TypeStr += ")";
13194 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13195 } else {
13196 TypeStr += ", ";
13197 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13198 TypeStr += ")";
13199 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13200 }
13201}
13202
13204 OverloadCandidate *Cand) {
13205 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13206 if (ICS.isBad()) break; // all meaningless after first invalid
13207 if (!ICS.isAmbiguous()) continue;
13208
13210 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13211 }
13212}
13213
13215 if (Cand->Function)
13216 return Cand->Function->getLocation();
13217 if (Cand->IsSurrogate)
13218 return Cand->Surrogate->getLocation();
13219 return SourceLocation();
13220}
13221
13222static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13223 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13227 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13228
13232 return 1;
13233
13236 return 2;
13237
13245 return 3;
13246
13248 return 4;
13249
13251 return 5;
13252
13255 return 6;
13256 }
13257 llvm_unreachable("Unhandled deduction result");
13258}
13259
13260namespace {
13261
13262struct CompareOverloadCandidatesForDisplay {
13263 Sema &S;
13264 SourceLocation Loc;
13265 size_t NumArgs;
13267
13268 CompareOverloadCandidatesForDisplay(
13269 Sema &S, SourceLocation Loc, size_t NArgs,
13271 : S(S), NumArgs(NArgs), CSK(CSK) {}
13272
13273 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13274 // If there are too many or too few arguments, that's the high-order bit we
13275 // want to sort by, even if the immediate failure kind was something else.
13276 if (C->FailureKind == ovl_fail_too_many_arguments ||
13277 C->FailureKind == ovl_fail_too_few_arguments)
13278 return static_cast<OverloadFailureKind>(C->FailureKind);
13279
13280 if (C->Function) {
13281 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13283 if (NumArgs < C->Function->getMinRequiredArguments())
13285 }
13286
13287 return static_cast<OverloadFailureKind>(C->FailureKind);
13288 }
13289
13290 bool operator()(const OverloadCandidate *L,
13291 const OverloadCandidate *R) {
13292 // Fast-path this check.
13293 if (L == R) return false;
13294
13295 // Order first by viability.
13296 if (L->Viable) {
13297 if (!R->Viable) return true;
13298
13299 if (int Ord = CompareConversions(*L, *R))
13300 return Ord < 0;
13301 // Use other tie breakers.
13302 } else if (R->Viable)
13303 return false;
13304
13305 assert(L->Viable == R->Viable);
13306
13307 // Criteria by which we can sort non-viable candidates:
13308 if (!L->Viable) {
13309 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13310 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13311
13312 // 1. Arity mismatches come after other candidates.
13313 if (LFailureKind == ovl_fail_too_many_arguments ||
13314 LFailureKind == ovl_fail_too_few_arguments) {
13315 if (RFailureKind == ovl_fail_too_many_arguments ||
13316 RFailureKind == ovl_fail_too_few_arguments) {
13317 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13318 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13319 if (LDist == RDist) {
13320 if (LFailureKind == RFailureKind)
13321 // Sort non-surrogates before surrogates.
13322 return !L->IsSurrogate && R->IsSurrogate;
13323 // Sort candidates requiring fewer parameters than there were
13324 // arguments given after candidates requiring more parameters
13325 // than there were arguments given.
13326 return LFailureKind == ovl_fail_too_many_arguments;
13327 }
13328 return LDist < RDist;
13329 }
13330 return false;
13331 }
13332 if (RFailureKind == ovl_fail_too_many_arguments ||
13333 RFailureKind == ovl_fail_too_few_arguments)
13334 return true;
13335
13336 // 2. Bad conversions come first and are ordered by the number
13337 // of bad conversions and quality of good conversions.
13338 if (LFailureKind == ovl_fail_bad_conversion) {
13339 if (RFailureKind != ovl_fail_bad_conversion)
13340 return true;
13341
13342 // The conversion that can be fixed with a smaller number of changes,
13343 // comes first.
13344 unsigned numLFixes = L->Fix.NumConversionsFixed;
13345 unsigned numRFixes = R->Fix.NumConversionsFixed;
13346 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13347 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13348 if (numLFixes != numRFixes) {
13349 return numLFixes < numRFixes;
13350 }
13351
13352 // If there's any ordering between the defined conversions...
13353 if (int Ord = CompareConversions(*L, *R))
13354 return Ord < 0;
13355 } else if (RFailureKind == ovl_fail_bad_conversion)
13356 return false;
13357
13358 if (LFailureKind == ovl_fail_bad_deduction) {
13359 if (RFailureKind != ovl_fail_bad_deduction)
13360 return true;
13361
13362 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13363 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13364 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13365 if (LRank != RRank)
13366 return LRank < RRank;
13367 }
13368 } else if (RFailureKind == ovl_fail_bad_deduction)
13369 return false;
13370
13371 // TODO: others?
13372 }
13373
13374 // Sort everything else by location.
13375 SourceLocation LLoc = GetLocationForCandidate(L);
13376 SourceLocation RLoc = GetLocationForCandidate(R);
13377
13378 // Put candidates without locations (e.g. builtins) at the end.
13379 if (LLoc.isValid() && RLoc.isValid())
13380 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13381 if (LLoc.isValid() && !RLoc.isValid())
13382 return true;
13383 if (RLoc.isValid() && !LLoc.isValid())
13384 return false;
13385 assert(!LLoc.isValid() && !RLoc.isValid());
13386 // For builtins and other functions without locations, fallback to the order
13387 // in which they were added into the candidate set.
13388 return L < R;
13389 }
13390
13391private:
13392 struct ConversionSignals {
13393 unsigned KindRank = 0;
13395
13396 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13397 ConversionSignals Sig;
13398 Sig.KindRank = Seq.getKindRank();
13399 if (Seq.isStandard())
13400 Sig.Rank = Seq.Standard.getRank();
13401 else if (Seq.isUserDefined())
13402 Sig.Rank = Seq.UserDefined.After.getRank();
13403 // We intend StaticObjectArgumentConversion to compare the same as
13404 // StandardConversion with ICR_ExactMatch rank.
13405 return Sig;
13406 }
13407
13408 static ConversionSignals ForObjectArgument() {
13409 // We intend StaticObjectArgumentConversion to compare the same as
13410 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13411 return {};
13412 }
13413 };
13414
13415 // Returns -1 if conversions in L are considered better.
13416 // 0 if they are considered indistinguishable.
13417 // 1 if conversions in R are better.
13418 int CompareConversions(const OverloadCandidate &L,
13419 const OverloadCandidate &R) {
13420 // We cannot use `isBetterOverloadCandidate` because it is defined
13421 // according to the C++ standard and provides a partial order, but we need
13422 // a total order as this function is used in sort.
13423 assert(L.Conversions.size() == R.Conversions.size());
13424 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13425 auto LS = L.IgnoreObjectArgument && I == 0
13426 ? ConversionSignals::ForObjectArgument()
13427 : ConversionSignals::ForSequence(L.Conversions[I]);
13428 auto RS = R.IgnoreObjectArgument
13429 ? ConversionSignals::ForObjectArgument()
13430 : ConversionSignals::ForSequence(R.Conversions[I]);
13431 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13432 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13433 ? -1
13434 : 1;
13435 }
13436 // FIXME: find a way to compare templates for being more or less
13437 // specialized that provides a strict weak ordering.
13438 return 0;
13439 }
13440};
13441}
13442
13443/// CompleteNonViableCandidate - Normally, overload resolution only
13444/// computes up to the first bad conversion. Produces the FixIt set if
13445/// possible.
13446static void
13448 ArrayRef<Expr *> Args,
13450 assert(!Cand->Viable);
13451
13452 // Don't do anything on failures other than bad conversion.
13454 return;
13455
13456 // We only want the FixIts if all the arguments can be corrected.
13457 bool Unfixable = false;
13458 // Use a implicit copy initialization to check conversion fixes.
13460
13461 // Attempt to fix the bad conversion.
13462 unsigned ConvCount = Cand->Conversions.size();
13463 for (unsigned ConvIdx =
13464 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13465 : 0);
13466 /**/; ++ConvIdx) {
13467 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13468 if (Cand->Conversions[ConvIdx].isInitialized() &&
13469 Cand->Conversions[ConvIdx].isBad()) {
13470 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13471 break;
13472 }
13473 }
13474
13475 // FIXME: this should probably be preserved from the overload
13476 // operation somehow.
13477 bool SuppressUserConversions = false;
13478
13479 unsigned ConvIdx = 0;
13480 unsigned ArgIdx = 0;
13481 ArrayRef<QualType> ParamTypes;
13482 bool Reversed = Cand->isReversed();
13483
13484 if (Cand->IsSurrogate) {
13485 QualType ConvType
13487 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13488 ConvType = ConvPtrType->getPointeeType();
13489 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13490 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13491 ConvIdx = 1;
13492 } else if (Cand->Function) {
13493 ParamTypes =
13494 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13495 if (isa<CXXMethodDecl>(Cand->Function) &&
13498 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13499 ConvIdx = 1;
13501 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13503 OO_Subscript)
13504 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13505 ArgIdx = 1;
13506 }
13507 } else {
13508 // Builtin operator.
13509 assert(ConvCount <= 3);
13510 ParamTypes = Cand->BuiltinParamTypes;
13511 }
13512
13513 // Fill in the rest of the conversions.
13514 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13515 ConvIdx != ConvCount && ArgIdx < Args.size();
13516 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13517 if (Cand->Conversions[ConvIdx].isInitialized()) {
13518 // We've already checked this conversion.
13519 } else if (ParamIdx < ParamTypes.size()) {
13520 if (ParamTypes[ParamIdx]->isDependentType())
13521 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13522 Args[ArgIdx]->getType());
13523 else {
13524 Cand->Conversions[ConvIdx] =
13525 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13526 SuppressUserConversions,
13527 /*InOverloadResolution=*/true,
13528 /*AllowObjCWritebackConversion=*/
13529 S.getLangOpts().ObjCAutoRefCount);
13530 // Store the FixIt in the candidate if it exists.
13531 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13532 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13533 }
13534 } else
13535 Cand->Conversions[ConvIdx].setEllipsis();
13536 }
13537}
13538
13541 SourceLocation OpLoc,
13542 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13543
13545
13546 // Sort the candidates by viability and position. Sorting directly would
13547 // be prohibitive, so we make a set of pointers and sort those.
13549 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13550 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13551 Cand != LastCand; ++Cand) {
13552 if (!Filter(*Cand))
13553 continue;
13554 switch (OCD) {
13555 case OCD_AllCandidates:
13556 if (!Cand->Viable) {
13557 if (!Cand->Function && !Cand->IsSurrogate) {
13558 // This a non-viable builtin candidate. We do not, in general,
13559 // want to list every possible builtin candidate.
13560 continue;
13561 }
13562 CompleteNonViableCandidate(S, Cand, Args, Kind);
13563 }
13564 break;
13565
13567 if (!Cand->Viable)
13568 continue;
13569 break;
13570
13572 if (!Cand->Best)
13573 continue;
13574 break;
13575 }
13576
13577 Cands.push_back(Cand);
13578 }
13579
13580 llvm::stable_sort(
13581 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13582
13583 return Cands;
13584}
13585
13587 SourceLocation OpLoc) {
13588 bool DeferHint = false;
13589 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13590 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13591 // host device candidates.
13592 auto WrongSidedCands =
13593 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13594 return (Cand.Viable == false &&
13596 (Cand.Function &&
13597 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13598 Cand.Function->template hasAttr<CUDADeviceAttr>());
13599 });
13600 DeferHint = !WrongSidedCands.empty();
13601 }
13602 return DeferHint;
13603}
13604
13605/// When overload resolution fails, prints diagnostic messages containing the
13606/// candidates in the candidate set.
13609 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13610 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13611
13612 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13613
13614 {
13615 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13616 S.Diag(PD.first, PD.second);
13617 }
13618
13619 // In WebAssembly we don't want to emit further diagnostics if a table is
13620 // passed as an argument to a function.
13621 bool NoteCands = true;
13622 for (const Expr *Arg : Args) {
13623 if (Arg->getType()->isWebAssemblyTableType())
13624 NoteCands = false;
13625 }
13626
13627 if (NoteCands)
13628 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13629
13630 if (OCD == OCD_AmbiguousCandidates)
13632 {Candidates.begin(), Candidates.end()});
13633}
13634
13637 StringRef Opc, SourceLocation OpLoc) {
13638 bool ReportedAmbiguousConversions = false;
13639
13640 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13641 unsigned CandsShown = 0;
13642 auto I = Cands.begin(), E = Cands.end();
13643 for (; I != E; ++I) {
13644 OverloadCandidate *Cand = *I;
13645
13646 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13647 ShowOverloads == Ovl_Best) {
13648 break;
13649 }
13650 ++CandsShown;
13651
13652 if (Cand->Function)
13653 NoteFunctionCandidate(S, Cand, Args.size(),
13654 Kind == CSK_AddressOfOverloadSet, DestAS);
13655 else if (Cand->IsSurrogate)
13656 NoteSurrogateCandidate(S, Cand);
13657 else {
13658 assert(Cand->Viable &&
13659 "Non-viable built-in candidates are not added to Cands.");
13660 // Generally we only see ambiguities including viable builtin
13661 // operators if overload resolution got screwed up by an
13662 // ambiguous user-defined conversion.
13663 //
13664 // FIXME: It's quite possible for different conversions to see
13665 // different ambiguities, though.
13666 if (!ReportedAmbiguousConversions) {
13667 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13668 ReportedAmbiguousConversions = true;
13669 }
13670
13671 // If this is a viable builtin, print it.
13672 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13673 }
13674 }
13675
13676 // Inform S.Diags that we've shown an overload set with N elements. This may
13677 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13678 S.Diags.overloadCandidatesShown(CandsShown);
13679
13680 if (I != E) {
13681 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13682 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13683 }
13684}
13685
13687 const Sema &S) const {
13688 if (S.getLangOpts().CUDA) {
13689 auto *Caller = S.getCurFunctionDecl(true);
13690 // Overloading based on __host__ and __device__ attributes takes
13691 // higher priority, HD functions may favor template candidates even when a
13692 // non-template candidate would be a perfect match.
13693 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13694 Caller->hasAttr<CUDADeviceAttr>())
13695 return false;
13696 }
13697
13698 return
13699 // For user defined conversion we need to check against different
13700 // combination of CV qualifiers and look at any explicit specifier, so
13701 // always deduce template candidates.
13703 // When doing code completion, we want to see all the
13704 // viable candidates.
13705 && Kind != CSK_CodeCompletion;
13706}
13707
13708static SourceLocation
13710 return Cand->Specialization ? Cand->Specialization->getLocation()
13711 : SourceLocation();
13712}
13713
13714namespace {
13715struct CompareTemplateSpecCandidatesForDisplay {
13716 Sema &S;
13717 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13718
13719 bool operator()(const TemplateSpecCandidate *L,
13720 const TemplateSpecCandidate *R) {
13721 // Fast-path this check.
13722 if (L == R)
13723 return false;
13724
13725 // Assuming that both candidates are not matches...
13726
13727 // Sort by the ranking of deduction failures.
13728 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13730 RankDeductionFailure(R->DeductionFailure);
13731
13732 // Sort everything else by location.
13733 SourceLocation LLoc = GetLocationForCandidate(L);
13734 SourceLocation RLoc = GetLocationForCandidate(R);
13735
13736 // Put candidates without locations (e.g. builtins) at the end.
13737 if (LLoc.isInvalid())
13738 return false;
13739 if (RLoc.isInvalid())
13740 return true;
13741
13742 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13743 }
13744};
13745}
13746
13747/// Diagnose a template argument deduction failure.
13748/// We are treating these failures as overload failures due to bad
13749/// deductions.
13751 Sema &S, bool ForTakingAddress,
13752 TemplateSpecCandidateSetKind CandidateSetKind) {
13754 DeductionFailure, /*NumArgs=*/0, ForTakingAddress,
13755 CandidateSetKind);
13756}
13757
13758void TemplateSpecCandidateSet::destroyCandidates() {
13759 for (iterator i = begin(), e = end(); i != e; ++i) {
13760 i->DeductionFailure.Destroy();
13761 }
13762}
13763
13765 destroyCandidates();
13766 Candidates.clear();
13767}
13768
13769/// NoteCandidates - When no template specialization match is found, prints
13770/// diagnostic messages containing the non-matching specializations that form
13771/// the candidate set.
13772/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13773/// OCD == OCD_AllCandidates and Cand->Viable == false.
13775 // Sort the candidates by position (assuming no candidate is a match).
13776 // Sorting directly would be prohibitive, so we make a set of pointers
13777 // and sort those.
13779 Cands.reserve(size());
13780 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13781 if (Cand->Specialization)
13782 Cands.push_back(Cand);
13783 // Otherwise, this is a non-matching builtin candidate. We do not,
13784 // in general, want to list every possible builtin candidate.
13785 }
13786
13787 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13788
13789 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13790 // for generalization purposes (?).
13791 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13792
13794 unsigned CandsShown = 0;
13795 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13796 TemplateSpecCandidate *Cand = *I;
13797
13798 // Set an arbitrary limit on the number of candidates we'll spam
13799 // the user with. FIXME: This limit should depend on details of the
13800 // candidate list.
13801 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13802 break;
13803 ++CandsShown;
13804
13805 assert(Cand->Specialization &&
13806 "Non-matching built-in candidates are not added to Cands.");
13807 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13808 }
13809
13810 if (I != E)
13811 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13812}
13813
13814// [PossiblyAFunctionType] --> [Return]
13815// NonFunctionType --> NonFunctionType
13816// R (A) --> R(A)
13817// R (*)(A) --> R (A)
13818// R (&)(A) --> R (A)
13819// R (S::*)(A) --> R (A)
13821 QualType Ret = PossiblyAFunctionType;
13822 if (const PointerType *ToTypePtr =
13823 PossiblyAFunctionType->getAs<PointerType>())
13824 Ret = ToTypePtr->getPointeeType();
13825 else if (const ReferenceType *ToTypeRef =
13826 PossiblyAFunctionType->getAs<ReferenceType>())
13827 Ret = ToTypeRef->getPointeeType();
13828 else if (const MemberPointerType *MemTypePtr =
13829 PossiblyAFunctionType->getAs<MemberPointerType>())
13830 Ret = MemTypePtr->getPointeeType();
13831 Ret =
13832 Context.getCanonicalType(Ret).getUnqualifiedType();
13833 return Ret;
13834}
13835
13837 bool Complain = true) {
13838 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13839 S.DeduceReturnType(FD, Loc, Complain))
13840 return true;
13841
13842 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13843 if (S.getLangOpts().CPlusPlus17 &&
13844 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13845 !S.ResolveExceptionSpec(Loc, FPT))
13846 return true;
13847
13848 return false;
13849}
13850
13851namespace {
13852// A helper class to help with address of function resolution
13853// - allows us to avoid passing around all those ugly parameters
13854class AddressOfFunctionResolver {
13855 Sema& S;
13856 Expr* SourceExpr;
13857 const QualType& TargetType;
13858 QualType TargetFunctionType; // Extracted function type from target type
13859
13860 bool Complain;
13861 //DeclAccessPair& ResultFunctionAccessPair;
13862 ASTContext& Context;
13863
13864 bool TargetTypeIsNonStaticMemberFunction;
13865 bool FoundNonTemplateFunction;
13866 bool StaticMemberFunctionFromBoundPointer;
13867 bool HasComplained;
13868
13869 OverloadExpr::FindResult OvlExprInfo;
13870 OverloadExpr *OvlExpr;
13871 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13872 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13873 TemplateSpecCandidateSet FailedCandidates;
13874
13875public:
13876 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13877 const QualType &TargetType, bool Complain)
13878 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13879 Complain(Complain), Context(S.getASTContext()),
13880 TargetTypeIsNonStaticMemberFunction(
13881 !!TargetType->getAs<MemberPointerType>()),
13882 FoundNonTemplateFunction(false),
13883 StaticMemberFunctionFromBoundPointer(false),
13884 HasComplained(false),
13885 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13886 OvlExpr(OvlExprInfo.Expression),
13887 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13888 ExtractUnqualifiedFunctionTypeFromTargetType();
13889
13890 if (TargetFunctionType->isFunctionType()) {
13891 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13892 if (!UME->isImplicitAccess() &&
13894 StaticMemberFunctionFromBoundPointer = true;
13895 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13896 DeclAccessPair dap;
13897 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13898 OvlExpr, false, &dap)) {
13899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13900 if (!Method->isStatic()) {
13901 // If the target type is a non-function type and the function found
13902 // is a non-static member function, pretend as if that was the
13903 // target, it's the only possible type to end up with.
13904 TargetTypeIsNonStaticMemberFunction = true;
13905
13906 // And skip adding the function if its not in the proper form.
13907 // We'll diagnose this due to an empty set of functions.
13908 if (!OvlExprInfo.HasFormOfMemberPointer)
13909 return;
13910 }
13911
13912 Matches.push_back(std::make_pair(dap, Fn));
13913 }
13914 return;
13915 }
13916
13917 if (OvlExpr->hasExplicitTemplateArgs())
13918 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13919
13920 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13921 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13922 EliminateSuboptimalCudaMatches();
13923
13924 // C++ [over.over]p4:
13925 // If more than one function is selected, [...]
13926 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13927 if (FoundNonTemplateFunction) {
13928 EliminateAllTemplateMatches();
13929 EliminateLessPartialOrderingConstrainedMatches();
13930 } else
13931 EliminateAllExceptMostSpecializedTemplate();
13932 }
13933 }
13934 }
13935
13936 bool hasComplained() const { return HasComplained; }
13937
13938private:
13939 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13940 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13941 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13942 }
13943
13944 /// \return true if A is considered a better overload candidate for the
13945 /// desired type than B.
13946 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13947 // If A doesn't have exactly the correct type, we don't want to classify it
13948 // as "better" than anything else. This way, the user is required to
13949 // disambiguate for us if there are multiple candidates and no exact match.
13950 return candidateHasExactlyCorrectType(A) &&
13951 (!candidateHasExactlyCorrectType(B) ||
13952 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13953 }
13954
13955 /// \return true if we were able to eliminate all but one overload candidate,
13956 /// false otherwise.
13957 bool eliminiateSuboptimalOverloadCandidates() {
13958 // Same algorithm as overload resolution -- one pass to pick the "best",
13959 // another pass to be sure that nothing is better than the best.
13960 auto Best = Matches.begin();
13961 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13962 if (isBetterCandidate(I->second, Best->second))
13963 Best = I;
13964
13965 const FunctionDecl *BestFn = Best->second;
13966 auto IsBestOrInferiorToBest = [this, BestFn](
13967 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13968 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13969 };
13970
13971 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13972 // option, so we can potentially give the user a better error
13973 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13974 return false;
13975 Matches[0] = *Best;
13976 Matches.resize(1);
13977 return true;
13978 }
13979
13980 bool isTargetTypeAFunction() const {
13981 return TargetFunctionType->isFunctionType();
13982 }
13983
13984 // [ToType] [Return]
13985
13986 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13987 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13988 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13989 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13990 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13991 }
13992
13993 // return true if any matching specializations were found
13994 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13995 const DeclAccessPair& CurAccessFunPair) {
13996 if (CXXMethodDecl *Method
13997 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13998 // Skip non-static function templates when converting to pointer, and
13999 // static when converting to member pointer.
14000 bool CanConvertToFunctionPointer =
14001 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14002 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14003 return false;
14004 }
14005 else if (TargetTypeIsNonStaticMemberFunction)
14006 return false;
14007
14008 // C++ [over.over]p2:
14009 // If the name is a function template, template argument deduction is
14010 // done (14.8.2.2), and if the argument deduction succeeds, the
14011 // resulting template argument list is used to generate a single
14012 // function template specialization, which is added to the set of
14013 // overloaded functions considered.
14014 FunctionDecl *Specialization = nullptr;
14015 TemplateDeductionInfo Info(FailedCandidates.getLocation());
14017 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
14018 Specialization, Info, /*IsAddressOfFunction*/ true);
14019 Result != TemplateDeductionResult::Success) {
14020 // Make a note of the failed deduction for diagnostics.
14021 FailedCandidates.addCandidate()
14022 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
14023 MakeDeductionFailureInfo(Context, Result, Info));
14024 return false;
14025 }
14026
14027 // Template argument deduction ensures that we have an exact match or
14028 // compatible pointer-to-function arguments that would be adjusted by ICS.
14029 // This function template specicalization works.
14031 Context.getCanonicalType(Specialization->getType()),
14032 Context.getCanonicalType(TargetFunctionType)));
14033
14035 return false;
14036
14037 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
14038 return true;
14039 }
14040
14041 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
14042 const DeclAccessPair& CurAccessFunPair) {
14043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14044 // Skip non-static functions when converting to pointer, and static
14045 // when converting to member pointer.
14046 bool CanConvertToFunctionPointer =
14047 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14048 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14049 return false;
14050 }
14051 else if (TargetTypeIsNonStaticMemberFunction)
14052 return false;
14053
14054 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
14055 if (S.getLangOpts().CUDA) {
14056 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
14057 if (!(Caller && Caller->isImplicit()) &&
14058 !S.CUDA().IsAllowedCall(Caller, FunDecl))
14059 return false;
14060 }
14061 if (FunDecl->isMultiVersion()) {
14062 const auto *TA = FunDecl->getAttr<TargetAttr>();
14063 if (TA && !TA->isDefaultVersion())
14064 return false;
14065 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
14066 if (TVA && !TVA->isDefaultVersion())
14067 return false;
14068 }
14069
14070 // If any candidate has a placeholder return type, trigger its deduction
14071 // now.
14072 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
14073 Complain)) {
14074 HasComplained |= Complain;
14075 return false;
14076 }
14077
14078 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
14079 return false;
14080
14081 // If we're in C, we need to support types that aren't exactly identical.
14082 if (!S.getLangOpts().CPlusPlus ||
14083 candidateHasExactlyCorrectType(FunDecl)) {
14084 Matches.push_back(std::make_pair(
14085 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
14086 FoundNonTemplateFunction = true;
14087 return true;
14088 }
14089 }
14090
14091 return false;
14092 }
14093
14094 bool FindAllFunctionsThatMatchTargetTypeExactly() {
14095 bool Ret = false;
14096
14097 // If the overload expression doesn't have the form of a pointer to
14098 // member, don't try to convert it to a pointer-to-member type.
14099 if (IsInvalidFormOfPointerToMemberFunction())
14100 return false;
14101
14102 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14103 E = OvlExpr->decls_end();
14104 I != E; ++I) {
14105 // Look through any using declarations to find the underlying function.
14106 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14107
14108 // C++ [over.over]p3:
14109 // Non-member functions and static member functions match
14110 // targets of type "pointer-to-function" or "reference-to-function."
14111 // Nonstatic member functions match targets of
14112 // type "pointer-to-member-function."
14113 // Note that according to DR 247, the containing class does not matter.
14114 if (FunctionTemplateDecl *FunctionTemplate
14115 = dyn_cast<FunctionTemplateDecl>(Fn)) {
14116 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
14117 Ret = true;
14118 }
14119 // If we have explicit template arguments supplied, skip non-templates.
14120 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14121 AddMatchingNonTemplateFunction(Fn, I.getPair()))
14122 Ret = true;
14123 }
14124 assert(Ret || Matches.empty());
14125 return Ret;
14126 }
14127
14128 void EliminateAllExceptMostSpecializedTemplate() {
14129 // [...] and any given function template specialization F1 is
14130 // eliminated if the set contains a second function template
14131 // specialization whose function template is more specialized
14132 // than the function template of F1 according to the partial
14133 // ordering rules of 14.5.5.2.
14134
14135 // The algorithm specified above is quadratic. We instead use a
14136 // two-pass algorithm (similar to the one used to identify the
14137 // best viable function in an overload set) that identifies the
14138 // best function template (if it exists).
14139
14140 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14141 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14142 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14143
14144 // TODO: It looks like FailedCandidates does not serve much purpose
14145 // here, since the no_viable diagnostic has index 0.
14146 UnresolvedSetIterator Result = S.getMostSpecialized(
14147 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14148 SourceExpr->getBeginLoc(), S.PDiag(),
14149 S.PDiag(diag::err_addr_ovl_ambiguous)
14150 << Matches[0].second->getDeclName(),
14151 S.PDiag(diag::note_ovl_candidate)
14152 << (unsigned)oc_function << (unsigned)ocs_described_template,
14153 Complain, TargetFunctionType);
14154
14155 if (Result != MatchesCopy.end()) {
14156 // Make it the first and only element
14157 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14158 Matches[0].second = cast<FunctionDecl>(*Result);
14159 Matches.resize(1);
14160 } else
14161 HasComplained |= Complain;
14162 }
14163
14164 void EliminateAllTemplateMatches() {
14165 // [...] any function template specializations in the set are
14166 // eliminated if the set also contains a non-template function, [...]
14167 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14168 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14169 ++I;
14170 else {
14171 Matches[I] = Matches[--N];
14172 Matches.resize(N);
14173 }
14174 }
14175 }
14176
14177 void EliminateLessPartialOrderingConstrainedMatches() {
14178 // C++ [over.over]p5:
14179 // [...] Any given non-template function F0 is eliminated if the set
14180 // contains a second non-template function that is more
14181 // partial-ordering-constrained than F0. [...]
14182 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14183 "Call EliminateAllTemplateMatches() first");
14184 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14185 Results.push_back(Matches[0]);
14186 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14187 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14188 FunctionDecl *F = getMorePartialOrderingConstrained(
14189 S, Matches[I].second, Results[0].second,
14190 /*IsFn1Reversed=*/false,
14191 /*IsFn2Reversed=*/false);
14192 if (!F) {
14193 Results.push_back(Matches[I]);
14194 continue;
14195 }
14196 if (F == Matches[I].second) {
14197 Results.clear();
14198 Results.push_back(Matches[I]);
14199 }
14200 }
14201 std::swap(Matches, Results);
14202 }
14203
14204 void EliminateSuboptimalCudaMatches() {
14205 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14206 Matches);
14207 }
14208
14209public:
14210 void ComplainNoMatchesFound() const {
14211 assert(Matches.empty());
14212 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14213 << OvlExpr->getName() << TargetFunctionType
14214 << OvlExpr->getSourceRange();
14215 if (FailedCandidates.empty())
14216 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14217 /*TakingAddress=*/true);
14218 else {
14219 // We have some deduction failure messages. Use them to diagnose
14220 // the function templates, and diagnose the non-template candidates
14221 // normally.
14222 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14223 IEnd = OvlExpr->decls_end();
14224 I != IEnd; ++I)
14225 if (FunctionDecl *Fun =
14226 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14228 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14229 /*TakingAddress=*/true);
14230 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14231 }
14232 }
14233
14234 bool IsInvalidFormOfPointerToMemberFunction() const {
14235 return TargetTypeIsNonStaticMemberFunction &&
14236 !OvlExprInfo.HasFormOfMemberPointer;
14237 }
14238
14239 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14240 // TODO: Should we condition this on whether any functions might
14241 // have matched, or is it more appropriate to do that in callers?
14242 // TODO: a fixit wouldn't hurt.
14243 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14244 << TargetType << OvlExpr->getSourceRange();
14245 }
14246
14247 bool IsStaticMemberFunctionFromBoundPointer() const {
14248 return StaticMemberFunctionFromBoundPointer;
14249 }
14250
14251 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14252 S.Diag(OvlExpr->getBeginLoc(),
14253 diag::err_invalid_form_pointer_member_function)
14254 << OvlExpr->getSourceRange();
14255 }
14256
14257 void ComplainOfInvalidConversion() const {
14258 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14259 << OvlExpr->getName() << TargetType;
14260 }
14261
14262 void ComplainMultipleMatchesFound() const {
14263 assert(Matches.size() > 1);
14264 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14265 << OvlExpr->getName() << OvlExpr->getSourceRange();
14266 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14267 /*TakingAddress=*/true);
14268 }
14269
14270 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14271
14272 int getNumMatches() const { return Matches.size(); }
14273
14274 FunctionDecl* getMatchingFunctionDecl() const {
14275 if (Matches.size() != 1) return nullptr;
14276 return Matches[0].second;
14277 }
14278
14279 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14280 if (Matches.size() != 1) return nullptr;
14281 return &Matches[0].first;
14282 }
14283};
14284}
14285
14286FunctionDecl *
14288 QualType TargetType,
14289 bool Complain,
14290 DeclAccessPair &FoundResult,
14291 bool *pHadMultipleCandidates) {
14292 assert(AddressOfExpr->getType() == Context.OverloadTy);
14293
14294 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14295 Complain);
14296 int NumMatches = Resolver.getNumMatches();
14297 FunctionDecl *Fn = nullptr;
14298 bool ShouldComplain = Complain && !Resolver.hasComplained();
14299 if (NumMatches == 0 && ShouldComplain) {
14300 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14301 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14302 else
14303 Resolver.ComplainNoMatchesFound();
14304 }
14305 else if (NumMatches > 1 && ShouldComplain)
14306 Resolver.ComplainMultipleMatchesFound();
14307 else if (NumMatches == 1) {
14308 Fn = Resolver.getMatchingFunctionDecl();
14309 assert(Fn);
14310 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14311 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14312 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14313 if (Complain) {
14314 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14315 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14316 else
14317 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14318 }
14319 }
14320
14321 if (pHadMultipleCandidates)
14322 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14323 return Fn;
14324}
14325
14329 OverloadExpr *Ovl = R.Expression;
14330 bool IsResultAmbiguous = false;
14331 FunctionDecl *Result = nullptr;
14332 DeclAccessPair DAP;
14333 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14334
14335 // Return positive for better, negative for worse, 0 for equal preference.
14336 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14337 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14338 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14339 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14340 };
14341
14342 // Don't use the AddressOfResolver because we're specifically looking for
14343 // cases where we have one overload candidate that lacks
14344 // enable_if/pass_object_size/...
14345 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14346 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14347 if (!FD)
14348 return nullptr;
14349
14351 continue;
14352
14353 // If we found a better result, update Result.
14354 auto FoundBetter = [&]() {
14355 IsResultAmbiguous = false;
14356 DAP = I.getPair();
14357 Result = FD;
14358 };
14359
14360 // We have more than one result - see if it is more
14361 // partial-ordering-constrained than the previous one.
14362 if (Result) {
14363 // Check CUDA preference first. If the candidates have differennt CUDA
14364 // preference, choose the one with higher CUDA preference. Otherwise,
14365 // choose the one with more constraints.
14366 if (getLangOpts().CUDA) {
14367 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14368 // FD has different preference than Result.
14369 if (PreferenceByCUDA != 0) {
14370 // FD is more preferable than Result.
14371 if (PreferenceByCUDA > 0)
14372 FoundBetter();
14373 continue;
14374 }
14375 }
14376 // FD has the same CUDA preference than Result. Continue to check
14377 // constraints.
14378
14379 // C++ [over.over]p5:
14380 // [...] If more than one function in the set remains, all function
14381 // template specializations in the set are eliminated if the set also
14382 // contains a function that is not a function template specialization.
14383 // [...]
14384 if (Result->isFunctionTemplateSpecialization() !=
14387 FoundBetter();
14388 continue;
14389 }
14390
14391 // C++ [over.over]p5:
14392 // [...] Any given non-template function F0 is eliminated if the set
14393 // contains a second non-template function that is more
14394 // partial-ordering-constrained than F0 [...]
14395 FunctionDecl *MoreConstrained =
14397 /*IsFn1Reversed=*/false,
14398 /*IsFn2Reversed=*/false);
14399 if (MoreConstrained != FD) {
14400 if (!MoreConstrained) {
14401 IsResultAmbiguous = true;
14402 AmbiguousDecls.push_back(FD);
14403 }
14404 continue;
14405 }
14406 // FD is more constrained - replace Result with it.
14407 }
14408 FoundBetter();
14409 }
14410
14411 if (IsResultAmbiguous)
14412 return nullptr;
14413
14414 if (Result) {
14415 // We skipped over some ambiguous declarations which might be ambiguous with
14416 // the selected result.
14417 for (FunctionDecl *Skipped : AmbiguousDecls) {
14418 // If skipped candidate has different CUDA preference than the result,
14419 // there is no ambiguity. Otherwise check whether they have different
14420 // constraints.
14421 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14422 continue;
14423 if (!getMoreConstrainedFunction(Skipped, Result))
14424 return nullptr;
14425 }
14426 Pair = DAP;
14427 }
14428 return Result;
14429}
14430
14432 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14433 Expr *E = SrcExpr.get();
14434 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14435
14436 DeclAccessPair DAP;
14438 if (!Found || Found->isCPUDispatchMultiVersion() ||
14439 Found->isCPUSpecificMultiVersion())
14440 return false;
14441
14442 // Emitting multiple diagnostics for a function that is both inaccessible and
14443 // unavailable is consistent with our behavior elsewhere. So, always check
14444 // for both.
14448 if (Res.isInvalid())
14449 return false;
14450 Expr *Fixed = Res.get();
14451 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14452 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14453 else
14454 SrcExpr = Fixed;
14455 return true;
14456}
14457
14459 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14460 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14461 // C++ [over.over]p1:
14462 // [...] [Note: any redundant set of parentheses surrounding the
14463 // overloaded function name is ignored (5.1). ]
14464 // C++ [over.over]p1:
14465 // [...] The overloaded function name can be preceded by the &
14466 // operator.
14467
14468 // If we didn't actually find any template-ids, we're done.
14469 if (!ovl->hasExplicitTemplateArgs())
14470 return nullptr;
14471
14472 TemplateArgumentListInfo ExplicitTemplateArgs;
14473 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14474
14475 // Look through all of the overloaded functions, searching for one
14476 // whose type matches exactly.
14477 FunctionDecl *Matched = nullptr;
14478 for (UnresolvedSetIterator I = ovl->decls_begin(),
14479 E = ovl->decls_end(); I != E; ++I) {
14480 // C++0x [temp.arg.explicit]p3:
14481 // [...] In contexts where deduction is done and fails, or in contexts
14482 // where deduction is not done, if a template argument list is
14483 // specified and it, along with any default template arguments,
14484 // identifies a single function template specialization, then the
14485 // template-id is an lvalue for the function template specialization.
14487 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14488 if (!FunctionTemplate)
14489 continue;
14490
14491 // C++ [over.over]p2:
14492 // If the name is a function template, template argument deduction is
14493 // done (14.8.2.2), and if the argument deduction succeeds, the
14494 // resulting template argument list is used to generate a single
14495 // function template specialization, which is added to the set of
14496 // overloaded functions considered.
14497 FunctionDecl *Specialization = nullptr;
14498 TemplateDeductionInfo Info(ovl->getNameLoc());
14500 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14501 /*IsAddressOfFunction*/ true);
14503 // Make a note of the failed deduction for diagnostics.
14504 if (FailedTSC)
14505 FailedTSC->addCandidate().set(
14506 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14508 continue;
14509 }
14510
14511 assert(Specialization && "no specialization and no error?");
14512
14513 // C++ [temp.deduct.call]p6:
14514 // [...] If all successful deductions yield the same deduced A, that
14515 // deduced A is the result of deduction; otherwise, the parameter is
14516 // treated as a non-deduced context.
14517 if (Matched) {
14518 if (ForTypeDeduction &&
14520 Specialization->getType()))
14521 continue;
14522 // Multiple matches; we can't resolve to a single declaration.
14523 if (Complain) {
14524 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14525 << ovl->getName();
14527 }
14528 return nullptr;
14529 }
14530
14531 Matched = Specialization;
14532 if (FoundResult) *FoundResult = I.getPair();
14533 }
14534
14535 if (Matched &&
14536 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14537 return nullptr;
14538
14539 return Matched;
14540}
14541
14543 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14544 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14545 unsigned DiagIDForComplaining) {
14546 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14547
14549
14550 DeclAccessPair found;
14551 ExprResult SingleFunctionExpression;
14553 ovl.Expression, /*complain*/ false, &found)) {
14554 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14555 SrcExpr = ExprError();
14556 return true;
14557 }
14558
14559 // It is only correct to resolve to an instance method if we're
14560 // resolving a form that's permitted to be a pointer to member.
14561 // Otherwise we'll end up making a bound member expression, which
14562 // is illegal in all the contexts we resolve like this.
14563 if (!ovl.HasFormOfMemberPointer &&
14564 isa<CXXMethodDecl>(fn) &&
14565 cast<CXXMethodDecl>(fn)->isInstance()) {
14566 if (!complain) return false;
14567
14568 Diag(ovl.Expression->getExprLoc(),
14569 diag::err_bound_member_function)
14570 << 0 << ovl.Expression->getSourceRange();
14571
14572 // TODO: I believe we only end up here if there's a mix of
14573 // static and non-static candidates (otherwise the expression
14574 // would have 'bound member' type, not 'overload' type).
14575 // Ideally we would note which candidate was chosen and why
14576 // the static candidates were rejected.
14577 SrcExpr = ExprError();
14578 return true;
14579 }
14580
14581 // Fix the expression to refer to 'fn'.
14582 SingleFunctionExpression =
14583 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14584
14585 // If desired, do function-to-pointer decay.
14586 if (doFunctionPointerConversion) {
14587 SingleFunctionExpression =
14588 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14589 if (SingleFunctionExpression.isInvalid()) {
14590 SrcExpr = ExprError();
14591 return true;
14592 }
14593 }
14594 }
14595
14596 if (!SingleFunctionExpression.isUsable()) {
14597 if (complain) {
14598 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14599 << ovl.Expression->getName()
14600 << DestTypeForComplaining
14601 << OpRangeForComplaining
14603 NoteAllOverloadCandidates(SrcExpr.get());
14604
14605 SrcExpr = ExprError();
14606 return true;
14607 }
14608
14609 return false;
14610 }
14611
14612 SrcExpr = SingleFunctionExpression;
14613 return true;
14614}
14615
14616/// Add a single candidate to the overload set.
14618 DeclAccessPair FoundDecl,
14619 TemplateArgumentListInfo *ExplicitTemplateArgs,
14620 ArrayRef<Expr *> Args,
14621 OverloadCandidateSet &CandidateSet,
14622 bool PartialOverloading,
14623 bool KnownValid) {
14624 NamedDecl *Callee = FoundDecl.getDecl();
14625 if (isa<UsingShadowDecl>(Callee))
14626 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14627
14628 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14629 if (ExplicitTemplateArgs) {
14630 assert(!KnownValid && "Explicit template arguments?");
14631 return;
14632 }
14633 // Prevent ill-formed function decls to be added as overload candidates.
14634 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14635 return;
14636
14637 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14638 /*SuppressUserConversions=*/false,
14639 PartialOverloading);
14640 return;
14641 }
14642
14643 if (FunctionTemplateDecl *FuncTemplate
14644 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14645 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14646 ExplicitTemplateArgs, Args, CandidateSet,
14647 /*SuppressUserConversions=*/false,
14648 PartialOverloading);
14649 return;
14650 }
14651
14652 assert(!KnownValid && "unhandled case in overloaded call candidate");
14653}
14654
14656 ArrayRef<Expr *> Args,
14657 OverloadCandidateSet &CandidateSet,
14658 bool PartialOverloading) {
14659
14660#ifndef NDEBUG
14661 // Verify that ArgumentDependentLookup is consistent with the rules
14662 // in C++0x [basic.lookup.argdep]p3:
14663 //
14664 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14665 // and let Y be the lookup set produced by argument dependent
14666 // lookup (defined as follows). If X contains
14667 //
14668 // -- a declaration of a class member, or
14669 //
14670 // -- a block-scope function declaration that is not a
14671 // using-declaration, or
14672 //
14673 // -- a declaration that is neither a function or a function
14674 // template
14675 //
14676 // then Y is empty.
14677
14678 if (ULE->requiresADL()) {
14680 E = ULE->decls_end(); I != E; ++I) {
14681 assert(!(*I)->getDeclContext()->isRecord());
14682 assert(isa<UsingShadowDecl>(*I) ||
14683 !(*I)->getDeclContext()->isFunctionOrMethod());
14684 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14685 }
14686 }
14687#endif
14688
14689 // It would be nice to avoid this copy.
14690 TemplateArgumentListInfo TABuffer;
14691 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14692 if (ULE->hasExplicitTemplateArgs()) {
14693 ULE->copyTemplateArgumentsInto(TABuffer);
14694 ExplicitTemplateArgs = &TABuffer;
14695 }
14696
14698 E = ULE->decls_end(); I != E; ++I)
14699 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14700 CandidateSet, PartialOverloading,
14701 /*KnownValid*/ true);
14702
14703 if (ULE->requiresADL())
14705 Args, ExplicitTemplateArgs,
14706 CandidateSet, PartialOverloading);
14707}
14708
14710 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14711 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14712 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14713 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14714 CandidateSet, false, /*KnownValid*/ false);
14715}
14716
14717/// Determine whether a declaration with the specified name could be moved into
14718/// a different namespace.
14720 switch (Name.getCXXOverloadedOperator()) {
14721 case OO_New: case OO_Array_New:
14722 case OO_Delete: case OO_Array_Delete:
14723 return false;
14724
14725 default:
14726 return true;
14727 }
14728}
14729
14730/// Attempt to recover from an ill-formed use of a non-dependent name in a
14731/// template, where the non-dependent name was declared after the template
14732/// was defined. This is common in code written for compilers which do not
14733/// correctly implement two-stage name lookup.
14734///
14735/// Returns true if a viable candidate was found and a diagnostic was issued.
14737 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14739 const OverloadCandidateSet &ResolvedCandidates,
14740 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14741 CXXRecordDecl **FoundInClass = nullptr) {
14742 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14743 return false;
14744
14745 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14746 if (DC->isTransparentContext())
14747 continue;
14748
14749 SemaRef.LookupQualifiedName(R, DC);
14750
14751 if (!R.empty()) {
14752 R.suppressDiagnostics();
14753
14754 OverloadCandidateSet Candidates(FnLoc, CSK);
14755 // We have performed a BestViableFunction over these candidates, so
14756 // exclude them.
14757 for (auto &Cand : ResolvedCandidates) {
14758 if (Cand.Function)
14759 Candidates.exclude(Cand.Function);
14760 else if (Cand.IsSurrogate)
14761 Candidates.exclude(Cand.Surrogate);
14762 }
14763 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14764 Candidates);
14765
14768 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14769
14770 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14771 // We either found non-function declarations or a best viable function
14772 // at class scope. A class-scope lookup result disables ADL. Don't
14773 // look past this, but let the caller know that we found something that
14774 // either is, or might be, usable in this class.
14775 if (FoundInClass) {
14776 *FoundInClass = RD;
14777 if (OR == OR_Success) {
14778 R.clear();
14779 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14780 R.resolveKind();
14781 }
14782 }
14783 return false;
14784 }
14785
14786 if (OR != OR_Success) {
14787 // There wasn't a unique best function or function template.
14788 return false;
14789 }
14790
14791 // Find the namespaces where ADL would have looked, and suggest
14792 // declaring the function there instead.
14793 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14794 Sema::AssociatedClassSet AssociatedClasses;
14795 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14796 AssociatedNamespaces,
14797 AssociatedClasses);
14798 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14799 if (canBeDeclaredInNamespace(R.getLookupName())) {
14800 DeclContext *Std = SemaRef.getStdNamespace();
14801 for (Sema::AssociatedNamespaceSet::iterator
14802 it = AssociatedNamespaces.begin(),
14803 end = AssociatedNamespaces.end(); it != end; ++it) {
14804 // Never suggest declaring a function within namespace 'std'.
14805 if (Std && Std->Encloses(*it))
14806 continue;
14807
14808 // Never suggest declaring a function within a namespace with a
14809 // reserved name, like __gnu_cxx.
14810 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14811 if (NS &&
14812 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14813 continue;
14814
14815 SuggestedNamespaces.insert(*it);
14816 }
14817 }
14818
14819 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14820 << R.getLookupName();
14821 if (SuggestedNamespaces.empty()) {
14822 SemaRef.Diag(Best->Function->getLocation(),
14823 diag::note_not_found_by_two_phase_lookup)
14824 << R.getLookupName() << 0;
14825 } else if (SuggestedNamespaces.size() == 1) {
14826 SemaRef.Diag(Best->Function->getLocation(),
14827 diag::note_not_found_by_two_phase_lookup)
14828 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14829 } else {
14830 // FIXME: It would be useful to list the associated namespaces here,
14831 // but the diagnostics infrastructure doesn't provide a way to produce
14832 // a localized representation of a list of items.
14833 SemaRef.Diag(Best->Function->getLocation(),
14834 diag::note_not_found_by_two_phase_lookup)
14835 << R.getLookupName() << 2;
14836 }
14837
14838 // Try to recover by calling this function.
14839 return true;
14840 }
14841
14842 R.clear();
14843 }
14844
14845 return false;
14846}
14847
14848/// Attempt to recover from ill-formed use of a non-dependent operator in a
14849/// template, where the non-dependent operator was declared after the template
14850/// was defined.
14851///
14852/// Returns true if a viable candidate was found and a diagnostic was issued.
14854 Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc,
14855 ArrayRef<Expr *> Args, const OverloadCandidateSet &ResolvedCandidateSet) {
14856 DeclarationName OpName =
14858 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14861 ResolvedCandidateSet,
14862 /*ExplicitTemplateArgs=*/nullptr, Args, /*FoundInClass=*/nullptr);
14863}
14864
14865namespace {
14866class BuildRecoveryCallExprRAII {
14867 Sema &SemaRef;
14868 Sema::SatisfactionStackResetRAII SatStack;
14869
14870public:
14871 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14872 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14873 SemaRef.IsBuildingRecoveryCallExpr = true;
14874 }
14875
14876 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14877};
14878}
14879
14880/// Attempts to recover from a call where no functions were found.
14881///
14882/// This function will do one of three things:
14883/// * Diagnose, recover, and return a recovery expression.
14884/// * Diagnose, fail to recover, and return ExprError().
14885/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14886/// expected to diagnose as appropriate.
14887static ExprResult
14889 UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
14891 const OverloadCandidateSet &ResolvedCandidateSet,
14892 bool AllowTypoCorrection) {
14893 // Do not try to recover if it is already building a recovery call.
14894 // This stops infinite loops for template instantiations like
14895 //
14896 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14897 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14898 if (SemaRef.IsBuildingRecoveryCallExpr)
14899 return ExprResult();
14900 BuildRecoveryCallExprRAII RCE(SemaRef);
14901
14902 CXXScopeSpec SS;
14903 SS.Adopt(ULE->getQualifierLoc());
14904 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14905
14906 TemplateArgumentListInfo TABuffer;
14907 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14908 if (ULE->hasExplicitTemplateArgs()) {
14909 ULE->copyTemplateArgumentsInto(TABuffer);
14910 ExplicitTemplateArgs = &TABuffer;
14911 }
14912
14913 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14915 CXXRecordDecl *FoundInClass = nullptr;
14917 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
14918 ResolvedCandidateSet, ExplicitTemplateArgs, Args, &FoundInClass)) {
14919 // OK, diagnosed a two-phase lookup issue.
14920 } else if (ResolvedCandidateSet.empty()) {
14921 // Try to recover from an empty lookup with typo correction.
14922 R.clear();
14923 NoTypoCorrectionCCC NoTypoValidator{};
14924 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14925 ExplicitTemplateArgs != nullptr,
14926 dyn_cast<MemberExpr>(Fn));
14927 CorrectionCandidateCallback &Validator =
14928 AllowTypoCorrection
14929 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14930 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14931 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14932 Args))
14933 return ExprError();
14934 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14935 // We found a usable declaration of the name in a dependent base of some
14936 // enclosing class.
14937 // FIXME: We should also explain why the candidates found by name lookup
14938 // were not viable.
14939 if (SemaRef.DiagnoseDependentMemberLookup(R))
14940 return ExprError();
14941 } else {
14942 // We had viable candidates and couldn't recover; let the caller diagnose
14943 // this.
14944 return ExprResult();
14945 }
14946
14947 // If we get here, we should have issued a diagnostic and formed a recovery
14948 // lookup result.
14949 assert(!R.empty() && "lookup results empty despite recovery");
14950
14951 // If recovery created an ambiguity, just bail out.
14952 if (R.isAmbiguous()) {
14953 R.suppressDiagnostics();
14954 return ExprError();
14955 }
14956
14957 // Build an implicit member call if appropriate. Just drop the
14958 // casts and such from the call, we don't really care.
14959 ExprResult NewFn = ExprError();
14960 if ((*R.begin())->isCXXClassMember())
14961 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14962 ExplicitTemplateArgs, S);
14963 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14964 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14965 ExplicitTemplateArgs);
14966 else
14967 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14968
14969 if (NewFn.isInvalid())
14970 return ExprError();
14971
14972 // This shouldn't cause an infinite loop because we're giving it
14973 // an expression with viable lookup results, which should never
14974 // end up here.
14975 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14976 MultiExprArg(Args.data(), Args.size()),
14977 RParenLoc);
14978}
14979
14982 MultiExprArg Args,
14983 SourceLocation RParenLoc,
14984 OverloadCandidateSet *CandidateSet,
14985 ExprResult *Result) {
14986#ifndef NDEBUG
14987 if (ULE->requiresADL()) {
14988 // To do ADL, we must have found an unqualified name.
14989 assert(!ULE->getQualifier() && "qualified name with ADL");
14990
14991 // We don't perform ADL for implicit declarations of builtins.
14992 // Verify that this was correctly set up.
14993 FunctionDecl *F;
14994 if (ULE->decls_begin() != ULE->decls_end() &&
14995 ULE->decls_begin() + 1 == ULE->decls_end() &&
14996 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14997 F->getBuiltinID() && F->isImplicit())
14998 llvm_unreachable("performing ADL for builtin");
14999
15000 // We don't perform ADL in C.
15001 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
15002 }
15003#endif
15004
15005 UnbridgedCastsSet UnbridgedCasts;
15006 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15007 *Result = ExprError();
15008 return true;
15009 }
15010
15011 // Add the functions denoted by the callee to the set of candidate
15012 // functions, including those from argument-dependent lookup.
15013 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
15014
15015 if (getLangOpts().MSVCCompat &&
15016 CurContext->isDependentContext() && !isSFINAEContext() &&
15018
15020 if (CandidateSet->empty() ||
15021 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
15023 // In Microsoft mode, if we are inside a template class member function
15024 // then create a type dependent CallExpr. The goal is to postpone name
15025 // lookup to instantiation time to be able to search into type dependent
15026 // base classes.
15027 CallExpr *CE =
15028 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
15029 RParenLoc, CurFPFeatureOverrides());
15031 *Result = CE;
15032 return true;
15033 }
15034 }
15035
15036 if (CandidateSet->empty())
15037 return false;
15038
15039 UnbridgedCasts.restore();
15040 return false;
15041}
15042
15043// Guess at what the return type for an unresolvable overload should be.
15046 std::optional<QualType> Result;
15047 // Adjust Type after seeing a candidate.
15048 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
15049 if (!Candidate.Function)
15050 return;
15051 if (Candidate.Function->isInvalidDecl())
15052 return;
15053 QualType T = Candidate.Function->getReturnType();
15054 if (T.isNull())
15055 return;
15056 if (!Result)
15057 Result = T;
15058 else if (Result != T)
15059 Result = QualType();
15060 };
15061
15062 // Look for an unambiguous type from a progressively larger subset.
15063 // e.g. if types disagree, but all *viable* overloads return int, choose int.
15064 //
15065 // First, consider only the best candidate.
15066 if (Best && *Best != CS.end())
15067 ConsiderCandidate(**Best);
15068 // Next, consider only viable candidates.
15069 if (!Result)
15070 for (const auto &C : CS)
15071 if (C.Viable)
15072 ConsiderCandidate(C);
15073 // Finally, consider all candidates.
15074 if (!Result)
15075 for (const auto &C : CS)
15076 ConsiderCandidate(C);
15077
15078 if (!Result)
15079 return QualType();
15080 auto Value = *Result;
15081 if (Value.isNull() || Value->isUndeducedType())
15082 return QualType();
15083 return Value;
15084}
15085
15086/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
15087/// the completed call expression. If overload resolution fails, emits
15088/// diagnostics and returns ExprError()
15091 SourceLocation LParenLoc,
15092 MultiExprArg Args,
15093 SourceLocation RParenLoc,
15094 Expr *ExecConfig,
15095 OverloadCandidateSet *CandidateSet,
15097 OverloadingResult OverloadResult,
15098 bool AllowTypoCorrection) {
15099 switch (OverloadResult) {
15100 case OR_Success: {
15101 FunctionDecl *FDecl = (*Best)->Function;
15102 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
15103 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
15104 return ExprError();
15105 ExprResult Res =
15106 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15107 if (Res.isInvalid())
15108 return ExprError();
15109 return SemaRef.BuildResolvedCallExpr(
15110 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15111 /*IsExecConfig=*/false,
15112 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15113 }
15114
15115 case OR_No_Viable_Function: {
15116 if (*Best != CandidateSet->end() &&
15117 CandidateSet->getKind() ==
15119 if (CXXMethodDecl *M =
15120 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
15122 CandidateSet->NoteCandidates(
15124 Fn->getBeginLoc(),
15125 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
15126 SemaRef, OCD_AmbiguousCandidates, Args);
15127 return ExprError();
15128 }
15129 }
15130
15131 // Try to recover by looking for viable functions which the user might
15132 // have meant to call.
15133 ExprResult Recovery =
15134 BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15135 *CandidateSet, AllowTypoCorrection);
15136 if (Recovery.isInvalid() || Recovery.isUsable())
15137 return Recovery;
15138
15139 // If the user passes in a function that we can't take the address of, we
15140 // generally end up emitting really bad error messages. Here, we attempt to
15141 // emit better ones.
15142 for (const Expr *Arg : Args) {
15143 if (!Arg->getType()->isFunctionType())
15144 continue;
15145 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
15146 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15147 if (FD &&
15148 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15149 Arg->getExprLoc()))
15150 return ExprError();
15151 }
15152 }
15153
15154 CandidateSet->NoteCandidates(
15156 Fn->getBeginLoc(),
15157 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15158 << ULE->getName() << Fn->getSourceRange()),
15159 SemaRef, OCD_AllCandidates, Args);
15160 break;
15161 }
15162
15163 case OR_Ambiguous:
15164 CandidateSet->NoteCandidates(
15165 PartialDiagnosticAt(Fn->getBeginLoc(),
15166 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15167 << ULE->getName() << Fn->getSourceRange()),
15168 SemaRef, OCD_AmbiguousCandidates, Args);
15169 break;
15170
15171 case OR_Deleted: {
15172 FunctionDecl *FDecl = (*Best)->Function;
15173 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15174 Fn->getSourceRange(), ULE->getName(),
15175 *CandidateSet, FDecl, Args);
15176
15177 // We emitted an error for the unavailable/deleted function call but keep
15178 // the call in the AST.
15179 ExprResult Res =
15180 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15181 if (Res.isInvalid())
15182 return ExprError();
15183 return SemaRef.BuildResolvedCallExpr(
15184 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15185 /*IsExecConfig=*/false,
15186 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15187 }
15188 }
15189
15190 // Overload resolution failed, try to recover.
15191 SmallVector<Expr *, 8> SubExprs = {Fn};
15192 SubExprs.append(Args.begin(), Args.end());
15193 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15194 chooseRecoveryType(*CandidateSet, Best));
15195}
15196
15199 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15200 if (I->Viable &&
15201 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15202 I->Viable = false;
15203 I->FailureKind = ovl_fail_addr_not_available;
15204 }
15205 }
15206}
15207
15210 SourceLocation LParenLoc,
15211 MultiExprArg Args,
15212 SourceLocation RParenLoc,
15213 Expr *ExecConfig,
15214 bool AllowTypoCorrection,
15215 bool CalleesAddressIsTaken) {
15216
15220
15221 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15222 ExprResult result;
15223
15224 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15225 &result))
15226 return result;
15227
15228 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15229 // functions that aren't addressible are considered unviable.
15230 if (CalleesAddressIsTaken)
15231 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15232
15234 OverloadingResult OverloadResult =
15235 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15236
15237 // [C++23][over.call.func]
15238 // if overload resolution selects a non-static member function,
15239 // the call is ill-formed;
15241 Best != CandidateSet.end()) {
15242 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15243 M && M->isImplicitObjectMemberFunction()) {
15244 OverloadResult = OR_No_Viable_Function;
15245 }
15246 }
15247
15248 // Model the case with a call to a templated function whose definition
15249 // encloses the call and whose return type contains a placeholder type as if
15250 // the UnresolvedLookupExpr was type-dependent.
15251 if (OverloadResult == OR_Success) {
15252 const FunctionDecl *FDecl = Best->Function;
15253 if (LangOpts.CUDA)
15254 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15255 if (FDecl && FDecl->isTemplateInstantiation() &&
15256 FDecl->getReturnType()->isUndeducedType()) {
15257
15258 // Creating dependent CallExpr is not okay if the enclosing context itself
15259 // is not dependent. This situation notably arises if a non-dependent
15260 // member function calls the later-defined overloaded static function.
15261 //
15262 // For example, in
15263 // class A {
15264 // void c() { callee(1); }
15265 // static auto callee(auto x) { }
15266 // };
15267 //
15268 // Here callee(1) is unresolved at the call site, but is not inside a
15269 // dependent context. There will be no further attempt to resolve this
15270 // call if it is made dependent.
15271
15272 if (const auto *TP =
15273 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15274 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15275 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15276 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15277 }
15278 }
15279 }
15280
15281 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15282 ExecConfig, &CandidateSet, &Best,
15283 OverloadResult, AllowTypoCorrection);
15284}
15285
15289 const UnresolvedSetImpl &Fns,
15290 bool PerformADL) {
15292 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15293 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15294}
15295
15298 bool HadMultipleCandidates) {
15299 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15300 // the FoundDecl as it impedes TransformMemberExpr.
15301 // We go a bit further here: if there's no difference in UnderlyingDecl,
15302 // then using FoundDecl vs Method shouldn't make a difference either.
15303 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15304 FoundDecl = Method;
15305 // Convert the expression to match the conversion function's implicit object
15306 // parameter.
15307 ExprResult Exp;
15308 if (Method->isExplicitObjectMemberFunction())
15310 else
15312 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15313 if (Exp.isInvalid())
15314 return true;
15315
15316 if (Method->getParent()->isLambda() &&
15317 Method->getConversionType()->isBlockPointerType()) {
15318 // This is a lambda conversion to block pointer; check if the argument
15319 // was a LambdaExpr.
15320 Expr *SubE = E;
15321 auto *CE = dyn_cast<CastExpr>(SubE);
15322 if (CE && CE->getCastKind() == CK_NoOp)
15323 SubE = CE->getSubExpr();
15324 SubE = SubE->IgnoreParens();
15325 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15326 SubE = BE->getSubExpr();
15327 if (isa<LambdaExpr>(SubE)) {
15328 // For the conversion to block pointer on a lambda expression, we
15329 // construct a special BlockLiteral instead; this doesn't really make
15330 // a difference in ARC, but outside of ARC the resulting block literal
15331 // follows the normal lifetime rules for block literals instead of being
15332 // autoreleased.
15336 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15338
15339 // FIXME: This note should be produced by a CodeSynthesisContext.
15340 if (BlockExp.isInvalid())
15341 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15342 return BlockExp;
15343 }
15344 }
15345 CallExpr *CE;
15346 QualType ResultType = Method->getReturnType();
15348 ResultType = ResultType.getNonLValueExprType(Context);
15349 if (Method->isExplicitObjectMemberFunction()) {
15350 ExprResult FnExpr =
15351 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15352 HadMultipleCandidates, E->getBeginLoc());
15353 if (FnExpr.isInvalid())
15354 return ExprError();
15355 Expr *ObjectParam = Exp.get();
15356 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15357 ResultType, VK, Exp.get()->getEndLoc(),
15359 CE->setUsesMemberSyntax(true);
15360 } else {
15361 MemberExpr *ME =
15362 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15364 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15365 HadMultipleCandidates, DeclarationNameInfo(),
15366 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15367
15368 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15369 Exp.get()->getEndLoc(),
15371 }
15372
15373 if (CheckFunctionCall(Method, CE,
15374 Method->getType()->castAs<FunctionProtoType>()))
15375 return ExprError();
15376
15378}
15379
15382 const UnresolvedSetImpl &Fns,
15383 ArrayRef<Expr *> Args, bool PerformADL) {
15384 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15385
15386 SourceLocation OpLoc = CandidateSet.getLocation();
15387 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15388
15389 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15390 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15391 if (PerformADL)
15392 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15393 /*ExplicitTemplateArgs*/ nullptr,
15394 CandidateSet);
15395 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15396}
15397
15400 const UnresolvedSetImpl &Fns,
15401 Expr *Input, bool PerformADL) {
15403 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15404 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15405 // TODO: provide better source location info.
15406 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15407
15408 if (checkPlaceholderForOverload(*this, Input))
15409 return ExprError();
15410
15411 Expr *Args[2] = { Input, nullptr };
15412 unsigned NumArgs = 1;
15413
15414 // For post-increment and post-decrement, add the implicit '0' as
15415 // the second argument, so that we know this is a post-increment or
15416 // post-decrement.
15417 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15418 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15419 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15420 SourceLocation());
15421 NumArgs = 2;
15422 }
15423
15424 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15425
15426 if (Input->isTypeDependent()) {
15428 // [C++26][expr.unary.op][expr.pre.incr]
15429 // The * operator yields an lvalue of type
15430 // The pre/post increment operators yied an lvalue.
15431 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15432 VK = VK_LValue;
15433
15434 if (Fns.empty())
15435 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15436 OK_Ordinary, OpLoc, false,
15438
15439 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15441 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15442 if (Fn.isInvalid())
15443 return ExprError();
15444 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15445 Context.DependentTy, VK_PRValue, OpLoc,
15447 }
15448
15449 // Build an empty overload set.
15451 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, ArgsArray, PerformADL);
15452
15453 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15454
15455 // Perform overload resolution.
15457 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15458 case OR_Success: {
15459 // We found a built-in operator or an overloaded operator.
15460 FunctionDecl *FnDecl = Best->Function;
15461
15462 if (FnDecl) {
15463 Expr *Base = nullptr;
15464 // We matched an overloaded operator. Build a call to that
15465 // operator.
15466
15467 // Convert the arguments.
15468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15469 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15470
15471 ExprResult InputInit;
15472 if (Method->isExplicitObjectMemberFunction())
15473 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15474 else
15476 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15477 if (InputInit.isInvalid())
15478 return ExprError();
15479 Base = Input = InputInit.get();
15480 } else {
15481 // Convert the arguments.
15482 ExprResult InputInit
15484 Context,
15485 FnDecl->getParamDecl(0)),
15487 Input);
15488 if (InputInit.isInvalid())
15489 return ExprError();
15490 Input = InputInit.get();
15491 }
15492
15493 // Build the actual expression node.
15494 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15495 Base, HadMultipleCandidates,
15496 OpLoc);
15497 if (FnExpr.isInvalid())
15498 return ExprError();
15499
15500 // Determine the result type.
15501 QualType ResultTy = FnDecl->getReturnType();
15503 ResultTy = ResultTy.getNonLValueExprType(Context);
15504
15505 Args[0] = Input;
15507 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15509 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15510
15511 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15512 return ExprError();
15513
15514 if (CheckFunctionCall(FnDecl, TheCall,
15515 FnDecl->getType()->castAs<FunctionProtoType>()))
15516 return ExprError();
15517 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15518 } else {
15519 // We matched a built-in operator. Convert the arguments, then
15520 // break out so that we will build the appropriate built-in
15521 // operator node.
15523 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15526 if (InputRes.isInvalid())
15527 return ExprError();
15528 Input = InputRes.get();
15529 break;
15530 }
15531 }
15532
15534 // This is an erroneous use of an operator which can be overloaded by
15535 // a non-member function. Check for non-member operators which were
15536 // defined too late to be candidates.
15537 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray,
15538 CandidateSet))
15539 // FIXME: Recover by calling the found function.
15540 return ExprError();
15541
15542 // No viable function; fall through to handling this as a
15543 // built-in operator, which will produce an error message for us.
15544 break;
15545
15546 case OR_Ambiguous:
15547 CandidateSet.NoteCandidates(
15548 PartialDiagnosticAt(OpLoc,
15549 PDiag(diag::err_ovl_ambiguous_oper_unary)
15551 << Input->getType() << Input->getSourceRange()),
15552 *this, OCD_AmbiguousCandidates, ArgsArray,
15553 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15554 return ExprError();
15555
15556 case OR_Deleted: {
15557 // A defaulted postfix increment or decrement operator that was implicitly
15558 // defined as deleted. Explain why it was deleted.
15559 if (FunctionDecl *DeletedFD = Best->Function;
15560 DeletedFD->isDefaulted() &&
15561 DeletedFD->getDefaultedFunctionKind().isPostfixOperator()) {
15562 Diag(OpLoc, diag::err_ovl_deleted_postfix_operator)
15563 << Input->getType()
15564 << (int)DeletedFD->getDefaultedFunctionKind().asPostfixOperator()
15565 << Input->getSourceRange();
15566 NoteDeletedFunction(DeletedFD);
15567 return ExprError();
15568 }
15569
15570 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15571 // object whose method was called. Later in NoteCandidates size of ArgsArray
15572 // is passed further and it eventually ends up compared to number of
15573 // function candidate parameters which never includes the object parameter,
15574 // so slice ArgsArray to make sure apples are compared to apples.
15575 StringLiteral *Msg = Best->Function->getDeletedMessage();
15576 CandidateSet.NoteCandidates(
15577 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15579 << (Msg != nullptr)
15580 << (Msg ? Msg->getString() : StringRef())
15581 << Input->getSourceRange()),
15582 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15583 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15584 return ExprError();
15585 }
15586 }
15587
15588 // Either we found no viable overloaded operator or we matched a
15589 // built-in operator. In either case, fall through to trying to
15590 // build a built-in operation.
15591 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15592}
15593
15596 const UnresolvedSetImpl &Fns,
15597 ArrayRef<Expr *> Args, bool PerformADL) {
15598 SourceLocation OpLoc = CandidateSet.getLocation();
15599
15600 OverloadedOperatorKind ExtraOp =
15603 : OO_None;
15604
15605 // Add the candidates from the given function set. This also adds the
15606 // rewritten candidates using these functions if necessary.
15607 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15608
15609 // As template candidates are not deduced immediately,
15610 // persist the array in the overload set.
15611 ArrayRef<Expr *> ReversedArgs;
15612 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15613 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15614 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15615
15616 // Add operator candidates that are member functions.
15617 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15618 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15619 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15621
15622 // In C++20, also add any rewritten member candidates.
15623 if (ExtraOp) {
15624 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15625 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15626 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15628 }
15629
15630 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15631 // performed for an assignment operator (nor for operator[] nor operator->,
15632 // which don't get here).
15633 if (Op != OO_Equal && PerformADL) {
15634 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15635 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15636 /*ExplicitTemplateArgs*/ nullptr,
15637 CandidateSet);
15638 if (ExtraOp) {
15639 DeclarationName ExtraOpName =
15640 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15641 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15642 /*ExplicitTemplateArgs*/ nullptr,
15643 CandidateSet);
15644 }
15645 }
15646
15647 // Add builtin operator candidates.
15648 //
15649 // FIXME: We don't add any rewritten candidates here. This is strictly
15650 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15651 // resulting in our selecting a rewritten builtin candidate. For example:
15652 //
15653 // enum class E { e };
15654 // bool operator!=(E, E) requires false;
15655 // bool k = E::e != E::e;
15656 //
15657 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15658 // it seems unreasonable to consider rewritten builtin candidates. A core
15659 // issue has been filed proposing to removed this requirement.
15660 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15661}
15662
15665 const UnresolvedSetImpl &Fns, Expr *LHS,
15666 Expr *RHS, bool PerformADL,
15667 bool AllowRewrittenCandidates,
15668 FunctionDecl *DefaultedFn) {
15669 Expr *Args[2] = { LHS, RHS };
15670 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15671
15672 if (!getLangOpts().CPlusPlus20)
15673 AllowRewrittenCandidates = false;
15674
15676
15677 // If either side is type-dependent, create an appropriate dependent
15678 // expression.
15679 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15680 if (Fns.empty()) {
15681 // If there are no functions to store, just build a dependent
15682 // BinaryOperator or CompoundAssignment.
15685 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15686 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15687 Context.DependentTy);
15689 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15691 }
15692
15693 // FIXME: save results of ADL from here?
15694 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15695 // TODO: provide better source location info in DNLoc component.
15696 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15697 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15699 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15700 if (Fn.isInvalid())
15701 return ExprError();
15702 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15703 Context.DependentTy, VK_PRValue, OpLoc,
15705 }
15706
15707 // If this is the .* operator, which is not overloadable, just
15708 // create a built-in binary operator.
15709 if (Opc == BO_PtrMemD) {
15710 auto CheckPlaceholder = [&](Expr *&Arg) {
15712 if (Res.isUsable())
15713 Arg = Res.get();
15714 return !Res.isUsable();
15715 };
15716
15717 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15718 // expression that contains placeholders (in either the LHS or RHS).
15719 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15720 return ExprError();
15721 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15722 }
15723
15724 // Always do placeholder-like conversions on the RHS.
15725 if (checkPlaceholderForOverload(*this, Args[1]))
15726 return ExprError();
15727
15728 // Do placeholder-like conversion on the LHS; note that we should
15729 // not get here with a PseudoObject LHS.
15730 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15731 if (checkPlaceholderForOverload(*this, Args[0]))
15732 return ExprError();
15733
15734 // If this is the assignment operator, we only perform overload resolution
15735 // if the left-hand side is a class or enumeration type. This is actually
15736 // a hack. The standard requires that we do overload resolution between the
15737 // various built-in candidates, but as DR507 points out, this can lead to
15738 // problems. So we do it this way, which pretty much follows what GCC does.
15739 // Note that we go the traditional code path for compound assignment forms.
15740 // In HLSL, user-defined structs/classes do not have constructors or
15741 // overloadable assignment operators, so we can take this shortcut too.
15742 const Type *LHSTy = Args[0]->getType().getTypePtr();
15743 if (Opc == BO_Assign &&
15744 (!LHSTy->isOverloadableType() ||
15745 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15747 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15748
15749 // Build the overload set.
15752 Op, OpLoc, AllowRewrittenCandidates));
15753 if (DefaultedFn)
15754 CandidateSet.exclude(DefaultedFn);
15755 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15756
15757 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15758
15759 // Perform overload resolution.
15761 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15762 case OR_Success: {
15763 // We found a built-in operator or an overloaded operator.
15764 FunctionDecl *FnDecl = Best->Function;
15765
15766 bool IsReversed = Best->isReversed();
15767 if (IsReversed)
15768 std::swap(Args[0], Args[1]);
15769
15770 if (FnDecl) {
15771
15772 if (FnDecl->isInvalidDecl())
15773 return ExprError();
15774
15775 Expr *Base = nullptr;
15776 // We matched an overloaded operator. Build a call to that
15777 // operator.
15778
15779 OverloadedOperatorKind ChosenOp =
15781
15782 // C++2a [over.match.oper]p9:
15783 // If a rewritten operator== candidate is selected by overload
15784 // resolution for an operator@, its return type shall be cv bool
15785 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15786 !FnDecl->getReturnType()->isBooleanType()) {
15787 bool IsExtension =
15789 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15790 : diag::err_ovl_rewrite_equalequal_not_bool)
15791 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15792 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15793 Diag(FnDecl->getLocation(), diag::note_declared_at);
15794 if (!IsExtension)
15795 return ExprError();
15796 }
15797
15798 if (AllowRewrittenCandidates && !IsReversed &&
15799 CandidateSet.getRewriteInfo().isReversible()) {
15800 // We could have reversed this operator, but didn't. Check if some
15801 // reversed form was a viable candidate, and if so, if it had a
15802 // better conversion for either parameter. If so, this call is
15803 // formally ambiguous, and allowing it is an extension.
15805 for (OverloadCandidate &Cand : CandidateSet) {
15806 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15807 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15808 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15810 *this, OpLoc, Cand.Conversions[ArgIdx],
15811 Best->Conversions[ArgIdx]) ==
15813 AmbiguousWith.push_back(Cand.Function);
15814 break;
15815 }
15816 }
15817 }
15818 }
15819
15820 if (!AmbiguousWith.empty()) {
15821 bool AmbiguousWithSelf =
15822 AmbiguousWith.size() == 1 &&
15823 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15824 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15826 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15827 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15828 if (AmbiguousWithSelf) {
15829 Diag(FnDecl->getLocation(),
15830 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15831 // Mark member== const or provide matching != to disallow reversed
15832 // args. Eg.
15833 // struct S { bool operator==(const S&); };
15834 // S()==S();
15835 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15836 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15837 !MD->isConst() &&
15838 !MD->hasCXXExplicitFunctionObjectParameter() &&
15839 Context.hasSameUnqualifiedType(
15840 MD->getFunctionObjectParameterType(),
15841 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15842 Context.hasSameUnqualifiedType(
15843 MD->getFunctionObjectParameterType(),
15844 Args[0]->getType()) &&
15845 Context.hasSameUnqualifiedType(
15846 MD->getFunctionObjectParameterType(),
15847 Args[1]->getType()))
15848 Diag(FnDecl->getLocation(),
15849 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15850 } else {
15851 Diag(FnDecl->getLocation(),
15852 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15853 for (auto *F : AmbiguousWith)
15854 Diag(F->getLocation(),
15855 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15856 }
15857 }
15858 }
15859
15860 // Check for nonnull = nullable.
15861 // This won't be caught in the arg's initialization: the parameter to
15862 // the assignment operator is not marked nonnull.
15863 if (Op == OO_Equal)
15865 Args[1]->getType(), OpLoc);
15866
15867 // Convert the arguments.
15868 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15869 // Best->Access is only meaningful for class members.
15870 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15871
15872 ExprResult Arg0, Arg1;
15873 unsigned ParamIdx = 0;
15874 if (Method->isExplicitObjectMemberFunction()) {
15875 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15876 ParamIdx = 1;
15877 } else {
15879 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15880 }
15883 Context, FnDecl->getParamDecl(ParamIdx)),
15884 SourceLocation(), Args[1]);
15885 if (Arg0.isInvalid() || Arg1.isInvalid())
15886 return ExprError();
15887
15888 Base = Args[0] = Arg0.getAs<Expr>();
15889 Args[1] = RHS = Arg1.getAs<Expr>();
15890 } else {
15891 // Convert the arguments.
15894 FnDecl->getParamDecl(0)),
15895 SourceLocation(), Args[0]);
15896 if (Arg0.isInvalid())
15897 return ExprError();
15898
15899 ExprResult Arg1 =
15902 FnDecl->getParamDecl(1)),
15903 SourceLocation(), Args[1]);
15904 if (Arg1.isInvalid())
15905 return ExprError();
15906 Args[0] = LHS = Arg0.getAs<Expr>();
15907 Args[1] = RHS = Arg1.getAs<Expr>();
15908 }
15909
15910 // Build the actual expression node.
15911 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15912 Best->FoundDecl, Base,
15913 HadMultipleCandidates, OpLoc);
15914 if (FnExpr.isInvalid())
15915 return ExprError();
15916
15917 if (auto *Pattern = FnDecl->getInstantiatedFromMemberFunction();
15918 Pattern && Pattern->getOverloadedOperator() == OO_Spaceship)
15919 Pattern->setIsUsed();
15920
15921 // Determine the result type.
15922 QualType ResultTy = FnDecl->getReturnType();
15924 ResultTy = ResultTy.getNonLValueExprType(Context);
15925
15926 CallExpr *TheCall;
15927 ArrayRef<const Expr *> ArgsArray(Args, 2);
15928 const Expr *ImplicitThis = nullptr;
15929
15930 // We always create a CXXOperatorCallExpr, even for explicit object
15931 // members; CodeGen should take care not to emit the this pointer.
15933 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15935 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15936 IsReversed);
15937
15938 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15939 Method && Method->isImplicitObjectMemberFunction()) {
15940 // Cut off the implicit 'this'.
15941 ImplicitThis = ArgsArray[0];
15942 ArgsArray = ArgsArray.slice(1);
15943 }
15944
15945 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15946 FnDecl))
15947 return ExprError();
15948
15949 if (Op == OO_Equal) {
15950 // Check for a self move.
15951 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15952 // lifetime check.
15954 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15955 Args[1]);
15956 }
15957 if (ImplicitThis) {
15958 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15959 QualType ThisTypeFromDecl = Context.getPointerType(
15960 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15961
15962 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15963 ThisTypeFromDecl);
15964 }
15965
15966 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15967 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15969
15970 ExprResult R = MaybeBindToTemporary(TheCall);
15971 if (R.isInvalid())
15972 return ExprError();
15973
15974 R = CheckForImmediateInvocation(R, FnDecl);
15975 if (R.isInvalid())
15976 return ExprError();
15977
15978 // For a rewritten candidate, we've already reversed the arguments
15979 // if needed. Perform the rest of the rewrite now.
15980 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15981 (Op == OO_Spaceship && IsReversed)) {
15982 if (Op == OO_ExclaimEqual) {
15983 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15984 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15985 } else {
15986 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15987 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15988 Expr *ZeroLiteral =
15990
15993 Ctx.Entity = FnDecl;
15995
15997 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15998 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15999 /*AllowRewrittenCandidates=*/false);
16000
16002 }
16003 if (R.isInvalid())
16004 return ExprError();
16005 } else {
16006 assert(ChosenOp == Op && "unexpected operator name");
16007 }
16008
16009 // Make a note in the AST if we did any rewriting.
16010 if (Best->RewriteKind != CRK_None)
16011 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
16012
16013 return R;
16014 } else {
16015 // We matched a built-in operator. Convert the arguments, then
16016 // break out so that we will build the appropriate built-in
16017 // operator node.
16019 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16022 if (ArgsRes0.isInvalid())
16023 return ExprError();
16024 Args[0] = ArgsRes0.get();
16025
16027 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16030 if (ArgsRes1.isInvalid())
16031 return ExprError();
16032 Args[1] = ArgsRes1.get();
16033 break;
16034 }
16035 }
16036
16037 case OR_No_Viable_Function: {
16038 // C++ [over.match.oper]p9:
16039 // If the operator is the operator , [...] and there are no
16040 // viable functions, then the operator is assumed to be the
16041 // built-in operator and interpreted according to clause 5.
16042 if (Opc == BO_Comma)
16043 break;
16044
16045 // When defaulting an 'operator<=>', we can try to synthesize a three-way
16046 // compare result using '==' and '<'.
16047 if (DefaultedFn && Opc == BO_Cmp) {
16048 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
16049 Args[1], DefaultedFn);
16050 if (E.isInvalid() || E.isUsable())
16051 return E;
16052 }
16053
16054 // For class as left operand for assignment or compound assignment
16055 // operator do not fall through to handling in built-in, but report that
16056 // no overloaded assignment operator found
16058 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
16059 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
16060 Args, OpLoc);
16061 DeferDiagsRAII DDR(*this,
16062 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
16063 if (Args[0]->getType()->isRecordType() &&
16064 Opc >= BO_Assign && Opc <= BO_OrAssign) {
16065 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16067 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16068 if (Args[0]->getType()->isIncompleteType()) {
16069 Diag(OpLoc, diag::note_assign_lhs_incomplete)
16070 << Args[0]->getType()
16071 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16072 }
16073 } else {
16074 // This is an erroneous use of an operator which can be overloaded by
16075 // a non-member function. Check for non-member operators which were
16076 // defined too late to be candidates.
16077 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args,
16078 CandidateSet))
16079 // FIXME: Recover by calling the found function.
16080 return ExprError();
16081
16082 // No viable function; try to create a built-in operation, which will
16083 // produce an error. Then, show the non-viable candidates.
16084 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
16085 }
16086 assert(Result.isInvalid() &&
16087 "C++ binary operator overloading is missing candidates!");
16088 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
16089 return Result;
16090 }
16091
16092 case OR_Ambiguous:
16093 CandidateSet.NoteCandidates(
16094 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16096 << Args[0]->getType()
16097 << Args[1]->getType()
16098 << Args[0]->getSourceRange()
16099 << Args[1]->getSourceRange()),
16101 OpLoc);
16102 return ExprError();
16103
16104 case OR_Deleted: {
16105 if (isImplicitlyDeleted(Best->Function)) {
16106 FunctionDecl *DeletedFD = Best->Function;
16108 DeletedFD->getDefaultedFunctionKind();
16109 if (DFK.isSpecialMember()) {
16110 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
16111 << Args[0]->getType() << DFK.asSpecialMember();
16112 } else {
16113 assert(DFK.isComparison());
16114 Diag(OpLoc, diag::err_ovl_deleted_comparison)
16115 << Args[0]->getType() << DeletedFD;
16116 }
16117
16118 // The user probably meant to call this special member. Just
16119 // explain why it's deleted.
16120 NoteDeletedFunction(DeletedFD);
16121 return ExprError();
16122 }
16123
16124 StringLiteral *Msg = Best->Function->getDeletedMessage();
16125 CandidateSet.NoteCandidates(
16127 OpLoc,
16128 PDiag(diag::err_ovl_deleted_oper)
16129 << getOperatorSpelling(Best->Function->getDeclName()
16130 .getCXXOverloadedOperator())
16131 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
16132 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
16134 OpLoc);
16135 return ExprError();
16136 }
16137 }
16138
16139 // We matched a built-in operator; build it.
16140 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
16141}
16142
16144 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16145 FunctionDecl *DefaultedFn) {
16146 const ComparisonCategoryInfo *Info =
16147 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
16148 // If we're not producing a known comparison category type, we can't
16149 // synthesize a three-way comparison. Let the caller diagnose this.
16150 if (!Info)
16151 return ExprResult((Expr*)nullptr);
16152
16153 // If we ever want to perform this synthesis more generally, we will need to
16154 // apply the temporary materialization conversion to the operands.
16155 assert(LHS->isGLValue() && RHS->isGLValue() &&
16156 "cannot use prvalue expressions more than once");
16157 Expr *OrigLHS = LHS;
16158 Expr *OrigRHS = RHS;
16159
16160 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16161 // each of them multiple times below.
16162 LHS = new (Context)
16163 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16164 LHS->getObjectKind(), LHS);
16165 RHS = new (Context)
16166 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16167 RHS->getObjectKind(), RHS);
16168
16169 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
16170 DefaultedFn);
16171 if (Eq.isInvalid())
16172 return ExprError();
16173
16174 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
16175 true, DefaultedFn);
16176 if (Less.isInvalid())
16177 return ExprError();
16178
16180 if (Info->isPartial()) {
16181 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16182 DefaultedFn);
16183 if (Greater.isInvalid())
16184 return ExprError();
16185 }
16186
16187 // Form the list of comparisons we're going to perform.
16188 struct Comparison {
16191 } Comparisons[4] =
16197 };
16198
16199 int I = Info->isPartial() ? 3 : 2;
16200
16201 // Combine the comparisons with suitable conditional expressions.
16203 for (; I >= 0; --I) {
16204 // Build a reference to the comparison category constant.
16205 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16206 // FIXME: Missing a constant for a comparison category. Diagnose this?
16207 if (!VI)
16208 return ExprResult((Expr*)nullptr);
16209 ExprResult ThisResult =
16211 if (ThisResult.isInvalid())
16212 return ExprError();
16213
16214 // Build a conditional unless this is the final case.
16215 if (Result.get()) {
16216 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16217 ThisResult.get(), Result.get());
16218 if (Result.isInvalid())
16219 return ExprError();
16220 } else {
16221 Result = ThisResult;
16222 }
16223 }
16224
16225 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16226 // bind the OpaqueValueExprs before they're (repeatedly) used.
16227 Expr *SyntacticForm = BinaryOperator::Create(
16228 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16229 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16231 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16232 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16233}
16234
16236 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16237 MultiExprArg Args, SourceLocation LParenLoc) {
16238
16239 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16240 unsigned NumParams = Proto->getNumParams();
16241 unsigned NumArgsSlots =
16242 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16243 // Build the full argument list for the method call (the implicit object
16244 // parameter is placed at the beginning of the list).
16245 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16246 bool IsError = false;
16247 // Initialize the implicit object parameter.
16248 // Check the argument types.
16249 for (unsigned i = 0; i != NumParams; i++) {
16250 Expr *Arg;
16251 if (i < Args.size()) {
16252 Arg = Args[i];
16253 ExprResult InputInit =
16255 S.Context, Method->getParamDecl(i)),
16256 SourceLocation(), Arg);
16257 IsError |= InputInit.isInvalid();
16258 Arg = InputInit.getAs<Expr>();
16259 } else {
16260 ExprResult DefArg =
16261 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16262 if (DefArg.isInvalid()) {
16263 IsError = true;
16264 break;
16265 }
16266 Arg = DefArg.getAs<Expr>();
16267 }
16268
16269 MethodArgs.push_back(Arg);
16270 }
16271 return IsError;
16272}
16273
16275 SourceLocation RLoc,
16276 Expr *Base,
16277 MultiExprArg ArgExpr) {
16279 Args.push_back(Base);
16280 for (auto *e : ArgExpr) {
16281 Args.push_back(e);
16282 }
16283 DeclarationName OpName =
16284 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16285
16286 SourceRange Range = ArgExpr.empty()
16287 ? SourceRange{}
16288 : SourceRange(ArgExpr.front()->getBeginLoc(),
16289 ArgExpr.back()->getEndLoc());
16290
16291 // If either side is type-dependent, create an appropriate dependent
16292 // expression.
16294
16295 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16296 // CHECKME: no 'operator' keyword?
16297 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16298 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16300 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16301 if (Fn.isInvalid())
16302 return ExprError();
16303 // Can't add any actual overloads yet
16304
16305 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16306 Context.DependentTy, VK_PRValue, RLoc,
16308 }
16309
16310 // Handle placeholders
16311 UnbridgedCastsSet UnbridgedCasts;
16312 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16313 return ExprError();
16314 }
16315 // Build an empty overload set.
16317
16318 // Subscript can only be overloaded as a member function.
16319
16320 // Add operator candidates that are member functions.
16321 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16322
16323 // Add builtin operator candidates.
16324 if (Args.size() == 2)
16325 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16326
16327 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16328
16329 // Perform overload resolution.
16331 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16332 case OR_Success: {
16333 // We found a built-in operator or an overloaded operator.
16334 FunctionDecl *FnDecl = Best->Function;
16335
16336 if (FnDecl) {
16337 // We matched an overloaded operator. Build a call to that
16338 // operator.
16339
16340 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16341
16342 // Convert the arguments.
16344 SmallVector<Expr *, 2> MethodArgs;
16345
16346 // Initialize the object parameter.
16347 if (Method->isExplicitObjectMemberFunction()) {
16348 ExprResult Res =
16350 if (Res.isInvalid())
16351 return ExprError();
16352 Args[0] = Res.get();
16353 ArgExpr = Args;
16354 } else {
16356 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16357 if (Arg0.isInvalid())
16358 return ExprError();
16359
16360 MethodArgs.push_back(Arg0.get());
16361 }
16362
16364 *this, MethodArgs, Method, ArgExpr, LLoc);
16365 if (IsError)
16366 return ExprError();
16367
16368 // Build the actual expression node.
16369 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16370 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16371 ExprResult FnExpr =
16372 CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, Base,
16373 HadMultipleCandidates, OpLocInfo);
16374 if (FnExpr.isInvalid())
16375 return ExprError();
16376
16377 // Determine the result type
16378 QualType ResultTy = FnDecl->getReturnType();
16380 ResultTy = ResultTy.getNonLValueExprType(Context);
16381
16383 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16385
16386 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16387 return ExprError();
16388
16389 if (CheckFunctionCall(Method, TheCall,
16390 Method->getType()->castAs<FunctionProtoType>()))
16391 return ExprError();
16392
16394 FnDecl);
16395 } else {
16396 // We matched a built-in operator. Convert the arguments, then
16397 // break out so that we will build the appropriate built-in
16398 // operator node.
16400 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16403 if (ArgsRes0.isInvalid())
16404 return ExprError();
16405 Args[0] = ArgsRes0.get();
16406
16408 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16411 if (ArgsRes1.isInvalid())
16412 return ExprError();
16413 Args[1] = ArgsRes1.get();
16414
16415 break;
16416 }
16417 }
16418
16419 case OR_No_Viable_Function: {
16421 CandidateSet.empty()
16422 ? (PDiag(diag::err_ovl_no_oper)
16423 << Args[0]->getType() << /*subscript*/ 0
16424 << Args[0]->getSourceRange() << Range)
16425 : (PDiag(diag::err_ovl_no_viable_subscript)
16426 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16427 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16428 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16429 return ExprError();
16430 }
16431
16432 case OR_Ambiguous:
16433 if (Args.size() == 2) {
16434 CandidateSet.NoteCandidates(
16436 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16437 << "[]" << Args[0]->getType() << Args[1]->getType()
16438 << Args[0]->getSourceRange() << Range),
16439 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16440 } else {
16441 CandidateSet.NoteCandidates(
16443 PDiag(diag::err_ovl_ambiguous_subscript_call)
16444 << Args[0]->getType()
16445 << Args[0]->getSourceRange() << Range),
16446 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16447 }
16448 return ExprError();
16449
16450 case OR_Deleted: {
16451 StringLiteral *Msg = Best->Function->getDeletedMessage();
16452 CandidateSet.NoteCandidates(
16454 PDiag(diag::err_ovl_deleted_oper)
16455 << "[]" << (Msg != nullptr)
16456 << (Msg ? Msg->getString() : StringRef())
16457 << Args[0]->getSourceRange() << Range),
16458 *this, OCD_AllCandidates, Args, "[]", LLoc);
16459 return ExprError();
16460 }
16461 }
16462
16463 // We matched a built-in operator; build it.
16464 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16465}
16466
16468 SourceLocation LParenLoc,
16469 MultiExprArg Args,
16470 SourceLocation RParenLoc,
16471 Expr *ExecConfig, bool IsExecConfig,
16472 bool AllowRecovery) {
16473 assert(MemExprE->getType() == Context.BoundMemberTy ||
16474 MemExprE->getType() == Context.OverloadTy);
16475
16476 // Dig out the member expression. This holds both the object
16477 // argument and the member function we're referring to.
16478 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16479
16480 // Determine whether this is a call to a pointer-to-member function.
16481 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16482 assert(op->getType() == Context.BoundMemberTy);
16483 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16484
16485 QualType fnType =
16486 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16487
16488 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16489 QualType resultType = proto->getCallResultType(Context);
16491
16492 // Check that the object type isn't more qualified than the
16493 // member function we're calling.
16494 Qualifiers funcQuals = proto->getMethodQuals();
16495
16496 QualType objectType = op->getLHS()->getType();
16497 if (op->getOpcode() == BO_PtrMemI)
16498 objectType = objectType->castAs<PointerType>()->getPointeeType();
16499 Qualifiers objectQuals = objectType.getQualifiers();
16500
16501 Qualifiers difference = objectQuals - funcQuals;
16502 difference.removeObjCGCAttr();
16503 difference.removeAddressSpace();
16504 if (difference) {
16505 std::string qualsString = difference.getAsString();
16506 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16507 << fnType.getUnqualifiedType()
16508 << qualsString
16509 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16510 }
16511
16513 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16515
16516 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16517 call, nullptr))
16518 return ExprError();
16519
16520 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16521 return ExprError();
16522
16523 if (CheckOtherCall(call, proto))
16524 return ExprError();
16525
16526 return MaybeBindToTemporary(call);
16527 }
16528
16529 // We only try to build a recovery expr at this level if we can preserve
16530 // the return type, otherwise we return ExprError() and let the caller
16531 // recover.
16532 auto BuildRecoveryExpr = [&](QualType Type) {
16533 if (!AllowRecovery)
16534 return ExprError();
16535 std::vector<Expr *> SubExprs = {MemExprE};
16536 llvm::append_range(SubExprs, Args);
16537 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16538 Type);
16539 };
16540 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16541 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16542 RParenLoc, CurFPFeatureOverrides());
16543
16544 UnbridgedCastsSet UnbridgedCasts;
16545 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16546 return ExprError();
16547
16548 MemberExpr *MemExpr;
16549 CXXMethodDecl *Method = nullptr;
16550 bool HadMultipleCandidates = false;
16551 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16552 NestedNameSpecifier Qualifier = std::nullopt;
16553 if (isa<MemberExpr>(NakedMemExpr)) {
16554 MemExpr = cast<MemberExpr>(NakedMemExpr);
16556 FoundDecl = MemExpr->getFoundDecl();
16557 Qualifier = MemExpr->getQualifier();
16558 UnbridgedCasts.restore();
16559 } else {
16560 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16561 Qualifier = UnresExpr->getQualifier();
16562
16563 QualType ObjectType = UnresExpr->getBaseType();
16564 Expr::Classification ObjectClassification
16566 : UnresExpr->getBase()->Classify(Context);
16567
16568 // Add overload candidates
16569 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16571
16572 // FIXME: avoid copy.
16573 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16574 if (UnresExpr->hasExplicitTemplateArgs()) {
16575 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16576 TemplateArgs = &TemplateArgsBuffer;
16577 }
16578
16580 E = UnresExpr->decls_end(); I != E; ++I) {
16581
16582 QualType ExplicitObjectType = ObjectType;
16583
16584 NamedDecl *Func = *I;
16585 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16587 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16588
16589 bool HasExplicitParameter = false;
16590 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16591 M && M->hasCXXExplicitFunctionObjectParameter())
16592 HasExplicitParameter = true;
16593 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16594 M &&
16595 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16596 HasExplicitParameter = true;
16597
16598 if (HasExplicitParameter)
16599 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16600
16601 // Microsoft supports direct constructor calls.
16602 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16604 CandidateSet,
16605 /*SuppressUserConversions*/ false);
16606 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16607 // If explicit template arguments were provided, we can't call a
16608 // non-template member function.
16609 if (TemplateArgs)
16610 continue;
16611
16612 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16613 ObjectClassification, Args, CandidateSet,
16614 /*SuppressUserConversions=*/false);
16615 } else {
16617 I.getPair(), ActingDC, TemplateArgs,
16618 ExplicitObjectType, ObjectClassification,
16619 Args, CandidateSet,
16620 /*SuppressUserConversions=*/false);
16621 }
16622 }
16623
16624 HadMultipleCandidates = (CandidateSet.size() > 1);
16625
16626 DeclarationName DeclName = UnresExpr->getMemberName();
16627
16628 UnbridgedCasts.restore();
16629
16631 bool Succeeded = false;
16632 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16633 Best)) {
16634 case OR_Success:
16635 Method = cast<CXXMethodDecl>(Best->Function);
16636 FoundDecl = Best->FoundDecl;
16637 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16638 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16639 break;
16640 // If FoundDecl is different from Method (such as if one is a template
16641 // and the other a specialization), make sure DiagnoseUseOfDecl is
16642 // called on both.
16643 // FIXME: This would be more comprehensively addressed by modifying
16644 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16645 // being used.
16646 if (Method != FoundDecl.getDecl() &&
16648 break;
16649 Succeeded = true;
16650 break;
16651
16653 CandidateSet.NoteCandidates(
16655 UnresExpr->getMemberLoc(),
16656 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16657 << DeclName << MemExprE->getSourceRange()),
16658 *this, OCD_AllCandidates, Args);
16659 break;
16660 case OR_Ambiguous:
16661 CandidateSet.NoteCandidates(
16662 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16663 PDiag(diag::err_ovl_ambiguous_member_call)
16664 << DeclName << MemExprE->getSourceRange()),
16665 *this, OCD_AmbiguousCandidates, Args);
16666 break;
16667 case OR_Deleted:
16669 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16670 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16671 break;
16672 }
16673 // Overload resolution fails, try to recover.
16674 if (!Succeeded)
16675 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16676
16677 ExprResult Res =
16678 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16679 if (Res.isInvalid())
16680 return ExprError();
16681 MemExprE = Res.get();
16682
16683 // If overload resolution picked a static member
16684 // build a non-member call based on that function.
16685 if (Method->isStatic()) {
16686 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16687 ExecConfig, IsExecConfig);
16688 }
16689
16690 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16691 }
16692
16693 QualType ResultType = Method->getReturnType();
16695 ResultType = ResultType.getNonLValueExprType(Context);
16696
16697 assert(Method && "Member call to something that isn't a method?");
16698 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16699
16700 CallExpr *TheCall = nullptr;
16702 if (Method->isExplicitObjectMemberFunction()) {
16703 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16704 NewArgs))
16705 return ExprError();
16706
16707 // FIXME: avoid copy.
16708 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16709 if (MemExpr->hasExplicitTemplateArgs()) {
16710 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16711 TemplateArgs = &TemplateArgsBuffer;
16712 }
16713
16714 // Build the actual expression node.
16716 *this, MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(),
16717 Method, FoundDecl, MemExpr, HadMultipleCandidates,
16718 MemExpr->getMemberNameInfo(), TemplateArgs);
16719 if (FnExpr.isInvalid())
16720 return ExprError();
16721
16722 TheCall =
16723 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16724 CurFPFeatureOverrides(), Proto->getNumParams());
16725 TheCall->setUsesMemberSyntax(true);
16726 } else {
16727 // Convert the object argument (for a non-static member function call).
16729 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16730 if (ObjectArg.isInvalid())
16731 return ExprError();
16732 MemExpr->setBase(ObjectArg.get());
16733 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16734 RParenLoc, CurFPFeatureOverrides(),
16735 Proto->getNumParams());
16736 }
16737
16738 // Check for a valid return type.
16739 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16740 TheCall, Method))
16741 return BuildRecoveryExpr(ResultType);
16742
16743 // Convert the rest of the arguments
16744 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16745 RParenLoc))
16746 return BuildRecoveryExpr(ResultType);
16747
16748 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16749
16750 if (CheckFunctionCall(Method, TheCall, Proto))
16751 return ExprError();
16752
16753 // In the case the method to call was not selected by the overloading
16754 // resolution process, we still need to handle the enable_if attribute. Do
16755 // that here, so it will not hide previous -- and more relevant -- errors.
16756 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16757 if (const EnableIfAttr *Attr =
16758 CheckEnableIf(Method, LParenLoc, Args, true)) {
16759 Diag(MemE->getMemberLoc(),
16760 diag::err_ovl_no_viable_member_function_in_call)
16761 << Method << Method->getSourceRange();
16762 Diag(Method->getLocation(),
16763 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16764 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16765 return ExprError();
16766 }
16767 }
16768
16770 TheCall->getDirectCallee()->isPureVirtual()) {
16771 const FunctionDecl *MD = TheCall->getDirectCallee();
16772
16773 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16775 Diag(MemExpr->getBeginLoc(),
16776 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16778 << MD->getParent();
16779
16780 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16781 if (getLangOpts().AppleKext)
16782 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16783 << MD->getParent() << MD->getDeclName();
16784 }
16785 }
16786
16787 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16788 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16789 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16790 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16791 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16792 MemExpr->getMemberLoc());
16793 }
16794
16796 TheCall->getDirectCallee());
16797}
16798
16801 SourceLocation LParenLoc,
16802 MultiExprArg Args,
16803 SourceLocation RParenLoc) {
16804 if (checkPlaceholderForOverload(*this, Obj))
16805 return ExprError();
16806 ExprResult Object = Obj;
16807
16808 UnbridgedCastsSet UnbridgedCasts;
16809 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16810 return ExprError();
16811
16812 assert(Object.get()->getType()->isRecordType() &&
16813 "Requires object type argument");
16814
16815 // C++ [over.call.object]p1:
16816 // If the primary-expression E in the function call syntax
16817 // evaluates to a class object of type "cv T", then the set of
16818 // candidate functions includes at least the function call
16819 // operators of T. The function call operators of T are obtained by
16820 // ordinary lookup of the name operator() in the context of
16821 // (E).operator().
16822 OverloadCandidateSet CandidateSet(LParenLoc,
16824 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16825
16826 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16827 diag::err_incomplete_object_call, Object.get()))
16828 return true;
16829
16830 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16831 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16833 R.suppressAccessDiagnostics();
16834
16835 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16836 Oper != OperEnd; ++Oper) {
16837 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16838 Object.get()->Classify(Context), Args, CandidateSet,
16839 /*SuppressUserConversion=*/false);
16840 }
16841
16842 // When calling a lambda, both the call operator, and
16843 // the conversion operator to function pointer
16844 // are considered. But when constraint checking
16845 // on the call operator fails, it will also fail on the
16846 // conversion operator as the constraints are always the same.
16847 // As the user probably does not intend to perform a surrogate call,
16848 // we filter them out to produce better error diagnostics, ie to avoid
16849 // showing 2 failed overloads instead of one.
16850 bool IgnoreSurrogateFunctions = false;
16851 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16852 const OverloadCandidate &Candidate = *CandidateSet.begin();
16853 if (!Candidate.Viable &&
16855 IgnoreSurrogateFunctions = true;
16856 }
16857
16858 // C++ [over.call.object]p2:
16859 // In addition, for each (non-explicit in C++0x) conversion function
16860 // declared in T of the form
16861 //
16862 // operator conversion-type-id () cv-qualifier;
16863 //
16864 // where cv-qualifier is the same cv-qualification as, or a
16865 // greater cv-qualification than, cv, and where conversion-type-id
16866 // denotes the type "pointer to function of (P1,...,Pn) returning
16867 // R", or the type "reference to pointer to function of
16868 // (P1,...,Pn) returning R", or the type "reference to function
16869 // of (P1,...,Pn) returning R", a surrogate call function [...]
16870 // is also considered as a candidate function. Similarly,
16871 // surrogate call functions are added to the set of candidate
16872 // functions for each conversion function declared in an
16873 // accessible base class provided the function is not hidden
16874 // within T by another intervening declaration.
16875 const auto &Conversions = Record->getVisibleConversionFunctions();
16876 for (auto I = Conversions.begin(), E = Conversions.end();
16877 !IgnoreSurrogateFunctions && I != E; ++I) {
16878 NamedDecl *D = *I;
16879 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16880 if (isa<UsingShadowDecl>(D))
16881 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16882
16883 // Skip over templated conversion functions; they aren't
16884 // surrogates.
16886 continue;
16887
16889 if (!Conv->isExplicit()) {
16890 // Strip the reference type (if any) and then the pointer type (if
16891 // any) to get down to what might be a function type.
16892 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16893 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16894 ConvType = ConvPtrType->getPointeeType();
16895
16896 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16897 {
16898 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16899 Object.get(), Args, CandidateSet);
16900 }
16901 }
16902 }
16903
16904 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16905
16906 // Perform overload resolution.
16908 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16909 Best)) {
16910 case OR_Success:
16911 // Overload resolution succeeded; we'll build the appropriate call
16912 // below.
16913 break;
16914
16915 case OR_No_Viable_Function: {
16917 CandidateSet.empty()
16918 ? (PDiag(diag::err_ovl_no_oper)
16919 << Object.get()->getType() << /*call*/ 1
16920 << Object.get()->getSourceRange())
16921 : (PDiag(diag::err_ovl_no_viable_object_call)
16922 << Object.get()->getType() << Object.get()->getSourceRange());
16923 CandidateSet.NoteCandidates(
16924 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16925 OCD_AllCandidates, Args);
16926 break;
16927 }
16928 case OR_Ambiguous:
16929 if (!R.isAmbiguous())
16930 CandidateSet.NoteCandidates(
16931 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16932 PDiag(diag::err_ovl_ambiguous_object_call)
16933 << Object.get()->getType()
16934 << Object.get()->getSourceRange()),
16935 *this, OCD_AmbiguousCandidates, Args);
16936 break;
16937
16938 case OR_Deleted: {
16939 // FIXME: Is this diagnostic here really necessary? It seems that
16940 // 1. we don't have any tests for this diagnostic, and
16941 // 2. we already issue err_deleted_function_use for this later on anyway.
16942 StringLiteral *Msg = Best->Function->getDeletedMessage();
16943 CandidateSet.NoteCandidates(
16944 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16945 PDiag(diag::err_ovl_deleted_object_call)
16946 << Object.get()->getType() << (Msg != nullptr)
16947 << (Msg ? Msg->getString() : StringRef())
16948 << Object.get()->getSourceRange()),
16949 *this, OCD_AllCandidates, Args);
16950 break;
16951 }
16952 }
16953
16954 if (Best == CandidateSet.end())
16955 return true;
16956
16957 UnbridgedCasts.restore();
16958
16959 if (Best->Function == nullptr) {
16960 // Since there is no function declaration, this is one of the
16961 // surrogate candidates. Dig out the conversion function.
16962 CXXConversionDecl *Conv
16964 Best->Conversions[0].UserDefined.ConversionFunction);
16965
16966 // FoundDecl may be a UsingShadowDecl naming the conversion function.
16967 assert(Conv == Best->FoundDecl.getDecl()->getUnderlyingDecl() &&
16968 "Found Decl & conversion-to-functionptr should be same, right?!");
16969 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16970 Best->FoundDecl);
16971 if (DiagnoseUseOfDecl(Conv, LParenLoc))
16972 return ExprError();
16973 // We selected one of the surrogate functions that converts the
16974 // object parameter to a function pointer. Perform the conversion
16975 // on the object argument, then let BuildCallExpr finish the job.
16976
16977 // Create an implicit member expr to refer to the conversion operator.
16978 // and then call it.
16979 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16980 Conv, HadMultipleCandidates);
16981 if (Call.isInvalid())
16982 return ExprError();
16983 // Record usage of conversion in an implicit cast.
16985 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16986 nullptr, VK_PRValue, CurFPFeatureOverrides());
16987
16988 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16989 }
16990
16991 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16992
16993 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16994 // that calls this method, using Object for the implicit object
16995 // parameter and passing along the remaining arguments.
16996 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16997
16998 // An error diagnostic has already been printed when parsing the declaration.
16999 if (Method->isInvalidDecl())
17000 return ExprError();
17001
17002 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
17003 unsigned NumParams = Proto->getNumParams();
17004
17005 DeclarationNameInfo OpLocInfo(
17006 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
17007 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
17008 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, Obj,
17009 HadMultipleCandidates, OpLocInfo);
17010 if (NewFn.isInvalid())
17011 return true;
17012
17013 SmallVector<Expr *, 8> MethodArgs;
17014 MethodArgs.reserve(NumParams + 1);
17015
17016 bool IsError = false;
17017
17018 // Initialize the object parameter.
17020 if (Method->isExplicitObjectMemberFunction()) {
17021 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
17022 } else {
17024 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17025 if (ObjRes.isInvalid())
17026 IsError = true;
17027 else
17028 Object = ObjRes;
17029 MethodArgs.push_back(Object.get());
17030 }
17031
17033 *this, MethodArgs, Method, Args, LParenLoc);
17034
17035 // If this is a variadic call, handle args passed through "...".
17036 if (Proto->isVariadic()) {
17037 // Promote the arguments (C99 6.5.2.2p7).
17038 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
17040 Args[i], VariadicCallType::Method, nullptr);
17041 IsError |= Arg.isInvalid();
17042 MethodArgs.push_back(Arg.get());
17043 }
17044 }
17045
17046 if (IsError)
17047 return true;
17048
17049 DiagnoseSentinelCalls(Method, LParenLoc, Args);
17050
17051 // Once we've built TheCall, all of the expressions are properly owned.
17052 QualType ResultTy = Method->getReturnType();
17054 ResultTy = ResultTy.getNonLValueExprType(Context);
17055
17057 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
17059
17060 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
17061 return true;
17062
17063 if (CheckFunctionCall(Method, TheCall, Proto))
17064 return true;
17065
17067}
17068
17070 SourceLocation OpLoc,
17071 bool *NoArrowOperatorFound) {
17072 assert(Base->getType()->isRecordType() &&
17073 "left-hand side must have class type");
17074
17076 return ExprError();
17077
17078 SourceLocation Loc = Base->getExprLoc();
17079
17080 // C++ [over.ref]p1:
17081 //
17082 // [...] An expression x->m is interpreted as (x.operator->())->m
17083 // for a class object x of type T if T::operator->() exists and if
17084 // the operator is selected as the best match function by the
17085 // overload resolution mechanism (13.3).
17086 DeclarationName OpName =
17087 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
17089
17090 if (RequireCompleteType(Loc, Base->getType(),
17091 diag::err_typecheck_incomplete_tag, Base))
17092 return ExprError();
17093
17094 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
17095 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
17096 R.suppressAccessDiagnostics();
17097
17098 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
17099 Oper != OperEnd; ++Oper) {
17100 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
17101 {}, CandidateSet,
17102 /*SuppressUserConversion=*/false);
17103 }
17104
17105 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17106
17107 // Perform overload resolution.
17109 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
17110 case OR_Success:
17111 // Overload resolution succeeded; we'll build the call below.
17112 break;
17113
17114 case OR_No_Viable_Function: {
17115 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
17116 if (CandidateSet.empty()) {
17117 QualType BaseType = Base->getType();
17118 if (NoArrowOperatorFound) {
17119 // Report this specific error to the caller instead of emitting a
17120 // diagnostic, as requested.
17121 *NoArrowOperatorFound = true;
17122 return ExprError();
17123 }
17124 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
17125 << BaseType << Base->getSourceRange();
17126 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
17127 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
17128 << FixItHint::CreateReplacement(OpLoc, ".");
17129 }
17130 } else
17131 Diag(OpLoc, diag::err_ovl_no_viable_oper)
17132 << "operator->" << Base->getSourceRange();
17133 CandidateSet.NoteCandidates(*this, Base, Cands);
17134 return ExprError();
17135 }
17136 case OR_Ambiguous:
17137 if (!R.isAmbiguous())
17138 CandidateSet.NoteCandidates(
17139 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
17140 << "->" << Base->getType()
17141 << Base->getSourceRange()),
17143 return ExprError();
17144
17145 case OR_Deleted: {
17146 StringLiteral *Msg = Best->Function->getDeletedMessage();
17147 CandidateSet.NoteCandidates(
17148 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
17149 << "->" << (Msg != nullptr)
17150 << (Msg ? Msg->getString() : StringRef())
17151 << Base->getSourceRange()),
17152 *this, OCD_AllCandidates, Base);
17153 return ExprError();
17154 }
17155 }
17156
17157 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
17158
17159 // Convert the object parameter.
17160 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
17161
17162 if (Method->isExplicitObjectMemberFunction()) {
17164 if (R.isInvalid())
17165 return ExprError();
17166 Base = R.get();
17167 } else {
17169 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17170 if (BaseResult.isInvalid())
17171 return ExprError();
17172 Base = BaseResult.get();
17173 }
17174
17175 // Build the operator call.
17176 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
17177 Base, HadMultipleCandidates, OpLoc);
17178 if (FnExpr.isInvalid())
17179 return ExprError();
17180
17181 QualType ResultTy = Method->getReturnType();
17183 ResultTy = ResultTy.getNonLValueExprType(Context);
17184
17185 CallExpr *TheCall =
17186 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17187 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17188
17189 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17190 return ExprError();
17191
17192 if (CheckFunctionCall(Method, TheCall,
17193 Method->getType()->castAs<FunctionProtoType>()))
17194 return ExprError();
17195
17197}
17198
17200 DeclarationNameInfo &SuffixInfo,
17201 ArrayRef<Expr*> Args,
17202 SourceLocation LitEndLoc,
17203 TemplateArgumentListInfo *TemplateArgs) {
17204 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17205
17206 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17208 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17209 TemplateArgs);
17210
17211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17212
17213 // Perform overload resolution. This will usually be trivial, but might need
17214 // to perform substitutions for a literal operator template.
17216 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17217 case OR_Success:
17218 case OR_Deleted:
17219 break;
17220
17222 CandidateSet.NoteCandidates(
17223 PartialDiagnosticAt(UDSuffixLoc,
17224 PDiag(diag::err_ovl_no_viable_function_in_call)
17225 << R.getLookupName()),
17226 *this, OCD_AllCandidates, Args);
17227 return ExprError();
17228
17229 case OR_Ambiguous:
17230 CandidateSet.NoteCandidates(
17231 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17232 << R.getLookupName()),
17233 *this, OCD_AmbiguousCandidates, Args);
17234 return ExprError();
17235 }
17236
17237 FunctionDecl *FD = Best->Function;
17238 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, nullptr,
17239 HadMultipleCandidates, SuffixInfo);
17240 if (Fn.isInvalid())
17241 return true;
17242
17243 // Check the argument types. This should almost always be a no-op, except
17244 // that array-to-pointer decay is applied to string literals.
17245 Expr *ConvArgs[2];
17246 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17249 SourceLocation(), Args[ArgIdx]);
17250 if (InputInit.isInvalid())
17251 return true;
17252 ConvArgs[ArgIdx] = InputInit.get();
17253 }
17254
17255 QualType ResultTy = FD->getReturnType();
17257 ResultTy = ResultTy.getNonLValueExprType(Context);
17258
17260 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17261 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17262
17263 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17264 return ExprError();
17265
17266 if (CheckFunctionCall(FD, UDL, nullptr))
17267 return ExprError();
17268
17270}
17271
17274 SourceLocation RangeLoc,
17275 const DeclarationNameInfo &NameInfo,
17276 LookupResult &MemberLookup,
17277 OverloadCandidateSet *CandidateSet,
17278 Expr *Range, ExprResult *CallExpr) {
17279 Scope *S = nullptr;
17280
17282 if (!MemberLookup.empty()) {
17283 ExprResult MemberRef =
17284 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17285 /*IsPtr=*/false, CXXScopeSpec(),
17286 /*TemplateKWLoc=*/SourceLocation(),
17287 /*FirstQualifierInScope=*/nullptr,
17288 MemberLookup,
17289 /*TemplateArgs=*/nullptr, S);
17290 if (MemberRef.isInvalid()) {
17291 *CallExpr = ExprError();
17292 return FRS_DiagnosticIssued;
17293 }
17294 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17295 if (CallExpr->isInvalid()) {
17296 *CallExpr = ExprError();
17297 return FRS_DiagnosticIssued;
17298 }
17299 } else {
17300 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17302 NameInfo, UnresolvedSet<0>());
17303 if (FnR.isInvalid())
17304 return FRS_DiagnosticIssued;
17306
17307 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17308 CandidateSet, CallExpr);
17309 if (CandidateSet->empty() || CandidateSetError) {
17310 *CallExpr = ExprError();
17311 return FRS_NoViableFunction;
17312 }
17314 OverloadingResult OverloadResult =
17315 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17316
17317 if (OverloadResult == OR_No_Viable_Function) {
17318 *CallExpr = ExprError();
17319 return FRS_NoViableFunction;
17320 }
17321 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17322 Loc, nullptr, CandidateSet, &Best,
17323 OverloadResult,
17324 /*AllowTypoCorrection=*/false);
17325 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17326 *CallExpr = ExprError();
17327 return FRS_DiagnosticIssued;
17328 }
17329 }
17330 return FRS_Success;
17331}
17332
17334 FunctionDecl *Fn) {
17335 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17336 ExprResult SubExpr =
17337 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17338 if (SubExpr.isInvalid())
17339 return ExprError();
17340 if (SubExpr.get() == PE->getSubExpr())
17341 return PE;
17342
17343 return new (Context)
17344 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17345 }
17346
17347 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17348 ExprResult SubExpr =
17349 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17350 if (SubExpr.isInvalid())
17351 return ExprError();
17352 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17353 SubExpr.get()->getType()) &&
17354 "Implicit cast type cannot be determined from overload");
17355 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17356 if (SubExpr.get() == ICE->getSubExpr())
17357 return ICE;
17358
17359 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17360 SubExpr.get(), nullptr, ICE->getValueKind(),
17362 }
17363
17364 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17365 if (!GSE->isResultDependent()) {
17366 ExprResult SubExpr =
17367 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17368 if (SubExpr.isInvalid())
17369 return ExprError();
17370 if (SubExpr.get() == GSE->getResultExpr())
17371 return GSE;
17372
17373 // Replace the resulting type information before rebuilding the generic
17374 // selection expression.
17375 ArrayRef<Expr *> A = GSE->getAssocExprs();
17376 SmallVector<Expr *, 4> AssocExprs(A);
17377 unsigned ResultIdx = GSE->getResultIndex();
17378 AssocExprs[ResultIdx] = SubExpr.get();
17379
17380 if (GSE->isExprPredicate())
17382 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17383 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17384 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17385 ResultIdx);
17387 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17388 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17389 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17390 ResultIdx);
17391 }
17392 // Rather than fall through to the unreachable, return the original generic
17393 // selection expression.
17394 return GSE;
17395 }
17396
17397 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17398 assert(UnOp->getOpcode() == UO_AddrOf &&
17399 "Can only take the address of an overloaded function");
17400 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17401 if (!Method->isImplicitObjectMemberFunction()) {
17402 // Do nothing: the address of static and
17403 // explicit object member functions is a (non-member) function pointer.
17404 } else {
17405 // Fix the subexpression, which really has to be an
17406 // UnresolvedLookupExpr holding an overloaded member function
17407 // or template.
17408 ExprResult SubExpr =
17409 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17410 if (SubExpr.isInvalid())
17411 return ExprError();
17412 if (SubExpr.get() == UnOp->getSubExpr())
17413 return UnOp;
17414
17415 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17416 SubExpr.get(), Method))
17417 return ExprError();
17418
17419 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17420 "fixed to something other than a decl ref");
17421 NestedNameSpecifier Qualifier =
17422 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17423 assert(Qualifier &&
17424 "fixed to a member ref with no nested name qualifier");
17425
17426 // We have taken the address of a pointer to member
17427 // function. Perform the computation here so that we get the
17428 // appropriate pointer to member type.
17429 QualType MemPtrType = Context.getMemberPointerType(
17430 Fn->getType(), Qualifier,
17431 cast<CXXRecordDecl>(Method->getDeclContext()));
17432 // Under the MS ABI, lock down the inheritance model now.
17433 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17434 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17435
17436 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17437 MemPtrType, VK_PRValue, OK_Ordinary,
17438 UnOp->getOperatorLoc(), false,
17440 }
17441 }
17442 ExprResult SubExpr =
17443 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17444 if (SubExpr.isInvalid())
17445 return ExprError();
17446 if (SubExpr.get() == UnOp->getSubExpr())
17447 return UnOp;
17448
17449 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17450 SubExpr.get());
17451 }
17452
17453 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17454 if (Found.getAccess() == AS_none) {
17456 }
17457 // FIXME: avoid copy.
17458 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17459 if (ULE->hasExplicitTemplateArgs()) {
17460 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17461 TemplateArgs = &TemplateArgsBuffer;
17462 }
17463
17464 QualType Type = Fn->getType();
17465 ExprValueKind ValueKind =
17466 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17467 ? VK_LValue
17468 : VK_PRValue;
17469
17470 // FIXME: Duplicated from BuildDeclarationNameExpr.
17471 if (unsigned BID = Fn->getBuiltinID()) {
17472 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17473 Type = Context.BuiltinFnTy;
17474 ValueKind = VK_PRValue;
17475 }
17476 }
17477
17479 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17480 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17481 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17482 return DRE;
17483 }
17484
17485 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17486 // FIXME: avoid copy.
17487 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17488 if (MemExpr->hasExplicitTemplateArgs()) {
17489 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17490 TemplateArgs = &TemplateArgsBuffer;
17491 }
17492
17493 Expr *Base;
17494
17495 // If we're filling in a static method where we used to have an
17496 // implicit member access, rewrite to a simple decl ref.
17497 if (MemExpr->isImplicitAccess()) {
17498 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17500 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17501 MemExpr->getQualifierLoc(), Found.getDecl(),
17502 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17503 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17504 return DRE;
17505 } else {
17506 SourceLocation Loc = MemExpr->getMemberLoc();
17507 if (MemExpr->getQualifier())
17508 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17509 Base =
17510 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17511 }
17512 } else
17513 Base = MemExpr->getBase();
17514
17515 ExprValueKind valueKind;
17516 QualType type;
17517 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17518 valueKind = VK_LValue;
17519 type = Fn->getType();
17520 } else {
17521 valueKind = VK_PRValue;
17522 type = Context.BoundMemberTy;
17523 }
17524
17525 return BuildMemberExpr(
17526 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17527 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17528 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17529 type, valueKind, OK_Ordinary, TemplateArgs);
17530 }
17531
17532 llvm_unreachable("Invalid reference to overloaded function");
17533}
17534
17540
17541bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17543 if (!PartialOverloading || !Function)
17544 return true;
17545 if (Function->isVariadic())
17546 return false;
17547 if (const auto *Proto =
17548 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17549 if (Proto->isTemplateVariadic())
17550 return false;
17551 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17552 if (const auto *Proto =
17553 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17554 if (Proto->isTemplateVariadic())
17555 return false;
17556 return true;
17557}
17558
17560 DeclarationName Name,
17561 OverloadCandidateSet &CandidateSet,
17562 FunctionDecl *Fn, MultiExprArg Args,
17563 bool IsMember) {
17564 StringLiteral *Msg = Fn->getDeletedMessage();
17565 CandidateSet.NoteCandidates(
17566 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17567 << IsMember << Name << (Msg != nullptr)
17568 << (Msg ? Msg->getString() : StringRef())
17569 << Range),
17570 *this, OCD_AllCandidates, Args);
17571}
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:52
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:591
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:859
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:975
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:974
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:2994
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3026
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3030
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:2110
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:828
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:813
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:804
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:640
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4192
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4410
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4308
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:3341
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
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:139
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:102
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2146
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2188
Represents a function declaration or definition.
Definition Decl.h:2082
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2862
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4283
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4271
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3838
param_iterator param_end()
Definition Decl.h:2960
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3742
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3946
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
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:4342
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4391
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3823
param_iterator param_begin()
Definition Decl.h:2959
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3139
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4407
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4335
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3950
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2639
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4208
bool isConsteval() const
Definition Decl.h:2651
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3786
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3307
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:3039
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:3791
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4243
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3902
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2858
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:624
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:675
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:772
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:679
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:829
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:683
bool hasInitializerListContainerType() const
Definition Overload.h:811
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:736
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:818
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:687
QualType getInitializerListContainerType() const
Definition Overload.h:821
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:5852
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:1685
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:1162
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:1362
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:1464
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1398
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:1414
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1352
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1187
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1183
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1178
@ CSK_Normal
Normal lookup.
Definition Overload.h:1166
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1173
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1192
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1378
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:1370
SourceLocation getLocation() const
Definition Overload.h:1350
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1429
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1351
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1389
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:3066
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:3832
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:4989
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:4506
field_range fields() const
Definition Decl.h:4709
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4694
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:1712
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1764
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:49
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:179
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:10559
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:10282
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1419
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1454
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:12748
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12782
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:1493
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:10300
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:9568
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9595
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9580
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9576
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:421
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:170
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
SemaCUDA & CUDA()
Definition Sema.h:1518
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:10642
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10645
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10651
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10649
@ AR_dependent
Definition Sema.h:1737
@ AR_accessible
Definition Sema.h:1735
@ AR_inaccessible
Definition Sema.h:1736
@ AR_delayed
Definition Sema.h:1738
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:2126
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:1780
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:1339
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:231
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1563
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:772
ASTContext & getASTContext() const
Definition Sema.h:935
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:11030
@ FRS_DiagnosticIssued
Definition Sema.h:11032
@ FRS_NoViableFunction
Definition Sema.h:11031
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9561
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:10351
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:1243
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:3776
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:12446
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:928
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:1337
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:1528
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9560
MemberPointerConversionDirection
Definition Sema.h:10483
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:10670
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:652
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:15883
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:10096
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:7178
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:1491
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:8400
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:14292
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:7684
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:14002
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:15838
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:130
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:6941
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6910
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:10475
SourceManager & SourceMgr
Definition Sema.h:1342
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1341
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:528
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:6611
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:1498
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:8884
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:3719
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:2417
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:2394
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:2301
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:2321
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:2552
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:2802
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:2284
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:2357
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:2638
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:2662
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:2535
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2823
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:2462
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:817
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
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:861
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:889
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:898
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:881
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:885
@ 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:926
@ ovl_fail_too_few_arguments
Definition Overload.h:863
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:905
@ ovl_fail_too_many_arguments
Definition Overload.h:862
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:913
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:922
@ ovl_fail_bad_conversion
Definition Overload.h:864
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:894
@ ovl_fail_bad_deduction
Definition Overload.h:865
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:909
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:918
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:902
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:870
@ Comparison
A comparison.
Definition Sema.h:661
@ 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:931
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:683
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:706
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:727
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:685
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:723
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:581
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:217
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:374
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:424
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:419
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:395
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:381
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:414
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:378
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:398
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:387
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:401
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:411
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:405
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:408
@ 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:1525
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:832
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:835
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:840
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:838
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:839
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:442
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
#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:614
QualType getFromType() const
Definition Overload.h:613
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:1104
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:1197
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:1219
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1246
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1208
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1210
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1236
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:935
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:1000
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:991
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1065
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1039
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1004
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:981
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:949
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:945
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:940
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1012
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:961
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:975
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1030
unsigned getNumParams() const
Definition Overload.h:1078
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1008
unsigned TookAddressOfOverload
Definition Overload.h:994
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1017
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1021
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:958
DeductionFailureInfo DeductionFailure
Definition Overload.h:1024
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:965
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:953
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1035
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10762
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10769
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13413
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13498
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13547
Abstract class used to diagnose incomplete types.
Definition Sema.h:8477
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.