clang 23.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaARM.h"
35#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/SemaObjC.h"
37#include "clang/Sema/Template.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/STLForwardCompat.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/ADT/SmallPtrSet.h"
44#include "llvm/ADT/SmallVector.h"
45#include <algorithm>
46#include <cassert>
47#include <cstddef>
48#include <cstdlib>
49#include <optional>
50
51using namespace clang;
52using namespace sema;
53
55
57 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
58 return P->hasAttr<PassObjectSizeAttr>();
59 });
60}
61
62/// A convenience routine for creating a decayed reference to a function.
64 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
65 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
66 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
67 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
68 return ExprError();
69 // If FoundDecl is different from Fn (such as if one is a template
70 // and the other a specialization), make sure DiagnoseUseOfDecl is
71 // called on both.
72 // FIXME: This would be more comprehensively addressed by modifying
73 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
74 // being used.
75 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
76 return ExprError();
77 DeclRefExpr *DRE = new (S.Context)
78 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
79 if (HadMultipleCandidates)
80 DRE->setHadMultipleCandidates(true);
81
83 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
84 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
85 S.ResolveExceptionSpec(Loc, FPT);
86 DRE->setType(Fn->getType());
87 }
88 }
89 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
90 CK_FunctionToPointerDecay);
91}
92
93static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
94 bool InOverloadResolution,
96 bool CStyle,
97 bool AllowObjCWritebackConversion);
98
100 QualType &ToType,
101 bool InOverloadResolution,
103 bool CStyle);
105IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
107 OverloadCandidateSet& Conversions,
108 AllowedExplicit AllowExplicit,
109 bool AllowObjCConversionOnExplicit);
110
113 const StandardConversionSequence& SCS1,
114 const StandardConversionSequence& SCS2);
115
118 const StandardConversionSequence& SCS1,
119 const StandardConversionSequence& SCS2);
120
123 const StandardConversionSequence &SCS1,
124 const StandardConversionSequence &SCS2);
125
128 const StandardConversionSequence& SCS1,
129 const StandardConversionSequence& SCS2);
130
131/// GetConversionRank - Retrieve the implicit conversion rank
132/// corresponding to the given implicit conversion kind.
134 static const ImplicitConversionRank Rank[] = {
161 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
162 // it was omitted by the patch that added
163 // ICK_Zero_Event_Conversion
164 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
165 // it was omitted by the patch that added
166 // ICK_Zero_Queue_Conversion
175 };
176 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
177 return Rank[(int)Kind];
178}
179
198
199/// GetImplicitConversionName - Return the name of this kind of
200/// implicit conversion.
202 static const char *const Name[] = {
203 "No conversion",
204 "Lvalue-to-rvalue",
205 "Array-to-pointer",
206 "Function-to-pointer",
207 "Function pointer conversion",
208 "Qualification",
209 "Integral promotion",
210 "Floating point promotion",
211 "Complex promotion",
212 "Integral conversion",
213 "Floating conversion",
214 "Complex conversion",
215 "Floating-integral conversion",
216 "Pointer conversion",
217 "Pointer-to-member conversion",
218 "Boolean conversion",
219 "Compatible-types conversion",
220 "Derived-to-base conversion",
221 "Vector conversion",
222 "SVE Vector conversion",
223 "RVV Vector conversion",
224 "Vector splat",
225 "Complex-real conversion",
226 "Block Pointer conversion",
227 "Transparent Union Conversion",
228 "Writeback conversion",
229 "OpenCL Zero Event Conversion",
230 "OpenCL Zero Queue Conversion",
231 "C specific type conversion",
232 "Incompatible pointer conversion",
233 "Fixed point conversion",
234 "HLSL vector truncation",
235 "HLSL matrix truncation",
236 "Non-decaying array conversion",
237 "HLSL vector splat",
238 "HLSL matrix splat",
239 };
240 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
241 return Name[Kind];
242}
243
244/// StandardConversionSequence - Set the standard conversion
245/// sequence to the identity conversion.
263
264/// getRank - Retrieve the rank of this standard conversion sequence
265/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
266/// implicit conversions.
279
280/// isPointerConversionToBool - Determines whether this conversion is
281/// a conversion of a pointer or pointer-to-member to bool. This is
282/// used as part of the ranking of standard conversion sequences
283/// (C++ 13.3.3.2p4).
285 // Note that FromType has not necessarily been transformed by the
286 // array-to-pointer or function-to-pointer implicit conversions, so
287 // check for their presence as well as checking whether FromType is
288 // a pointer.
289 if (getToType(1)->isBooleanType() &&
290 (getFromType()->isPointerType() ||
291 getFromType()->isMemberPointerType() ||
292 getFromType()->isObjCObjectPointerType() ||
293 getFromType()->isBlockPointerType() ||
295 return true;
296
297 return false;
298}
299
300/// isPointerConversionToVoidPointer - Determines whether this
301/// conversion is a conversion of a pointer to a void pointer. This is
302/// used as part of the ranking of standard conversion sequences (C++
303/// 13.3.3.2p4).
304bool
307 QualType FromType = getFromType();
308 QualType ToType = getToType(1);
309
310 // Note that FromType has not necessarily been transformed by the
311 // array-to-pointer implicit conversion, so check for its presence
312 // and redo the conversion to get a pointer.
314 FromType = Context.getArrayDecayedType(FromType);
315
316 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
317 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
318 return ToPtrType->getPointeeType()->isVoidType();
319
320 return false;
321}
322
323/// Skip any implicit casts which could be either part of a narrowing conversion
324/// or after one in an implicit conversion.
326 const Expr *Converted) {
327 // We can have cleanups wrapping the converted expression; these need to be
328 // preserved so that destructors run if necessary.
329 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
330 Expr *Inner =
331 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
332 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
333 EWC->getObjects());
334 }
335
336 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
337 switch (ICE->getCastKind()) {
338 case CK_NoOp:
339 case CK_IntegralCast:
340 case CK_IntegralToBoolean:
341 case CK_IntegralToFloating:
342 case CK_BooleanToSignedIntegral:
343 case CK_FloatingToIntegral:
344 case CK_FloatingToBoolean:
345 case CK_FloatingCast:
346 Converted = ICE->getSubExpr();
347 continue;
348
349 default:
350 return Converted;
351 }
352 }
353
354 return Converted;
355}
356
357/// Check if this standard conversion sequence represents a narrowing
358/// conversion, according to C++11 [dcl.init.list]p7.
359///
360/// \param Ctx The AST context.
361/// \param Converted The result of applying this standard conversion sequence.
362/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
363/// value of the expression prior to the narrowing conversion.
364/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
365/// type of the expression prior to the narrowing conversion.
366/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
367/// from floating point types to integral types should be ignored.
369 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
370 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
371 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
372 "narrowing check outside C++");
373
374 // C++11 [dcl.init.list]p7:
375 // A narrowing conversion is an implicit conversion ...
376 QualType FromType = getToType(0);
377 QualType ToType = getToType(1);
378
379 // A conversion to an enumeration type is narrowing if the conversion to
380 // the underlying type is narrowing. This only arises for expressions of
381 // the form 'Enum{init}'.
382 if (const auto *ED = ToType->getAsEnumDecl())
383 ToType = ED->getIntegerType();
384
385 switch (Second) {
386 // 'bool' is an integral type; dispatch to the right place to handle it.
388 if (FromType->isRealFloatingType())
389 goto FloatingIntegralConversion;
391 goto IntegralConversion;
392 // -- from a pointer type or pointer-to-member type to bool, or
393 return NK_Type_Narrowing;
394
395 // -- from a floating-point type to an integer type, or
396 //
397 // -- from an integer type or unscoped enumeration type to a floating-point
398 // type, except where the source is a constant expression and the actual
399 // value after conversion will fit into the target type and will produce
400 // the original value when converted back to the original type, or
402 FloatingIntegralConversion:
403 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
404 return NK_Type_Narrowing;
405 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
406 ToType->isRealFloatingType()) {
407 if (IgnoreFloatToIntegralConversion)
408 return NK_Not_Narrowing;
409 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
410 assert(Initializer && "Unknown conversion expression");
411
412 // If it's value-dependent, we can't tell whether it's narrowing.
413 if (Initializer->isValueDependent())
415
416 if (std::optional<llvm::APSInt> IntConstantValue =
417 Initializer->getIntegerConstantExpr(Ctx)) {
418 // Convert the integer to the floating type.
419 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
420 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
421 llvm::APFloat::rmNearestTiesToEven);
422 // And back.
423 llvm::APSInt ConvertedValue = *IntConstantValue;
424 bool ignored;
425 llvm::APFloat::opStatus Status = Result.convertToInteger(
426 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
427 // If the converted-back integer has unspecified value, or if the
428 // resulting value is different, this was a narrowing conversion.
429 if (Status == llvm::APFloat::opInvalidOp ||
430 *IntConstantValue != ConvertedValue) {
431 ConstantValue = APValue(*IntConstantValue);
432 ConstantType = Initializer->getType();
434 }
435 } else {
436 // Variables are always narrowings.
438 }
439 }
440 return NK_Not_Narrowing;
441
442 // -- from long double to double or float, or from double to float, except
443 // where the source is a constant expression and the actual value after
444 // conversion is within the range of values that can be represented (even
445 // if it cannot be represented exactly), or
447 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
448 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
449 // FromType is larger than ToType.
450 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
451
452 // If it's value-dependent, we can't tell whether it's narrowing.
453 if (Initializer->isValueDependent())
455
457 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
458 ((Ctx.getLangOpts().CPlusPlus &&
459 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
460 // Constant!
461 if (Ctx.getLangOpts().C23)
462 ConstantValue = R.Val;
463 assert(ConstantValue.isFloat());
464 llvm::APFloat FloatVal = ConstantValue.getFloat();
465 // Convert the source value into the target type.
466 bool ignored;
467 llvm::APFloat Converted = FloatVal;
468 llvm::APFloat::opStatus ConvertStatus =
469 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
470 llvm::APFloat::rmNearestTiesToEven, &ignored);
471 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
472 llvm::APFloat::rmNearestTiesToEven, &ignored);
473 if (Ctx.getLangOpts().C23) {
474 if (FloatVal.isNaN() && Converted.isNaN() &&
475 !FloatVal.isSignaling() && !Converted.isSignaling()) {
476 // Quiet NaNs are considered the same value, regardless of
477 // payloads.
478 return NK_Not_Narrowing;
479 }
480 // For normal values, check exact equality.
481 if (!Converted.bitwiseIsEqual(FloatVal)) {
482 ConstantType = Initializer->getType();
484 }
485 } else {
486 // If there was no overflow, the source value is within the range of
487 // values that can be represented.
488 if (ConvertStatus & llvm::APFloat::opOverflow) {
489 ConstantType = Initializer->getType();
491 }
492 }
493 } else {
495 }
496 }
497 return NK_Not_Narrowing;
498
499 // -- from an integer type or unscoped enumeration type to an integer type
500 // that cannot represent all the values of the original type, except where
501 // (CWG2627) -- the source is a bit-field whose width w is less than that
502 // of its type (or, for an enumeration type, its underlying type) and the
503 // target type can represent all the values of a hypothetical extended
504 // integer type with width w and with the same signedness as the original
505 // type or
506 // -- the source is a constant expression and the actual value after
507 // conversion will fit into the target type and will produce the original
508 // value when converted back to the original type.
510 IntegralConversion: {
511 assert(FromType->isIntegralOrUnscopedEnumerationType());
512 assert(ToType->isIntegralOrUnscopedEnumerationType());
513 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
514 unsigned FromWidth = Ctx.getIntWidth(FromType);
515 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
516 const unsigned ToWidth = Ctx.getIntWidth(ToType);
517
518 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
519 bool ToSigned, unsigned ToWidth) {
520 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
521 !(FromSigned && !ToSigned);
522 };
523
524 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
525 return NK_Not_Narrowing;
526
527 // Not all values of FromType can be represented in ToType.
528 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
529
530 bool DependentBitField = false;
531 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
532 if (BitField->getBitWidth()->isValueDependent())
533 DependentBitField = true;
534 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
535 BitFieldWidth < FromWidth) {
536 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
537 return NK_Not_Narrowing;
538
539 // The initializer will be truncated to the bit-field width
540 FromWidth = BitFieldWidth;
541 }
542 }
543
544 // If it's value-dependent, we can't tell whether it's narrowing.
545 if (Initializer->isValueDependent())
547
548 std::optional<llvm::APSInt> OptInitializerValue =
549 Initializer->getIntegerConstantExpr(Ctx);
550 if (!OptInitializerValue) {
551 // If the bit-field width was dependent, it might end up being small
552 // enough to fit in the target type (unless the target type is unsigned
553 // and the source type is signed, in which case it will never fit)
554 if (DependentBitField && !(FromSigned && !ToSigned))
556
557 // Otherwise, such a conversion is always narrowing
559 }
560 llvm::APSInt &InitializerValue = *OptInitializerValue;
561 bool Narrowing = false;
562 if (FromWidth < ToWidth) {
563 // Negative -> unsigned is narrowing. Otherwise, more bits is never
564 // narrowing.
565 if (InitializerValue.isSigned() && InitializerValue.isNegative())
566 Narrowing = true;
567 } else {
568 // Add a bit to the InitializerValue so we don't have to worry about
569 // signed vs. unsigned comparisons.
570 InitializerValue =
571 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
572 // Convert the initializer to and from the target width and signed-ness.
573 llvm::APSInt ConvertedValue = InitializerValue;
574 ConvertedValue = ConvertedValue.trunc(ToWidth);
575 ConvertedValue.setIsSigned(ToSigned);
576 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
577 ConvertedValue.setIsSigned(InitializerValue.isSigned());
578 // If the result is different, this was a narrowing conversion.
579 if (ConvertedValue != InitializerValue)
580 Narrowing = true;
581 }
582 if (Narrowing) {
583 ConstantType = Initializer->getType();
584 ConstantValue = APValue(InitializerValue);
586 }
587
588 return NK_Not_Narrowing;
589 }
590 case ICK_Complex_Real:
591 if (FromType->isComplexType() && !ToType->isComplexType())
592 return NK_Type_Narrowing;
593 return NK_Not_Narrowing;
594
596 if (Ctx.getLangOpts().C23) {
597 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
599 if (Initializer->EvaluateAsRValue(R, Ctx)) {
600 ConstantValue = R.Val;
601 assert(ConstantValue.isFloat());
602 llvm::APFloat FloatVal = ConstantValue.getFloat();
603 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
604 // value, the unqualified versions of the type of the initializer and
605 // the corresponding real type of the object declared shall be
606 // compatible.
607 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
608 ConstantType = Initializer->getType();
610 }
611 }
612 }
613 return NK_Not_Narrowing;
614 default:
615 // Other kinds of conversions are not narrowings.
616 return NK_Not_Narrowing;
617 }
618}
619
620/// dump - Print this standard conversion sequence to standard
621/// error. Useful for debugging overloading issues.
622LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
623 raw_ostream &OS = llvm::errs();
624 bool PrintedSomething = false;
625 if (First != ICK_Identity) {
627 PrintedSomething = true;
628 }
629
630 if (Second != ICK_Identity) {
631 if (PrintedSomething) {
632 OS << " -> ";
633 }
635
636 if (CopyConstructor) {
637 OS << " (by copy constructor)";
638 } else if (DirectBinding) {
639 OS << " (direct reference binding)";
640 } else if (ReferenceBinding) {
641 OS << " (reference binding)";
642 }
643 PrintedSomething = true;
644 }
645
646 if (Third != ICK_Identity) {
647 if (PrintedSomething) {
648 OS << " -> ";
649 }
651 PrintedSomething = true;
652 }
653
654 if (!PrintedSomething) {
655 OS << "No conversions required";
656 }
657}
658
659/// dump - Print this user-defined conversion sequence to standard
660/// error. Useful for debugging overloading issues.
662 raw_ostream &OS = llvm::errs();
663 if (Before.First || Before.Second || Before.Third) {
664 Before.dump();
665 OS << " -> ";
666 }
668 OS << '\'' << *ConversionFunction << '\'';
669 else
670 OS << "aggregate initialization";
671 if (After.First || After.Second || After.Third) {
672 OS << " -> ";
673 After.dump();
674 }
675}
676
677/// dump - Print this implicit conversion sequence to standard
678/// error. Useful for debugging overloading issues.
680 raw_ostream &OS = llvm::errs();
682 OS << "Worst list element conversion: ";
683 switch (ConversionKind) {
685 OS << "Standard conversion: ";
686 Standard.dump();
687 break;
689 OS << "User-defined conversion: ";
690 UserDefined.dump();
691 break;
693 OS << "Ellipsis conversion";
694 break;
696 OS << "Ambiguous conversion";
697 break;
698 case BadConversion:
699 OS << "Bad conversion";
700 break;
701 }
702
703 OS << "\n";
704}
705
709
711 conversions().~ConversionSet();
712}
713
714void
720
721namespace {
722 // Structure used by DeductionFailureInfo to store
723 // template argument information.
724 struct DFIArguments {
725 TemplateArgument FirstArg;
726 TemplateArgument SecondArg;
727 };
728 // Structure used by DeductionFailureInfo to store
729 // template parameter and template argument information.
730 struct DFIParamWithArguments : DFIArguments {
731 TemplateParameter Param;
732 };
733 // Structure used by DeductionFailureInfo to store template argument
734 // information and the index of the problematic call argument.
735 struct DFIDeducedMismatchArgs : DFIArguments {
736 TemplateArgumentList *TemplateArgs;
737 unsigned CallArgIndex;
738 };
739 // Structure used by DeductionFailureInfo to store information about
740 // unsatisfied constraints.
741 struct CNSInfo {
742 TemplateArgumentList *TemplateArgs;
743 ConstraintSatisfaction Satisfaction;
744 };
745}
746
747/// Convert from Sema's representation of template deduction information
748/// to the form used in overload-candidate information.
752 TemplateDeductionInfo &Info) {
754 Result.Result = static_cast<unsigned>(TDK);
755 Result.HasDiagnostic = false;
756 switch (TDK) {
763 Result.Data = nullptr;
764 break;
765
768 Result.Data = Info.Param.getOpaqueValue();
769 break;
770
773 // FIXME: Should allocate from normal heap so that we can free this later.
774 auto *Saved = new (Context) DFIDeducedMismatchArgs;
775 Saved->FirstArg = Info.FirstArg;
776 Saved->SecondArg = Info.SecondArg;
777 Saved->TemplateArgs = Info.takeSugared();
778 Saved->CallArgIndex = Info.CallArgIndex;
779 Result.Data = Saved;
780 break;
781 }
782
784 // FIXME: Should allocate from normal heap so that we can free this later.
785 DFIArguments *Saved = new (Context) DFIArguments;
786 Saved->FirstArg = Info.FirstArg;
787 Saved->SecondArg = Info.SecondArg;
788 Result.Data = Saved;
789 break;
790 }
791
793 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
796 // FIXME: Should allocate from normal heap so that we can free this later.
797 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
798 Saved->Param = Info.Param;
799 Saved->FirstArg = Info.FirstArg;
800 Saved->SecondArg = Info.SecondArg;
801 Result.Data = Saved;
802 break;
803 }
804
806 Result.Data = Info.takeSugared();
807 if (Info.hasSFINAEDiagnostic()) {
811 Result.HasDiagnostic = true;
812 }
813 break;
814
816 CNSInfo *Saved = new (Context) CNSInfo;
817 Saved->TemplateArgs = Info.takeSugared();
818 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
819 Result.Data = Saved;
820 break;
821 }
822
826 llvm_unreachable("not a deduction failure");
827 }
828
829 return Result;
830}
831
833 switch (static_cast<TemplateDeductionResult>(Result)) {
843 break;
844
851 // FIXME: Destroy the data?
852 Data = nullptr;
853 break;
854
856 // FIXME: Destroy the template argument list?
857 Data = nullptr;
859 Diag->~PartialDiagnosticAt();
860 HasDiagnostic = false;
861 }
862 break;
863
865 // FIXME: Destroy the template argument list?
866 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
867 Data = nullptr;
869 Diag->~PartialDiagnosticAt();
870 HasDiagnostic = false;
871 }
872 break;
873
874 // Unhandled
877 break;
878 }
879}
880
882 if (HasDiagnostic)
883 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
884 return nullptr;
885}
886
920
956
988
1020
1022 switch (static_cast<TemplateDeductionResult>(Result)) {
1025 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1026
1027 default:
1028 return std::nullopt;
1029 }
1030}
1031
1033 const FunctionDecl *Y) {
1034 if (!X || !Y)
1035 return false;
1036 if (X->getNumParams() != Y->getNumParams())
1037 return false;
1038 // FIXME: when do rewritten comparison operators
1039 // with explicit object parameters correspond?
1040 // https://cplusplus.github.io/CWG/issues/2797.html
1041 for (unsigned I = 0; I < X->getNumParams(); ++I)
1042 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1043 Y->getParamDecl(I)->getType()))
1044 return false;
1045 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1046 auto *FTY = Y->getDescribedFunctionTemplate();
1047 if (!FTY)
1048 return false;
1049 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1050 FTY->getTemplateParameters()))
1051 return false;
1052 }
1053 return true;
1054}
1055
1057 Expr *FirstOperand, FunctionDecl *EqFD) {
1058 assert(EqFD->getOverloadedOperator() ==
1059 OverloadedOperatorKind::OO_EqualEqual);
1060 // C++2a [over.match.oper]p4:
1061 // A non-template function or function template F named operator== is a
1062 // rewrite target with first operand o unless a search for the name operator!=
1063 // in the scope S from the instantiation context of the operator expression
1064 // finds a function or function template that would correspond
1065 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1066 // scope of the class type of o if F is a class member, and the namespace
1067 // scope of which F is a member otherwise. A function template specialization
1068 // named operator== is a rewrite target if its function template is a rewrite
1069 // target.
1071 OverloadedOperatorKind::OO_ExclaimEqual);
1072 if (isa<CXXMethodDecl>(EqFD)) {
1073 // If F is a class member, search scope is class type of first operand.
1074 QualType RHS = FirstOperand->getType();
1075 auto *RHSRec = RHS->getAsCXXRecordDecl();
1076 if (!RHSRec)
1077 return true;
1078 LookupResult Members(S, NotEqOp, OpLoc,
1080 S.LookupQualifiedName(Members, RHSRec);
1081 Members.suppressAccessDiagnostics();
1082 for (NamedDecl *Op : Members)
1083 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1084 return false;
1085 return true;
1086 }
1087 // Otherwise the search scope is the namespace scope of which F is a member.
1088 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1089 auto *NotEqFD = Op->getAsFunction();
1090 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1091 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1092 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1094 cast<Decl>(Op->getLexicalDeclContext())))
1095 return false;
1096 }
1097 return true;
1098}
1099
1101 OverloadedOperatorKind Op) const {
1103 return false;
1104 return Op == OO_EqualEqual || Op == OO_Spaceship;
1105}
1106
1108 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1109 auto Op = FD->getOverloadedOperator();
1110 if (!allowsReversed(Op))
1111 return false;
1112 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1113 assert(OriginalArgs.size() == 2);
1115 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1116 return false;
1117 }
1118 // Don't bother adding a reversed candidate that can never be a better
1119 // match than the non-reversed version.
1120 return FD->getNumNonObjectParams() != 2 ||
1122 FD->getParamDecl(1)->getType()) ||
1123 FD->hasAttr<EnableIfAttr>();
1124}
1125
1126void OverloadCandidateSet::destroyCandidates() {
1127 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1128 for (auto &C : i->Conversions)
1129 C.~ImplicitConversionSequence();
1130 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1131 i->DeductionFailure.Destroy();
1132 }
1133}
1134
1136 destroyCandidates();
1137 SlabAllocator.Reset();
1138 NumInlineBytesUsed = 0;
1139 Candidates.clear();
1140 Functions.clear();
1141 Kind = CSK;
1142 FirstDeferredCandidate = nullptr;
1143 DeferredCandidatesCount = 0;
1144 HasDeferredTemplateConstructors = false;
1145 ResolutionByPerfectCandidateIsDisabled = false;
1146}
1147
1148namespace {
1149 class UnbridgedCastsSet {
1150 struct Entry {
1151 Expr **Addr;
1152 Expr *Saved;
1153 };
1154 SmallVector<Entry, 2> Entries;
1155
1156 public:
1157 void save(Sema &S, Expr *&E) {
1158 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1159 Entry entry = { &E, E };
1160 Entries.push_back(entry);
1161 E = S.ObjC().stripARCUnbridgedCast(E);
1162 }
1163
1164 void restore() {
1165 for (SmallVectorImpl<Entry>::iterator
1166 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1167 *i->Addr = i->Saved;
1168 }
1169 };
1170}
1171
1172/// checkPlaceholderForOverload - Do any interesting placeholder-like
1173/// preprocessing on the given expression.
1174///
1175/// \param unbridgedCasts a collection to which to add unbridged casts;
1176/// without this, they will be immediately diagnosed as errors
1177///
1178/// Return true on unrecoverable error.
1179static bool
1181 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1182 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1183 // We can't handle overloaded expressions here because overload
1184 // resolution might reasonably tweak them.
1185 if (placeholder->getKind() == BuiltinType::Overload) return false;
1186
1187 // If the context potentially accepts unbridged ARC casts, strip
1188 // the unbridged cast and add it to the collection for later restoration.
1189 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1190 unbridgedCasts) {
1191 unbridgedCasts->save(S, E);
1192 return false;
1193 }
1194
1195 // Go ahead and check everything else.
1196 ExprResult result = S.CheckPlaceholderExpr(E);
1197 if (result.isInvalid())
1198 return true;
1199
1200 E = result.get();
1201 return false;
1202 }
1203
1204 // Nothing to do.
1205 return false;
1206}
1207
1208/// checkArgPlaceholdersForOverload - Check a set of call operands for
1209/// placeholders.
1211 UnbridgedCastsSet &unbridged) {
1212 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1213 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1214 return true;
1215
1216 return false;
1217}
1218
1220 const LookupResult &Old, NamedDecl *&Match,
1221 bool NewIsUsingDecl) {
1222 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1223 I != E; ++I) {
1224 NamedDecl *OldD = *I;
1225
1226 bool OldIsUsingDecl = false;
1227 if (isa<UsingShadowDecl>(OldD)) {
1228 OldIsUsingDecl = true;
1229
1230 // We can always introduce two using declarations into the same
1231 // context, even if they have identical signatures.
1232 if (NewIsUsingDecl) continue;
1233
1234 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1235 }
1236
1237 // A using-declaration does not conflict with another declaration
1238 // if one of them is hidden.
1239 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1240 continue;
1241
1242 // If either declaration was introduced by a using declaration,
1243 // we'll need to use slightly different rules for matching.
1244 // Essentially, these rules are the normal rules, except that
1245 // function templates hide function templates with different
1246 // return types or template parameter lists.
1247 bool UseMemberUsingDeclRules =
1248 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1249 !New->getFriendObjectKind();
1250
1251 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1252 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1253 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1255 continue;
1256 }
1257
1258 if (!isa<FunctionTemplateDecl>(OldD) &&
1259 !shouldLinkPossiblyHiddenDecl(*I, New))
1260 continue;
1261
1262 Match = *I;
1263 return OverloadKind::Match;
1264 }
1265
1266 // Builtins that have custom typechecking or have a reference should
1267 // not be overloadable or redeclarable.
1268 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1269 Match = *I;
1271 }
1272 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1273 // We can overload with these, which can show up when doing
1274 // redeclaration checks for UsingDecls.
1275 assert(Old.getLookupKind() == LookupUsingDeclName);
1276 } else if (isa<TagDecl>(OldD)) {
1277 // We can always overload with tags by hiding them.
1278 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1279 // Optimistically assume that an unresolved using decl will
1280 // overload; if it doesn't, we'll have to diagnose during
1281 // template instantiation.
1282 //
1283 // Exception: if the scope is dependent and this is not a class
1284 // member, the using declaration can only introduce an enumerator.
1285 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1286 Match = *I;
1288 }
1289 } else {
1290 // (C++ 13p1):
1291 // Only function declarations can be overloaded; object and type
1292 // declarations cannot be overloaded.
1293 Match = *I;
1295 }
1296 }
1297
1298 // C++ [temp.friend]p1:
1299 // For a friend function declaration that is not a template declaration:
1300 // -- if the name of the friend is a qualified or unqualified template-id,
1301 // [...], otherwise
1302 // -- if the name of the friend is a qualified-id and a matching
1303 // non-template function is found in the specified class or namespace,
1304 // the friend declaration refers to that function, otherwise,
1305 // -- if the name of the friend is a qualified-id and a matching function
1306 // template is found in the specified class or namespace, the friend
1307 // declaration refers to the deduced specialization of that function
1308 // template, otherwise
1309 // -- the name shall be an unqualified-id [...]
1310 // If we get here for a qualified friend declaration, we've just reached the
1311 // third bullet. If the type of the friend is dependent, skip this lookup
1312 // until instantiation.
1313 if (New->getFriendObjectKind() && New->getQualifier() &&
1314 !New->getDescribedFunctionTemplate() &&
1315 !New->getDependentSpecializationInfo() &&
1316 !New->getType()->isDependentType()) {
1317 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1318 TemplateSpecResult.addAllDecls(Old);
1319 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1320 /*QualifiedFriend*/true)) {
1321 New->setInvalidDecl();
1323 }
1324
1325 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1326 return OverloadKind::Match;
1327 }
1328
1330}
1331
1332template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1333 assert(D && "function decl should not be null");
1334 if (auto *A = D->getAttr<AttrT>())
1335 return !A->isImplicit();
1336 return false;
1337}
1338
1340 FunctionDecl *Old,
1341 bool UseMemberUsingDeclRules,
1342 bool ConsiderCudaAttrs,
1343 bool UseOverrideRules = false) {
1344 // C++ [basic.start.main]p2: This function shall not be overloaded.
1345 if (New->isMain())
1346 return false;
1347
1348 // MSVCRT user defined entry points cannot be overloaded.
1349 if (New->isMSVCRTEntryPoint())
1350 return false;
1351
1352 NamedDecl *OldDecl = Old;
1353 NamedDecl *NewDecl = New;
1355 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1356
1357 // C++ [temp.fct]p2:
1358 // A function template can be overloaded with other function templates
1359 // and with normal (non-template) functions.
1360 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1361 return true;
1362
1363 // Is the function New an overload of the function Old?
1364 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1365 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1366
1367 // Compare the signatures (C++ 1.3.10) of the two functions to
1368 // determine whether they are overloads. If we find any mismatch
1369 // in the signature, they are overloads.
1370
1371 // If either of these functions is a K&R-style function (no
1372 // prototype), then we consider them to have matching signatures.
1373 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1375 return false;
1376
1377 const auto *OldType = cast<FunctionProtoType>(OldQType);
1378 const auto *NewType = cast<FunctionProtoType>(NewQType);
1379
1380 // The signature of a function includes the types of its
1381 // parameters (C++ 1.3.10), which includes the presence or absence
1382 // of the ellipsis; see C++ DR 357).
1383 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1384 return true;
1385
1386 // For member-like friends, the enclosing class is part of the signature.
1387 if ((New->isMemberLikeConstrainedFriend() ||
1389 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1390 return true;
1391
1392 // Compare the parameter lists.
1393 // This can only be done once we have establish that friend functions
1394 // inhabit the same context, otherwise we might tried to instantiate
1395 // references to non-instantiated entities during constraint substitution.
1396 // GH78101.
1397 if (NewTemplate) {
1398 OldDecl = OldTemplate;
1399 NewDecl = NewTemplate;
1400 // C++ [temp.over.link]p4:
1401 // The signature of a function template consists of its function
1402 // signature, its return type and its template parameter list. The names
1403 // of the template parameters are significant only for establishing the
1404 // relationship between the template parameters and the rest of the
1405 // signature.
1406 //
1407 // We check the return type and template parameter lists for function
1408 // templates first; the remaining checks follow.
1409 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1410 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1411 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1412 bool SameReturnType = SemaRef.Context.hasSameType(
1413 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1414 // FIXME(GH58571): Match template parameter list even for non-constrained
1415 // template heads. This currently ensures that the code prior to C++20 is
1416 // not newly broken.
1417 bool ConstraintsInTemplateHead =
1420 // C++ [namespace.udecl]p11:
1421 // The set of declarations named by a using-declarator that inhabits a
1422 // class C does not include member functions and member function
1423 // templates of a base class that "correspond" to (and thus would
1424 // conflict with) a declaration of a function or function template in
1425 // C.
1426 // Comparing return types is not required for the "correspond" check to
1427 // decide whether a member introduced by a shadow declaration is hidden.
1428 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1429 !SameTemplateParameterList)
1430 return true;
1431 if (!UseMemberUsingDeclRules &&
1432 (!SameTemplateParameterList || !SameReturnType))
1433 return true;
1434 }
1435
1436 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1437 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1438
1439 int OldParamsOffset = 0;
1440 int NewParamsOffset = 0;
1441
1442 // When determining if a method is an overload from a base class, act as if
1443 // the implicit object parameter are of the same type.
1444
1445 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1447 auto ThisType = M->getFunctionObjectParameterReferenceType();
1448 if (ThisType.isConstQualified())
1449 Q.removeConst();
1450 return Q;
1451 }
1452
1453 // We do not allow overloading based off of '__restrict'.
1454 Q.removeRestrict();
1455
1456 // We may not have applied the implicit const for a constexpr member
1457 // function yet (because we haven't yet resolved whether this is a static
1458 // or non-static member function). Add it now, on the assumption that this
1459 // is a redeclaration of OldMethod.
1460 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1461 (M->isConstexpr() || M->isConsteval()) &&
1462 !isa<CXXConstructorDecl>(NewMethod))
1463 Q.addConst();
1464 return Q;
1465 };
1466
1467 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1468 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1469 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1470
1471 if (OldMethod->isExplicitObjectMemberFunction()) {
1472 BS.Quals.removeVolatile();
1473 DS.Quals.removeVolatile();
1474 }
1475
1476 return BS.Quals == DS.Quals;
1477 };
1478
1479 auto CompareType = [&](QualType Base, QualType D) {
1480 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1481 auto DS = D.getNonReferenceType().getCanonicalType().split();
1482
1483 if (!AreQualifiersEqual(BS, DS))
1484 return false;
1485
1486 if (OldMethod->isImplicitObjectMemberFunction() &&
1487 OldMethod->getParent() != NewMethod->getParent()) {
1488 CanQualType ParentType =
1489 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1490 if (ParentType.getTypePtr() != BS.Ty)
1491 return false;
1492 BS.Ty = DS.Ty;
1493 }
1494
1495 // FIXME: should we ignore some type attributes here?
1496 if (BS.Ty != DS.Ty)
1497 return false;
1498
1499 if (Base->isLValueReferenceType())
1500 return D->isLValueReferenceType();
1501 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1502 };
1503
1504 // If the function is a class member, its signature includes the
1505 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1506 auto DiagnoseInconsistentRefQualifiers = [&]() {
1507 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1508 return false;
1509 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1510 return false;
1511 if (OldMethod->isExplicitObjectMemberFunction() ||
1512 NewMethod->isExplicitObjectMemberFunction())
1513 return false;
1514 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1515 NewMethod->getRefQualifier() == RQ_None)) {
1516 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1517 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1518 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1519 return true;
1520 }
1521 return false;
1522 };
1523
1524 // We look at the parameters first, as it is the common case.
1525 // However we should not emit diagnostic before checking
1526 // the overloads do not differ by constraints or other discriminant.
1527 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1528 bool HaveInconsistentQualifiers = false;
1529
1530 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1531 OldParamsOffset++;
1532 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1533 NewParamsOffset++;
1534
1535 if (OldType->getNumParams() - OldParamsOffset !=
1536 NewType->getNumParams() - NewParamsOffset ||
1538 {OldType->param_type_begin() + OldParamsOffset,
1539 OldType->param_type_end()},
1540 {NewType->param_type_begin() + NewParamsOffset,
1541 NewType->param_type_end()},
1542 nullptr)) {
1543 return true;
1544 }
1545
1546 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1547 !NewMethod->isStatic()) {
1548 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1549 const CXXMethodDecl *New) {
1550 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1551 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1552
1553 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1554 return F->getRefQualifier() == RQ_None &&
1555 !F->isExplicitObjectMemberFunction();
1556 };
1557
1558 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1559 CompareType(OldObjectType.getNonReferenceType(),
1560 NewObjectType.getNonReferenceType()))
1561 return true;
1562 return CompareType(OldObjectType, NewObjectType);
1563 }(OldMethod, NewMethod);
1564
1565 if (!HaveCorrespondingObjectParameters) {
1566 ShouldDiagnoseInconsistentRefQualifiers = true;
1567 // CWG2554
1568 // and, if at least one is an explicit object member function, ignoring
1569 // object parameters
1570 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1571 !OldMethod->isExplicitObjectMemberFunction()))
1572 HaveInconsistentQualifiers = true;
1573 }
1574 }
1575
1576 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1577 NewMethod->isImplicitObjectMemberFunction())
1578 ShouldDiagnoseInconsistentRefQualifiers = true;
1579
1580 if (!UseOverrideRules &&
1581 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1582 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1583 OldRC = Old->getTrailingRequiresClause();
1584 if (!NewRC != !OldRC)
1585 return true;
1586 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1587 return true;
1588 if (NewRC &&
1589 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1590 NewDecl, NewRC.ConstraintExpr))
1591 return true;
1592 }
1593
1594 // Though pass_object_size is placed on parameters and takes an argument, we
1595 // consider it to be a function-level modifier for the sake of function
1596 // identity. Either the function has one or more parameters with
1597 // pass_object_size or it doesn't.
1600 return true;
1601
1602 // enable_if attributes are an order-sensitive part of the signature.
1604 NewI = New->specific_attr_begin<EnableIfAttr>(),
1605 NewE = New->specific_attr_end<EnableIfAttr>(),
1606 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1607 OldE = Old->specific_attr_end<EnableIfAttr>();
1608 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1609 if (NewI == NewE || OldI == OldE)
1610 return true;
1611 llvm::FoldingSetNodeID NewID, OldID;
1612 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1613 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1614 if (NewID != OldID)
1615 return true;
1616 }
1617
1618 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1619 DiagnoseInconsistentRefQualifiers()) ||
1620 HaveInconsistentQualifiers)
1621 return true;
1622
1623 // At this point, it is known that the two functions have the same signature.
1624 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1625 // Don't allow overloading of destructors. (In theory we could, but it
1626 // would be a giant change to clang.)
1628 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1629 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1630 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1631 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1632 "Unexpected invalid target.");
1633
1634 // Allow overloading of functions with same signature and different CUDA
1635 // target attributes.
1636 if (NewTarget != OldTarget) {
1637 // Special case: non-constexpr function is allowed to override
1638 // constexpr virtual function
1639 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1640 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1645 return false;
1646 }
1647 return true;
1648 }
1649 }
1650 }
1651 }
1652
1653 // The signatures match; this is not an overload.
1654 return false;
1655}
1656
1658 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1659 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1660 ConsiderCudaAttrs);
1661}
1662
1664 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1665 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1666 /*UseMemberUsingDeclRules=*/false,
1667 /*ConsiderCudaAttrs=*/true,
1668 /*UseOverrideRules=*/true);
1669}
1670
1671/// Tries a user-defined conversion from From to ToType.
1672///
1673/// Produces an implicit conversion sequence for when a standard conversion
1674/// is not an option. See TryImplicitConversion for more information.
1677 bool SuppressUserConversions,
1678 AllowedExplicit AllowExplicit,
1679 bool InOverloadResolution,
1680 bool CStyle,
1681 bool AllowObjCWritebackConversion,
1682 bool AllowObjCConversionOnExplicit) {
1684
1685 if (SuppressUserConversions) {
1686 // We're not in the case above, so there is no conversion that
1687 // we can perform.
1689 return ICS;
1690 }
1691
1692 // Attempt user-defined conversion.
1693 OverloadCandidateSet Conversions(From->getExprLoc(),
1695 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1696 Conversions, AllowExplicit,
1697 AllowObjCConversionOnExplicit)) {
1698 case OR_Success:
1699 case OR_Deleted:
1700 ICS.setUserDefined();
1701 // C++ [over.ics.user]p4:
1702 // A conversion of an expression of class type to the same class
1703 // type is given Exact Match rank, and a conversion of an
1704 // expression of class type to a base class of that type is
1705 // given Conversion rank, in spite of the fact that a copy
1706 // constructor (i.e., a user-defined conversion function) is
1707 // called for those cases.
1709 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1710 QualType FromType;
1711 SourceLocation FromLoc;
1712 // C++11 [over.ics.list]p6, per DR2137:
1713 // C++17 [over.ics.list]p6:
1714 // If C is not an initializer-list constructor and the initializer list
1715 // has a single element of type cv U, where U is X or a class derived
1716 // from X, the implicit conversion sequence has Exact Match rank if U is
1717 // X, or Conversion rank if U is derived from X.
1718 bool FromListInit = false;
1719 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1720 InitList && InitList->getNumInits() == 1 &&
1722 const Expr *SingleInit = InitList->getInit(0);
1723 FromType = SingleInit->getType();
1724 FromLoc = SingleInit->getBeginLoc();
1725 FromListInit = true;
1726 } else {
1727 FromType = From->getType();
1728 FromLoc = From->getBeginLoc();
1729 }
1730 QualType FromCanon =
1732 QualType ToCanon
1734 if ((FromCanon == ToCanon ||
1735 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1736 // Turn this into a "standard" conversion sequence, so that it
1737 // gets ranked with standard conversion sequences.
1739 ICS.setStandard();
1741 ICS.Standard.setFromType(FromType);
1742 ICS.Standard.setAllToTypes(ToType);
1743 ICS.Standard.FromBracedInitList = FromListInit;
1746 if (ToCanon != FromCanon)
1748 }
1749 }
1750 break;
1751
1752 case OR_Ambiguous:
1753 ICS.setAmbiguous();
1754 ICS.Ambiguous.setFromType(From->getType());
1755 ICS.Ambiguous.setToType(ToType);
1756 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1757 Cand != Conversions.end(); ++Cand)
1758 if (Cand->Best)
1759 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1760 break;
1761
1762 // Fall through.
1765 break;
1766 }
1767
1768 return ICS;
1769}
1770
1771/// TryImplicitConversion - Attempt to perform an implicit conversion
1772/// from the given expression (Expr) to the given type (ToType). This
1773/// function returns an implicit conversion sequence that can be used
1774/// to perform the initialization. Given
1775///
1776/// void f(float f);
1777/// void g(int i) { f(i); }
1778///
1779/// this routine would produce an implicit conversion sequence to
1780/// describe the initialization of f from i, which will be a standard
1781/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1782/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1783//
1784/// Note that this routine only determines how the conversion can be
1785/// performed; it does not actually perform the conversion. As such,
1786/// it will not produce any diagnostics if no conversion is available,
1787/// but will instead return an implicit conversion sequence of kind
1788/// "BadConversion".
1789///
1790/// If @p SuppressUserConversions, then user-defined conversions are
1791/// not permitted.
1792/// If @p AllowExplicit, then explicit user-defined conversions are
1793/// permitted.
1794///
1795/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1796/// writeback conversion, which allows __autoreleasing id* parameters to
1797/// be initialized with __strong id* or __weak id* arguments.
1798static ImplicitConversionSequence
1800 bool SuppressUserConversions,
1801 AllowedExplicit AllowExplicit,
1802 bool InOverloadResolution,
1803 bool CStyle,
1804 bool AllowObjCWritebackConversion,
1805 bool AllowObjCConversionOnExplicit) {
1807 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1808 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1809 ICS.setStandard();
1810 return ICS;
1811 }
1812
1813 if (!S.getLangOpts().CPlusPlus) {
1815 return ICS;
1816 }
1817
1818 // C++ [over.ics.user]p4:
1819 // A conversion of an expression of class type to the same class
1820 // type is given Exact Match rank, and a conversion of an
1821 // expression of class type to a base class of that type is
1822 // given Conversion rank, in spite of the fact that a copy/move
1823 // constructor (i.e., a user-defined conversion function) is
1824 // called for those cases.
1825 QualType FromType = From->getType();
1826 if (ToType->isRecordType() &&
1827 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1828 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1829 ICS.setStandard();
1831 ICS.Standard.setFromType(FromType);
1832 ICS.Standard.setAllToTypes(ToType);
1833
1834 // We don't actually check at this point whether there is a valid
1835 // copy/move constructor, since overloading just assumes that it
1836 // exists. When we actually perform initialization, we'll find the
1837 // appropriate constructor to copy the returned object, if needed.
1838 ICS.Standard.CopyConstructor = nullptr;
1839
1840 // Determine whether this is considered a derived-to-base conversion.
1841 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1843
1844 return ICS;
1845 }
1846
1847 if (S.getLangOpts().HLSL) {
1848 // Handle conversion of the HLSL resource types.
1849 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1850 if (FromTy->isHLSLAttributedResourceType()) {
1851 // Attributed resource types can convert to other attributed
1852 // resource types with the same attributes and contained types,
1853 // or to __hlsl_resource_t without any attributes.
1854 bool CanConvert = false;
1855 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1856 if (ToTy->isHLSLAttributedResourceType()) {
1857 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1858 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1859 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1860 FromResType->getWrappedType()) &&
1861 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1862 FromResType->getContainedType()) &&
1863 ToResType->getAttrs() == FromResType->getAttrs())
1864 CanConvert = true;
1865 } else if (ToTy->isHLSLResourceType()) {
1866 CanConvert = true;
1867 }
1868 if (CanConvert) {
1869 ICS.setStandard();
1871 ICS.Standard.setFromType(FromType);
1872 ICS.Standard.setAllToTypes(ToType);
1873 return ICS;
1874 }
1875 }
1876 }
1877
1878 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1879 AllowExplicit, InOverloadResolution, CStyle,
1880 AllowObjCWritebackConversion,
1881 AllowObjCConversionOnExplicit);
1882}
1883
1884ImplicitConversionSequence
1886 bool SuppressUserConversions,
1887 AllowedExplicit AllowExplicit,
1888 bool InOverloadResolution,
1889 bool CStyle,
1890 bool AllowObjCWritebackConversion) {
1891 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1892 AllowExplicit, InOverloadResolution, CStyle,
1893 AllowObjCWritebackConversion,
1894 /*AllowObjCConversionOnExplicit=*/false);
1895}
1896
1898 AssignmentAction Action,
1899 bool AllowExplicit) {
1900 if (checkPlaceholderForOverload(*this, From))
1901 return ExprError();
1902
1903 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1904 bool AllowObjCWritebackConversion =
1905 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1906 Action == AssignmentAction::Sending);
1907 if (getLangOpts().ObjC)
1908 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1909 From->getType(), From);
1911 *this, From, ToType,
1912 /*SuppressUserConversions=*/false,
1913 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1914 /*InOverloadResolution=*/false,
1915 /*CStyle=*/false, AllowObjCWritebackConversion,
1916 /*AllowObjCConversionOnExplicit=*/false);
1917 return PerformImplicitConversion(From, ToType, ICS, Action);
1918}
1919
1921 QualType &ResultTy) const {
1922 bool Changed = IsFunctionConversion(FromType, ToType);
1923 if (Changed)
1924 ResultTy = ToType;
1925 return Changed;
1926}
1927
1928bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1929 if (Context.hasSameUnqualifiedType(FromType, ToType))
1930 return false;
1931
1932 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1933 // or F(t noexcept) -> F(t)
1934 // where F adds one of the following at most once:
1935 // - a pointer
1936 // - a member pointer
1937 // - a block pointer
1938 // Changes here need matching changes in FindCompositePointerType.
1939 CanQualType CanTo = Context.getCanonicalType(ToType);
1940 CanQualType CanFrom = Context.getCanonicalType(FromType);
1941 Type::TypeClass TyClass = CanTo->getTypeClass();
1942 if (TyClass != CanFrom->getTypeClass()) return false;
1943 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1944 if (TyClass == Type::Pointer) {
1945 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1946 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1947 } else if (TyClass == Type::BlockPointer) {
1948 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1949 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1950 } else if (TyClass == Type::MemberPointer) {
1951 auto ToMPT = CanTo.castAs<MemberPointerType>();
1952 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1953 // A function pointer conversion cannot change the class of the function.
1954 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1955 FromMPT->getMostRecentCXXRecordDecl()))
1956 return false;
1957 CanTo = ToMPT->getPointeeType();
1958 CanFrom = FromMPT->getPointeeType();
1959 } else {
1960 return false;
1961 }
1962
1963 TyClass = CanTo->getTypeClass();
1964 if (TyClass != CanFrom->getTypeClass()) return false;
1965 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1966 return false;
1967 }
1968
1969 const auto *FromFn = cast<FunctionType>(CanFrom);
1970 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1971
1972 const auto *ToFn = cast<FunctionType>(CanTo);
1973 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1974
1975 bool Changed = false;
1976
1977 // Drop 'noreturn' if not present in target type.
1978 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1979 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1980 Changed = true;
1981 }
1982
1983 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1984 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1985
1986 if (FromFPT && ToFPT) {
1987 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1988 QualType NewTy = Context.getFunctionType(
1989 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1990 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1991 ToFPT->hasCFIUncheckedCallee()));
1992 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1993 FromFn = FromFPT;
1994 Changed = true;
1995 }
1996 }
1997
1998 // Drop 'noexcept' if not present in target type.
1999 if (FromFPT && ToFPT) {
2000 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2001 FromFn = cast<FunctionType>(
2002 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2003 EST_None)
2004 .getTypePtr());
2005 Changed = true;
2006 }
2007
2008 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2009 // only if the ExtParameterInfo lists of the two function prototypes can be
2010 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2012 bool CanUseToFPT, CanUseFromFPT;
2013 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2014 CanUseFromFPT, NewParamInfos) &&
2015 CanUseToFPT && !CanUseFromFPT) {
2016 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2017 ExtInfo.ExtParameterInfos =
2018 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2019 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2020 FromFPT->getParamTypes(), ExtInfo);
2021 FromFn = QT->getAs<FunctionType>();
2022 Changed = true;
2023 }
2024
2025 if (Context.hasAnyFunctionEffects()) {
2026 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2027
2028 // Transparently add/drop effects; here we are concerned with
2029 // language rules/canonicalization. Adding/dropping effects is a warning.
2030 const auto FromFX = FromFPT->getFunctionEffects();
2031 const auto ToFX = ToFPT->getFunctionEffects();
2032 if (FromFX != ToFX) {
2033 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2034 ExtInfo.FunctionEffects = ToFX;
2035 QualType QT = Context.getFunctionType(
2036 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2037 FromFn = QT->getAs<FunctionType>();
2038 Changed = true;
2039 }
2040 }
2041 }
2042
2043 if (!Changed)
2044 return false;
2045
2046 assert(QualType(FromFn, 0).isCanonical());
2047 if (QualType(FromFn, 0) != CanTo) return false;
2048
2049 return true;
2050}
2051
2052/// Determine whether the conversion from FromType to ToType is a valid
2053/// floating point conversion.
2054///
2055static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2056 QualType ToType) {
2057 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2058 return false;
2059 // FIXME: disable conversions between long double, __ibm128 and __float128
2060 // if their representation is different until there is back end support
2061 // We of course allow this conversion if long double is really double.
2062
2063 // Conversions between bfloat16 and float16 are currently not supported.
2064 if ((FromType->isBFloat16Type() &&
2065 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2066 (ToType->isBFloat16Type() &&
2067 (FromType->isFloat16Type() || FromType->isHalfType())))
2068 return false;
2069
2070 // Conversions between IEEE-quad and IBM-extended semantics are not
2071 // permitted.
2072 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2073 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2074 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2075 &ToSem == &llvm::APFloat::IEEEquad()) ||
2076 (&FromSem == &llvm::APFloat::IEEEquad() &&
2077 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2078 return false;
2079 return true;
2080}
2081
2083 QualType ToType,
2085 Expr *From) {
2086 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2087 return true;
2088
2089 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2091 return true;
2092 }
2093
2094 if (IsFloatingPointConversion(S, FromType, ToType)) {
2096 return true;
2097 }
2098
2099 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2101 return true;
2102 }
2103
2104 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2106 ToType->isRealFloatingType())) {
2108 return true;
2109 }
2110
2111 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2113 return true;
2114 }
2115
2116 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2117 ToType->isIntegralType(S.Context)) {
2119 return true;
2120 }
2121
2122 return false;
2123}
2124
2125/// Determine whether the conversion from FromType to ToType is a valid
2126/// matrix conversion.
2127///
2128/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2129/// conversion.
2130static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2132 ImplicitConversionKind &ElConv, Expr *From,
2133 bool InOverloadResolution, bool CStyle) {
2134 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2135 if (!S.getLangOpts().HLSL)
2136 return false;
2137
2138 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2139 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2140
2141 // If both arguments are matrix, handle possible matrix truncation and
2142 // element conversion.
2143 if (ToMatrixType && FromMatrixType) {
2144 unsigned FromCols = FromMatrixType->getNumColumns();
2145 unsigned ToCols = ToMatrixType->getNumColumns();
2146 if (FromCols < ToCols)
2147 return false;
2148
2149 unsigned FromRows = FromMatrixType->getNumRows();
2150 unsigned ToRows = ToMatrixType->getNumRows();
2151 if (FromRows < ToRows)
2152 return false;
2153
2154 if (FromRows == ToRows && FromCols == ToCols)
2155 ElConv = ICK_Identity;
2156 else
2158
2159 QualType FromElTy = FromMatrixType->getElementType();
2160 QualType ToElTy = ToMatrixType->getElementType();
2161 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2162 return true;
2163 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2164 }
2165
2166 // Matrix splat from any arithmetic type to a matrix.
2167 if (ToMatrixType && FromType->isArithmeticType()) {
2168 ElConv = ICK_HLSL_Matrix_Splat;
2169 QualType ToElTy = ToMatrixType->getElementType();
2170 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2171 }
2172 if (FromMatrixType && !ToMatrixType) {
2174 QualType FromElTy = FromMatrixType->getElementType();
2175 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2176 return true;
2177 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2178 }
2179
2180 return false;
2181}
2182
2183/// Determine whether the conversion from FromType to ToType is a valid
2184/// vector conversion.
2185///
2186/// \param ICK Will be set to the vector conversion kind, if this is a vector
2187/// conversion.
2188static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2190 ImplicitConversionKind &ElConv, Expr *From,
2191 bool InOverloadResolution, bool CStyle) {
2192 // We need at least one of these types to be a vector type to have a vector
2193 // conversion.
2194 if (!ToType->isVectorType() && !FromType->isVectorType())
2195 return false;
2196
2197 // Identical types require no conversions.
2198 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2199 return false;
2200
2201 // HLSL allows implicit truncation of vector types.
2202 if (S.getLangOpts().HLSL) {
2203 auto *ToExtType = ToType->getAs<ExtVectorType>();
2204 auto *FromExtType = FromType->getAs<ExtVectorType>();
2205
2206 // If both arguments are vectors, handle possible vector truncation and
2207 // element conversion.
2208 if (ToExtType && FromExtType) {
2209 unsigned FromElts = FromExtType->getNumElements();
2210 unsigned ToElts = ToExtType->getNumElements();
2211 if (FromElts < ToElts)
2212 return false;
2213 if (FromElts == ToElts)
2214 ElConv = ICK_Identity;
2215 else
2217
2218 QualType FromElTy = FromExtType->getElementType();
2219 QualType ToElTy = ToExtType->getElementType();
2220 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2221 return true;
2222 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2223 }
2224 if (FromExtType && !ToExtType) {
2226 QualType FromElTy = FromExtType->getElementType();
2227 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2228 return true;
2229 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2230 }
2231 // Fallthrough for the case where ToType is a vector and FromType is not.
2232 }
2233
2234 // There are no conversions between extended vector types, only identity.
2235 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2236 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2237 // Implicit conversions require the same number of elements.
2238 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2239 return false;
2240
2241 // Permit implicit conversions from integral values to boolean vectors.
2242 if (ToType->isExtVectorBoolType() &&
2243 FromExtType->getElementType()->isIntegerType()) {
2245 return true;
2246 }
2247 // There are no other conversions between extended vector types.
2248 return false;
2249 }
2250
2251 // Vector splat from any arithmetic type to a vector.
2252 if (FromType->isArithmeticType()) {
2253 if (S.getLangOpts().HLSL) {
2254 ElConv = ICK_HLSL_Vector_Splat;
2255 QualType ToElTy = ToExtType->getElementType();
2256 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2257 From);
2258 }
2259 ICK = ICK_Vector_Splat;
2260 return true;
2261 }
2262 }
2263
2264 if (ToType->isSVESizelessBuiltinType() ||
2265 FromType->isSVESizelessBuiltinType())
2266 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2267 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2269 return true;
2270 }
2271
2272 if (ToType->isRVVSizelessBuiltinType() ||
2273 FromType->isRVVSizelessBuiltinType())
2274 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2275 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2277 return true;
2278 }
2279
2280 // We can perform the conversion between vector types in the following cases:
2281 // 1)vector types are equivalent AltiVec and GCC vector types
2282 // 2)lax vector conversions are permitted and the vector types are of the
2283 // same size
2284 // 3)the destination type does not have the ARM MVE strict-polymorphism
2285 // attribute, which inhibits lax vector conversion for overload resolution
2286 // only
2287 if (ToType->isVectorType() && FromType->isVectorType()) {
2288 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2289 (S.isLaxVectorConversion(FromType, ToType) &&
2290 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2291 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2292 S.isLaxVectorConversion(FromType, ToType) &&
2293 S.anyAltivecTypes(FromType, ToType) &&
2294 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2295 !InOverloadResolution && !CStyle) {
2296 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2297 << FromType << ToType;
2298 }
2300 return true;
2301 }
2302 }
2303
2304 return false;
2305}
2306
2307static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2308 bool InOverloadResolution,
2309 StandardConversionSequence &SCS,
2310 bool CStyle);
2311
2312static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2313 QualType ToType,
2314 bool InOverloadResolution,
2315 StandardConversionSequence &SCS,
2316 bool CStyle);
2317
2318/// IsStandardConversion - Determines whether there is a standard
2319/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2320/// expression From to the type ToType. Standard conversion sequences
2321/// only consider non-class types; for conversions that involve class
2322/// types, use TryImplicitConversion. If a conversion exists, SCS will
2323/// contain the standard conversion sequence required to perform this
2324/// conversion and this routine will return true. Otherwise, this
2325/// routine will return false and the value of SCS is unspecified.
2326static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2327 bool InOverloadResolution,
2329 bool CStyle,
2330 bool AllowObjCWritebackConversion) {
2331 QualType FromType = From->getType();
2332
2333 // Standard conversions (C++ [conv])
2335 SCS.IncompatibleObjC = false;
2336 SCS.setFromType(FromType);
2337 SCS.CopyConstructor = nullptr;
2338
2339 // There are no standard conversions for class types in C++, so
2340 // abort early. When overloading in C, however, we do permit them.
2341 if (S.getLangOpts().CPlusPlus &&
2342 (FromType->isRecordType() || ToType->isRecordType()))
2343 return false;
2344
2345 // The first conversion can be an lvalue-to-rvalue conversion,
2346 // array-to-pointer conversion, or function-to-pointer conversion
2347 // (C++ 4p1).
2348
2349 if (FromType == S.Context.OverloadTy) {
2350 DeclAccessPair AccessPair;
2351 if (FunctionDecl *Fn
2352 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2353 AccessPair)) {
2354 // We were able to resolve the address of the overloaded function,
2355 // so we can convert to the type of that function.
2356 FromType = Fn->getType();
2357 SCS.setFromType(FromType);
2358
2359 // we can sometimes resolve &foo<int> regardless of ToType, so check
2360 // if the type matches (identity) or we are converting to bool
2362 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2363 // if the function type matches except for [[noreturn]], it's ok
2364 if (!S.IsFunctionConversion(FromType,
2366 // otherwise, only a boolean conversion is standard
2367 if (!ToType->isBooleanType())
2368 return false;
2369 }
2370
2371 // Check if the "from" expression is taking the address of an overloaded
2372 // function and recompute the FromType accordingly. Take advantage of the
2373 // fact that non-static member functions *must* have such an address-of
2374 // expression.
2375 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2376 if (Method && !Method->isStatic() &&
2377 !Method->isExplicitObjectMemberFunction()) {
2378 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2379 "Non-unary operator on non-static member address");
2380 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2381 == UO_AddrOf &&
2382 "Non-address-of operator on non-static member address");
2383 FromType = S.Context.getMemberPointerType(
2384 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2385 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2386 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2387 UO_AddrOf &&
2388 "Non-address-of operator for overloaded function expression");
2389 FromType = S.Context.getPointerType(FromType);
2390 }
2391 } else {
2392 return false;
2393 }
2394 }
2395
2396 bool argIsLValue = From->isGLValue();
2397 // To handle conversion from ArrayParameterType to ConstantArrayType
2398 // this block must be above the one below because Array parameters
2399 // do not decay and when handling HLSLOutArgExprs and
2400 // the From expression is an LValue.
2401 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2402 ToType->isConstantArrayType()) {
2403 // HLSL constant array parameters do not decay, so if the argument is a
2404 // constant array and the parameter is an ArrayParameterType we have special
2405 // handling here.
2406 if (ToType->isArrayParameterType()) {
2407 FromType = S.Context.getArrayParameterType(FromType);
2408 } else if (FromType->isArrayParameterType()) {
2409 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2410 FromType = APT->getConstantArrayType(S.Context);
2411 }
2412
2414
2415 // Don't consider qualifiers, which include things like address spaces
2416 if (FromType.getCanonicalType().getUnqualifiedType() !=
2418 return false;
2419
2420 SCS.setAllToTypes(ToType);
2421 return true;
2422 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2423 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2424 // Lvalue-to-rvalue conversion (C++11 4.1):
2425 // A glvalue (3.10) of a non-function, non-array type T can
2426 // be converted to a prvalue.
2427
2429
2430 // C11 6.3.2.1p2:
2431 // ... if the lvalue has atomic type, the value has the non-atomic version
2432 // of the type of the lvalue ...
2433 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2434 FromType = Atomic->getValueType();
2435
2436 // If T is a non-class type, the type of the rvalue is the
2437 // cv-unqualified version of T. Otherwise, the type of the rvalue
2438 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2439 // just strip the qualifiers because they don't matter.
2440 FromType = FromType.getUnqualifiedType();
2441 } else if (FromType->isArrayType()) {
2442 // Array-to-pointer conversion (C++ 4.2)
2444
2445 // An lvalue or rvalue of type "array of N T" or "array of unknown
2446 // bound of T" can be converted to an rvalue of type "pointer to
2447 // T" (C++ 4.2p1).
2448 FromType = S.Context.getArrayDecayedType(FromType);
2449
2450 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2451 // This conversion is deprecated in C++03 (D.4)
2453
2454 // For the purpose of ranking in overload resolution
2455 // (13.3.3.1.1), this conversion is considered an
2456 // array-to-pointer conversion followed by a qualification
2457 // conversion (4.4). (C++ 4.2p2)
2458 SCS.Second = ICK_Identity;
2461 SCS.setAllToTypes(FromType);
2462 return true;
2463 }
2464 } else if (FromType->isFunctionType() && argIsLValue) {
2465 // Function-to-pointer conversion (C++ 4.3).
2467
2468 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2469 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2471 return false;
2472
2473 // An lvalue of function type T can be converted to an rvalue of
2474 // type "pointer to T." The result is a pointer to the
2475 // function. (C++ 4.3p1).
2476 FromType = S.Context.getPointerType(FromType);
2477 } else {
2478 // We don't require any conversions for the first step.
2479 SCS.First = ICK_Identity;
2480 }
2481 SCS.setToType(0, FromType);
2482
2483 // The second conversion can be an integral promotion, floating
2484 // point promotion, integral conversion, floating point conversion,
2485 // floating-integral conversion, pointer conversion,
2486 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2487 // For overloading in C, this can also be a "compatible-type"
2488 // conversion.
2489 bool IncompatibleObjC = false;
2491 ImplicitConversionKind DimensionICK = ICK_Identity;
2492 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2493 // The unqualified versions of the types are the same: there's no
2494 // conversion to do.
2495 SCS.Second = ICK_Identity;
2496 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2497 // Integral promotion (C++ 4.5).
2499 FromType = ToType.getUnqualifiedType();
2500 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2501 // Floating point promotion (C++ 4.6).
2503 FromType = ToType.getUnqualifiedType();
2504 } else if (S.IsComplexPromotion(FromType, ToType)) {
2505 // Complex promotion (Clang extension)
2507 FromType = ToType.getUnqualifiedType();
2508 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2509 // OverflowBehaviorType promotions
2511 FromType = ToType.getUnqualifiedType();
2512 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2513 // OverflowBehaviorType conversions
2515 FromType = ToType.getUnqualifiedType();
2516 } else if (ToType->isBooleanType() &&
2517 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2518 FromType->isBlockPointerType() ||
2519 FromType->isMemberPointerType())) {
2520 // Boolean conversions (C++ 4.12).
2522 FromType = S.Context.BoolTy;
2523 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2524 ToType->isIntegralType(S.Context)) {
2525 // Integral conversions (C++ 4.7).
2527 FromType = ToType.getUnqualifiedType();
2528 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2529 // Complex conversions (C99 6.3.1.6)
2531 FromType = ToType.getUnqualifiedType();
2532 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2533 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2534 // Complex-real conversions (C99 6.3.1.7)
2536 FromType = ToType.getUnqualifiedType();
2537 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2538 // Floating point conversions (C++ 4.8).
2540 FromType = ToType.getUnqualifiedType();
2541 } else if ((FromType->isRealFloatingType() &&
2542 ToType->isIntegralType(S.Context)) ||
2544 ToType->isRealFloatingType())) {
2545
2546 // Floating-integral conversions (C++ 4.9).
2548 FromType = ToType.getUnqualifiedType();
2549 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2551 } else if (AllowObjCWritebackConversion &&
2552 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2554 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2555 FromType, IncompatibleObjC)) {
2556 // Pointer conversions (C++ 4.10).
2558 SCS.IncompatibleObjC = IncompatibleObjC;
2559 FromType = FromType.getUnqualifiedType();
2560 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2561 InOverloadResolution, FromType)) {
2562 // Pointer to member conversions (4.11).
2564 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2565 From, InOverloadResolution, CStyle)) {
2566 SCS.Second = SecondICK;
2567 SCS.Dimension = DimensionICK;
2568 FromType = ToType.getUnqualifiedType();
2569 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2570 From, InOverloadResolution, CStyle)) {
2571 SCS.Second = SecondICK;
2572 SCS.Dimension = DimensionICK;
2573 FromType = ToType.getUnqualifiedType();
2574 } else if (!S.getLangOpts().CPlusPlus &&
2575 S.Context.typesAreCompatible(ToType, FromType)) {
2576 // Compatible conversions (Clang extension for C function overloading)
2578 FromType = ToType.getUnqualifiedType();
2580 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2582 FromType = ToType;
2583 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2584 CStyle)) {
2585 // tryAtomicConversion has updated the standard conversion sequence
2586 // appropriately.
2587 return true;
2589 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2590 return true;
2591 } else if (ToType->isEventT() &&
2593 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2595 FromType = ToType;
2596 } else if (ToType->isQueueT() &&
2598 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2600 FromType = ToType;
2601 } else if (ToType->isSamplerT() &&
2604 FromType = ToType;
2605 } else if ((ToType->isFixedPointType() &&
2606 FromType->isConvertibleToFixedPointType()) ||
2607 (FromType->isFixedPointType() &&
2608 ToType->isConvertibleToFixedPointType())) {
2610 FromType = ToType;
2611 } else {
2612 // No second conversion required.
2613 SCS.Second = ICK_Identity;
2614 }
2615 SCS.setToType(1, FromType);
2616
2617 // The third conversion can be a function pointer conversion or a
2618 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2619 bool ObjCLifetimeConversion;
2620 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2621 // Function pointer conversions (removing 'noexcept') including removal of
2622 // 'noreturn' (Clang extension).
2624 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2625 ObjCLifetimeConversion)) {
2627 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2628 FromType = ToType;
2629 } else {
2630 // No conversion required
2631 SCS.Third = ICK_Identity;
2632 }
2633
2634 // C++ [over.best.ics]p6:
2635 // [...] Any difference in top-level cv-qualification is
2636 // subsumed by the initialization itself and does not constitute
2637 // a conversion. [...]
2638 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2639 QualType CanonTo = S.Context.getCanonicalType(ToType);
2640 if (CanonFrom.getLocalUnqualifiedType()
2641 == CanonTo.getLocalUnqualifiedType() &&
2642 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2643 FromType = ToType;
2644 CanonFrom = CanonTo;
2645 }
2646
2647 SCS.setToType(2, FromType);
2648
2649 if (CanonFrom == CanonTo)
2650 return true;
2651
2652 // If we have not converted the argument type to the parameter type,
2653 // this is a bad conversion sequence, unless we're resolving an overload in C.
2654 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2655 return false;
2656
2657 ExprResult ER = ExprResult{From};
2658 AssignConvertType Conv =
2660 /*Diagnose=*/false,
2661 /*DiagnoseCFAudited=*/false,
2662 /*ConvertRHS=*/false);
2663 ImplicitConversionKind SecondConv;
2664 switch (Conv) {
2666 case AssignConvertType::
2667 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2668 SecondConv = ICK_C_Only_Conversion;
2669 break;
2670 // For our purposes, discarding qualifiers is just as bad as using an
2671 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2672 // qualifiers, as well.
2677 break;
2678 default:
2679 return false;
2680 }
2681
2682 // First can only be an lvalue conversion, so we pretend that this was the
2683 // second conversion. First should already be valid from earlier in the
2684 // function.
2685 SCS.Second = SecondConv;
2686 SCS.setToType(1, ToType);
2687
2688 // Third is Identity, because Second should rank us worse than any other
2689 // conversion. This could also be ICK_Qualification, but it's simpler to just
2690 // lump everything in with the second conversion, and we don't gain anything
2691 // from making this ICK_Qualification.
2692 SCS.Third = ICK_Identity;
2693 SCS.setToType(2, ToType);
2694 return true;
2695}
2696
2697static bool
2699 QualType &ToType,
2700 bool InOverloadResolution,
2702 bool CStyle) {
2703
2704 const RecordType *UT = ToType->getAsUnionType();
2705 if (!UT)
2706 return false;
2707 // The field to initialize within the transparent union.
2708 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2709 if (!UD->hasAttr<TransparentUnionAttr>())
2710 return false;
2711 // It's compatible if the expression matches any of the fields.
2712 for (const auto *it : UD->fields()) {
2713 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2714 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2715 ToType = it->getType();
2716 return true;
2717 }
2718 }
2719 return false;
2720}
2721
2722bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2723 const BuiltinType *To = ToType->getAs<BuiltinType>();
2724 // All integers are built-in.
2725 if (!To) {
2726 return false;
2727 }
2728
2729 // An rvalue of type char, signed char, unsigned char, short int, or
2730 // unsigned short int can be converted to an rvalue of type int if
2731 // int can represent all the values of the source type; otherwise,
2732 // the source rvalue can be converted to an rvalue of type unsigned
2733 // int (C++ 4.5p1).
2734 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2735 !FromType->isEnumeralType()) {
2736 if ( // We can promote any signed, promotable integer type to an int
2737 (FromType->isSignedIntegerType() ||
2738 // We can promote any unsigned integer type whose size is
2739 // less than int to an int.
2740 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2741 return To->getKind() == BuiltinType::Int;
2742 }
2743
2744 return To->getKind() == BuiltinType::UInt;
2745 }
2746
2747 // C++11 [conv.prom]p3:
2748 // A prvalue of an unscoped enumeration type whose underlying type is not
2749 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2750 // following types that can represent all the values of the enumeration
2751 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2752 // unsigned int, long int, unsigned long int, long long int, or unsigned
2753 // long long int. If none of the types in that list can represent all the
2754 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2755 // type can be converted to an rvalue a prvalue of the extended integer type
2756 // with lowest integer conversion rank (4.13) greater than the rank of long
2757 // long in which all the values of the enumeration can be represented. If
2758 // there are two such extended types, the signed one is chosen.
2759 // C++11 [conv.prom]p4:
2760 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2761 // can be converted to a prvalue of its underlying type. Moreover, if
2762 // integral promotion can be applied to its underlying type, a prvalue of an
2763 // unscoped enumeration type whose underlying type is fixed can also be
2764 // converted to a prvalue of the promoted underlying type.
2765 if (const auto *FromED = FromType->getAsEnumDecl()) {
2766 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2767 // provided for a scoped enumeration.
2768 if (FromED->isScoped())
2769 return false;
2770
2771 // We can perform an integral promotion to the underlying type of the enum,
2772 // even if that's not the promoted type. Note that the check for promoting
2773 // the underlying type is based on the type alone, and does not consider
2774 // the bitfield-ness of the actual source expression.
2775 if (FromED->isFixed()) {
2776 QualType Underlying = FromED->getIntegerType();
2777 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2778 IsIntegralPromotion(nullptr, Underlying, ToType);
2779 }
2780
2781 // We have already pre-calculated the promotion type, so this is trivial.
2782 if (ToType->isIntegerType() &&
2783 isCompleteType(From->getBeginLoc(), FromType))
2784 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2785
2786 // C++ [conv.prom]p5:
2787 // If the bit-field has an enumerated type, it is treated as any other
2788 // value of that type for promotion purposes.
2789 //
2790 // ... so do not fall through into the bit-field checks below in C++.
2791 if (getLangOpts().CPlusPlus)
2792 return false;
2793 }
2794
2795 // C++0x [conv.prom]p2:
2796 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2797 // to an rvalue a prvalue of the first of the following types that can
2798 // represent all the values of its underlying type: int, unsigned int,
2799 // long int, unsigned long int, long long int, or unsigned long long int.
2800 // If none of the types in that list can represent all the values of its
2801 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2802 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2803 // type.
2804 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2805 ToType->isIntegerType()) {
2806 // Determine whether the type we're converting from is signed or
2807 // unsigned.
2808 bool FromIsSigned = FromType->isSignedIntegerType();
2809 uint64_t FromSize = Context.getTypeSize(FromType);
2810
2811 // The types we'll try to promote to, in the appropriate
2812 // order. Try each of these types.
2813 QualType PromoteTypes[6] = {
2814 Context.IntTy, Context.UnsignedIntTy,
2815 Context.LongTy, Context.UnsignedLongTy ,
2816 Context.LongLongTy, Context.UnsignedLongLongTy
2817 };
2818 for (int Idx = 0; Idx < 6; ++Idx) {
2819 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2820 if (FromSize < ToSize ||
2821 (FromSize == ToSize &&
2822 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2823 // We found the type that we can promote to. If this is the
2824 // type we wanted, we have a promotion. Otherwise, no
2825 // promotion.
2826 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2827 }
2828 }
2829 }
2830
2831 // An rvalue for an integral bit-field (9.6) can be converted to an
2832 // rvalue of type int if int can represent all the values of the
2833 // bit-field; otherwise, it can be converted to unsigned int if
2834 // unsigned int can represent all the values of the bit-field. If
2835 // the bit-field is larger yet, no integral promotion applies to
2836 // it. If the bit-field has an enumerated type, it is treated as any
2837 // other value of that type for promotion purposes (C++ 4.5p3).
2838 // FIXME: We should delay checking of bit-fields until we actually perform the
2839 // conversion.
2840 //
2841 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2842 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2843 // bit-fields and those whose underlying type is larger than int) for GCC
2844 // compatibility.
2845 if (From) {
2846 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2847 std::optional<llvm::APSInt> BitWidth;
2848 if (FromType->isIntegralType(Context) &&
2849 (BitWidth =
2850 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2851 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2852 ToSize = Context.getTypeSize(ToType);
2853
2854 // Are we promoting to an int from a bitfield that fits in an int?
2855 if (*BitWidth < ToSize ||
2856 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2857 return To->getKind() == BuiltinType::Int;
2858 }
2859
2860 // Are we promoting to an unsigned int from an unsigned bitfield
2861 // that fits into an unsigned int?
2862 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2863 return To->getKind() == BuiltinType::UInt;
2864 }
2865
2866 return false;
2867 }
2868 }
2869 }
2870
2871 // An rvalue of type bool can be converted to an rvalue of type int,
2872 // with false becoming zero and true becoming one (C++ 4.5p4).
2873 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2874 return true;
2875 }
2876
2877 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2878 // integral type.
2879 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2880 ToType->isIntegerType())
2881 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2882
2883 return false;
2884}
2885
2887 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2888 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2889 /// An rvalue of type float can be converted to an rvalue of type
2890 /// double. (C++ 4.6p1).
2891 if (FromBuiltin->getKind() == BuiltinType::Float &&
2892 ToBuiltin->getKind() == BuiltinType::Double)
2893 return true;
2894
2895 // C99 6.3.1.5p1:
2896 // When a float is promoted to double or long double, or a
2897 // double is promoted to long double [...].
2898 if (!getLangOpts().CPlusPlus &&
2899 (FromBuiltin->getKind() == BuiltinType::Float ||
2900 FromBuiltin->getKind() == BuiltinType::Double) &&
2901 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2902 ToBuiltin->getKind() == BuiltinType::Float128 ||
2903 ToBuiltin->getKind() == BuiltinType::Ibm128))
2904 return true;
2905
2906 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2907 // or not native half types are enabled.
2908 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2909 (ToBuiltin->getKind() == BuiltinType::Float ||
2910 ToBuiltin->getKind() == BuiltinType::Double))
2911 return true;
2912
2913 // Half can be promoted to float.
2914 if (!getLangOpts().NativeHalfType &&
2915 FromBuiltin->getKind() == BuiltinType::Half &&
2916 ToBuiltin->getKind() == BuiltinType::Float)
2917 return true;
2918 }
2919
2920 return false;
2921}
2922
2924 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2925 if (!FromComplex)
2926 return false;
2927
2928 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2929 if (!ToComplex)
2930 return false;
2931
2932 return IsFloatingPointPromotion(FromComplex->getElementType(),
2933 ToComplex->getElementType()) ||
2934 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2935 ToComplex->getElementType());
2936}
2937
2939 if (!getLangOpts().OverflowBehaviorTypes)
2940 return false;
2941
2942 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2943 return false;
2944
2945 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2946}
2947
2949 QualType ToType) {
2950 if (!getLangOpts().OverflowBehaviorTypes)
2951 return false;
2952
2953 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2954 if (ToType->isBooleanType())
2955 return false;
2956 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2957 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2958 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2959 if (ToED->isScoped())
2960 return false;
2961 }
2962 return true;
2963 }
2964
2965 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2966 return true;
2967
2968 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2969 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2970
2971 return false;
2972}
2973
2974/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2975/// the pointer type FromPtr to a pointer to type ToPointee, with the
2976/// same type qualifiers as FromPtr has on its pointee type. ToType,
2977/// if non-empty, will be a pointer to ToType that may or may not have
2978/// the right set of qualifiers on its pointee.
2979///
2980static QualType
2982 QualType ToPointee, QualType ToType,
2983 ASTContext &Context,
2984 bool StripObjCLifetime = false) {
2985 assert((FromPtr->getTypeClass() == Type::Pointer ||
2986 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2987 "Invalid similarly-qualified pointer type");
2988
2989 /// Conversions to 'id' subsume cv-qualifier conversions.
2990 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2991 return ToType.getUnqualifiedType();
2992
2993 QualType CanonFromPointee
2994 = Context.getCanonicalType(FromPtr->getPointeeType());
2995 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2996 Qualifiers Quals = CanonFromPointee.getQualifiers();
2997
2998 if (StripObjCLifetime)
2999 Quals.removeObjCLifetime();
3000
3001 // Exact qualifier match -> return the pointer type we're converting to.
3002 if (CanonToPointee.getLocalQualifiers() == Quals) {
3003 // ToType is exactly what we need. Return it.
3004 if (!ToType.isNull())
3005 return ToType.getUnqualifiedType();
3006
3007 // Build a pointer to ToPointee. It has the right qualifiers
3008 // already.
3009 if (isa<ObjCObjectPointerType>(ToType))
3010 return Context.getObjCObjectPointerType(ToPointee);
3011 return Context.getPointerType(ToPointee);
3012 }
3013
3014 // Just build a canonical type that has the right qualifiers.
3015 QualType QualifiedCanonToPointee
3016 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3017
3018 if (isa<ObjCObjectPointerType>(ToType))
3019 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3020 return Context.getPointerType(QualifiedCanonToPointee);
3021}
3022
3024 bool InOverloadResolution,
3025 ASTContext &Context) {
3026 // Handle value-dependent integral null pointer constants correctly.
3027 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3028 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3030 return !InOverloadResolution;
3031
3032 return Expr->isNullPointerConstant(Context,
3033 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3035}
3036
3038 bool InOverloadResolution,
3039 QualType& ConvertedType,
3040 bool &IncompatibleObjC) {
3041 IncompatibleObjC = false;
3042 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3043 IncompatibleObjC))
3044 return true;
3045
3046 // Conversion from a null pointer constant to any Objective-C pointer type.
3047 if (ToType->isObjCObjectPointerType() &&
3048 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3049 ConvertedType = ToType;
3050 return true;
3051 }
3052
3053 // Blocks: Block pointers can be converted to void*.
3054 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3055 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3056 ConvertedType = ToType;
3057 return true;
3058 }
3059 // Blocks: A null pointer constant can be converted to a block
3060 // pointer type.
3061 if (ToType->isBlockPointerType() &&
3062 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3063 ConvertedType = ToType;
3064 return true;
3065 }
3066
3067 // If the left-hand-side is nullptr_t, the right side can be a null
3068 // pointer constant.
3069 if (ToType->isNullPtrType() &&
3070 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3071 ConvertedType = ToType;
3072 return true;
3073 }
3074
3075 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3076 if (!ToTypePtr)
3077 return false;
3078
3079 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3080 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3081 ConvertedType = ToType;
3082 return true;
3083 }
3084
3085 // Beyond this point, both types need to be pointers
3086 // , including objective-c pointers.
3087 QualType ToPointeeType = ToTypePtr->getPointeeType();
3088 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3089 !getLangOpts().ObjCAutoRefCount) {
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(
3091 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3092 Context);
3093 return true;
3094 }
3095 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3096 if (!FromTypePtr)
3097 return false;
3098
3099 QualType FromPointeeType = FromTypePtr->getPointeeType();
3100
3101 // If the unqualified pointee types are the same, this can't be a
3102 // pointer conversion, so don't do all of the work below.
3103 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3104 return false;
3105
3106 // An rvalue of type "pointer to cv T," where T is an object type,
3107 // can be converted to an rvalue of type "pointer to cv void" (C++
3108 // 4.10p2).
3109 if (FromPointeeType->isIncompleteOrObjectType() &&
3110 ToPointeeType->isVoidType()) {
3111 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3112 ToPointeeType,
3113 ToType, Context,
3114 /*StripObjCLifetime=*/true);
3115 return true;
3116 }
3117
3118 // MSVC allows implicit function to void* type conversion.
3119 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3120 ToPointeeType->isVoidType()) {
3121 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3122 ToPointeeType,
3123 ToType, Context);
3124 return true;
3125 }
3126
3127 // When we're overloading in C, we allow a special kind of pointer
3128 // conversion for compatible-but-not-identical pointee types.
3129 if (!getLangOpts().CPlusPlus &&
3130 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3131 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3132 ToPointeeType,
3133 ToType, Context);
3134 return true;
3135 }
3136
3137 // C++ [conv.ptr]p3:
3138 //
3139 // An rvalue of type "pointer to cv D," where D is a class type,
3140 // can be converted to an rvalue of type "pointer to cv B," where
3141 // B is a base class (clause 10) of D. If B is an inaccessible
3142 // (clause 11) or ambiguous (10.2) base class of D, a program that
3143 // necessitates this conversion is ill-formed. The result of the
3144 // conversion is a pointer to the base class sub-object of the
3145 // derived class object. The null pointer value is converted to
3146 // the null pointer value of the destination type.
3147 //
3148 // Note that we do not check for ambiguity or inaccessibility
3149 // here. That is handled by CheckPointerConversion.
3150 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3151 ToPointeeType->isRecordType() &&
3152 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3153 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3154 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3155 ToPointeeType,
3156 ToType, Context);
3157 return true;
3158 }
3159
3160 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3161 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3162 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3163 ToPointeeType,
3164 ToType, Context);
3165 return true;
3166 }
3167
3168 return false;
3169}
3170
3171/// Adopt the given qualifiers for the given type.
3173 Qualifiers TQs = T.getQualifiers();
3174
3175 // Check whether qualifiers already match.
3176 if (TQs == Qs)
3177 return T;
3178
3179 if (Qs.compatiblyIncludes(TQs, Context))
3180 return Context.getQualifiedType(T, Qs);
3181
3182 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3183}
3184
3186 QualType& ConvertedType,
3187 bool &IncompatibleObjC) {
3188 if (!getLangOpts().ObjC)
3189 return false;
3190
3191 // The set of qualifiers on the type we're converting from.
3192 Qualifiers FromQualifiers = FromType.getQualifiers();
3193
3194 // First, we handle all conversions on ObjC object pointer types.
3195 const ObjCObjectPointerType* ToObjCPtr =
3196 ToType->getAs<ObjCObjectPointerType>();
3197 const ObjCObjectPointerType *FromObjCPtr =
3198 FromType->getAs<ObjCObjectPointerType>();
3199
3200 if (ToObjCPtr && FromObjCPtr) {
3201 // If the pointee types are the same (ignoring qualifications),
3202 // then this is not a pointer conversion.
3203 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3204 FromObjCPtr->getPointeeType()))
3205 return false;
3206
3207 // Conversion between Objective-C pointers.
3208 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3209 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3210 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3211 if (getLangOpts().CPlusPlus && LHS && RHS &&
3213 FromObjCPtr->getPointeeType(), getASTContext()))
3214 return false;
3215 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3216 ToObjCPtr->getPointeeType(),
3217 ToType, Context);
3218 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3219 return true;
3220 }
3221
3222 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3223 // Okay: this is some kind of implicit downcast of Objective-C
3224 // interfaces, which is permitted. However, we're going to
3225 // complain about it.
3226 IncompatibleObjC = true;
3227 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3228 ToObjCPtr->getPointeeType(),
3229 ToType, Context);
3230 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3231 return true;
3232 }
3233 }
3234 // Beyond this point, both types need to be C pointers or block pointers.
3235 QualType ToPointeeType;
3236 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3237 ToPointeeType = ToCPtr->getPointeeType();
3238 else if (const BlockPointerType *ToBlockPtr =
3239 ToType->getAs<BlockPointerType>()) {
3240 // Objective C++: We're able to convert from a pointer to any object
3241 // to a block pointer type.
3242 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3243 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3244 return true;
3245 }
3246 ToPointeeType = ToBlockPtr->getPointeeType();
3247 }
3248 else if (FromType->getAs<BlockPointerType>() &&
3249 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3250 // Objective C++: We're able to convert from a block pointer type to a
3251 // pointer to any object.
3252 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3253 return true;
3254 }
3255 else
3256 return false;
3257
3258 QualType FromPointeeType;
3259 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3260 FromPointeeType = FromCPtr->getPointeeType();
3261 else if (const BlockPointerType *FromBlockPtr =
3262 FromType->getAs<BlockPointerType>())
3263 FromPointeeType = FromBlockPtr->getPointeeType();
3264 else
3265 return false;
3266
3267 // If we have pointers to pointers, recursively check whether this
3268 // is an Objective-C conversion.
3269 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3270 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3271 IncompatibleObjC)) {
3272 // We always complain about this conversion.
3273 IncompatibleObjC = true;
3274 ConvertedType = Context.getPointerType(ConvertedType);
3275 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3276 return true;
3277 }
3278 // Allow conversion of pointee being objective-c pointer to another one;
3279 // as in I* to id.
3280 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3281 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3282 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3283 IncompatibleObjC)) {
3284
3285 ConvertedType = Context.getPointerType(ConvertedType);
3286 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3287 return true;
3288 }
3289
3290 // If we have pointers to functions or blocks, check whether the only
3291 // differences in the argument and result types are in Objective-C
3292 // pointer conversions. If so, we permit the conversion (but
3293 // complain about it).
3294 const FunctionProtoType *FromFunctionType
3295 = FromPointeeType->getAs<FunctionProtoType>();
3296 const FunctionProtoType *ToFunctionType
3297 = ToPointeeType->getAs<FunctionProtoType>();
3298 if (FromFunctionType && ToFunctionType) {
3299 // If the function types are exactly the same, this isn't an
3300 // Objective-C pointer conversion.
3301 if (Context.getCanonicalType(FromPointeeType)
3302 == Context.getCanonicalType(ToPointeeType))
3303 return false;
3304
3305 // Perform the quick checks that will tell us whether these
3306 // function types are obviously different.
3307 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3308 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3309 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3310 return false;
3311
3312 bool HasObjCConversion = false;
3313 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3314 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3315 // Okay, the types match exactly. Nothing to do.
3316 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3317 ToFunctionType->getReturnType(),
3318 ConvertedType, IncompatibleObjC)) {
3319 // Okay, we have an Objective-C pointer conversion.
3320 HasObjCConversion = true;
3321 } else {
3322 // Function types are too different. Abort.
3323 return false;
3324 }
3325
3326 // Check argument types.
3327 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3328 ArgIdx != NumArgs; ++ArgIdx) {
3329 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3330 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3331 if (Context.getCanonicalType(FromArgType)
3332 == Context.getCanonicalType(ToArgType)) {
3333 // Okay, the types match exactly. Nothing to do.
3334 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3335 ConvertedType, IncompatibleObjC)) {
3336 // Okay, we have an Objective-C pointer conversion.
3337 HasObjCConversion = true;
3338 } else {
3339 // Argument types are too different. Abort.
3340 return false;
3341 }
3342 }
3343
3344 if (HasObjCConversion) {
3345 // We had an Objective-C conversion. Allow this pointer
3346 // conversion, but complain about it.
3347 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3348 IncompatibleObjC = true;
3349 return true;
3350 }
3351 }
3352
3353 return false;
3354}
3355
3357 QualType& ConvertedType) {
3358 QualType ToPointeeType;
3359 if (const BlockPointerType *ToBlockPtr =
3360 ToType->getAs<BlockPointerType>())
3361 ToPointeeType = ToBlockPtr->getPointeeType();
3362 else
3363 return false;
3364
3365 QualType FromPointeeType;
3366 if (const BlockPointerType *FromBlockPtr =
3367 FromType->getAs<BlockPointerType>())
3368 FromPointeeType = FromBlockPtr->getPointeeType();
3369 else
3370 return false;
3371 // We have pointer to blocks, check whether the only
3372 // differences in the argument and result types are in Objective-C
3373 // pointer conversions. If so, we permit the conversion.
3374
3375 const FunctionProtoType *FromFunctionType
3376 = FromPointeeType->getAs<FunctionProtoType>();
3377 const FunctionProtoType *ToFunctionType
3378 = ToPointeeType->getAs<FunctionProtoType>();
3379
3380 if (!FromFunctionType || !ToFunctionType)
3381 return false;
3382
3383 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3384 return true;
3385
3386 // Perform the quick checks that will tell us whether these
3387 // function types are obviously different.
3388 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3389 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3390 return false;
3391
3392 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3393 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3394 if (FromEInfo != ToEInfo)
3395 return false;
3396
3397 bool IncompatibleObjC = false;
3398 if (Context.hasSameType(FromFunctionType->getReturnType(),
3399 ToFunctionType->getReturnType())) {
3400 // Okay, the types match exactly. Nothing to do.
3401 } else {
3402 QualType RHS = FromFunctionType->getReturnType();
3403 QualType LHS = ToFunctionType->getReturnType();
3404 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3405 !RHS.hasQualifiers() && LHS.hasQualifiers())
3406 LHS = LHS.getUnqualifiedType();
3407
3408 if (Context.hasSameType(RHS,LHS)) {
3409 // OK exact match.
3410 } else if (isObjCPointerConversion(RHS, LHS,
3411 ConvertedType, IncompatibleObjC)) {
3412 if (IncompatibleObjC)
3413 return false;
3414 // Okay, we have an Objective-C pointer conversion.
3415 }
3416 else
3417 return false;
3418 }
3419
3420 // Check argument types.
3421 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3422 ArgIdx != NumArgs; ++ArgIdx) {
3423 IncompatibleObjC = false;
3424 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3425 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3426 if (Context.hasSameType(FromArgType, ToArgType)) {
3427 // Okay, the types match exactly. Nothing to do.
3428 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3429 ConvertedType, IncompatibleObjC)) {
3430 if (IncompatibleObjC)
3431 return false;
3432 // Okay, we have an Objective-C pointer conversion.
3433 } else
3434 // Argument types are too different. Abort.
3435 return false;
3436 }
3437
3439 bool CanUseToFPT, CanUseFromFPT;
3440 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3441 CanUseToFPT, CanUseFromFPT,
3442 NewParamInfos))
3443 return false;
3444
3445 ConvertedType = ToType;
3446 return true;
3447}
3448
3449enum {
3457};
3458
3459/// Attempts to get the FunctionProtoType from a Type. Handles
3460/// MemberFunctionPointers properly.
3462 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3463 return FPT;
3464
3465 if (auto *MPT = FromType->getAs<MemberPointerType>())
3466 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3467
3468 return nullptr;
3469}
3470
3472 QualType FromType, QualType ToType) {
3473 // If either type is not valid, include no extra info.
3474 if (FromType.isNull() || ToType.isNull()) {
3475 PDiag << ft_default;
3476 return;
3477 }
3478
3479 // Get the function type from the pointers.
3480 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3481 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3482 *ToMember = ToType->castAs<MemberPointerType>();
3483 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3484 ToMember->getMostRecentCXXRecordDecl())) {
3486 if (ToMember->isSugared())
3487 PDiag << Context.getCanonicalTagType(
3488 ToMember->getMostRecentCXXRecordDecl());
3489 else
3490 PDiag << ToMember->getQualifier();
3491 if (FromMember->isSugared())
3492 PDiag << Context.getCanonicalTagType(
3493 FromMember->getMostRecentCXXRecordDecl());
3494 else
3495 PDiag << FromMember->getQualifier();
3496 return;
3497 }
3498 FromType = FromMember->getPointeeType();
3499 ToType = ToMember->getPointeeType();
3500 }
3501
3502 if (FromType->isPointerType())
3503 FromType = FromType->getPointeeType();
3504 if (ToType->isPointerType())
3505 ToType = ToType->getPointeeType();
3506
3507 // Remove references.
3508 FromType = FromType.getNonReferenceType();
3509 ToType = ToType.getNonReferenceType();
3510
3511 // Don't print extra info for non-specialized template functions.
3512 if (FromType->isInstantiationDependentType() &&
3513 !FromType->getAs<TemplateSpecializationType>()) {
3514 PDiag << ft_default;
3515 return;
3516 }
3517
3518 // No extra info for same types.
3519 if (Context.hasSameType(FromType, ToType)) {
3520 PDiag << ft_default;
3521 return;
3522 }
3523
3524 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3525 *ToFunction = tryGetFunctionProtoType(ToType);
3526
3527 // Both types need to be function types.
3528 if (!FromFunction || !ToFunction) {
3529 PDiag << ft_default;
3530 return;
3531 }
3532
3533 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3534 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3535 << FromFunction->getNumParams();
3536 return;
3537 }
3538
3539 // Handle different parameter types.
3540 unsigned ArgPos;
3541 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3542 PDiag << ft_parameter_mismatch << ArgPos + 1
3543 << ToFunction->getParamType(ArgPos)
3544 << FromFunction->getParamType(ArgPos);
3545 return;
3546 }
3547
3548 // Handle different return type.
3549 if (!Context.hasSameType(FromFunction->getReturnType(),
3550 ToFunction->getReturnType())) {
3551 PDiag << ft_return_type << ToFunction->getReturnType()
3552 << FromFunction->getReturnType();
3553 return;
3554 }
3555
3556 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3557 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3558 << FromFunction->getMethodQuals();
3559 return;
3560 }
3561
3562 // Handle exception specification differences on canonical type (in C++17
3563 // onwards).
3565 ->isNothrow() !=
3566 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3567 ->isNothrow()) {
3568 PDiag << ft_noexcept;
3569 return;
3570 }
3571
3572 // Unable to find a difference, so add no extra info.
3573 PDiag << ft_default;
3574}
3575
3577 ArrayRef<QualType> New, unsigned *ArgPos,
3578 bool Reversed) {
3579 assert(llvm::size(Old) == llvm::size(New) &&
3580 "Can't compare parameters of functions with different number of "
3581 "parameters!");
3582
3583 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3584 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3585 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3586
3587 // Ignore address spaces in pointee type. This is to disallow overloading
3588 // on __ptr32/__ptr64 address spaces.
3589 QualType OldType =
3590 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3591 QualType NewType =
3592 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3593
3594 if (!Context.hasSameType(OldType, NewType)) {
3595 if (ArgPos)
3596 *ArgPos = Idx;
3597 return false;
3598 }
3599 }
3600 return true;
3601}
3602
3604 const FunctionProtoType *NewType,
3605 unsigned *ArgPos, bool Reversed) {
3606 return FunctionParamTypesAreEqual(OldType->param_types(),
3607 NewType->param_types(), ArgPos, Reversed);
3608}
3609
3611 const FunctionDecl *NewFunction,
3612 unsigned *ArgPos,
3613 bool Reversed) {
3614
3615 if (OldFunction->getNumNonObjectParams() !=
3616 NewFunction->getNumNonObjectParams())
3617 return false;
3618
3619 unsigned OldIgnore =
3621 unsigned NewIgnore =
3623
3624 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3625 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3626
3627 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3628 NewPT->param_types().slice(NewIgnore),
3629 ArgPos, Reversed);
3630}
3631
3633 CastKind &Kind,
3634 CXXCastPath& BasePath,
3635 bool IgnoreBaseAccess,
3636 bool Diagnose) {
3637 QualType FromType = From->getType();
3638 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3639
3640 Kind = CK_BitCast;
3641
3642 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3645 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3646 DiagRuntimeBehavior(From->getExprLoc(), From,
3647 PDiag(diag::warn_impcast_bool_to_null_pointer)
3648 << ToType << From->getSourceRange());
3649 else if (!isUnevaluatedContext())
3650 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3651 << ToType << From->getSourceRange();
3652 }
3653 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3654 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3655 QualType FromPointeeType = FromPtrType->getPointeeType(),
3656 ToPointeeType = ToPtrType->getPointeeType();
3657
3658 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3659 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3660 // We must have a derived-to-base conversion. Check an
3661 // ambiguous or inaccessible conversion.
3662 unsigned InaccessibleID = 0;
3663 unsigned AmbiguousID = 0;
3664 if (Diagnose) {
3665 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3666 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3667 }
3669 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3670 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3671 &BasePath, IgnoreBaseAccess))
3672 return true;
3673
3674 // The conversion was successful.
3675 Kind = CK_DerivedToBase;
3676 }
3677
3678 if (Diagnose && !IsCStyleOrFunctionalCast &&
3679 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3680 assert(getLangOpts().MSVCCompat &&
3681 "this should only be possible with MSVCCompat!");
3682 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3683 << From->getSourceRange();
3684 }
3685 }
3686 } else if (const ObjCObjectPointerType *ToPtrType =
3687 ToType->getAs<ObjCObjectPointerType>()) {
3688 if (const ObjCObjectPointerType *FromPtrType =
3689 FromType->getAs<ObjCObjectPointerType>()) {
3690 // Objective-C++ conversions are always okay.
3691 // FIXME: We should have a different class of conversions for the
3692 // Objective-C++ implicit conversions.
3693 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3694 return false;
3695 } else if (FromType->isBlockPointerType()) {
3696 Kind = CK_BlockPointerToObjCPointerCast;
3697 } else {
3698 Kind = CK_CPointerToObjCPointerCast;
3699 }
3700 } else if (ToType->isBlockPointerType()) {
3701 if (!FromType->isBlockPointerType())
3702 Kind = CK_AnyPointerToBlockPointerCast;
3703 }
3704
3705 // We shouldn't fall into this case unless it's valid for other
3706 // reasons.
3708 Kind = CK_NullToPointer;
3709
3710 return false;
3711}
3712
3714 QualType ToType,
3715 bool InOverloadResolution,
3716 QualType &ConvertedType) {
3717 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3718 if (!ToTypePtr)
3719 return false;
3720
3721 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3723 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3725 ConvertedType = ToType;
3726 return true;
3727 }
3728
3729 // Otherwise, both types have to be member pointers.
3730 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3731 if (!FromTypePtr)
3732 return false;
3733
3734 // A pointer to member of B can be converted to a pointer to member of D,
3735 // where D is derived from B (C++ 4.11p2).
3736 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3737 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3738
3739 if (!declaresSameEntity(FromClass, ToClass) &&
3740 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3741 ConvertedType = Context.getMemberPointerType(
3742 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3743 return true;
3744 }
3745
3746 return false;
3747}
3748
3750 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3751 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3752 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3753 // Lock down the inheritance model right now in MS ABI, whether or not the
3754 // pointee types are the same.
3755 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3756 (void)isCompleteType(CheckLoc, FromType);
3757 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3758 }
3759
3760 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3761 if (!FromPtrType) {
3762 // This must be a null pointer to member pointer conversion
3763 Kind = CK_NullToMemberPointer;
3765 }
3766
3767 // T == T, modulo cv
3769 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3770 ToPtrType->getPointeeType()))
3772
3773 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3774 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3775
3776 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3777 const CXXRecordDecl *Cls) {
3778 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3779 PD << Qual;
3780 else
3781 PD << Context.getCanonicalTagType(Cls);
3782 };
3783 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3784 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3785 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3786 return PD;
3787 };
3788
3789 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3791 std::swap(Base, Derived);
3792
3793 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3794 /*DetectVirtual=*/true);
3795 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3797
3798 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3799 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3800 PD << int(Direction);
3801 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3802 Diag(CheckLoc, PD);
3804 }
3805
3806 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3807 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3808 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3809 Diag(CheckLoc, PD);
3811 }
3812
3813 // Must be a base to derived member conversion.
3814 BuildBasePathArray(Paths, BasePath);
3816 ? CK_DerivedToBaseMemberPointer
3817 : CK_BaseToDerivedMemberPointer;
3818
3819 if (!IgnoreBaseAccess)
3820 switch (CheckBaseClassAccess(
3821 CheckLoc, Base, Derived, Paths.front(),
3823 ? diag::err_upcast_to_inaccessible_base
3824 : diag::err_downcast_from_inaccessible_base,
3825 [&](PartialDiagnostic &PD) {
3826 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3827 DerivedQual = ToPtrType->getQualifier();
3828 if (Direction == MemberPointerConversionDirection::Upcast)
3829 std::swap(BaseQual, DerivedQual);
3830 DiagCls(PD, DerivedQual, Derived);
3831 DiagCls(PD, BaseQual, Base);
3832 })) {
3834 case Sema::AR_delayed:
3835 case Sema::AR_dependent:
3836 // Optimistically assume that the delayed and dependent cases
3837 // will work out.
3838 break;
3839
3842 }
3843
3845}
3846
3847/// Determine whether the lifetime conversion between the two given
3848/// qualifiers sets is nontrivial.
3850 Qualifiers ToQuals) {
3851 // Converting anything to const __unsafe_unretained is trivial.
3852 if (ToQuals.hasConst() &&
3854 return false;
3855
3856 return true;
3857}
3858
3859/// Perform a single iteration of the loop for checking if a qualification
3860/// conversion is valid.
3861///
3862/// Specifically, check whether any change between the qualifiers of \p
3863/// FromType and \p ToType is permissible, given knowledge about whether every
3864/// outer layer is const-qualified.
3866 bool CStyle, bool IsTopLevel,
3867 bool &PreviousToQualsIncludeConst,
3868 bool &ObjCLifetimeConversion,
3869 const ASTContext &Ctx) {
3870 Qualifiers FromQuals = FromType.getQualifiers();
3871 Qualifiers ToQuals = ToType.getQualifiers();
3872
3873 // Ignore __unaligned qualifier.
3874 FromQuals.removeUnaligned();
3875
3876 // Objective-C ARC:
3877 // Check Objective-C lifetime conversions.
3878 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3879 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3880 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3881 ObjCLifetimeConversion = true;
3882 FromQuals.removeObjCLifetime();
3883 ToQuals.removeObjCLifetime();
3884 } else {
3885 // Qualification conversions cannot cast between different
3886 // Objective-C lifetime qualifiers.
3887 return false;
3888 }
3889 }
3890
3891 // Allow addition/removal of GC attributes but not changing GC attributes.
3892 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3893 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3894 FromQuals.removeObjCGCAttr();
3895 ToQuals.removeObjCGCAttr();
3896 }
3897
3898 // __ptrauth qualifiers must match exactly.
3899 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3900 return false;
3901
3902 // -- for every j > 0, if const is in cv 1,j then const is in cv
3903 // 2,j, and similarly for volatile.
3904 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3905 return false;
3906
3907 // If address spaces mismatch:
3908 // - in top level it is only valid to convert to addr space that is a
3909 // superset in all cases apart from C-style casts where we allow
3910 // conversions between overlapping address spaces.
3911 // - in non-top levels it is not a valid conversion.
3912 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3913 (!IsTopLevel ||
3914 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3915 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3916 return false;
3917
3918 // -- if the cv 1,j and cv 2,j are different, then const is in
3919 // every cv for 0 < k < j.
3920 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3921 !PreviousToQualsIncludeConst)
3922 return false;
3923
3924 // The following wording is from C++20, where the result of the conversion
3925 // is T3, not T2.
3926 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3927 // "array of unknown bound of"
3928 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3929 return false;
3930
3931 // -- if the resulting P3,i is different from P1,i [...], then const is
3932 // added to every cv 3_k for 0 < k < i.
3933 if (!CStyle && FromType->isConstantArrayType() &&
3934 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3935 return false;
3936
3937 // Keep track of whether all prior cv-qualifiers in the "to" type
3938 // include const.
3939 PreviousToQualsIncludeConst =
3940 PreviousToQualsIncludeConst && ToQuals.hasConst();
3941 return true;
3942}
3943
3944bool
3946 bool CStyle, bool &ObjCLifetimeConversion) {
3947 FromType = Context.getCanonicalType(FromType);
3948 ToType = Context.getCanonicalType(ToType);
3949 ObjCLifetimeConversion = false;
3950
3951 // If FromType and ToType are the same type, this is not a
3952 // qualification conversion.
3953 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3954 return false;
3955
3956 // (C++ 4.4p4):
3957 // A conversion can add cv-qualifiers at levels other than the first
3958 // in multi-level pointers, subject to the following rules: [...]
3959 bool PreviousToQualsIncludeConst = true;
3960 bool UnwrappedAnyPointer = false;
3961 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3962 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3963 !UnwrappedAnyPointer,
3964 PreviousToQualsIncludeConst,
3965 ObjCLifetimeConversion, getASTContext()))
3966 return false;
3967 UnwrappedAnyPointer = true;
3968 }
3969
3970 // We are left with FromType and ToType being the pointee types
3971 // after unwrapping the original FromType and ToType the same number
3972 // of times. If we unwrapped any pointers, and if FromType and
3973 // ToType have the same unqualified type (since we checked
3974 // qualifiers above), then this is a qualification conversion.
3975 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3976}
3977
3978/// - Determine whether this is a conversion from a scalar type to an
3979/// atomic type.
3980///
3981/// If successful, updates \c SCS's second and third steps in the conversion
3982/// sequence to finish the conversion.
3983static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3984 bool InOverloadResolution,
3986 bool CStyle) {
3987 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3988 if (!ToAtomic)
3989 return false;
3990
3992 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3993 InOverloadResolution, InnerSCS,
3994 CStyle, /*AllowObjCWritebackConversion=*/false))
3995 return false;
3996
3997 SCS.Second = InnerSCS.Second;
3998 SCS.setToType(1, InnerSCS.getToType(1));
3999 SCS.Third = InnerSCS.Third;
4002 SCS.setToType(2, InnerSCS.getToType(2));
4003 return true;
4004}
4005
4007 QualType ToType,
4008 bool InOverloadResolution,
4010 bool CStyle) {
4011 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4012 if (!ToOBT)
4013 return false;
4014
4015 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4016 QualType FromType = From->getType();
4017 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4018 return false;
4019
4021 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4022 InOverloadResolution, InnerSCS, CStyle,
4023 /*AllowObjCWritebackConversion=*/false))
4024 return false;
4025
4026 SCS.Second = InnerSCS.Second;
4027 SCS.setToType(1, InnerSCS.getToType(1));
4028 SCS.Third = InnerSCS.Third;
4031 SCS.setToType(2, InnerSCS.getToType(2));
4032 return true;
4033}
4034
4037 QualType Type) {
4038 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4039 if (CtorType->getNumParams() > 0) {
4040 QualType FirstArg = CtorType->getParamType(0);
4041 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4042 return true;
4043 }
4044 return false;
4045}
4046
4047static OverloadingResult
4049 CXXRecordDecl *To,
4051 OverloadCandidateSet &CandidateSet,
4052 bool AllowExplicit) {
4054 for (auto *D : S.LookupConstructors(To)) {
4055 auto Info = getConstructorInfo(D);
4056 if (!Info)
4057 continue;
4058
4059 bool Usable = !Info.Constructor->isInvalidDecl() &&
4060 S.isInitListConstructor(Info.Constructor);
4061 if (Usable) {
4062 bool SuppressUserConversions = false;
4063 if (Info.ConstructorTmpl)
4064 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4065 /*ExplicitArgs*/ nullptr, From,
4066 CandidateSet, SuppressUserConversions,
4067 /*PartialOverloading*/ false,
4068 AllowExplicit);
4069 else
4070 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4071 CandidateSet, SuppressUserConversions,
4072 /*PartialOverloading*/ false, AllowExplicit);
4073 }
4074 }
4075
4076 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4077
4079 switch (auto Result =
4080 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4081 case OR_Deleted:
4082 case OR_Success: {
4083 // Record the standard conversion we used and the conversion function.
4085 QualType ThisType = Constructor->getFunctionObjectParameterType();
4086 // Initializer lists don't have conversions as such.
4088 User.HadMultipleCandidates = HadMultipleCandidates;
4090 User.FoundConversionFunction = Best->FoundDecl;
4092 User.After.setFromType(ThisType);
4093 User.After.setAllToTypes(ToType);
4094 return Result;
4095 }
4096
4098 return OR_No_Viable_Function;
4099 case OR_Ambiguous:
4100 return OR_Ambiguous;
4101 }
4102
4103 llvm_unreachable("Invalid OverloadResult!");
4104}
4105
4106/// Determines whether there is a user-defined conversion sequence
4107/// (C++ [over.ics.user]) that converts expression From to the type
4108/// ToType. If such a conversion exists, User will contain the
4109/// user-defined conversion sequence that performs such a conversion
4110/// and this routine will return true. Otherwise, this routine returns
4111/// false and User is unspecified.
4112///
4113/// \param AllowExplicit true if the conversion should consider C++0x
4114/// "explicit" conversion functions as well as non-explicit conversion
4115/// functions (C++0x [class.conv.fct]p2).
4116///
4117/// \param AllowObjCConversionOnExplicit true if the conversion should
4118/// allow an extra Objective-C pointer conversion on uses of explicit
4119/// constructors. Requires \c AllowExplicit to also be set.
4120static OverloadingResult
4123 OverloadCandidateSet &CandidateSet,
4124 AllowedExplicit AllowExplicit,
4125 bool AllowObjCConversionOnExplicit) {
4126 assert(AllowExplicit != AllowedExplicit::None ||
4127 !AllowObjCConversionOnExplicit);
4129
4130 // Whether we will only visit constructors.
4131 bool ConstructorsOnly = false;
4132
4133 // If the type we are conversion to is a class type, enumerate its
4134 // constructors.
4135 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4136 // C++ [over.match.ctor]p1:
4137 // When objects of class type are direct-initialized (8.5), or
4138 // copy-initialized from an expression of the same or a
4139 // derived class type (8.5), overload resolution selects the
4140 // constructor. [...] For copy-initialization, the candidate
4141 // functions are all the converting constructors (12.3.1) of
4142 // that class. The argument list is the expression-list within
4143 // the parentheses of the initializer.
4144 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4145 (From->getType()->isRecordType() &&
4146 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4147 ConstructorsOnly = true;
4148
4149 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4150 // We're not going to find any constructors.
4151 } else if (auto *ToRecordDecl =
4152 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4153 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4154
4155 Expr **Args = &From;
4156 unsigned NumArgs = 1;
4157 bool ListInitializing = false;
4158 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4159 // But first, see if there is an init-list-constructor that will work.
4161 S, From, ToType, ToRecordDecl, User, CandidateSet,
4162 AllowExplicit == AllowedExplicit::All);
4163 if (Result != OR_No_Viable_Function)
4164 return Result;
4165 // Never mind.
4166 CandidateSet.clear(
4168
4169 // If we're list-initializing, we pass the individual elements as
4170 // arguments, not the entire list.
4171 Args = InitList->getInits();
4172 NumArgs = InitList->getNumInits();
4173 ListInitializing = true;
4174 }
4175
4176 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4177 auto Info = getConstructorInfo(D);
4178 if (!Info)
4179 continue;
4180
4181 bool Usable = !Info.Constructor->isInvalidDecl();
4182 if (!ListInitializing)
4183 Usable = Usable && Info.Constructor->isConvertingConstructor(
4184 /*AllowExplicit*/ true);
4185 if (Usable) {
4186 bool SuppressUserConversions = !ConstructorsOnly;
4187 // C++20 [over.best.ics.general]/4.5:
4188 // if the target is the first parameter of a constructor [of class
4189 // X] and the constructor [...] is a candidate by [...] the second
4190 // phase of [over.match.list] when the initializer list has exactly
4191 // one element that is itself an initializer list, [...] and the
4192 // conversion is to X or reference to cv X, user-defined conversion
4193 // sequences are not considered.
4194 if (SuppressUserConversions && ListInitializing) {
4195 SuppressUserConversions =
4196 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4197 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4198 ToType);
4199 }
4200 if (Info.ConstructorTmpl)
4202 Info.ConstructorTmpl, Info.FoundDecl,
4203 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4204 CandidateSet, SuppressUserConversions,
4205 /*PartialOverloading*/ false,
4206 AllowExplicit == AllowedExplicit::All);
4207 else
4208 // Allow one user-defined conversion when user specifies a
4209 // From->ToType conversion via an static cast (c-style, etc).
4210 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4211 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4212 SuppressUserConversions,
4213 /*PartialOverloading*/ false,
4214 AllowExplicit == AllowedExplicit::All);
4215 }
4216 }
4217 }
4218 }
4219
4220 // Enumerate conversion functions, if we're allowed to.
4221 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4222 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4223 // No conversion functions from incomplete types.
4224 } else if (const RecordType *FromRecordType =
4225 From->getType()->getAsCanonical<RecordType>()) {
4226 if (auto *FromRecordDecl =
4227 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4228 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4229 // Add all of the conversion functions as candidates.
4230 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4231 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4232 DeclAccessPair FoundDecl = I.getPair();
4233 NamedDecl *D = FoundDecl.getDecl();
4234 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4235 if (isa<UsingShadowDecl>(D))
4236 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4237
4238 CXXConversionDecl *Conv;
4239 FunctionTemplateDecl *ConvTemplate;
4240 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4241 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4242 else
4243 Conv = cast<CXXConversionDecl>(D);
4244
4245 if (ConvTemplate)
4247 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4248 CandidateSet, AllowObjCConversionOnExplicit,
4249 AllowExplicit != AllowedExplicit::None);
4250 else
4251 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4252 CandidateSet, AllowObjCConversionOnExplicit,
4253 AllowExplicit != AllowedExplicit::None);
4254 }
4255 }
4256 }
4257
4258 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4259
4261 switch (auto Result =
4262 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4263 case OR_Success:
4264 case OR_Deleted:
4265 // Record the standard conversion we used and the conversion function.
4267 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4268 // C++ [over.ics.user]p1:
4269 // If the user-defined conversion is specified by a
4270 // constructor (12.3.1), the initial standard conversion
4271 // sequence converts the source type to the type required by
4272 // the argument of the constructor.
4273 //
4274 if (isa<InitListExpr>(From)) {
4275 // Initializer lists don't have conversions as such.
4277 User.Before.FromBracedInitList = true;
4278 } else {
4279 if (Best->Conversions[0].isEllipsis())
4280 User.EllipsisConversion = true;
4281 else {
4282 User.Before = Best->Conversions[0].Standard;
4283 User.EllipsisConversion = false;
4284 }
4285 }
4286 User.HadMultipleCandidates = HadMultipleCandidates;
4288 User.FoundConversionFunction = Best->FoundDecl;
4290 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4291 User.After.setAllToTypes(ToType);
4292 return Result;
4293 }
4294 if (CXXConversionDecl *Conversion
4295 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4296
4297 assert(Best->HasFinalConversion);
4298
4299 // C++ [over.ics.user]p1:
4300 //
4301 // [...] If the user-defined conversion is specified by a
4302 // conversion function (12.3.2), the initial standard
4303 // conversion sequence converts the source type to the
4304 // implicit object parameter of the conversion function.
4305 User.Before = Best->Conversions[0].Standard;
4306 User.HadMultipleCandidates = HadMultipleCandidates;
4307 User.ConversionFunction = Conversion;
4308 User.FoundConversionFunction = Best->FoundDecl;
4309 User.EllipsisConversion = false;
4310
4311 // C++ [over.ics.user]p2:
4312 // The second standard conversion sequence converts the
4313 // result of the user-defined conversion to the target type
4314 // for the sequence. Since an implicit conversion sequence
4315 // is an initialization, the special rules for
4316 // initialization by user-defined conversion apply when
4317 // selecting the best user-defined conversion for a
4318 // user-defined conversion sequence (see 13.3.3 and
4319 // 13.3.3.1).
4320 User.After = Best->FinalConversion;
4321 return Result;
4322 }
4323 llvm_unreachable("Not a constructor or conversion function?");
4324
4326 return OR_No_Viable_Function;
4327
4328 case OR_Ambiguous:
4329 return OR_Ambiguous;
4330 }
4331
4332 llvm_unreachable("Invalid OverloadResult!");
4333}
4334
4335bool
4338 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4340 OverloadingResult OvResult =
4341 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4342 CandidateSet, AllowedExplicit::None, false);
4343
4344 if (!(OvResult == OR_Ambiguous ||
4345 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4346 return false;
4347
4348 auto Cands = CandidateSet.CompleteCandidates(
4349 *this,
4351 From);
4352 if (OvResult == OR_Ambiguous)
4353 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4354 << From->getType() << ToType << From->getSourceRange();
4355 else { // OR_No_Viable_Function && !CandidateSet.empty()
4356 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4357 diag::err_typecheck_nonviable_condition_incomplete,
4358 From->getType(), From->getSourceRange()))
4359 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4360 << false << From->getType() << From->getSourceRange() << ToType;
4361 }
4362
4363 CandidateSet.NoteCandidates(
4364 *this, From, Cands);
4365 return true;
4366}
4367
4368// Helper for compareConversionFunctions that gets the FunctionType that the
4369// conversion-operator return value 'points' to, or nullptr.
4370static const FunctionType *
4372 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4373 const PointerType *RetPtrTy =
4374 ConvFuncTy->getReturnType()->getAs<PointerType>();
4375
4376 if (!RetPtrTy)
4377 return nullptr;
4378
4379 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4380}
4381
4382/// Compare the user-defined conversion functions or constructors
4383/// of two user-defined conversion sequences to determine whether any ordering
4384/// is possible.
4387 FunctionDecl *Function2) {
4388 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4389 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4390 if (!Conv1 || !Conv2)
4392
4393 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4395
4396 // Objective-C++:
4397 // If both conversion functions are implicitly-declared conversions from
4398 // a lambda closure type to a function pointer and a block pointer,
4399 // respectively, always prefer the conversion to a function pointer,
4400 // because the function pointer is more lightweight and is more likely
4401 // to keep code working.
4402 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4403 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4404 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4405 if (Block1 != Block2)
4406 return Block1 ? ImplicitConversionSequence::Worse
4408 }
4409
4410 // In order to support multiple calling conventions for the lambda conversion
4411 // operator (such as when the free and member function calling convention is
4412 // different), prefer the 'free' mechanism, followed by the calling-convention
4413 // of operator(). The latter is in place to support the MSVC-like solution of
4414 // defining ALL of the possible conversions in regards to calling-convention.
4415 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4416 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4417
4418 if (Conv1FuncRet && Conv2FuncRet &&
4419 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4420 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4421 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4422
4423 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4424 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4425
4426 CallingConv CallOpCC =
4427 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4429 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4431 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4432
4433 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4434 for (CallingConv CC : PrefOrder) {
4435 if (Conv1CC == CC)
4437 if (Conv2CC == CC)
4439 }
4440 }
4441
4443}
4444
4451
4452/// CompareImplicitConversionSequences - Compare two implicit
4453/// conversion sequences to determine whether one is better than the
4454/// other or if they are indistinguishable (C++ 13.3.3.2).
4457 const ImplicitConversionSequence& ICS1,
4458 const ImplicitConversionSequence& ICS2)
4459{
4460 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4461 // conversion sequences (as defined in 13.3.3.1)
4462 // -- a standard conversion sequence (13.3.3.1.1) is a better
4463 // conversion sequence than a user-defined conversion sequence or
4464 // an ellipsis conversion sequence, and
4465 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4466 // conversion sequence than an ellipsis conversion sequence
4467 // (13.3.3.1.3).
4468 //
4469 // C++0x [over.best.ics]p10:
4470 // For the purpose of ranking implicit conversion sequences as
4471 // described in 13.3.3.2, the ambiguous conversion sequence is
4472 // treated as a user-defined sequence that is indistinguishable
4473 // from any other user-defined conversion sequence.
4474
4475 // String literal to 'char *' conversion has been deprecated in C++03. It has
4476 // been removed from C++11. We still accept this conversion, if it happens at
4477 // the best viable function. Otherwise, this conversion is considered worse
4478 // than ellipsis conversion. Consider this as an extension; this is not in the
4479 // standard. For example:
4480 //
4481 // int &f(...); // #1
4482 // void f(char*); // #2
4483 // void g() { int &r = f("foo"); }
4484 //
4485 // In C++03, we pick #2 as the best viable function.
4486 // In C++11, we pick #1 as the best viable function, because ellipsis
4487 // conversion is better than string-literal to char* conversion (since there
4488 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4489 // convert arguments, #2 would be the best viable function in C++11.
4490 // If the best viable function has this conversion, a warning will be issued
4491 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4492
4493 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4496 // Ill-formedness must not differ
4497 ICS1.isBad() == ICS2.isBad())
4501
4502 if (ICS1.getKindRank() < ICS2.getKindRank())
4504 if (ICS2.getKindRank() < ICS1.getKindRank())
4506
4507 // The following checks require both conversion sequences to be of
4508 // the same kind.
4509 if (ICS1.getKind() != ICS2.getKind())
4511
4514
4515 // Two implicit conversion sequences of the same form are
4516 // indistinguishable conversion sequences unless one of the
4517 // following rules apply: (C++ 13.3.3.2p3):
4518
4519 // List-initialization sequence L1 is a better conversion sequence than
4520 // list-initialization sequence L2 if:
4521 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4522 // if not that,
4523 // — L1 and L2 convert to arrays of the same element type, and either the
4524 // number of elements n_1 initialized by L1 is less than the number of
4525 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4526 // an array of unknown bound and L1 does not,
4527 // even if one of the other rules in this paragraph would otherwise apply.
4528 if (!ICS1.isBad()) {
4529 bool StdInit1 = false, StdInit2 = false;
4532 nullptr);
4535 nullptr);
4536 if (StdInit1 != StdInit2)
4537 return StdInit1 ? ImplicitConversionSequence::Better
4539
4542 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4544 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4546 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4547 CAT2->getElementType())) {
4548 // Both to arrays of the same element type
4549 if (CAT1->getSize() != CAT2->getSize())
4550 // Different sized, the smaller wins
4551 return CAT1->getSize().ult(CAT2->getSize())
4556 // One is incomplete, it loses
4560 }
4561 }
4562 }
4563
4564 if (ICS1.isStandard())
4565 // Standard conversion sequence S1 is a better conversion sequence than
4566 // standard conversion sequence S2 if [...]
4567 Result = CompareStandardConversionSequences(S, Loc,
4568 ICS1.Standard, ICS2.Standard);
4569 else if (ICS1.isUserDefined()) {
4570 // With lazy template loading, it is possible to find non-canonical
4571 // FunctionDecls, depending on when redecl chains are completed. Make sure
4572 // to compare the canonical decls of conversion functions. This avoids
4573 // ambiguity problems for templated conversion operators.
4574 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4575 if (ConvFunc1)
4576 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4577 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4578 if (ConvFunc2)
4579 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4580 // User-defined conversion sequence U1 is a better conversion
4581 // sequence than another user-defined conversion sequence U2 if
4582 // they contain the same user-defined conversion function or
4583 // constructor and if the second standard conversion sequence of
4584 // U1 is better than the second standard conversion sequence of
4585 // U2 (C++ 13.3.3.2p3).
4586 if (ConvFunc1 == ConvFunc2)
4587 Result = CompareStandardConversionSequences(S, Loc,
4588 ICS1.UserDefined.After,
4589 ICS2.UserDefined.After);
4590 else
4591 Result = compareConversionFunctions(S,
4594 }
4595
4596 return Result;
4597}
4598
4599// Per 13.3.3.2p3, compare the given standard conversion sequences to
4600// determine if one is a proper subset of the other.
4603 const StandardConversionSequence& SCS1,
4604 const StandardConversionSequence& SCS2) {
4607
4608 // the identity conversion sequence is considered to be a subsequence of
4609 // any non-identity conversion sequence
4610 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4612 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4614
4615 if (SCS1.Second != SCS2.Second) {
4616 if (SCS1.Second == ICK_Identity)
4618 else if (SCS2.Second == ICK_Identity)
4620 else
4622 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4624
4625 if (SCS1.Third == SCS2.Third) {
4626 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4628 }
4629
4630 if (SCS1.Third == ICK_Identity)
4631 return Result == ImplicitConversionSequence::Worse
4634
4635 if (SCS2.Third == ICK_Identity)
4636 return Result == ImplicitConversionSequence::Better
4639
4641}
4642
4643/// Determine whether one of the given reference bindings is better
4644/// than the other based on what kind of bindings they are.
4645static bool
4647 const StandardConversionSequence &SCS2) {
4648 // C++0x [over.ics.rank]p3b4:
4649 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4650 // implicit object parameter of a non-static member function declared
4651 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4652 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4653 // lvalue reference to a function lvalue and S2 binds an rvalue
4654 // reference*.
4655 //
4656 // FIXME: Rvalue references. We're going rogue with the above edits,
4657 // because the semantics in the current C++0x working paper (N3225 at the
4658 // time of this writing) break the standard definition of std::forward
4659 // and std::reference_wrapper when dealing with references to functions.
4660 // Proposed wording changes submitted to CWG for consideration.
4663 return false;
4664
4665 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4666 SCS2.IsLvalueReference) ||
4669}
4670
4676
4677/// Returns kind of fixed enum promotion the \a SCS uses.
4678static FixedEnumPromotion
4680
4681 if (SCS.Second != ICK_Integral_Promotion)
4683
4684 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4685 if (!Enum)
4687
4688 if (!Enum->isFixed())
4690
4691 QualType UnderlyingType = Enum->getIntegerType();
4692 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4694
4696}
4697
4698/// CompareStandardConversionSequences - Compare two standard
4699/// conversion sequences to determine whether one is better than the
4700/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4703 const StandardConversionSequence& SCS1,
4704 const StandardConversionSequence& SCS2)
4705{
4706 // Standard conversion sequence S1 is a better conversion sequence
4707 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4708
4709 // -- S1 is a proper subsequence of S2 (comparing the conversion
4710 // sequences in the canonical form defined by 13.3.3.1.1,
4711 // excluding any Lvalue Transformation; the identity conversion
4712 // sequence is considered to be a subsequence of any
4713 // non-identity conversion sequence) or, if not that,
4716 return CK;
4717
4718 // -- the rank of S1 is better than the rank of S2 (by the rules
4719 // defined below), or, if not that,
4720 ImplicitConversionRank Rank1 = SCS1.getRank();
4721 ImplicitConversionRank Rank2 = SCS2.getRank();
4722 if (Rank1 < Rank2)
4724 else if (Rank2 < Rank1)
4726
4727 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4728 // are indistinguishable unless one of the following rules
4729 // applies:
4730
4731 // A conversion that is not a conversion of a pointer, or
4732 // pointer to member, to bool is better than another conversion
4733 // that is such a conversion.
4735 return SCS2.isPointerConversionToBool()
4738
4739 // C++14 [over.ics.rank]p4b2:
4740 // This is retroactively applied to C++11 by CWG 1601.
4741 //
4742 // A conversion that promotes an enumeration whose underlying type is fixed
4743 // to its underlying type is better than one that promotes to the promoted
4744 // underlying type, if the two are different.
4747 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4748 FEP1 != FEP2)
4752
4753 // C++ [over.ics.rank]p4b2:
4754 //
4755 // If class B is derived directly or indirectly from class A,
4756 // conversion of B* to A* is better than conversion of B* to
4757 // void*, and conversion of A* to void* is better than conversion
4758 // of B* to void*.
4759 bool SCS1ConvertsToVoid
4761 bool SCS2ConvertsToVoid
4763 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4764 // Exactly one of the conversion sequences is a conversion to
4765 // a void pointer; it's the worse conversion.
4766 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4768 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4769 // Neither conversion sequence converts to a void pointer; compare
4770 // their derived-to-base conversions.
4772 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4773 return DerivedCK;
4774 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4775 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4776 // Both conversion sequences are conversions to void
4777 // pointers. Compare the source types to determine if there's an
4778 // inheritance relationship in their sources.
4779 QualType FromType1 = SCS1.getFromType();
4780 QualType FromType2 = SCS2.getFromType();
4781
4782 // Adjust the types we're converting from via the array-to-pointer
4783 // conversion, if we need to.
4784 if (SCS1.First == ICK_Array_To_Pointer)
4785 FromType1 = S.Context.getArrayDecayedType(FromType1);
4786 if (SCS2.First == ICK_Array_To_Pointer)
4787 FromType2 = S.Context.getArrayDecayedType(FromType2);
4788
4789 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4790 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4791
4792 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4794 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4796
4797 // Objective-C++: If one interface is more specific than the
4798 // other, it is the better one.
4799 const ObjCObjectPointerType* FromObjCPtr1
4800 = FromType1->getAs<ObjCObjectPointerType>();
4801 const ObjCObjectPointerType* FromObjCPtr2
4802 = FromType2->getAs<ObjCObjectPointerType>();
4803 if (FromObjCPtr1 && FromObjCPtr2) {
4804 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4805 FromObjCPtr2);
4806 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4807 FromObjCPtr1);
4808 if (AssignLeft != AssignRight) {
4809 return AssignLeft? ImplicitConversionSequence::Better
4811 }
4812 }
4813 }
4814
4815 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4816 // Check for a better reference binding based on the kind of bindings.
4817 if (isBetterReferenceBindingKind(SCS1, SCS2))
4819 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4821 }
4822
4823 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4824 // bullet 3).
4826 = CompareQualificationConversions(S, SCS1, SCS2))
4827 return QualCK;
4828
4831 return ObtCK;
4832
4833 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4834 // C++ [over.ics.rank]p3b4:
4835 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4836 // which the references refer are the same type except for
4837 // top-level cv-qualifiers, and the type to which the reference
4838 // initialized by S2 refers is more cv-qualified than the type
4839 // to which the reference initialized by S1 refers.
4840 QualType T1 = SCS1.getToType(2);
4841 QualType T2 = SCS2.getToType(2);
4842 T1 = S.Context.getCanonicalType(T1);
4843 T2 = S.Context.getCanonicalType(T2);
4844 Qualifiers T1Quals, T2Quals;
4845 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4846 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4847 if (UnqualT1 == UnqualT2) {
4848 // Objective-C++ ARC: If the references refer to objects with different
4849 // lifetimes, prefer bindings that don't change lifetime.
4855 }
4856
4857 // If the type is an array type, promote the element qualifiers to the
4858 // type for comparison.
4859 if (isa<ArrayType>(T1) && T1Quals)
4860 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4861 if (isa<ArrayType>(T2) && T2Quals)
4862 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4863 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4865 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4867 }
4868 }
4869
4870 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4871 // floating-to-integral conversion if the integral conversion
4872 // is between types of the same size.
4873 // For example:
4874 // void f(float);
4875 // void f(int);
4876 // int main {
4877 // long a;
4878 // f(a);
4879 // }
4880 // Here, MSVC will call f(int) instead of generating a compile error
4881 // as clang will do in standard mode.
4882 if (S.getLangOpts().MSVCCompat &&
4885 SCS2.Second == ICK_Floating_Integral &&
4886 S.Context.getTypeSize(SCS1.getFromType()) ==
4887 S.Context.getTypeSize(SCS1.getToType(2)))
4889
4890 // Prefer a compatible vector conversion over a lax vector conversion
4891 // For example:
4892 //
4893 // typedef float __v4sf __attribute__((__vector_size__(16)));
4894 // void f(vector float);
4895 // void f(vector signed int);
4896 // int main() {
4897 // __v4sf a;
4898 // f(a);
4899 // }
4900 // Here, we'd like to choose f(vector float) and not
4901 // report an ambiguous call error
4902 if (SCS1.Second == ICK_Vector_Conversion &&
4903 SCS2.Second == ICK_Vector_Conversion) {
4904 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4905 SCS1.getFromType(), SCS1.getToType(2));
4906 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4907 SCS2.getFromType(), SCS2.getToType(2));
4908
4909 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4910 return SCS1IsCompatibleVectorConversion
4913 }
4914
4915 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4917 bool SCS1IsCompatibleSVEVectorConversion =
4918 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4919 bool SCS2IsCompatibleSVEVectorConversion =
4920 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4921
4922 if (SCS1IsCompatibleSVEVectorConversion !=
4923 SCS2IsCompatibleSVEVectorConversion)
4924 return SCS1IsCompatibleSVEVectorConversion
4927 }
4928
4929 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4931 bool SCS1IsCompatibleRVVVectorConversion =
4933 bool SCS2IsCompatibleRVVVectorConversion =
4935
4936 if (SCS1IsCompatibleRVVVectorConversion !=
4937 SCS2IsCompatibleRVVVectorConversion)
4938 return SCS1IsCompatibleRVVVectorConversion
4941 }
4943}
4944
4945/// CompareOverflowBehaviorConversions - Compares two standard conversion
4946/// sequences to determine whether they can be ranked based on their
4947/// OverflowBehaviorType's underlying type.
4963
4964/// CompareQualificationConversions - Compares two standard conversion
4965/// sequences to determine whether they can be ranked based on their
4966/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4969 const StandardConversionSequence& SCS1,
4970 const StandardConversionSequence& SCS2) {
4971 // C++ [over.ics.rank]p3:
4972 // -- S1 and S2 differ only in their qualification conversion and
4973 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4974 // [C++98]
4975 // [...] and the cv-qualification signature of type T1 is a proper subset
4976 // of the cv-qualification signature of type T2, and S1 is not the
4977 // deprecated string literal array-to-pointer conversion (4.2).
4978 // [C++2a]
4979 // [...] where T1 can be converted to T2 by a qualification conversion.
4980 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4981 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4983
4984 // FIXME: the example in the standard doesn't use a qualification
4985 // conversion (!)
4986 QualType T1 = SCS1.getToType(2);
4987 QualType T2 = SCS2.getToType(2);
4988 T1 = S.Context.getCanonicalType(T1);
4989 T2 = S.Context.getCanonicalType(T2);
4990 assert(!T1->isReferenceType() && !T2->isReferenceType());
4991 Qualifiers T1Quals, T2Quals;
4992 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4993 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4994
4995 // If the types are the same, we won't learn anything by unwrapping
4996 // them.
4997 if (UnqualT1 == UnqualT2)
4999
5000 // Don't ever prefer a standard conversion sequence that uses the deprecated
5001 // string literal array to pointer conversion.
5002 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5003 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5004
5005 // Objective-C++ ARC:
5006 // Prefer qualification conversions not involving a change in lifetime
5007 // to qualification conversions that do change lifetime.
5010 CanPick1 = false;
5013 CanPick2 = false;
5014
5015 bool ObjCLifetimeConversion;
5016 if (CanPick1 &&
5017 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5018 CanPick1 = false;
5019 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5020 // directions, so we can't short-cut this second check in general.
5021 if (CanPick2 &&
5022 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5023 CanPick2 = false;
5024
5025 if (CanPick1 != CanPick2)
5026 return CanPick1 ? ImplicitConversionSequence::Better
5029}
5030
5031/// CompareDerivedToBaseConversions - Compares two standard conversion
5032/// sequences to determine whether they can be ranked based on their
5033/// various kinds of derived-to-base conversions (C++
5034/// [over.ics.rank]p4b3). As part of these checks, we also look at
5035/// conversions between Objective-C interface types.
5038 const StandardConversionSequence& SCS1,
5039 const StandardConversionSequence& SCS2) {
5040 QualType FromType1 = SCS1.getFromType();
5041 QualType ToType1 = SCS1.getToType(1);
5042 QualType FromType2 = SCS2.getFromType();
5043 QualType ToType2 = SCS2.getToType(1);
5044
5045 // Adjust the types we're converting from via the array-to-pointer
5046 // conversion, if we need to.
5047 if (SCS1.First == ICK_Array_To_Pointer)
5048 FromType1 = S.Context.getArrayDecayedType(FromType1);
5049 if (SCS2.First == ICK_Array_To_Pointer)
5050 FromType2 = S.Context.getArrayDecayedType(FromType2);
5051
5052 // Canonicalize all of the types.
5053 FromType1 = S.Context.getCanonicalType(FromType1);
5054 ToType1 = S.Context.getCanonicalType(ToType1);
5055 FromType2 = S.Context.getCanonicalType(FromType2);
5056 ToType2 = S.Context.getCanonicalType(ToType2);
5057
5058 // C++ [over.ics.rank]p4b3:
5059 //
5060 // If class B is derived directly or indirectly from class A and
5061 // class C is derived directly or indirectly from B,
5062 //
5063 // Compare based on pointer conversions.
5064 if (SCS1.Second == ICK_Pointer_Conversion &&
5066 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5067 FromType1->isPointerType() && FromType2->isPointerType() &&
5068 ToType1->isPointerType() && ToType2->isPointerType()) {
5069 QualType FromPointee1 =
5071 QualType ToPointee1 =
5073 QualType FromPointee2 =
5075 QualType ToPointee2 =
5077
5078 // -- conversion of C* to B* is better than conversion of C* to A*,
5079 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5080 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5082 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5084 }
5085
5086 // -- conversion of B* to A* is better than conversion of C* to A*,
5087 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5088 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5090 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5092 }
5093 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5095 const ObjCObjectPointerType *FromPtr1
5096 = FromType1->getAs<ObjCObjectPointerType>();
5097 const ObjCObjectPointerType *FromPtr2
5098 = FromType2->getAs<ObjCObjectPointerType>();
5099 const ObjCObjectPointerType *ToPtr1
5100 = ToType1->getAs<ObjCObjectPointerType>();
5101 const ObjCObjectPointerType *ToPtr2
5102 = ToType2->getAs<ObjCObjectPointerType>();
5103
5104 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5105 // Apply the same conversion ranking rules for Objective-C pointer types
5106 // that we do for C++ pointers to class types. However, we employ the
5107 // Objective-C pseudo-subtyping relationship used for assignment of
5108 // Objective-C pointer types.
5109 bool FromAssignLeft
5110 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5111 bool FromAssignRight
5112 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5113 bool ToAssignLeft
5114 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5115 bool ToAssignRight
5116 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5117
5118 // A conversion to an a non-id object pointer type or qualified 'id'
5119 // type is better than a conversion to 'id'.
5120 if (ToPtr1->isObjCIdType() &&
5121 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5123 if (ToPtr2->isObjCIdType() &&
5124 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5126
5127 // A conversion to a non-id object pointer type is better than a
5128 // conversion to a qualified 'id' type
5129 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5131 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5133
5134 // A conversion to an a non-Class object pointer type or qualified 'Class'
5135 // type is better than a conversion to 'Class'.
5136 if (ToPtr1->isObjCClassType() &&
5137 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5139 if (ToPtr2->isObjCClassType() &&
5140 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5142
5143 // A conversion to a non-Class object pointer type is better than a
5144 // conversion to a qualified 'Class' type.
5145 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5147 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5149
5150 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5151 if (S.Context.hasSameType(FromType1, FromType2) &&
5152 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5153 (ToAssignLeft != ToAssignRight)) {
5154 if (FromPtr1->isSpecialized()) {
5155 // "conversion of B<A> * to B * is better than conversion of B * to
5156 // C *.
5157 bool IsFirstSame =
5158 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5159 bool IsSecondSame =
5160 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5161 if (IsFirstSame) {
5162 if (!IsSecondSame)
5164 } else if (IsSecondSame)
5166 }
5167 return ToAssignLeft? ImplicitConversionSequence::Worse
5169 }
5170
5171 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5172 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5173 (FromAssignLeft != FromAssignRight))
5174 return FromAssignLeft? ImplicitConversionSequence::Better
5176 }
5177 }
5178
5179 // Ranking of member-pointer types.
5180 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5181 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5182 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5183 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5184 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5185 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5186 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5187 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5188 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5189 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5190 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5191 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5192 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5193 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5195 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5197 }
5198 // conversion of B::* to C::* is better than conversion of A::* to C::*
5199 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5200 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5202 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5204 }
5205 }
5206
5207 if (SCS1.Second == ICK_Derived_To_Base) {
5208 // -- conversion of C to B is better than conversion of C to A,
5209 // -- binding of an expression of type C to a reference of type
5210 // B& is better than binding an expression of type C to a
5211 // reference of type A&,
5212 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5213 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5214 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5216 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5218 }
5219
5220 // -- conversion of B to A is better than conversion of C to A.
5221 // -- binding of an expression of type B to a reference of type
5222 // A& is better than binding an expression of type C to a
5223 // reference of type A&,
5224 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5225 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5226 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5228 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5230 }
5231 }
5232
5234}
5235
5237 if (!T.getQualifiers().hasUnaligned())
5238 return T;
5239
5240 Qualifiers Q;
5241 T = Ctx.getUnqualifiedArrayType(T, Q);
5242 Q.removeUnaligned();
5243 return Ctx.getQualifiedType(T, Q);
5244}
5245
5248 QualType OrigT1, QualType OrigT2,
5249 ReferenceConversions *ConvOut) {
5250 assert(!OrigT1->isReferenceType() &&
5251 "T1 must be the pointee type of the reference type");
5252 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5253
5254 QualType T1 = Context.getCanonicalType(OrigT1);
5255 QualType T2 = Context.getCanonicalType(OrigT2);
5256 Qualifiers T1Quals, T2Quals;
5257 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5258 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5259
5260 ReferenceConversions ConvTmp;
5261 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5262 Conv = ReferenceConversions();
5263
5264 // C++2a [dcl.init.ref]p4:
5265 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5266 // reference-related to "cv2 T2" if T1 is similar to T2, or
5267 // T1 is a base class of T2.
5268 // "cv1 T1" is reference-compatible with "cv2 T2" if
5269 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5270 // "pointer to cv1 T1" via a standard conversion sequence.
5271
5272 // Check for standard conversions we can apply to pointers: derived-to-base
5273 // conversions, ObjC pointer conversions, and function pointer conversions.
5274 // (Qualification conversions are checked last.)
5275 if (UnqualT1 == UnqualT2) {
5276 // Nothing to do.
5277 } else if (isCompleteType(Loc, OrigT2) &&
5278 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5279 Conv |= ReferenceConversions::DerivedToBase;
5280 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5281 UnqualT2->isObjCObjectOrInterfaceType() &&
5282 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5283 Conv |= ReferenceConversions::ObjC;
5284 else if (UnqualT2->isFunctionType() &&
5285 IsFunctionConversion(UnqualT2, UnqualT1)) {
5286 Conv |= ReferenceConversions::Function;
5287 // No need to check qualifiers; function types don't have them.
5288 return Ref_Compatible;
5289 }
5290 bool ConvertedReferent = Conv != 0;
5291
5292 // We can have a qualification conversion. Compute whether the types are
5293 // similar at the same time.
5294 bool PreviousToQualsIncludeConst = true;
5295 bool TopLevel = true;
5296 do {
5297 if (T1 == T2)
5298 break;
5299
5300 // We will need a qualification conversion.
5301 Conv |= ReferenceConversions::Qualification;
5302
5303 // Track whether we performed a qualification conversion anywhere other
5304 // than the top level. This matters for ranking reference bindings in
5305 // overload resolution.
5306 if (!TopLevel)
5307 Conv |= ReferenceConversions::NestedQualification;
5308
5309 // MS compiler ignores __unaligned qualifier for references; do the same.
5310 T1 = withoutUnaligned(Context, T1);
5311 T2 = withoutUnaligned(Context, T2);
5312
5313 // If we find a qualifier mismatch, the types are not reference-compatible,
5314 // but are still be reference-related if they're similar.
5315 bool ObjCLifetimeConversion = false;
5316 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5317 PreviousToQualsIncludeConst,
5318 ObjCLifetimeConversion, getASTContext()))
5319 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5320 ? Ref_Related
5322
5323 // FIXME: Should we track this for any level other than the first?
5324 if (ObjCLifetimeConversion)
5325 Conv |= ReferenceConversions::ObjCLifetime;
5326
5327 TopLevel = false;
5328 } while (Context.UnwrapSimilarTypes(T1, T2));
5329
5330 // At this point, if the types are reference-related, we must either have the
5331 // same inner type (ignoring qualifiers), or must have already worked out how
5332 // to convert the referent.
5333 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5336}
5337
5338/// Look for a user-defined conversion to a value reference-compatible
5339/// with DeclType. Return true if something definite is found.
5340static bool
5342 QualType DeclType, SourceLocation DeclLoc,
5343 Expr *Init, QualType T2, bool AllowRvalues,
5344 bool AllowExplicit) {
5345 assert(T2->isRecordType() && "Can only find conversions of record types.");
5346 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5347 OverloadCandidateSet CandidateSet(
5349 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5350 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5351 NamedDecl *D = *I;
5353 if (isa<UsingShadowDecl>(D))
5354 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5355
5356 FunctionTemplateDecl *ConvTemplate
5357 = dyn_cast<FunctionTemplateDecl>(D);
5358 CXXConversionDecl *Conv;
5359 if (ConvTemplate)
5360 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5361 else
5362 Conv = cast<CXXConversionDecl>(D);
5363
5364 if (AllowRvalues) {
5365 // If we are initializing an rvalue reference, don't permit conversion
5366 // functions that return lvalues.
5367 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5368 const ReferenceType *RefType
5370 if (RefType && !RefType->getPointeeType()->isFunctionType())
5371 continue;
5372 }
5373
5374 if (!ConvTemplate &&
5376 DeclLoc,
5377 Conv->getConversionType()
5382 continue;
5383 } else {
5384 // If the conversion function doesn't return a reference type,
5385 // it can't be considered for this conversion. An rvalue reference
5386 // is only acceptable if its referencee is a function type.
5387
5388 const ReferenceType *RefType =
5390 if (!RefType ||
5391 (!RefType->isLValueReferenceType() &&
5392 !RefType->getPointeeType()->isFunctionType()))
5393 continue;
5394 }
5395
5396 if (ConvTemplate)
5398 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5399 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5400 else
5402 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5403 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5404 }
5405
5406 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5407
5409 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5410 case OR_Success:
5411
5412 assert(Best->HasFinalConversion);
5413
5414 // C++ [over.ics.ref]p1:
5415 //
5416 // [...] If the parameter binds directly to the result of
5417 // applying a conversion function to the argument
5418 // expression, the implicit conversion sequence is a
5419 // user-defined conversion sequence (13.3.3.1.2), with the
5420 // second standard conversion sequence either an identity
5421 // conversion or, if the conversion function returns an
5422 // entity of a type that is a derived class of the parameter
5423 // type, a derived-to-base Conversion.
5424 if (!Best->FinalConversion.DirectBinding)
5425 return false;
5426
5427 ICS.setUserDefined();
5428 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5429 ICS.UserDefined.After = Best->FinalConversion;
5430 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5431 ICS.UserDefined.ConversionFunction = Best->Function;
5432 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5433 ICS.UserDefined.EllipsisConversion = false;
5434 assert(ICS.UserDefined.After.ReferenceBinding &&
5436 "Expected a direct reference binding!");
5437 return true;
5438
5439 case OR_Ambiguous:
5440 ICS.setAmbiguous();
5441 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5442 Cand != CandidateSet.end(); ++Cand)
5443 if (Cand->Best)
5444 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5445 return true;
5446
5448 case OR_Deleted:
5449 // There was no suitable conversion, or we found a deleted
5450 // conversion; continue with other checks.
5451 return false;
5452 }
5453
5454 llvm_unreachable("Invalid OverloadResult!");
5455}
5456
5457/// Compute an implicit conversion sequence for reference
5458/// initialization.
5459static ImplicitConversionSequence
5461 SourceLocation DeclLoc,
5462 bool SuppressUserConversions,
5463 bool AllowExplicit) {
5464 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5465
5466 // Most paths end in a failed conversion.
5469
5470 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5471 QualType T2 = Init->getType();
5472
5473 // If the initializer is the address of an overloaded function, try
5474 // to resolve the overloaded function. If all goes well, T2 is the
5475 // type of the resulting function.
5476 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5479 false, Found))
5480 T2 = Fn->getType();
5481 }
5482
5483 // Compute some basic properties of the types and the initializer.
5484 bool isRValRef = DeclType->isRValueReferenceType();
5485 Expr::Classification InitCategory = Init->Classify(S.Context);
5486
5488 Sema::ReferenceCompareResult RefRelationship =
5489 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5490
5491 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5492 ICS.setStandard();
5494 // FIXME: A reference binding can be a function conversion too. We should
5495 // consider that when ordering reference-to-function bindings.
5496 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5498 : (RefConv & Sema::ReferenceConversions::ObjC)
5500 : ICK_Identity;
5502 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5503 // a reference binding that performs a non-top-level qualification
5504 // conversion as a qualification conversion, not as an identity conversion.
5505 ICS.Standard.Third = (RefConv &
5506 Sema::ReferenceConversions::NestedQualification)
5508 : ICK_Identity;
5509 ICS.Standard.setFromType(T2);
5510 ICS.Standard.setToType(0, T2);
5511 ICS.Standard.setToType(1, T1);
5512 ICS.Standard.setToType(2, T1);
5513 ICS.Standard.ReferenceBinding = true;
5514 ICS.Standard.DirectBinding = BindsDirectly;
5515 ICS.Standard.IsLvalueReference = !isRValRef;
5517 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5520 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5521 ICS.Standard.FromBracedInitList = false;
5522 ICS.Standard.CopyConstructor = nullptr;
5524 };
5525
5526 // C++0x [dcl.init.ref]p5:
5527 // A reference to type "cv1 T1" is initialized by an expression
5528 // of type "cv2 T2" as follows:
5529
5530 // -- If reference is an lvalue reference and the initializer expression
5531 if (!isRValRef) {
5532 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5533 // reference-compatible with "cv2 T2," or
5534 //
5535 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5536 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5537 // C++ [over.ics.ref]p1:
5538 // When a parameter of reference type binds directly (8.5.3)
5539 // to an argument expression, the implicit conversion sequence
5540 // is the identity conversion, unless the argument expression
5541 // has a type that is a derived class of the parameter type,
5542 // in which case the implicit conversion sequence is a
5543 // derived-to-base Conversion (13.3.3.1).
5544 SetAsReferenceBinding(/*BindsDirectly=*/true);
5545
5546 // Nothing more to do: the inaccessibility/ambiguity check for
5547 // derived-to-base conversions is suppressed when we're
5548 // computing the implicit conversion sequence (C++
5549 // [over.best.ics]p2).
5550 return ICS;
5551 }
5552
5553 // -- has a class type (i.e., T2 is a class type), where T1 is
5554 // not reference-related to T2, and can be implicitly
5555 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5556 // is reference-compatible with "cv3 T3" 92) (this
5557 // conversion is selected by enumerating the applicable
5558 // conversion functions (13.3.1.6) and choosing the best
5559 // one through overload resolution (13.3)),
5560 if (!SuppressUserConversions && T2->isRecordType() &&
5561 S.isCompleteType(DeclLoc, T2) &&
5562 RefRelationship == Sema::Ref_Incompatible) {
5563 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5564 Init, T2, /*AllowRvalues=*/false,
5565 AllowExplicit))
5566 return ICS;
5567 }
5568 }
5569
5570 // -- Otherwise, the reference shall be an lvalue reference to a
5571 // non-volatile const type (i.e., cv1 shall be const), or the reference
5572 // shall be an rvalue reference.
5573 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5574 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5576 return ICS;
5577 }
5578
5579 // -- If the initializer expression
5580 //
5581 // -- is an xvalue, class prvalue, array prvalue or function
5582 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5583 if (RefRelationship == Sema::Ref_Compatible &&
5584 (InitCategory.isXValue() ||
5585 (InitCategory.isPRValue() &&
5586 (T2->isRecordType() || T2->isArrayType())) ||
5587 (InitCategory.isLValue() && T2->isFunctionType()))) {
5588 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5589 // binding unless we're binding to a class prvalue.
5590 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5591 // allow the use of rvalue references in C++98/03 for the benefit of
5592 // standard library implementors; therefore, we need the xvalue check here.
5593 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5594 !(InitCategory.isPRValue() || T2->isRecordType()));
5595 return ICS;
5596 }
5597
5598 // -- has a class type (i.e., T2 is a class type), where T1 is not
5599 // reference-related to T2, and can be implicitly converted to
5600 // an xvalue, class prvalue, or function lvalue of type
5601 // "cv3 T3", where "cv1 T1" is reference-compatible with
5602 // "cv3 T3",
5603 //
5604 // then the reference is bound to the value of the initializer
5605 // expression in the first case and to the result of the conversion
5606 // in the second case (or, in either case, to an appropriate base
5607 // class subobject).
5608 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5609 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5610 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5611 Init, T2, /*AllowRvalues=*/true,
5612 AllowExplicit)) {
5613 // In the second case, if the reference is an rvalue reference
5614 // and the second standard conversion sequence of the
5615 // user-defined conversion sequence includes an lvalue-to-rvalue
5616 // conversion, the program is ill-formed.
5617 if (ICS.isUserDefined() && isRValRef &&
5620
5621 return ICS;
5622 }
5623
5624 // A temporary of function type cannot be created; don't even try.
5625 if (T1->isFunctionType())
5626 return ICS;
5627
5628 // -- Otherwise, a temporary of type "cv1 T1" is created and
5629 // initialized from the initializer expression using the
5630 // rules for a non-reference copy initialization (8.5). The
5631 // reference is then bound to the temporary. If T1 is
5632 // reference-related to T2, cv1 must be the same
5633 // cv-qualification as, or greater cv-qualification than,
5634 // cv2; otherwise, the program is ill-formed.
5635 if (RefRelationship == Sema::Ref_Related) {
5636 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5637 // we would be reference-compatible or reference-compatible with
5638 // added qualification. But that wasn't the case, so the reference
5639 // initialization fails.
5640 //
5641 // Note that we only want to check address spaces and cvr-qualifiers here.
5642 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5643 Qualifiers T1Quals = T1.getQualifiers();
5644 Qualifiers T2Quals = T2.getQualifiers();
5645 T1Quals.removeObjCGCAttr();
5646 T1Quals.removeObjCLifetime();
5647 T2Quals.removeObjCGCAttr();
5648 T2Quals.removeObjCLifetime();
5649 // MS compiler ignores __unaligned qualifier for references; do the same.
5650 T1Quals.removeUnaligned();
5651 T2Quals.removeUnaligned();
5652 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5653 return ICS;
5654 }
5655
5656 // If at least one of the types is a class type, the types are not
5657 // related, and we aren't allowed any user conversions, the
5658 // reference binding fails. This case is important for breaking
5659 // recursion, since TryImplicitConversion below will attempt to
5660 // create a temporary through the use of a copy constructor.
5661 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5662 (T1->isRecordType() || T2->isRecordType()))
5663 return ICS;
5664
5665 // If T1 is reference-related to T2 and the reference is an rvalue
5666 // reference, the initializer expression shall not be an lvalue.
5667 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5668 Init->Classify(S.Context).isLValue()) {
5670 return ICS;
5671 }
5672
5673 // C++ [over.ics.ref]p2:
5674 // When a parameter of reference type is not bound directly to
5675 // an argument expression, the conversion sequence is the one
5676 // required to convert the argument expression to the
5677 // underlying type of the reference according to
5678 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5679 // to copy-initializing a temporary of the underlying type with
5680 // the argument expression. Any difference in top-level
5681 // cv-qualification is subsumed by the initialization itself
5682 // and does not constitute a conversion.
5683 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5684 AllowedExplicit::None,
5685 /*InOverloadResolution=*/false,
5686 /*CStyle=*/false,
5687 /*AllowObjCWritebackConversion=*/false,
5688 /*AllowObjCConversionOnExplicit=*/false);
5689
5690 // Of course, that's still a reference binding.
5691 if (ICS.isStandard()) {
5692 ICS.Standard.ReferenceBinding = true;
5693 ICS.Standard.IsLvalueReference = !isRValRef;
5694 ICS.Standard.BindsToFunctionLvalue = false;
5695 ICS.Standard.BindsToRvalue = true;
5698 } else if (ICS.isUserDefined()) {
5699 const ReferenceType *LValRefType =
5702
5703 // C++ [over.ics.ref]p3:
5704 // Except for an implicit object parameter, for which see 13.3.1, a
5705 // standard conversion sequence cannot be formed if it requires [...]
5706 // binding an rvalue reference to an lvalue other than a function
5707 // lvalue.
5708 // Note that the function case is not possible here.
5709 if (isRValRef && LValRefType) {
5711 return ICS;
5712 }
5713
5715 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5717 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5721 }
5722
5723 return ICS;
5724}
5725
5726static ImplicitConversionSequence
5727TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5728 bool SuppressUserConversions,
5729 bool InOverloadResolution,
5730 bool AllowObjCWritebackConversion,
5731 bool AllowExplicit = false);
5732
5733/// TryListConversion - Try to copy-initialize a value of type ToType from the
5734/// initializer list From.
5735static ImplicitConversionSequence
5737 bool SuppressUserConversions,
5738 bool InOverloadResolution,
5739 bool AllowObjCWritebackConversion) {
5740 // C++11 [over.ics.list]p1:
5741 // When an argument is an initializer list, it is not an expression and
5742 // special rules apply for converting it to a parameter type.
5743
5745 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5746
5747 // We need a complete type for what follows. With one C++20 exception,
5748 // incomplete types can never be initialized from init lists.
5749 QualType InitTy = ToType;
5750 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5751 if (AT && S.getLangOpts().CPlusPlus20)
5752 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5753 // C++20 allows list initialization of an incomplete array type.
5754 InitTy = IAT->getElementType();
5755 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5756 return Result;
5757
5758 // C++20 [over.ics.list]/2:
5759 // If the initializer list is a designated-initializer-list, a conversion
5760 // is only possible if the parameter has an aggregate type
5761 //
5762 // FIXME: The exception for reference initialization here is not part of the
5763 // language rules, but follow other compilers in adding it as a tentative DR
5764 // resolution.
5765 bool IsDesignatedInit = From->hasDesignatedInit();
5766 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5767 IsDesignatedInit)
5768 return Result;
5769
5770 // Per DR1467 and DR2137:
5771 // If the parameter type is an aggregate class X and the initializer list
5772 // has a single element of type cv U, where U is X or a class derived from
5773 // X, the implicit conversion sequence is the one required to convert the
5774 // element to the parameter type.
5775 //
5776 // Otherwise, if the parameter type is a character array [... ]
5777 // and the initializer list has a single element that is an
5778 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5779 // implicit conversion sequence is the identity conversion.
5780 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5781 if (ToType->isRecordType() && ToType->isAggregateType()) {
5782 QualType InitType = From->getInit(0)->getType();
5783 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5784 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5785 return TryCopyInitialization(S, From->getInit(0), ToType,
5786 SuppressUserConversions,
5787 InOverloadResolution,
5788 AllowObjCWritebackConversion);
5789 }
5790
5791 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5792 InitializedEntity Entity =
5794 /*Consumed=*/false);
5795 if (S.CanPerformCopyInitialization(Entity, From)) {
5796 Result.setStandard();
5797 Result.Standard.setAsIdentityConversion();
5798 Result.Standard.setFromType(ToType);
5799 Result.Standard.setAllToTypes(ToType);
5800 return Result;
5801 }
5802 }
5803 }
5804
5805 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5806 // C++11 [over.ics.list]p2:
5807 // If the parameter type is std::initializer_list<X> or "array of X" and
5808 // all the elements can be implicitly converted to X, the implicit
5809 // conversion sequence is the worst conversion necessary to convert an
5810 // element of the list to X.
5811 //
5812 // C++14 [over.ics.list]p3:
5813 // Otherwise, if the parameter type is "array of N X", if the initializer
5814 // list has exactly N elements or if it has fewer than N elements and X is
5815 // default-constructible, and if all the elements of the initializer list
5816 // can be implicitly converted to X, the implicit conversion sequence is
5817 // the worst conversion necessary to convert an element of the list to X.
5818 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5819 unsigned e = From->getNumInits();
5822 QualType());
5823 QualType ContTy = ToType;
5824 bool IsUnbounded = false;
5825 if (AT) {
5826 InitTy = AT->getElementType();
5827 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5828 if (CT->getSize().ult(e)) {
5829 // Too many inits, fatally bad
5831 ToType);
5832 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5833 return Result;
5834 }
5835 if (CT->getSize().ugt(e)) {
5836 // Need an init from empty {}, is there one?
5837 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5838 From->getEndLoc());
5839 EmptyList.setType(S.Context.VoidTy);
5840 DfltElt = TryListConversion(
5841 S, &EmptyList, InitTy, SuppressUserConversions,
5842 InOverloadResolution, AllowObjCWritebackConversion);
5843 if (DfltElt.isBad()) {
5844 // No {} init, fatally bad
5846 ToType);
5847 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5848 return Result;
5849 }
5850 }
5851 } else {
5852 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5853 IsUnbounded = true;
5854 if (!e) {
5855 // Cannot convert to zero-sized.
5857 ToType);
5858 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5859 return Result;
5860 }
5861 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5862 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5864 }
5865 }
5866
5867 Result.setStandard();
5868 Result.Standard.setAsIdentityConversion();
5869 Result.Standard.setFromType(InitTy);
5870 Result.Standard.setAllToTypes(InitTy);
5871 for (unsigned i = 0; i < e; ++i) {
5872 Expr *Init = From->getInit(i);
5874 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5875 AllowObjCWritebackConversion);
5876
5877 // Keep the worse conversion seen so far.
5878 // FIXME: Sequences are not totally ordered, so 'worse' can be
5879 // ambiguous. CWG has been informed.
5881 Result) ==
5883 Result = ICS;
5884 // Bail as soon as we find something unconvertible.
5885 if (Result.isBad()) {
5886 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5887 return Result;
5888 }
5889 }
5890 }
5891
5892 // If we needed any implicit {} initialization, compare that now.
5893 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5894 // has been informed that this might not be the best thing.
5895 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5896 S, From->getEndLoc(), DfltElt, Result) ==
5898 Result = DfltElt;
5899 // Record the type being initialized so that we may compare sequences
5900 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5901 return Result;
5902 }
5903
5904 // C++14 [over.ics.list]p4:
5905 // C++11 [over.ics.list]p3:
5906 // Otherwise, if the parameter is a non-aggregate class X and overload
5907 // resolution chooses a single best constructor [...] the implicit
5908 // conversion sequence is a user-defined conversion sequence. If multiple
5909 // constructors are viable but none is better than the others, the
5910 // implicit conversion sequence is a user-defined conversion sequence.
5911 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5912 // This function can deal with initializer lists.
5913 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5914 AllowedExplicit::None,
5915 InOverloadResolution, /*CStyle=*/false,
5916 AllowObjCWritebackConversion,
5917 /*AllowObjCConversionOnExplicit=*/false);
5918 }
5919
5920 // C++14 [over.ics.list]p5:
5921 // C++11 [over.ics.list]p4:
5922 // Otherwise, if the parameter has an aggregate type which can be
5923 // initialized from the initializer list [...] the implicit conversion
5924 // sequence is a user-defined conversion sequence.
5925 if (ToType->isAggregateType()) {
5926 // Type is an aggregate, argument is an init list. At this point it comes
5927 // down to checking whether the initialization works.
5928 // FIXME: Find out whether this parameter is consumed or not.
5929 InitializedEntity Entity =
5931 /*Consumed=*/false);
5933 From)) {
5934 Result.setUserDefined();
5935 Result.UserDefined.Before.setAsIdentityConversion();
5936 // Initializer lists don't have a type.
5937 Result.UserDefined.Before.setFromType(QualType());
5938 Result.UserDefined.Before.setAllToTypes(QualType());
5939
5940 Result.UserDefined.After.setAsIdentityConversion();
5941 Result.UserDefined.After.setFromType(ToType);
5942 Result.UserDefined.After.setAllToTypes(ToType);
5943 Result.UserDefined.ConversionFunction = nullptr;
5944 }
5945 return Result;
5946 }
5947
5948 // C++14 [over.ics.list]p6:
5949 // C++11 [over.ics.list]p5:
5950 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5951 if (ToType->isReferenceType()) {
5952 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5953 // mention initializer lists in any way. So we go by what list-
5954 // initialization would do and try to extrapolate from that.
5955
5956 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5957
5958 // If the initializer list has a single element that is reference-related
5959 // to the parameter type, we initialize the reference from that.
5960 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5961 Expr *Init = From->getInit(0);
5962
5963 QualType T2 = Init->getType();
5964
5965 // If the initializer is the address of an overloaded function, try
5966 // to resolve the overloaded function. If all goes well, T2 is the
5967 // type of the resulting function.
5968 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5971 Init, ToType, false, Found))
5972 T2 = Fn->getType();
5973 }
5974
5975 // Compute some basic properties of the types and the initializer.
5976 Sema::ReferenceCompareResult RefRelationship =
5977 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5978
5979 if (RefRelationship >= Sema::Ref_Related) {
5980 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5981 SuppressUserConversions,
5982 /*AllowExplicit=*/false);
5983 }
5984 }
5985
5986 // Otherwise, we bind the reference to a temporary created from the
5987 // initializer list.
5988 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5989 InOverloadResolution,
5990 AllowObjCWritebackConversion);
5991 if (Result.isFailure())
5992 return Result;
5993 assert(!Result.isEllipsis() &&
5994 "Sub-initialization cannot result in ellipsis conversion.");
5995
5996 // Can we even bind to a temporary?
5997 if (ToType->isRValueReferenceType() ||
5998 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5999 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6000 Result.UserDefined.After;
6001 SCS.ReferenceBinding = true;
6003 SCS.BindsToRvalue = true;
6004 SCS.BindsToFunctionLvalue = false;
6007 SCS.FromBracedInitList = false;
6008
6009 } else
6011 From, ToType);
6012 return Result;
6013 }
6014
6015 // C++14 [over.ics.list]p7:
6016 // C++11 [over.ics.list]p6:
6017 // Otherwise, if the parameter type is not a class:
6018 if (!ToType->isRecordType()) {
6019 // - if the initializer list has one element that is not itself an
6020 // initializer list, the implicit conversion sequence is the one
6021 // required to convert the element to the parameter type.
6022 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6023 // single integer.
6024 unsigned NumInits = From->getNumInits();
6025 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6026 !isa<EmbedExpr>(From->getInit(0))) {
6027 Result = TryCopyInitialization(
6028 S, From->getInit(0), ToType, SuppressUserConversions,
6029 InOverloadResolution, AllowObjCWritebackConversion);
6030 if (Result.isStandard())
6031 Result.Standard.FromBracedInitList = true;
6032 }
6033 // - if the initializer list has no elements, the implicit conversion
6034 // sequence is the identity conversion.
6035 else if (NumInits == 0) {
6036 Result.setStandard();
6037 Result.Standard.setAsIdentityConversion();
6038 Result.Standard.setFromType(ToType);
6039 Result.Standard.setAllToTypes(ToType);
6040 }
6041 return Result;
6042 }
6043
6044 // C++14 [over.ics.list]p8:
6045 // C++11 [over.ics.list]p7:
6046 // In all cases other than those enumerated above, no conversion is possible
6047 return Result;
6048}
6049
6050/// TryCopyInitialization - Try to copy-initialize a value of type
6051/// ToType from the expression From. Return the implicit conversion
6052/// sequence required to pass this argument, which may be a bad
6053/// conversion sequence (meaning that the argument cannot be passed to
6054/// a parameter of this type). If @p SuppressUserConversions, then we
6055/// do not permit any user-defined conversion sequences.
6056static ImplicitConversionSequence
6058 bool SuppressUserConversions,
6059 bool InOverloadResolution,
6060 bool AllowObjCWritebackConversion,
6061 bool AllowExplicit) {
6062 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6063 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6064 InOverloadResolution,AllowObjCWritebackConversion);
6065
6066 if (ToType->isReferenceType())
6067 return TryReferenceInit(S, From, ToType,
6068 /*FIXME:*/ From->getBeginLoc(),
6069 SuppressUserConversions, AllowExplicit);
6070
6071 return TryImplicitConversion(S, From, ToType,
6072 SuppressUserConversions,
6073 AllowedExplicit::None,
6074 InOverloadResolution,
6075 /*CStyle=*/false,
6076 AllowObjCWritebackConversion,
6077 /*AllowObjCConversionOnExplicit=*/false);
6078}
6079
6080static bool TryCopyInitialization(const CanQualType FromQTy,
6081 const CanQualType ToQTy,
6082 Sema &S,
6083 SourceLocation Loc,
6084 ExprValueKind FromVK) {
6085 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6087 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6088
6089 return !ICS.isBad();
6090}
6091
6092/// TryObjectArgumentInitialization - Try to initialize the object
6093/// parameter of the given member function (@c Method) from the
6094/// expression @p From.
6096 Sema &S, SourceLocation Loc, QualType FromType,
6097 Expr::Classification FromClassification, CXXMethodDecl *Method,
6098 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6099 QualType ExplicitParameterType = QualType(),
6100 bool SuppressUserConversion = false) {
6101
6102 // We need to have an object of class type.
6103 if (const auto *PT = FromType->getAs<PointerType>()) {
6104 FromType = PT->getPointeeType();
6105
6106 // When we had a pointer, it's implicitly dereferenced, so we
6107 // better have an lvalue.
6108 assert(FromClassification.isLValue());
6109 }
6110
6111 auto ValueKindFromClassification = [](Expr::Classification C) {
6112 if (C.isPRValue())
6113 return clang::VK_PRValue;
6114 if (C.isXValue())
6115 return VK_XValue;
6116 return clang::VK_LValue;
6117 };
6118
6119 if (Method->isExplicitObjectMemberFunction()) {
6120 if (ExplicitParameterType.isNull())
6121 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6122 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6123 ValueKindFromClassification(FromClassification));
6125 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6126 /*InOverloadResolution=*/true, false);
6127 if (ICS.isBad())
6128 ICS.Bad.FromExpr = nullptr;
6129 return ICS;
6130 }
6131
6132 assert(FromType->isRecordType());
6133
6134 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6135 // C++98 [class.dtor]p2:
6136 // A destructor can be invoked for a const, volatile or const volatile
6137 // object.
6138 // C++98 [over.match.funcs]p4:
6139 // For static member functions, the implicit object parameter is considered
6140 // to match any object (since if the function is selected, the object is
6141 // discarded).
6142 Qualifiers Quals = Method->getMethodQualifiers();
6143 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6144 Quals.addConst();
6145 Quals.addVolatile();
6146 }
6147
6148 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6149
6150 // Set up the conversion sequence as a "bad" conversion, to allow us
6151 // to exit early.
6153
6154 // C++0x [over.match.funcs]p4:
6155 // For non-static member functions, the type of the implicit object
6156 // parameter is
6157 //
6158 // - "lvalue reference to cv X" for functions declared without a
6159 // ref-qualifier or with the & ref-qualifier
6160 // - "rvalue reference to cv X" for functions declared with the &&
6161 // ref-qualifier
6162 //
6163 // where X is the class of which the function is a member and cv is the
6164 // cv-qualification on the member function declaration.
6165 //
6166 // However, when finding an implicit conversion sequence for the argument, we
6167 // are not allowed to perform user-defined conversions
6168 // (C++ [over.match.funcs]p5). We perform a simplified version of
6169 // reference binding here, that allows class rvalues to bind to
6170 // non-constant references.
6171
6172 // First check the qualifiers.
6173 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6174 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6175 if (ImplicitParamType.getCVRQualifiers() !=
6176 FromTypeCanon.getLocalCVRQualifiers() &&
6177 !ImplicitParamType.isAtLeastAsQualifiedAs(
6178 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6180 FromType, ImplicitParamType);
6181 return ICS;
6182 }
6183
6184 if (FromTypeCanon.hasAddressSpace()) {
6185 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6186 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6187 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6188 S.getASTContext())) {
6190 FromType, ImplicitParamType);
6191 return ICS;
6192 }
6193 }
6194
6195 // Check that we have either the same type or a derived type. It
6196 // affects the conversion rank.
6197 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6198 ImplicitConversionKind SecondKind;
6199 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6200 SecondKind = ICK_Identity;
6201 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6202 SecondKind = ICK_Derived_To_Base;
6203 } else if (!Method->isExplicitObjectMemberFunction()) {
6205 FromType, ImplicitParamType);
6206 return ICS;
6207 }
6208
6209 // Check the ref-qualifier.
6210 switch (Method->getRefQualifier()) {
6211 case RQ_None:
6212 // Do nothing; we don't care about lvalueness or rvalueness.
6213 break;
6214
6215 case RQ_LValue:
6216 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6217 // non-const lvalue reference cannot bind to an rvalue
6219 ImplicitParamType);
6220 return ICS;
6221 }
6222 break;
6223
6224 case RQ_RValue:
6225 if (!FromClassification.isRValue()) {
6226 // rvalue reference cannot bind to an lvalue
6228 ImplicitParamType);
6229 return ICS;
6230 }
6231 break;
6232 }
6233
6234 // Success. Mark this as a reference binding.
6235 ICS.setStandard();
6237 ICS.Standard.Second = SecondKind;
6238 ICS.Standard.setFromType(FromType);
6239 ICS.Standard.setAllToTypes(ImplicitParamType);
6240 ICS.Standard.ReferenceBinding = true;
6241 ICS.Standard.DirectBinding = true;
6242 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6243 ICS.Standard.BindsToFunctionLvalue = false;
6244 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6245 ICS.Standard.FromBracedInitList = false;
6247 = (Method->getRefQualifier() == RQ_None);
6248 return ICS;
6249}
6250
6251/// PerformObjectArgumentInitialization - Perform initialization of
6252/// the implicit object parameter for the given Method with the given
6253/// expression.
6255 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6257 QualType FromRecordType, DestType;
6258 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6259
6260 Expr::Classification FromClassification;
6261 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6262 FromRecordType = PT->getPointeeType();
6263 DestType = Method->getThisType();
6264 FromClassification = Expr::Classification::makeSimpleLValue();
6265 } else {
6266 FromRecordType = From->getType();
6267 DestType = ImplicitParamRecordType;
6268 FromClassification = From->Classify(Context);
6269
6270 // CWG2813 [expr.call]p6:
6271 // If the function is an implicit object member function, the object
6272 // expression of the class member access shall be a glvalue [...]
6273 if (From->isPRValue()) {
6274 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6275 Method->getRefQualifier() !=
6277 }
6278 }
6279
6280 // Note that we always use the true parent context when performing
6281 // the actual argument initialization.
6283 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6284 Method->getParent());
6285 if (ICS.isBad()) {
6286 switch (ICS.Bad.Kind) {
6288 Qualifiers FromQs = FromRecordType.getQualifiers();
6289 Qualifiers ToQs = DestType.getQualifiers();
6290 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6291 if (CVR) {
6292 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6293 << Method->getDeclName() << FromRecordType << (CVR - 1)
6294 << From->getSourceRange();
6295 Diag(Method->getLocation(), diag::note_previous_decl)
6296 << Method->getDeclName();
6297 return ExprError();
6298 }
6299 break;
6300 }
6301
6304 bool IsRValueQualified =
6305 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6306 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6307 << Method->getDeclName() << FromClassification.isRValue()
6308 << IsRValueQualified;
6309 Diag(Method->getLocation(), diag::note_previous_decl)
6310 << Method->getDeclName();
6311 return ExprError();
6312 }
6313
6316 break;
6317
6320 llvm_unreachable("Lists are not objects");
6321 }
6322
6323 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6324 << ImplicitParamRecordType << FromRecordType
6325 << From->getSourceRange();
6326 }
6327
6328 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6329 ExprResult FromRes =
6330 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6331 if (FromRes.isInvalid())
6332 return ExprError();
6333 From = FromRes.get();
6334 }
6335
6336 if (!Context.hasSameType(From->getType(), DestType)) {
6337 CastKind CK;
6338 QualType PteeTy = DestType->getPointeeType();
6339 LangAS DestAS =
6340 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6341 if (FromRecordType.getAddressSpace() != DestAS)
6342 CK = CK_AddressSpaceConversion;
6343 else
6344 CK = CK_NoOp;
6345 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6346 }
6347 return From;
6348}
6349
6350/// TryContextuallyConvertToBool - Attempt to contextually convert the
6351/// expression From to bool (C++0x [conv]p3).
6354 // C++ [dcl.init]/17.8:
6355 // - Otherwise, if the initialization is direct-initialization, the source
6356 // type is std::nullptr_t, and the destination type is bool, the initial
6357 // value of the object being initialized is false.
6358 if (From->getType()->isNullPtrType())
6360 S.Context.BoolTy,
6361 From->isGLValue());
6362
6363 // All other direct-initialization of bool is equivalent to an implicit
6364 // conversion to bool in which explicit conversions are permitted.
6365 return TryImplicitConversion(S, From, S.Context.BoolTy,
6366 /*SuppressUserConversions=*/false,
6367 AllowedExplicit::Conversions,
6368 /*InOverloadResolution=*/false,
6369 /*CStyle=*/false,
6370 /*AllowObjCWritebackConversion=*/false,
6371 /*AllowObjCConversionOnExplicit=*/false);
6372}
6373
6375 if (checkPlaceholderForOverload(*this, From))
6376 return ExprError();
6377 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6378 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6379
6381 if (!ICS.isBad())
6382 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6385 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6386 << From->getType() << From->getSourceRange();
6387 return ExprError();
6388}
6389
6390/// Check that the specified conversion is permitted in a converted constant
6391/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6392/// is acceptable.
6395 // Since we know that the target type is an integral or unscoped enumeration
6396 // type, most conversion kinds are impossible. All possible First and Third
6397 // conversions are fine.
6398 switch (SCS.Second) {
6399 case ICK_Identity:
6401 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6403 return true;
6404
6406 // Conversion from an integral or unscoped enumeration type to bool is
6407 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6408 // conversion, so we allow it in a converted constant expression.
6409 //
6410 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6411 // a lot of popular code. We should at least add a warning for this
6412 // (non-conforming) extension.
6414 SCS.getToType(2)->isBooleanType();
6415
6417 case ICK_Pointer_Member:
6418 // C++1z: null pointer conversions and null member pointer conversions are
6419 // only permitted if the source type is std::nullptr_t.
6420 return SCS.getFromType()->isNullPtrType();
6421
6434 case ICK_Vector_Splat:
6435 case ICK_Complex_Real:
6445 return false;
6446
6451 llvm_unreachable("found a first conversion kind in Second");
6452
6454 case ICK_Qualification:
6455 llvm_unreachable("found a third conversion kind in Second");
6456
6458 break;
6459 }
6460
6461 llvm_unreachable("unknown conversion kind");
6462}
6463
6464/// BuildConvertedConstantExpression - Check that the expression From is a
6465/// converted constant expression of type T, perform the conversion but
6466/// does not evaluate the expression
6468 QualType T, CCEKind CCE,
6469 NamedDecl *Dest,
6470 APValue &PreNarrowingValue) {
6471 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6473 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6474 "converted constant expression outside C++11 or TTP matching");
6475
6476 if (checkPlaceholderForOverload(S, From))
6477 return ExprError();
6478
6479 if (From->containsErrors()) {
6480 // The expression already has errors, so the correct cast kind can't be
6481 // determined. Use RecoveryExpr to keep the expected type T and mark the
6482 // result as invalid, preventing further cascading errors.
6483 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6484 T);
6485 }
6486
6487 // C++1z [expr.const]p3:
6488 // A converted constant expression of type T is an expression,
6489 // implicitly converted to type T, where the converted
6490 // expression is a constant expression and the implicit conversion
6491 // sequence contains only [... list of conversions ...].
6493 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6495 : TryCopyInitialization(S, From, T,
6496 /*SuppressUserConversions=*/false,
6497 /*InOverloadResolution=*/false,
6498 /*AllowObjCWritebackConversion=*/false,
6499 /*AllowExplicit=*/false);
6500 StandardConversionSequence *SCS = nullptr;
6501 switch (ICS.getKind()) {
6503 SCS = &ICS.Standard;
6504 break;
6506 if (T->isRecordType())
6507 SCS = &ICS.UserDefined.Before;
6508 else
6509 SCS = &ICS.UserDefined.After;
6510 break;
6514 return S.Diag(From->getBeginLoc(),
6515 diag::err_typecheck_converted_constant_expression)
6516 << From->getType() << From->getSourceRange() << T;
6517 return ExprError();
6518
6521 llvm_unreachable("bad conversion in converted constant expression");
6522 }
6523
6524 // Check that we would only use permitted conversions.
6525 if (!CheckConvertedConstantConversions(S, *SCS)) {
6526 return S.Diag(From->getBeginLoc(),
6527 diag::err_typecheck_converted_constant_expression_disallowed)
6528 << From->getType() << From->getSourceRange() << T;
6529 }
6530 // [...] and where the reference binding (if any) binds directly.
6531 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6532 return S.Diag(From->getBeginLoc(),
6533 diag::err_typecheck_converted_constant_expression_indirect)
6534 << From->getType() << From->getSourceRange() << T;
6535 }
6536 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6537 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6538 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6539 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6540 // case explicitly.
6541 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6542 return S.Diag(From->getBeginLoc(),
6543 diag::err_reference_bind_to_bitfield_in_cce)
6544 << From->getSourceRange();
6545 }
6546
6547 // Usually we can simply apply the ImplicitConversionSequence we formed
6548 // earlier, but that's not guaranteed to work when initializing an object of
6549 // class type.
6550 ExprResult Result;
6551 bool IsTemplateArgument =
6553 if (T->isRecordType()) {
6554 assert(IsTemplateArgument &&
6555 "unexpected class type converted constant expr");
6556 Result = S.PerformCopyInitialization(
6559 SourceLocation(), From);
6560 } else {
6561 Result =
6563 }
6564 if (Result.isInvalid())
6565 return Result;
6566
6567 // C++2a [intro.execution]p5:
6568 // A full-expression is [...] a constant-expression [...]
6569 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6570 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6571 IsTemplateArgument);
6572 if (Result.isInvalid())
6573 return Result;
6574
6575 // Check for a narrowing implicit conversion.
6576 bool ReturnPreNarrowingValue = false;
6577 QualType PreNarrowingType;
6578 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6579 PreNarrowingType)) {
6581 // Implicit conversion to a narrower type, and the value is not a constant
6582 // expression. We'll diagnose this in a moment.
6583 case NK_Not_Narrowing:
6584 break;
6585
6587 if (CCE == CCEKind::ArrayBound &&
6588 PreNarrowingType->isIntegralOrEnumerationType() &&
6589 PreNarrowingValue.isInt()) {
6590 // Don't diagnose array bound narrowing here; we produce more precise
6591 // errors by allowing the un-narrowed value through.
6592 ReturnPreNarrowingValue = true;
6593 break;
6594 }
6595 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6596 << CCE << /*Constant*/ 1
6597 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6598 // If this is an SFINAE Context, treat the result as invalid so it stops
6599 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6600 // FIXME: Should do this whenever the above diagnostic is an error, but
6601 // without further changes this would degrade some other diagnostics.
6602 if (S.isSFINAEContext())
6603 return ExprError();
6604 break;
6605
6607 // Implicit conversion to a narrower type, but the expression is
6608 // value-dependent so we can't tell whether it's actually narrowing.
6609 // For matching the parameters of a TTP, the conversion is ill-formed
6610 // if it may narrow.
6611 if (CCE != CCEKind::TempArgStrict)
6612 break;
6613 [[fallthrough]];
6614 case NK_Type_Narrowing:
6615 // FIXME: It would be better to diagnose that the expression is not a
6616 // constant expression.
6617 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6618 << CCE << /*Constant*/ 0 << From->getType() << T;
6619 if (S.isSFINAEContext())
6620 return ExprError();
6621 break;
6622 }
6623 if (!ReturnPreNarrowingValue)
6624 PreNarrowingValue = {};
6625
6626 return Result;
6627}
6628
6629/// CheckConvertedConstantExpression - Check that the expression From is a
6630/// converted constant expression of type T, perform the conversion and produce
6631/// the converted expression, per C++11 [expr.const]p3.
6634 CCEKind CCE, bool RequireInt,
6635 NamedDecl *Dest) {
6636
6637 APValue PreNarrowingValue;
6638 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6639 PreNarrowingValue);
6640 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6641 Value = APValue();
6642 return Result;
6643 }
6644 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6645 RequireInt, PreNarrowingValue);
6646}
6647
6649 CCEKind CCE,
6650 NamedDecl *Dest) {
6651 APValue PreNarrowingValue;
6652 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6653 PreNarrowingValue);
6654}
6655
6657 APValue &Value, CCEKind CCE,
6658 NamedDecl *Dest) {
6659 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6660 Dest);
6661}
6662
6664 llvm::APSInt &Value,
6665 CCEKind CCE) {
6666 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6667
6668 APValue V;
6669 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6670 /*Dest=*/nullptr);
6671 if (!R.isInvalid() && !R.get()->isValueDependent())
6672 Value = V.getInt();
6673 return R;
6674}
6675
6678 CCEKind CCE, bool RequireInt,
6679 const APValue &PreNarrowingValue) {
6680
6681 ExprResult Result = E;
6682 // Check the expression is a constant expression.
6684 Expr::EvalResult Eval;
6685 Eval.Diag = &Notes;
6686
6687 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6688
6689 ConstantExprKind Kind;
6690 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6691 Kind = ConstantExprKind::ClassTemplateArgument;
6692 else if (CCE == CCEKind::TemplateArg)
6693 Kind = ConstantExprKind::NonClassTemplateArgument;
6694 else
6695 Kind = ConstantExprKind::Normal;
6696
6697 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6698 (RequireInt && !Eval.Val.isInt())) {
6699 // The expression can't be folded, so we can't keep it at this position in
6700 // the AST.
6701 Result = ExprError();
6702 } else {
6703 Value = Eval.Val;
6704
6705 if (Notes.empty()) {
6706 // It's a constant expression.
6707 Expr *E = Result.get();
6708 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6709 // We expect a ConstantExpr to have a value associated with it
6710 // by this point.
6711 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6712 "ConstantExpr has no value associated with it");
6713 (void)CE;
6714 } else {
6716 }
6717 if (!PreNarrowingValue.isAbsent())
6718 Value = std::move(PreNarrowingValue);
6719 return E;
6720 }
6721 }
6722
6723 // It's not a constant expression. Produce an appropriate diagnostic.
6724 if (Notes.size() == 1 &&
6725 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6726 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6727 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6728 diag::note_constexpr_invalid_template_arg) {
6729 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6730 for (unsigned I = 0; I < Notes.size(); ++I)
6731 Diag(Notes[I].first, Notes[I].second);
6732 } else {
6733 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6734 << CCE << E->getSourceRange();
6735 for (unsigned I = 0; I < Notes.size(); ++I)
6736 Diag(Notes[I].first, Notes[I].second);
6737 }
6738 return ExprError();
6739}
6740
6741/// dropPointerConversions - If the given standard conversion sequence
6742/// involves any pointer conversions, remove them. This may change
6743/// the result type of the conversion sequence.
6745 if (SCS.Second == ICK_Pointer_Conversion) {
6746 SCS.Second = ICK_Identity;
6747 SCS.Dimension = ICK_Identity;
6748 SCS.Third = ICK_Identity;
6749 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6750 }
6751}
6752
6753/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6754/// convert the expression From to an Objective-C pointer type.
6755static ImplicitConversionSequence
6757 // Do an implicit conversion to 'id'.
6760 = TryImplicitConversion(S, From, Ty,
6761 // FIXME: Are these flags correct?
6762 /*SuppressUserConversions=*/false,
6763 AllowedExplicit::Conversions,
6764 /*InOverloadResolution=*/false,
6765 /*CStyle=*/false,
6766 /*AllowObjCWritebackConversion=*/false,
6767 /*AllowObjCConversionOnExplicit=*/true);
6768
6769 // Strip off any final conversions to 'id'.
6770 switch (ICS.getKind()) {
6775 break;
6776
6779 break;
6780
6783 break;
6784 }
6785
6786 return ICS;
6787}
6788
6790 if (checkPlaceholderForOverload(*this, From))
6791 return ExprError();
6792
6793 QualType Ty = Context.getObjCIdType();
6796 if (!ICS.isBad())
6797 return PerformImplicitConversion(From, Ty, ICS,
6799 return ExprResult();
6800}
6801
6802static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6803 const Expr *Base = nullptr;
6804 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6805 "expected a member expression");
6806
6807 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6808 M && !M->isImplicitAccess())
6809 Base = M->getBase();
6810 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6811 M && !M->isImplicitAccess())
6812 Base = M->getBase();
6813
6814 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6815
6816 if (T->isPointerType())
6817 T = T->getPointeeType();
6818
6819 return T;
6820}
6821
6823 const FunctionDecl *Fun) {
6824 QualType ObjType = Obj->getType();
6825 if (ObjType->isPointerType()) {
6826 ObjType = ObjType->getPointeeType();
6827 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6829 /*CanOverflow=*/false, FPOptionsOverride());
6830 }
6831 return Obj;
6832}
6833
6841
6843 Expr *Object, MultiExprArg &Args,
6844 SmallVectorImpl<Expr *> &NewArgs) {
6845 assert(Method->isExplicitObjectMemberFunction() &&
6846 "Method is not an explicit member function");
6847 assert(NewArgs.empty() && "NewArgs should be empty");
6848
6849 NewArgs.reserve(Args.size() + 1);
6850 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6851 NewArgs.push_back(This);
6852 NewArgs.append(Args.begin(), Args.end());
6853 Args = NewArgs;
6855 Method, Object->getBeginLoc());
6856}
6857
6858/// Determine whether the provided type is an integral type, or an enumeration
6859/// type of a permitted flavor.
6861 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6862 : T->isIntegralOrUnscopedEnumerationType();
6863}
6864
6865static ExprResult
6868 QualType T, UnresolvedSetImpl &ViableConversions) {
6869
6870 if (Converter.Suppress)
6871 return ExprError();
6872
6873 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6874 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6875 CXXConversionDecl *Conv =
6876 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6878 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6879 }
6880 return From;
6881}
6882
6883static bool
6886 QualType T, bool HadMultipleCandidates,
6887 UnresolvedSetImpl &ExplicitConversions) {
6888 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6889 DeclAccessPair Found = ExplicitConversions[0];
6890 CXXConversionDecl *Conversion =
6891 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6892
6893 // The user probably meant to invoke the given explicit
6894 // conversion; use it.
6895 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6896 std::string TypeStr;
6897 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6898
6899 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6901 "static_cast<" + TypeStr + ">(")
6903 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6904 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6905
6906 // If we aren't in a SFINAE context, build a call to the
6907 // explicit conversion function.
6908 if (SemaRef.isSFINAEContext())
6909 return true;
6910
6911 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6912 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6913 HadMultipleCandidates);
6914 if (Result.isInvalid())
6915 return true;
6916
6917 // Replace the conversion with a RecoveryExpr, so we don't try to
6918 // instantiate it later, but can further diagnose here.
6919 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6920 From, Result.get()->getType());
6921 if (Result.isInvalid())
6922 return true;
6923 From = Result.get();
6924 }
6925 return false;
6926}
6927
6928static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6930 QualType T, bool HadMultipleCandidates,
6932 CXXConversionDecl *Conversion =
6933 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6934 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6935
6936 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6937 if (!Converter.SuppressConversion) {
6938 if (SemaRef.isSFINAEContext())
6939 return true;
6940
6941 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6942 << From->getSourceRange();
6943 }
6944
6945 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6946 HadMultipleCandidates);
6947 if (Result.isInvalid())
6948 return true;
6949 // Record usage of conversion in an implicit cast.
6950 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6951 CK_UserDefinedConversion, Result.get(),
6952 nullptr, Result.get()->getValueKind(),
6953 SemaRef.CurFPFeatureOverrides());
6954 return false;
6955}
6956
6958 Sema &SemaRef, SourceLocation Loc, Expr *From,
6960 if (!Converter.match(From->getType()) && !Converter.Suppress)
6961 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6962 << From->getSourceRange();
6963
6964 return SemaRef.DefaultLvalueConversion(From);
6965}
6966
6967static void
6969 UnresolvedSetImpl &ViableConversions,
6970 OverloadCandidateSet &CandidateSet) {
6971 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6972 NamedDecl *D = FoundDecl.getDecl();
6973 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6974 if (isa<UsingShadowDecl>(D))
6975 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6976
6977 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6979 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6980 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6981 continue;
6982 }
6984 SemaRef.AddConversionCandidate(
6985 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6986 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6987 }
6988}
6989
6990/// Attempt to convert the given expression to a type which is accepted
6991/// by the given converter.
6992///
6993/// This routine will attempt to convert an expression of class type to a
6994/// type accepted by the specified converter. In C++11 and before, the class
6995/// must have a single non-explicit conversion function converting to a matching
6996/// type. In C++1y, there can be multiple such conversion functions, but only
6997/// one target type.
6998///
6999/// \param Loc The source location of the construct that requires the
7000/// conversion.
7001///
7002/// \param From The expression we're converting from.
7003///
7004/// \param Converter Used to control and diagnose the conversion process.
7005///
7006/// \returns The expression, converted to an integral or enumeration type if
7007/// successful.
7009 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7010 // We can't perform any more checking for type-dependent expressions.
7011 if (From->isTypeDependent())
7012 return From;
7013
7014 // Process placeholders immediately.
7015 if (From->hasPlaceholderType()) {
7016 ExprResult result = CheckPlaceholderExpr(From);
7017 if (result.isInvalid())
7018 return result;
7019 From = result.get();
7020 }
7021
7022 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7023 ExprResult Converted = DefaultLvalueConversion(From);
7024 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7025 // If the expression already has a matching type, we're golden.
7026 if (Converter.match(T))
7027 return Converted;
7028
7029 // FIXME: Check for missing '()' if T is a function type?
7030
7031 // We can only perform contextual implicit conversions on objects of class
7032 // type.
7033 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7034 if (!RecordTy || !getLangOpts().CPlusPlus) {
7035 if (!Converter.Suppress)
7036 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7037 return From;
7038 }
7039
7040 // We must have a complete class type.
7041 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7042 ContextualImplicitConverter &Converter;
7043 Expr *From;
7044
7045 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7046 : Converter(Converter), From(From) {}
7047
7048 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7049 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7050 }
7051 } IncompleteDiagnoser(Converter, From);
7052
7053 if (Converter.Suppress ? !isCompleteType(Loc, T)
7054 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7055 return From;
7056
7057 // Look for a conversion to an integral or enumeration type.
7059 ViableConversions; // These are *potentially* viable in C++1y.
7060 UnresolvedSet<4> ExplicitConversions;
7061 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7062 ->getDefinitionOrSelf()
7063 ->getVisibleConversionFunctions();
7064
7065 bool HadMultipleCandidates =
7066 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7067
7068 // To check that there is only one target type, in C++1y:
7069 QualType ToType;
7070 bool HasUniqueTargetType = true;
7071
7072 // Collect explicit or viable (potentially in C++1y) conversions.
7073 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7074 NamedDecl *D = (*I)->getUnderlyingDecl();
7075 CXXConversionDecl *Conversion;
7076 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7077 if (ConvTemplate) {
7079 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7080 else
7081 continue; // C++11 does not consider conversion operator templates(?).
7082 } else
7083 Conversion = cast<CXXConversionDecl>(D);
7084
7085 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7086 "Conversion operator templates are considered potentially "
7087 "viable in C++1y");
7088
7089 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7090 if (Converter.match(CurToType) || ConvTemplate) {
7091
7092 if (Conversion->isExplicit()) {
7093 // FIXME: For C++1y, do we need this restriction?
7094 // cf. diagnoseNoViableConversion()
7095 if (!ConvTemplate)
7096 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7097 } else {
7098 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7099 if (ToType.isNull())
7100 ToType = CurToType.getUnqualifiedType();
7101 else if (HasUniqueTargetType &&
7102 (CurToType.getUnqualifiedType() != ToType))
7103 HasUniqueTargetType = false;
7104 }
7105 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7106 }
7107 }
7108 }
7109
7110 if (getLangOpts().CPlusPlus14) {
7111 // C++1y [conv]p6:
7112 // ... An expression e of class type E appearing in such a context
7113 // is said to be contextually implicitly converted to a specified
7114 // type T and is well-formed if and only if e can be implicitly
7115 // converted to a type T that is determined as follows: E is searched
7116 // for conversion functions whose return type is cv T or reference to
7117 // cv T such that T is allowed by the context. There shall be
7118 // exactly one such T.
7119
7120 // If no unique T is found:
7121 if (ToType.isNull()) {
7122 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7123 HadMultipleCandidates,
7124 ExplicitConversions))
7125 return ExprError();
7126 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7127 }
7128
7129 // If more than one unique Ts are found:
7130 if (!HasUniqueTargetType)
7131 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7132 ViableConversions);
7133
7134 // If one unique T is found:
7135 // First, build a candidate set from the previously recorded
7136 // potentially viable conversions.
7138 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7139 CandidateSet);
7140
7141 // Then, perform overload resolution over the candidate set.
7143 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7144 case OR_Success: {
7145 // Apply this conversion.
7147 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7148 if (recordConversion(*this, Loc, From, Converter, T,
7149 HadMultipleCandidates, Found))
7150 return ExprError();
7151 break;
7152 }
7153 case OR_Ambiguous:
7154 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7155 ViableConversions);
7157 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7158 HadMultipleCandidates,
7159 ExplicitConversions))
7160 return ExprError();
7161 [[fallthrough]];
7162 case OR_Deleted:
7163 // We'll complain below about a non-integral condition type.
7164 break;
7165 }
7166 } else {
7167 switch (ViableConversions.size()) {
7168 case 0: {
7169 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7170 HadMultipleCandidates,
7171 ExplicitConversions))
7172 return ExprError();
7173
7174 // We'll complain below about a non-integral condition type.
7175 break;
7176 }
7177 case 1: {
7178 // Apply this conversion.
7179 DeclAccessPair Found = ViableConversions[0];
7180 if (recordConversion(*this, Loc, From, Converter, T,
7181 HadMultipleCandidates, Found))
7182 return ExprError();
7183 break;
7184 }
7185 default:
7186 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7187 ViableConversions);
7188 }
7189 }
7190
7191 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7192}
7193
7194/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7195/// an acceptable non-member overloaded operator for a call whose
7196/// arguments have types T1 (and, if non-empty, T2). This routine
7197/// implements the check in C++ [over.match.oper]p3b2 concerning
7198/// enumeration types.
7200 FunctionDecl *Fn,
7201 ArrayRef<Expr *> Args) {
7202 QualType T1 = Args[0]->getType();
7203 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7204
7205 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7206 return true;
7207
7208 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7209 return true;
7210
7211 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7212 if (Proto->getNumParams() < 1)
7213 return false;
7214
7215 if (T1->isEnumeralType()) {
7216 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7217 if (Context.hasSameUnqualifiedType(T1, ArgType))
7218 return true;
7219 }
7220
7221 if (Proto->getNumParams() < 2)
7222 return false;
7223
7224 if (!T2.isNull() && T2->isEnumeralType()) {
7225 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7226 if (Context.hasSameUnqualifiedType(T2, ArgType))
7227 return true;
7228 }
7229
7230 return false;
7231}
7232
7235 return false;
7236
7237 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7238 return FD->isTargetMultiVersion();
7239
7240 if (!FD->isMultiVersion())
7241 return false;
7242
7243 // Among multiple target versions consider either the default,
7244 // or the first non-default in the absence of default version.
7245 unsigned SeenAt = 0;
7246 unsigned I = 0;
7247 bool HasDefault = false;
7249 FD, [&](const FunctionDecl *CurFD) {
7250 if (FD == CurFD)
7251 SeenAt = I;
7252 else if (CurFD->isTargetMultiVersionDefault())
7253 HasDefault = true;
7254 ++I;
7255 });
7256 return HasDefault || SeenAt != 0;
7257}
7258
7261 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7262 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7263 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7264 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7265 bool StrictPackMatch) {
7266 const FunctionProtoType *Proto
7267 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7268 assert(Proto && "Functions without a prototype cannot be overloaded");
7269 assert(!Function->getDescribedFunctionTemplate() &&
7270 "Use AddTemplateOverloadCandidate for function templates");
7271
7272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7274 // If we get here, it's because we're calling a member function
7275 // that is named without a member access expression (e.g.,
7276 // "this->f") that was either written explicitly or created
7277 // implicitly. This can happen with a qualified call to a member
7278 // function, e.g., X::f(). We use an empty type for the implied
7279 // object argument (C++ [over.call.func]p3), and the acting context
7280 // is irrelevant.
7281 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7283 CandidateSet, SuppressUserConversions,
7284 PartialOverloading, EarlyConversions, PO,
7285 StrictPackMatch);
7286 return;
7287 }
7288 // We treat a constructor like a non-member function, since its object
7289 // argument doesn't participate in overload resolution.
7290 }
7291
7292 if (!CandidateSet.isNewCandidate(Function, PO))
7293 return;
7294
7295 // C++11 [class.copy]p11: [DR1402]
7296 // A defaulted move constructor that is defined as deleted is ignored by
7297 // overload resolution.
7298 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7299 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7300 Constructor->isMoveConstructor())
7301 return;
7302
7303 // Overload resolution is always an unevaluated context.
7306
7307 // C++ [over.match.oper]p3:
7308 // if no operand has a class type, only those non-member functions in the
7309 // lookup set that have a first parameter of type T1 or "reference to
7310 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7311 // is a right operand) a second parameter of type T2 or "reference to
7312 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7313 // candidate functions.
7314 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7316 return;
7317
7318 // Add this candidate
7319 OverloadCandidate &Candidate =
7320 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7321 Candidate.FoundDecl = FoundDecl;
7322 Candidate.Function = Function;
7323 Candidate.Viable = true;
7324 Candidate.RewriteKind =
7325 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7326 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7327 Candidate.ExplicitCallArguments = Args.size();
7328 Candidate.StrictPackMatch = StrictPackMatch;
7329
7330 // Explicit functions are not actually candidates at all if we're not
7331 // allowing them in this context, but keep them around so we can point
7332 // to them in diagnostics.
7333 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7334 Candidate.Viable = false;
7335 Candidate.FailureKind = ovl_fail_explicit;
7336 return;
7337 }
7338
7339 // Functions with internal linkage are only viable in the same module unit.
7340 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7341 /// FIXME: Currently, the semantics of linkage in clang is slightly
7342 /// different from the semantics in C++ spec. In C++ spec, only names
7343 /// have linkage. So that all entities of the same should share one
7344 /// linkage. But in clang, different entities of the same could have
7345 /// different linkage.
7346 const NamedDecl *ND = Function;
7347 bool IsImplicitlyInstantiated = false;
7348 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7349 ND = SpecInfo->getTemplate();
7350 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7352 }
7353
7354 /// Don't remove inline functions with internal linkage from the overload
7355 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7356 /// However:
7357 /// - Inline functions with internal linkage are a common pattern in
7358 /// headers to avoid ODR issues.
7359 /// - The global module is meant to be a transition mechanism for C and C++
7360 /// headers, and the current rules as written work against that goal.
7361 const bool IsInlineFunctionInGMF =
7362 Function->isFromGlobalModule() &&
7363 (IsImplicitlyInstantiated || Function->isInlined());
7364
7365 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7366 Candidate.Viable = false;
7368 return;
7369 }
7370 }
7371
7373 Candidate.Viable = false;
7375 return;
7376 }
7377
7378 if (Constructor) {
7379 // C++ [class.copy]p3:
7380 // A member function template is never instantiated to perform the copy
7381 // of a class object to an object of its class type.
7382 CanQualType ClassType =
7383 Context.getCanonicalTagType(Constructor->getParent());
7384 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7385 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7386 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7387 ClassType))) {
7388 Candidate.Viable = false;
7390 return;
7391 }
7392
7393 // C++ [over.match.funcs]p8: (proposed DR resolution)
7394 // A constructor inherited from class type C that has a first parameter
7395 // of type "reference to P" (including such a constructor instantiated
7396 // from a template) is excluded from the set of candidate functions when
7397 // constructing an object of type cv D if the argument list has exactly
7398 // one argument and D is reference-related to P and P is reference-related
7399 // to C.
7400 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7401 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7402 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7403 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7404 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7405 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7406 SourceLocation Loc = Args.front()->getExprLoc();
7407 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7408 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7409 Candidate.Viable = false;
7411 return;
7412 }
7413 }
7414
7415 // Check that the constructor is capable of constructing an object in the
7416 // destination address space.
7418 Constructor->getMethodQualifiers().getAddressSpace(),
7419 CandidateSet.getDestAS(), getASTContext())) {
7420 Candidate.Viable = false;
7422 }
7423 }
7424
7425 unsigned NumParams = Proto->getNumParams();
7426
7427 // (C++ 13.3.2p2): A candidate function having fewer than m
7428 // parameters is viable only if it has an ellipsis in its parameter
7429 // list (8.3.5).
7430 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7431 !Proto->isVariadic() &&
7432 shouldEnforceArgLimit(PartialOverloading, Function)) {
7433 Candidate.Viable = false;
7435 return;
7436 }
7437
7438 // (C++ 13.3.2p2): A candidate function having more than m parameters
7439 // is viable only if the (m+1)st parameter has a default argument
7440 // (8.3.6). For the purposes of overload resolution, the
7441 // parameter list is truncated on the right, so that there are
7442 // exactly m parameters.
7443 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7444 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7445 !PartialOverloading) {
7446 // Not enough arguments.
7447 Candidate.Viable = false;
7449 return;
7450 }
7451
7452 // (CUDA B.1): Check for invalid calls between targets.
7453 if (getLangOpts().CUDA) {
7454 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7455 // Skip the check for callers that are implicit members, because in this
7456 // case we may not yet know what the member's target is; the target is
7457 // inferred for the member automatically, based on the bases and fields of
7458 // the class.
7459 if (!(Caller && Caller->isImplicit()) &&
7460 !CUDA().IsAllowedCall(Caller, Function)) {
7461 Candidate.Viable = false;
7462 Candidate.FailureKind = ovl_fail_bad_target;
7463 return;
7464 }
7465 }
7466
7467 if (Function->getTrailingRequiresClause()) {
7468 ConstraintSatisfaction Satisfaction;
7469 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7470 /*ForOverloadResolution*/ true) ||
7471 !Satisfaction.IsSatisfied) {
7472 Candidate.Viable = false;
7474 return;
7475 }
7476 }
7477
7478 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7479 // Determine the implicit conversion sequences for each of the
7480 // arguments.
7481 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7482 unsigned ConvIdx =
7483 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7484 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7485 // We already formed a conversion sequence for this parameter during
7486 // template argument deduction.
7487 } else if (ArgIdx < NumParams) {
7488 // (C++ 13.3.2p3): for F to be a viable function, there shall
7489 // exist for each argument an implicit conversion sequence
7490 // (13.3.3.1) that converts that argument to the corresponding
7491 // parameter of F.
7492 QualType ParamType = Proto->getParamType(ArgIdx);
7493 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7494 if (ParamABI == ParameterABI::HLSLOut ||
7495 ParamABI == ParameterABI::HLSLInOut) {
7496 ParamType = ParamType.getNonReferenceType();
7497 if (ParamABI == ParameterABI::HLSLInOut &&
7498 Args[ArgIdx]->getType().getAddressSpace() ==
7500 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7501 }
7502 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7503 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7504 /*InOverloadResolution=*/true,
7505 /*AllowObjCWritebackConversion=*/
7506 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7507 if (Candidate.Conversions[ConvIdx].isBad()) {
7508 Candidate.Viable = false;
7510 return;
7511 }
7512 } else {
7513 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7514 // argument for which there is no corresponding parameter is
7515 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7516 Candidate.Conversions[ConvIdx].setEllipsis();
7517 }
7518 }
7519
7520 if (EnableIfAttr *FailedAttr =
7521 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7522 Candidate.Viable = false;
7523 Candidate.FailureKind = ovl_fail_enable_if;
7524 Candidate.DeductionFailure.Data = FailedAttr;
7525 return;
7526 }
7527}
7528
7532 if (Methods.size() <= 1)
7533 return nullptr;
7534
7535 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7536 bool Match = true;
7537 ObjCMethodDecl *Method = Methods[b];
7538 unsigned NumNamedArgs = Sel.getNumArgs();
7539 // Method might have more arguments than selector indicates. This is due
7540 // to addition of c-style arguments in method.
7541 if (Method->param_size() > NumNamedArgs)
7542 NumNamedArgs = Method->param_size();
7543 if (Args.size() < NumNamedArgs)
7544 continue;
7545
7546 for (unsigned i = 0; i < NumNamedArgs; i++) {
7547 // We can't do any type-checking on a type-dependent argument.
7548 if (Args[i]->isTypeDependent()) {
7549 Match = false;
7550 break;
7551 }
7552
7553 ParmVarDecl *param = Method->parameters()[i];
7554 Expr *argExpr = Args[i];
7555 assert(argExpr && "SelectBestMethod(): missing expression");
7556
7557 // Strip the unbridged-cast placeholder expression off unless it's
7558 // a consumed argument.
7559 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7560 !param->hasAttr<CFConsumedAttr>())
7561 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7562
7563 // If the parameter is __unknown_anytype, move on to the next method.
7564 if (param->getType() == Context.UnknownAnyTy) {
7565 Match = false;
7566 break;
7567 }
7568
7569 ImplicitConversionSequence ConversionState
7570 = TryCopyInitialization(*this, argExpr, param->getType(),
7571 /*SuppressUserConversions*/false,
7572 /*InOverloadResolution=*/true,
7573 /*AllowObjCWritebackConversion=*/
7574 getLangOpts().ObjCAutoRefCount,
7575 /*AllowExplicit*/false);
7576 // This function looks for a reasonably-exact match, so we consider
7577 // incompatible pointer conversions to be a failure here.
7578 if (ConversionState.isBad() ||
7579 (ConversionState.isStandard() &&
7580 ConversionState.Standard.Second ==
7582 Match = false;
7583 break;
7584 }
7585 }
7586 // Promote additional arguments to variadic methods.
7587 if (Match && Method->isVariadic()) {
7588 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7589 if (Args[i]->isTypeDependent()) {
7590 Match = false;
7591 break;
7592 }
7594 Args[i], VariadicCallType::Method, nullptr);
7595 if (Arg.isInvalid()) {
7596 Match = false;
7597 break;
7598 }
7599 }
7600 } else {
7601 // Check for extra arguments to non-variadic methods.
7602 if (Args.size() != NumNamedArgs)
7603 Match = false;
7604 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7605 // Special case when selectors have no argument. In this case, select
7606 // one with the most general result type of 'id'.
7607 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7608 QualType ReturnT = Methods[b]->getReturnType();
7609 if (ReturnT->isObjCIdType())
7610 return Methods[b];
7611 }
7612 }
7613 }
7614
7615 if (Match)
7616 return Method;
7617 }
7618 return nullptr;
7619}
7620
7622 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7623 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7624 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7625 if (ThisArg) {
7626 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7627 assert(!isa<CXXConstructorDecl>(Method) &&
7628 "Shouldn't have `this` for ctors!");
7629 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7631 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7632 if (R.isInvalid())
7633 return false;
7634 ConvertedThis = R.get();
7635 } else {
7636 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7637 (void)MD;
7638 assert((MissingImplicitThis || MD->isStatic() ||
7640 "Expected `this` for non-ctor instance methods");
7641 }
7642 ConvertedThis = nullptr;
7643 }
7644
7645 // Ignore any variadic arguments. Converting them is pointless, since the
7646 // user can't refer to them in the function condition.
7647 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7648
7649 // Convert the arguments.
7650 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7651 ExprResult R;
7653 S.Context, Function->getParamDecl(I)),
7654 SourceLocation(), Args[I]);
7655
7656 if (R.isInvalid())
7657 return false;
7658
7659 ConvertedArgs.push_back(R.get());
7660 }
7661
7662 if (Trap.hasErrorOccurred())
7663 return false;
7664
7665 // Push default arguments if needed.
7666 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7667 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7668 ParmVarDecl *P = Function->getParamDecl(i);
7669 if (!P->hasDefaultArg())
7670 return false;
7671 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7672 if (R.isInvalid())
7673 return false;
7674 ConvertedArgs.push_back(R.get());
7675 }
7676
7677 if (Trap.hasErrorOccurred())
7678 return false;
7679 }
7680 return true;
7681}
7682
7684 SourceLocation CallLoc,
7685 ArrayRef<Expr *> Args,
7686 bool MissingImplicitThis) {
7687 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7688 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7689 return nullptr;
7690
7691 SFINAETrap Trap(*this);
7692 // Perform the access checking immediately so any access diagnostics are
7693 // caught by the SFINAE trap.
7694 llvm::scope_exit UndelayDiags(
7695 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7696 DelayedDiagnostics.popUndelayed(CurrentState);
7697 });
7698 SmallVector<Expr *, 16> ConvertedArgs;
7699 // FIXME: We should look into making enable_if late-parsed.
7700 Expr *DiscardedThis;
7702 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7703 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7704 return *EnableIfAttrs.begin();
7705
7706 for (auto *EIA : EnableIfAttrs) {
7708 // FIXME: This doesn't consider value-dependent cases, because doing so is
7709 // very difficult. Ideally, we should handle them more gracefully.
7710 if (EIA->getCond()->isValueDependent() ||
7711 !EIA->getCond()->EvaluateWithSubstitution(
7712 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7713 return EIA;
7714
7715 if (!Result.isInt() || !Result.getInt().getBoolValue())
7716 return EIA;
7717 }
7718 return nullptr;
7719}
7720
7721template <typename CheckFn>
7723 bool ArgDependent, SourceLocation Loc,
7724 CheckFn &&IsSuccessful) {
7726 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7727 if (ArgDependent == DIA->getArgDependent())
7728 Attrs.push_back(DIA);
7729 }
7730
7731 // Common case: No diagnose_if attributes, so we can quit early.
7732 if (Attrs.empty())
7733 return false;
7734
7735 auto WarningBegin = std::stable_partition(
7736 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7737 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7738 DIA->getWarningGroup().empty();
7739 });
7740
7741 // Note that diagnose_if attributes are late-parsed, so they appear in the
7742 // correct order (unlike enable_if attributes).
7743 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7744 IsSuccessful);
7745 if (ErrAttr != WarningBegin) {
7746 const DiagnoseIfAttr *DIA = *ErrAttr;
7747 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7748 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7749 << DIA->getParent() << DIA->getCond()->getSourceRange();
7750 return true;
7751 }
7752
7753 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7754 switch (Sev) {
7755 case DiagnoseIfAttr::DS_warning:
7757 case DiagnoseIfAttr::DS_error:
7758 return diag::Severity::Error;
7759 }
7760 llvm_unreachable("Fully covered switch above!");
7761 };
7762
7763 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7764 if (IsSuccessful(DIA)) {
7765 if (DIA->getWarningGroup().empty() &&
7766 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7767 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7768 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7769 << DIA->getParent() << DIA->getCond()->getSourceRange();
7770 } else {
7771 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7772 DIA->getWarningGroup());
7773 assert(DiagGroup);
7774 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7775 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7776 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7777 S.Diag(Loc, DiagID) << DIA->getMessage();
7778 }
7779 }
7780
7781 return false;
7782}
7783
7785 const Expr *ThisArg,
7787 SourceLocation Loc) {
7789 *this, Function, /*ArgDependent=*/true, Loc,
7790 [&](const DiagnoseIfAttr *DIA) {
7792 // It's sane to use the same Args for any redecl of this function, since
7793 // EvaluateWithSubstitution only cares about the position of each
7794 // argument in the arg list, not the ParmVarDecl* it maps to.
7795 if (!DIA->getCond()->EvaluateWithSubstitution(
7796 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7797 return false;
7798 return Result.isInt() && Result.getInt().getBoolValue();
7799 });
7800}
7801
7803 SourceLocation Loc) {
7805 *this, ND, /*ArgDependent=*/false, Loc,
7806 [&](const DiagnoseIfAttr *DIA) {
7807 bool Result;
7808 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7809 Result;
7810 });
7811}
7812
7814 ArrayRef<Expr *> Args,
7815 OverloadCandidateSet &CandidateSet,
7816 TemplateArgumentListInfo *ExplicitTemplateArgs,
7817 bool SuppressUserConversions,
7818 bool PartialOverloading,
7819 bool FirstArgumentIsBase) {
7820 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7821 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7822 ArrayRef<Expr *> FunctionArgs = Args;
7823
7824 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7825 FunctionDecl *FD =
7826 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7827
7828 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7829 QualType ObjectType;
7830 Expr::Classification ObjectClassification;
7831 if (Args.size() > 0) {
7832 if (Expr *E = Args[0]) {
7833 // Use the explicit base to restrict the lookup:
7834 ObjectType = E->getType();
7835 // Pointers in the object arguments are implicitly dereferenced, so we
7836 // always classify them as l-values.
7837 if (!ObjectType.isNull() && ObjectType->isPointerType())
7838 ObjectClassification = Expr::Classification::makeSimpleLValue();
7839 else
7840 ObjectClassification = E->Classify(Context);
7841 } // .. else there is an implicit base.
7842 FunctionArgs = Args.slice(1);
7843 }
7844 if (FunTmpl) {
7846 FunTmpl, F.getPair(),
7848 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7849 FunctionArgs, CandidateSet, SuppressUserConversions,
7850 PartialOverloading);
7851 } else {
7852 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7853 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7854 ObjectClassification, FunctionArgs, CandidateSet,
7855 SuppressUserConversions, PartialOverloading);
7856 }
7857 } else {
7858 // This branch handles both standalone functions and static methods.
7859
7860 // Slice the first argument (which is the base) when we access
7861 // static method as non-static.
7862 if (Args.size() > 0 &&
7863 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7864 !isa<CXXConstructorDecl>(FD)))) {
7865 assert(cast<CXXMethodDecl>(FD)->isStatic());
7866 FunctionArgs = Args.slice(1);
7867 }
7868 if (FunTmpl) {
7869 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7870 ExplicitTemplateArgs, FunctionArgs,
7871 CandidateSet, SuppressUserConversions,
7872 PartialOverloading);
7873 } else {
7874 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7875 SuppressUserConversions, PartialOverloading);
7876 }
7877 }
7878 }
7879}
7880
7882 Expr::Classification ObjectClassification,
7883 ArrayRef<Expr *> Args,
7884 OverloadCandidateSet &CandidateSet,
7885 bool SuppressUserConversions,
7887 NamedDecl *Decl = FoundDecl.getDecl();
7889
7891 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7892
7893 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7894 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7895 "Expected a member function template");
7896 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7897 /*ExplicitArgs*/ nullptr, ObjectType,
7898 ObjectClassification, Args, CandidateSet,
7899 SuppressUserConversions, false, PO);
7900 } else {
7901 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7902 ObjectType, ObjectClassification, Args, CandidateSet,
7903 SuppressUserConversions, false, {}, PO);
7904 }
7905}
7906
7909 CXXRecordDecl *ActingContext, QualType ObjectType,
7910 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7911 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7912 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7913 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7914 const FunctionProtoType *Proto
7915 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7916 assert(Proto && "Methods without a prototype cannot be overloaded");
7918 "Use AddOverloadCandidate for constructors");
7919
7920 if (!CandidateSet.isNewCandidate(Method, PO))
7921 return;
7922
7923 // C++11 [class.copy]p23: [DR1402]
7924 // A defaulted move assignment operator that is defined as deleted is
7925 // ignored by overload resolution.
7926 if (Method->isDefaulted() && Method->isDeleted() &&
7927 Method->isMoveAssignmentOperator())
7928 return;
7929
7930 // Overload resolution is always an unevaluated context.
7933
7934 bool IgnoreExplicitObject =
7935 (Method->isExplicitObjectMemberFunction() &&
7936 CandidateSet.getKind() ==
7938 bool ImplicitObjectMethodTreatedAsStatic =
7939 CandidateSet.getKind() ==
7941 Method->isImplicitObjectMemberFunction();
7942
7943 unsigned ExplicitOffset =
7944 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7945
7946 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7947 int(ImplicitObjectMethodTreatedAsStatic);
7948
7949 unsigned ExtraArgs =
7951 ? 0
7952 : 1;
7953
7954 // Add this candidate
7955 OverloadCandidate &Candidate =
7956 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7957 Candidate.FoundDecl = FoundDecl;
7958 Candidate.Function = Method;
7959 Candidate.RewriteKind =
7960 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7961 Candidate.TookAddressOfOverload =
7963 Candidate.ExplicitCallArguments = Args.size();
7964 Candidate.StrictPackMatch = StrictPackMatch;
7965
7966 // (C++ 13.3.2p2): A candidate function having fewer than m
7967 // parameters is viable only if it has an ellipsis in its parameter
7968 // list (8.3.5).
7969 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7970 !Proto->isVariadic() &&
7971 shouldEnforceArgLimit(PartialOverloading, Method)) {
7972 Candidate.Viable = false;
7974 return;
7975 }
7976
7977 // (C++ 13.3.2p2): A candidate function having more than m parameters
7978 // is viable only if the (m+1)st parameter has a default argument
7979 // (8.3.6). For the purposes of overload resolution, the
7980 // parameter list is truncated on the right, so that there are
7981 // exactly m parameters.
7982 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7983 ExplicitOffset +
7984 int(ImplicitObjectMethodTreatedAsStatic);
7985
7986 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7987 // Not enough arguments.
7988 Candidate.Viable = false;
7990 return;
7991 }
7992
7993 Candidate.Viable = true;
7994
7995 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7996 if (!IgnoreExplicitObject) {
7997 if (ObjectType.isNull())
7998 Candidate.IgnoreObjectArgument = true;
7999 else if (Method->isStatic()) {
8000 // [over.best.ics.general]p8
8001 // When the parameter is the implicit object parameter of a static member
8002 // function, the implicit conversion sequence is a standard conversion
8003 // sequence that is neither better nor worse than any other standard
8004 // conversion sequence.
8005 //
8006 // This is a rule that was introduced in C++23 to support static lambdas.
8007 // We apply it retroactively because we want to support static lambdas as
8008 // an extension and it doesn't hurt previous code.
8009 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8010 } else {
8011 // Determine the implicit conversion sequence for the object
8012 // parameter.
8013 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8014 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8015 Method, ActingContext, /*InOverloadResolution=*/true);
8016 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8017 Candidate.Viable = false;
8019 return;
8020 }
8021 }
8022 }
8023
8024 // (CUDA B.1): Check for invalid calls between targets.
8025 if (getLangOpts().CUDA)
8026 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8027 Method)) {
8028 Candidate.Viable = false;
8029 Candidate.FailureKind = ovl_fail_bad_target;
8030 return;
8031 }
8032
8033 if (Method->getTrailingRequiresClause()) {
8034 ConstraintSatisfaction Satisfaction;
8035 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8036 /*ForOverloadResolution*/ true) ||
8037 !Satisfaction.IsSatisfied) {
8038 Candidate.Viable = false;
8040 return;
8041 }
8042 }
8043
8044 // Determine the implicit conversion sequences for each of the
8045 // arguments.
8046 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8047 unsigned ConvIdx =
8048 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8049 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8050 // We already formed a conversion sequence for this parameter during
8051 // template argument deduction.
8052 } else if (ArgIdx < NumParams) {
8053 // (C++ 13.3.2p3): for F to be a viable function, there shall
8054 // exist for each argument an implicit conversion sequence
8055 // (13.3.3.1) that converts that argument to the corresponding
8056 // parameter of F.
8057 QualType ParamType;
8058 if (ImplicitObjectMethodTreatedAsStatic) {
8059 ParamType = ArgIdx == 0
8060 ? Method->getFunctionObjectParameterReferenceType()
8061 : Proto->getParamType(ArgIdx - 1);
8062 } else {
8063 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8064 }
8065 Candidate.Conversions[ConvIdx]
8066 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8067 SuppressUserConversions,
8068 /*InOverloadResolution=*/true,
8069 /*AllowObjCWritebackConversion=*/
8070 getLangOpts().ObjCAutoRefCount);
8071 if (Candidate.Conversions[ConvIdx].isBad()) {
8072 Candidate.Viable = false;
8074 return;
8075 }
8076 } else {
8077 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8078 // argument for which there is no corresponding parameter is
8079 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8080 Candidate.Conversions[ConvIdx].setEllipsis();
8081 }
8082 }
8083
8084 if (EnableIfAttr *FailedAttr =
8085 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8086 Candidate.Viable = false;
8087 Candidate.FailureKind = ovl_fail_enable_if;
8088 Candidate.DeductionFailure.Data = FailedAttr;
8089 return;
8090 }
8091
8093 Candidate.Viable = false;
8095 }
8096}
8097
8099 Sema &S, OverloadCandidateSet &CandidateSet,
8100 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8101 CXXRecordDecl *ActingContext,
8102 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8103 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8104 bool SuppressUserConversions, bool PartialOverloading,
8106
8107 // C++ [over.match.funcs]p7:
8108 // In each case where a candidate is a function template, candidate
8109 // function template specializations are generated using template argument
8110 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8111 // candidate functions in the usual way.113) A given name can refer to one
8112 // or more function templates and also to a set of overloaded non-template
8113 // functions. In such a case, the candidate functions generated from each
8114 // function template are combined with the set of non-template candidate
8115 // functions.
8116 TemplateDeductionInfo Info(CandidateSet.getLocation());
8117 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8118 FunctionDecl *Specialization = nullptr;
8119 ConversionSequenceList Conversions;
8121 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8122 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8123 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8124 CandidateSet.getKind() ==
8126 [&](ArrayRef<QualType> ParamTypes,
8127 bool OnlyInitializeNonUserDefinedConversions) {
8128 return S.CheckNonDependentConversions(
8129 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8130 Sema::CheckNonDependentConversionsFlag(
8131 SuppressUserConversions,
8132 OnlyInitializeNonUserDefinedConversions),
8133 ActingContext, ObjectType, ObjectClassification, PO);
8134 });
8136 OverloadCandidate &Candidate =
8137 CandidateSet.addCandidate(Conversions.size(), Conversions);
8138 Candidate.FoundDecl = FoundDecl;
8139 Candidate.Function = Method;
8140 Candidate.Viable = false;
8141 Candidate.RewriteKind =
8142 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8143 Candidate.IsSurrogate = false;
8144 Candidate.TookAddressOfOverload =
8145 CandidateSet.getKind() ==
8147
8148 Candidate.IgnoreObjectArgument =
8149 Method->isStatic() ||
8150 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8151 Candidate.ExplicitCallArguments = Args.size();
8154 else {
8156 Candidate.DeductionFailure =
8157 MakeDeductionFailureInfo(S.Context, Result, Info);
8158 }
8159 return;
8160 }
8161
8162 // Add the function template specialization produced by template argument
8163 // deduction as a candidate.
8164 assert(Specialization && "Missing member function template specialization?");
8166 "Specialization is not a member function?");
8168 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8169 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8170 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8171}
8172
8174 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8175 CXXRecordDecl *ActingContext,
8176 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8177 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8178 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8179 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8180 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8181 return;
8182
8183 if (ExplicitTemplateArgs ||
8186 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8187 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8188 SuppressUserConversions, PartialOverloading, PO);
8189 return;
8190 }
8191
8193 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8194 Args, SuppressUserConversions, PartialOverloading, PO);
8195}
8196
8197/// Determine whether a given function template has a simple explicit specifier
8198/// or a non-value-dependent explicit-specification that evaluates to true.
8202
8207
8209 Sema &S, OverloadCandidateSet &CandidateSet,
8211 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8212 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8214 bool AggregateCandidateDeduction) {
8215
8216 // If the function template has a non-dependent explicit specification,
8217 // exclude it now if appropriate; we are not permitted to perform deduction
8218 // and substitution in this case.
8219 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8220 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8221 Candidate.FoundDecl = FoundDecl;
8222 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8223 Candidate.Viable = false;
8224 Candidate.FailureKind = ovl_fail_explicit;
8225 return;
8226 }
8227
8228 // C++ [over.match.funcs]p7:
8229 // In each case where a candidate is a function template, candidate
8230 // function template specializations are generated using template argument
8231 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8232 // candidate functions in the usual way.113) A given name can refer to one
8233 // or more function templates and also to a set of overloaded non-template
8234 // functions. In such a case, the candidate functions generated from each
8235 // function template are combined with the set of non-template candidate
8236 // functions.
8237 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8238 FunctionTemplate->getTemplateDepth());
8239 FunctionDecl *Specialization = nullptr;
8240 ConversionSequenceList Conversions;
8242 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8243 PartialOverloading, AggregateCandidateDeduction,
8244 /*PartialOrdering=*/false,
8245 /*ObjectType=*/QualType(),
8246 /*ObjectClassification=*/Expr::Classification(),
8247 CandidateSet.getKind() ==
8249 [&](ArrayRef<QualType> ParamTypes,
8250 bool OnlyInitializeNonUserDefinedConversions) {
8251 return S.CheckNonDependentConversions(
8252 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8253 Sema::CheckNonDependentConversionsFlag(
8254 SuppressUserConversions,
8255 OnlyInitializeNonUserDefinedConversions),
8256 nullptr, QualType(), {}, PO);
8257 });
8259 OverloadCandidate &Candidate =
8260 CandidateSet.addCandidate(Conversions.size(), Conversions);
8261 Candidate.FoundDecl = FoundDecl;
8262 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8263 Candidate.Viable = false;
8264 Candidate.RewriteKind =
8265 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8266 Candidate.IsSurrogate = false;
8267 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8268 // Ignore the object argument if there is one, since we don't have an object
8269 // type.
8270 Candidate.TookAddressOfOverload =
8271 CandidateSet.getKind() ==
8273
8274 Candidate.IgnoreObjectArgument =
8275 isa<CXXMethodDecl>(Candidate.Function) &&
8276 !cast<CXXMethodDecl>(Candidate.Function)
8277 ->isExplicitObjectMemberFunction() &&
8279
8280 Candidate.ExplicitCallArguments = Args.size();
8283 else {
8285 Candidate.DeductionFailure =
8287 }
8288 return;
8289 }
8290
8291 // Add the function template specialization produced by template argument
8292 // deduction as a candidate.
8293 assert(Specialization && "Missing function template specialization?");
8295 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8296 PartialOverloading, AllowExplicit,
8297 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8298 Info.AggregateDeductionCandidateHasMismatchedArity,
8299 Info.hasStrictPackMatch());
8300}
8301
8304 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8305 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8306 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8307 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8308 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8309 return;
8310
8311 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8312
8313 if (ExplicitTemplateArgs ||
8315 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8316 DependentExplicitSpecifier)) {
8317
8319 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8320 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8321 IsADLCandidate, PO, AggregateCandidateDeduction);
8322
8323 if (DependentExplicitSpecifier)
8325 return;
8326 }
8327
8328 CandidateSet.AddDeferredTemplateCandidate(
8329 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8330 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8331 AggregateCandidateDeduction);
8332}
8333
8336 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8338 CheckNonDependentConversionsFlag UserConversionFlag,
8339 CXXRecordDecl *ActingContext, QualType ObjectType,
8340 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8341 // FIXME: The cases in which we allow explicit conversions for constructor
8342 // arguments never consider calling a constructor template. It's not clear
8343 // that is correct.
8344 const bool AllowExplicit = false;
8345
8346 bool ForOverloadSetAddressResolution =
8348 auto *FD = FunctionTemplate->getTemplatedDecl();
8349 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8350 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8352 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8353
8354 if (Conversions.empty())
8355 Conversions =
8356 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8357
8358 // Overload resolution is always an unevaluated context.
8361
8362 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8363 // require that, but this check should never result in a hard error, and
8364 // overload resolution is permitted to sidestep instantiations.
8365 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8366 !ObjectType.isNull()) {
8367 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8368 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8369 !ParamTypes[0]->isDependentType()) {
8371 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8372 Method, ActingContext, /*InOverloadResolution=*/true,
8373 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8374 : QualType());
8375 if (Conversions[ConvIdx].isBad())
8376 return true;
8377 }
8378 }
8379
8380 // A speculative workaround for self-dependent constraint bugs that manifest
8381 // after CWG2369.
8382 // FIXME: Add references to the standard once P3606 is adopted.
8383 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8384 QualType ArgType) {
8385 ParamType = ParamType.getNonReferenceType();
8386 ArgType = ArgType.getNonReferenceType();
8387 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8388 if (PointerConv) {
8389 ParamType = ParamType->getPointeeType();
8390 ArgType = ArgType->getPointeeType();
8391 }
8392
8393 if (auto *RD = ParamType->getAsCXXRecordDecl();
8394 RD && RD->hasDefinition() &&
8395 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8396 auto Info = getConstructorInfo(ND);
8397 if (!Info)
8398 return false;
8399 CXXConstructorDecl *Ctor = Info.Constructor;
8400 /// isConvertingConstructor takes copy/move constructors into
8401 /// account!
8402 return !Ctor->isCopyOrMoveConstructor() &&
8404 /*AllowExplicit=*/true);
8405 }))
8406 return true;
8407 if (auto *RD = ArgType->getAsCXXRecordDecl();
8408 RD && RD->hasDefinition() &&
8409 !RD->getVisibleConversionFunctions().empty())
8410 return true;
8411
8412 return false;
8413 };
8414
8415 unsigned Offset =
8416 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8417 : 0;
8418
8419 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8420 I != N; ++I) {
8421 QualType ParamType = ParamTypes[I + Offset];
8422 if (!ParamType->isDependentType()) {
8423 unsigned ConvIdx;
8425 ConvIdx = Args.size() - 1 - I;
8426 assert(Args.size() + ThisConversions == 2 &&
8427 "number of args (including 'this') must be exactly 2 for "
8428 "reversed order");
8429 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8430 // would also be 0. 'this' got ConvIdx = 1 previously.
8431 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8432 } else {
8433 // For members, 'this' got ConvIdx = 0 previously.
8434 ConvIdx = ThisConversions + I;
8435 }
8436 if (Conversions[ConvIdx].isInitialized())
8437 continue;
8438 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8439 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8440 continue;
8442 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8443 /*InOverloadResolution=*/true,
8444 /*AllowObjCWritebackConversion=*/
8445 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8446 if (Conversions[ConvIdx].isBad())
8447 return true;
8448 }
8449 }
8450
8451 return false;
8452}
8453
8454/// Determine whether this is an allowable conversion from the result
8455/// of an explicit conversion operator to the expected type, per C++
8456/// [over.match.conv]p1 and [over.match.ref]p1.
8457///
8458/// \param ConvType The return type of the conversion function.
8459///
8460/// \param ToType The type we are converting to.
8461///
8462/// \param AllowObjCPointerConversion Allow a conversion from one
8463/// Objective-C pointer to another.
8464///
8465/// \returns true if the conversion is allowable, false otherwise.
8467 QualType ConvType, QualType ToType,
8468 bool AllowObjCPointerConversion) {
8469 QualType ToNonRefType = ToType.getNonReferenceType();
8470
8471 // Easy case: the types are the same.
8472 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8473 return true;
8474
8475 // Allow qualification conversions.
8476 bool ObjCLifetimeConversion;
8477 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8478 ObjCLifetimeConversion))
8479 return true;
8480
8481 // If we're not allowed to consider Objective-C pointer conversions,
8482 // we're done.
8483 if (!AllowObjCPointerConversion)
8484 return false;
8485
8486 // Is this an Objective-C pointer conversion?
8487 bool IncompatibleObjC = false;
8488 QualType ConvertedType;
8489 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8490 IncompatibleObjC);
8491}
8492
8494 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8495 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8496 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8497 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8498 assert(!Conversion->getDescribedFunctionTemplate() &&
8499 "Conversion function templates use AddTemplateConversionCandidate");
8500 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8501 if (!CandidateSet.isNewCandidate(Conversion))
8502 return;
8503
8504 // If the conversion function has an undeduced return type, trigger its
8505 // deduction now.
8506 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8507 if (DeduceReturnType(Conversion, From->getExprLoc()))
8508 return;
8509 ConvType = Conversion->getConversionType().getNonReferenceType();
8510 }
8511
8512 // If we don't allow any conversion of the result type, ignore conversion
8513 // functions that don't convert to exactly (possibly cv-qualified) T.
8514 if (!AllowResultConversion &&
8515 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8516 return;
8517
8518 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8519 // operator is only a candidate if its return type is the target type or
8520 // can be converted to the target type with a qualification conversion.
8521 //
8522 // FIXME: Include such functions in the candidate list and explain why we
8523 // can't select them.
8524 if (Conversion->isExplicit() &&
8525 !isAllowableExplicitConversion(*this, ConvType, ToType,
8526 AllowObjCConversionOnExplicit))
8527 return;
8528
8529 // Overload resolution is always an unevaluated context.
8532
8533 // Add this candidate
8534 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8535 Candidate.FoundDecl = FoundDecl;
8536 Candidate.Function = Conversion;
8538 Candidate.FinalConversion.setFromType(ConvType);
8539 Candidate.FinalConversion.setAllToTypes(ToType);
8540 Candidate.HasFinalConversion = true;
8541 Candidate.Viable = true;
8542 Candidate.ExplicitCallArguments = 1;
8543 Candidate.StrictPackMatch = StrictPackMatch;
8544
8545 // Explicit functions are not actually candidates at all if we're not
8546 // allowing them in this context, but keep them around so we can point
8547 // to them in diagnostics.
8548 if (!AllowExplicit && Conversion->isExplicit()) {
8549 Candidate.Viable = false;
8550 Candidate.FailureKind = ovl_fail_explicit;
8551 return;
8552 }
8553
8554 // C++ [over.match.funcs]p4:
8555 // For conversion functions, the function is considered to be a member of
8556 // the class of the implicit implied object argument for the purpose of
8557 // defining the type of the implicit object parameter.
8558 //
8559 // Determine the implicit conversion sequence for the implicit
8560 // object parameter.
8561 QualType ObjectType = From->getType();
8562 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8563 ObjectType = FromPtrType->getPointeeType();
8564 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8565 // C++23 [over.best.ics.general]
8566 // However, if the target is [...]
8567 // - the object parameter of a user-defined conversion function
8568 // [...] user-defined conversion sequences are not considered.
8570 *this, CandidateSet.getLocation(), From->getType(),
8571 From->Classify(Context), Conversion, ConversionContext,
8572 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8573 /*SuppressUserConversion*/ true);
8574
8575 if (Candidate.Conversions[0].isBad()) {
8576 Candidate.Viable = false;
8578 return;
8579 }
8580
8581 if (Conversion->getTrailingRequiresClause()) {
8582 ConstraintSatisfaction Satisfaction;
8583 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8584 !Satisfaction.IsSatisfied) {
8585 Candidate.Viable = false;
8587 return;
8588 }
8589 }
8590
8591 // We won't go through a user-defined type conversion function to convert a
8592 // derived to base as such conversions are given Conversion Rank. They only
8593 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8594 QualType FromCanon
8595 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8596 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8597 if (FromCanon == ToCanon ||
8598 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8599 Candidate.Viable = false;
8601 return;
8602 }
8603
8604 // To determine what the conversion from the result of calling the
8605 // conversion function to the type we're eventually trying to
8606 // convert to (ToType), we need to synthesize a call to the
8607 // conversion function and attempt copy initialization from it. This
8608 // makes sure that we get the right semantics with respect to
8609 // lvalues/rvalues and the type. Fortunately, we can allocate this
8610 // call on the stack and we don't need its arguments to be
8611 // well-formed.
8612 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8613 VK_LValue, From->getBeginLoc());
8615 Context.getPointerType(Conversion->getType()),
8616 CK_FunctionToPointerDecay, &ConversionRef,
8618
8619 QualType ConversionType = Conversion->getConversionType();
8620 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8621 Candidate.Viable = false;
8623 return;
8624 }
8625
8626 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8627
8628 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8629
8630 // Introduce a temporary expression with the right type and value category
8631 // that we can use for deduction purposes.
8632 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8633
8635 TryCopyInitialization(*this, &FakeCall, ToType,
8636 /*SuppressUserConversions=*/true,
8637 /*InOverloadResolution=*/false,
8638 /*AllowObjCWritebackConversion=*/false);
8639
8640 switch (ICS.getKind()) {
8642 Candidate.FinalConversion = ICS.Standard;
8643 Candidate.HasFinalConversion = true;
8644
8645 // C++ [over.ics.user]p3:
8646 // If the user-defined conversion is specified by a specialization of a
8647 // conversion function template, the second standard conversion sequence
8648 // shall have exact match rank.
8649 if (Conversion->getPrimaryTemplate() &&
8651 Candidate.Viable = false;
8653 return;
8654 }
8655
8656 // C++0x [dcl.init.ref]p5:
8657 // In the second case, if the reference is an rvalue reference and
8658 // the second standard conversion sequence of the user-defined
8659 // conversion sequence includes an lvalue-to-rvalue conversion, the
8660 // program is ill-formed.
8661 if (ToType->isRValueReferenceType() &&
8663 Candidate.Viable = false;
8665 return;
8666 }
8667 break;
8668
8670 Candidate.Viable = false;
8672 return;
8673
8674 default:
8675 llvm_unreachable(
8676 "Can only end up with a standard conversion sequence or failure");
8677 }
8678
8679 if (EnableIfAttr *FailedAttr =
8680 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8681 Candidate.Viable = false;
8682 Candidate.FailureKind = ovl_fail_enable_if;
8683 Candidate.DeductionFailure.Data = FailedAttr;
8684 return;
8685 }
8686
8687 if (isNonViableMultiVersionOverload(Conversion)) {
8688 Candidate.Viable = false;
8690 }
8691}
8692
8694 Sema &S, OverloadCandidateSet &CandidateSet,
8696 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8697 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8698 bool AllowResultConversion) {
8699
8700 // If the function template has a non-dependent explicit specification,
8701 // exclude it now if appropriate; we are not permitted to perform deduction
8702 // and substitution in this case.
8703 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8704 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8705 Candidate.FoundDecl = FoundDecl;
8706 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8707 Candidate.Viable = false;
8708 Candidate.FailureKind = ovl_fail_explicit;
8709 return;
8710 }
8711
8712 QualType ObjectType = From->getType();
8713 Expr::Classification ObjectClassification = From->Classify(S.Context);
8714
8715 TemplateDeductionInfo Info(CandidateSet.getLocation());
8718 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8719 Specialization, Info);
8721 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8722 Candidate.FoundDecl = FoundDecl;
8723 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8724 Candidate.Viable = false;
8726 Candidate.ExplicitCallArguments = 1;
8727 Candidate.DeductionFailure =
8728 MakeDeductionFailureInfo(S.Context, Result, Info);
8729 return;
8730 }
8731
8732 // Add the conversion function template specialization produced by
8733 // template argument deduction as a candidate.
8734 assert(Specialization && "Missing function template specialization?");
8735 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8736 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8737 AllowExplicit, AllowResultConversion,
8738 Info.hasStrictPackMatch());
8739}
8740
8743 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8744 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8745 bool AllowExplicit, bool AllowResultConversion) {
8746 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8747 "Only conversion function templates permitted here");
8748
8749 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8750 return;
8751
8753 CandidateSet.getKind() ==
8757 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8758 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8759 AllowResultConversion);
8760
8762 return;
8763 }
8764
8766 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8767 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8768}
8769
8771 DeclAccessPair FoundDecl,
8772 CXXRecordDecl *ActingContext,
8773 const FunctionProtoType *Proto,
8774 Expr *Object,
8775 ArrayRef<Expr *> Args,
8776 OverloadCandidateSet& CandidateSet) {
8777 if (!CandidateSet.isNewCandidate(Conversion))
8778 return;
8779
8780 // Overload resolution is always an unevaluated context.
8783
8784 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8785 Candidate.FoundDecl = FoundDecl;
8786 Candidate.Function = nullptr;
8787 Candidate.Surrogate = Conversion;
8788 Candidate.IsSurrogate = true;
8789 Candidate.Viable = true;
8790 Candidate.ExplicitCallArguments = Args.size();
8791
8792 // Determine the implicit conversion sequence for the implicit
8793 // object parameter.
8794 ImplicitConversionSequence ObjectInit;
8795 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8796 ObjectInit = TryCopyInitialization(*this, Object,
8797 Conversion->getParamDecl(0)->getType(),
8798 /*SuppressUserConversions=*/false,
8799 /*InOverloadResolution=*/true, false);
8800 } else {
8802 *this, CandidateSet.getLocation(), Object->getType(),
8803 Object->Classify(Context), Conversion, ActingContext);
8804 }
8805
8806 if (ObjectInit.isBad()) {
8807 Candidate.Viable = false;
8809 Candidate.Conversions[0] = ObjectInit;
8810 return;
8811 }
8812
8813 // The first conversion is actually a user-defined conversion whose
8814 // first conversion is ObjectInit's standard conversion (which is
8815 // effectively a reference binding). Record it as such.
8816 Candidate.Conversions[0].setUserDefined();
8817 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8818 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8819 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8820 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8821 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8822 Candidate.Conversions[0].UserDefined.After
8823 = Candidate.Conversions[0].UserDefined.Before;
8824 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8825
8826 // Find the
8827 unsigned NumParams = Proto->getNumParams();
8828
8829 // (C++ 13.3.2p2): A candidate function having fewer than m
8830 // parameters is viable only if it has an ellipsis in its parameter
8831 // list (8.3.5).
8832 if (Args.size() > NumParams && !Proto->isVariadic()) {
8833 Candidate.Viable = false;
8835 return;
8836 }
8837
8838 // Function types don't have any default arguments, so just check if
8839 // we have enough arguments.
8840 if (Args.size() < NumParams) {
8841 // Not enough arguments.
8842 Candidate.Viable = false;
8844 return;
8845 }
8846
8847 // Determine the implicit conversion sequences for each of the
8848 // arguments.
8849 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8850 if (ArgIdx < NumParams) {
8851 // (C++ 13.3.2p3): for F to be a viable function, there shall
8852 // exist for each argument an implicit conversion sequence
8853 // (13.3.3.1) that converts that argument to the corresponding
8854 // parameter of F.
8855 QualType ParamType = Proto->getParamType(ArgIdx);
8856 Candidate.Conversions[ArgIdx + 1]
8857 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8858 /*SuppressUserConversions=*/false,
8859 /*InOverloadResolution=*/false,
8860 /*AllowObjCWritebackConversion=*/
8861 getLangOpts().ObjCAutoRefCount);
8862 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8863 Candidate.Viable = false;
8865 return;
8866 }
8867 } else {
8868 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8869 // argument for which there is no corresponding parameter is
8870 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8871 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8872 }
8873 }
8874
8875 if (Conversion->getTrailingRequiresClause()) {
8876 ConstraintSatisfaction Satisfaction;
8877 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8878 /*ForOverloadResolution*/ true) ||
8879 !Satisfaction.IsSatisfied) {
8880 Candidate.Viable = false;
8882 return;
8883 }
8884 }
8885
8886 if (EnableIfAttr *FailedAttr =
8887 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8888 Candidate.Viable = false;
8889 Candidate.FailureKind = ovl_fail_enable_if;
8890 Candidate.DeductionFailure.Data = FailedAttr;
8891 return;
8892 }
8893}
8894
8896 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8897 OverloadCandidateSet &CandidateSet,
8898 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8899 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8900 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8901 ArrayRef<Expr *> FunctionArgs = Args;
8902
8903 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8904 FunctionDecl *FD =
8905 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8906
8907 // Don't consider rewritten functions if we're not rewriting.
8908 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8909 continue;
8910
8911 assert(!isa<CXXMethodDecl>(FD) &&
8912 "unqualified operator lookup found a member function");
8913
8914 if (FunTmpl) {
8915 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8916 FunctionArgs, CandidateSet);
8917 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8918
8919 // As template candidates are not deduced immediately,
8920 // persist the array in the overload set.
8922 FunctionArgs[1], FunctionArgs[0]);
8923 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8924 Reversed, CandidateSet, false, false, true,
8925 ADLCallKind::NotADL,
8927 }
8928 } else {
8929 if (ExplicitTemplateArgs)
8930 continue;
8931 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8932 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8933 AddOverloadCandidate(FD, F.getPair(),
8934 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8935 false, false, true, false, ADLCallKind::NotADL, {},
8937 }
8938 }
8939}
8940
8942 SourceLocation OpLoc,
8943 ArrayRef<Expr *> Args,
8944 OverloadCandidateSet &CandidateSet,
8946 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8947
8948 // C++ [over.match.oper]p3:
8949 // For a unary operator @ with an operand of a type whose
8950 // cv-unqualified version is T1, and for a binary operator @ with
8951 // a left operand of a type whose cv-unqualified version is T1 and
8952 // a right operand of a type whose cv-unqualified version is T2,
8953 // three sets of candidate functions, designated member
8954 // candidates, non-member candidates and built-in candidates, are
8955 // constructed as follows:
8956 QualType T1 = Args[0]->getType();
8957
8958 // -- If T1 is a complete class type or a class currently being
8959 // defined, the set of member candidates is the result of the
8960 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8961 // the set of member candidates is empty.
8962 if (T1->isRecordType()) {
8963 bool IsComplete = isCompleteType(OpLoc, T1);
8964 auto *T1RD = T1->getAsCXXRecordDecl();
8965 // Complete the type if it can be completed.
8966 // If the type is neither complete nor being defined, bail out now.
8967 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8968 return;
8969
8970 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8971 LookupQualifiedName(Operators, T1RD);
8972 Operators.suppressAccessDiagnostics();
8973
8974 for (LookupResult::iterator Oper = Operators.begin(),
8975 OperEnd = Operators.end();
8976 Oper != OperEnd; ++Oper) {
8977 if (Oper->getAsFunction() &&
8979 !CandidateSet.getRewriteInfo().shouldAddReversed(
8980 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8981 continue;
8982 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8983 Args[0]->Classify(Context), Args.slice(1),
8984 CandidateSet, /*SuppressUserConversion=*/false, PO);
8985 }
8986 }
8987}
8988
8990 OverloadCandidateSet& CandidateSet,
8991 bool IsAssignmentOperator,
8992 unsigned NumContextualBoolArguments) {
8993 // Overload resolution is always an unevaluated context.
8996
8997 // Add this candidate
8998 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8999 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9000 Candidate.Function = nullptr;
9001 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9002
9003 // Determine the implicit conversion sequences for each of the
9004 // arguments.
9005 Candidate.Viable = true;
9006 Candidate.ExplicitCallArguments = Args.size();
9007 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9008 // C++ [over.match.oper]p4:
9009 // For the built-in assignment operators, conversions of the
9010 // left operand are restricted as follows:
9011 // -- no temporaries are introduced to hold the left operand, and
9012 // -- no user-defined conversions are applied to the left
9013 // operand to achieve a type match with the left-most
9014 // parameter of a built-in candidate.
9015 //
9016 // We block these conversions by turning off user-defined
9017 // conversions, since that is the only way that initialization of
9018 // a reference to a non-class type can occur from something that
9019 // is not of the same type.
9020 if (ArgIdx < NumContextualBoolArguments) {
9021 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9022 "Contextual conversion to bool requires bool type");
9023 Candidate.Conversions[ArgIdx]
9024 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9025 } else {
9026 Candidate.Conversions[ArgIdx]
9027 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9028 ArgIdx == 0 && IsAssignmentOperator,
9029 /*InOverloadResolution=*/false,
9030 /*AllowObjCWritebackConversion=*/
9031 getLangOpts().ObjCAutoRefCount);
9032 }
9033 if (Candidate.Conversions[ArgIdx].isBad()) {
9034 Candidate.Viable = false;
9036 break;
9037 }
9038 }
9039}
9040
9041namespace {
9042
9043/// BuiltinCandidateTypeSet - A set of types that will be used for the
9044/// candidate operator functions for built-in operators (C++
9045/// [over.built]). The types are separated into pointer types and
9046/// enumeration types.
9047class BuiltinCandidateTypeSet {
9048 /// TypeSet - A set of types.
9049 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9050
9051 /// PointerTypes - The set of pointer types that will be used in the
9052 /// built-in candidates.
9053 TypeSet PointerTypes;
9054
9055 /// MemberPointerTypes - The set of member pointer types that will be
9056 /// used in the built-in candidates.
9057 TypeSet MemberPointerTypes;
9058
9059 /// EnumerationTypes - The set of enumeration types that will be
9060 /// used in the built-in candidates.
9061 TypeSet EnumerationTypes;
9062
9063 /// The set of vector types that will be used in the built-in
9064 /// candidates.
9065 TypeSet VectorTypes;
9066
9067 /// The set of matrix types that will be used in the built-in
9068 /// candidates.
9069 TypeSet MatrixTypes;
9070
9071 /// The set of _BitInt types that will be used in the built-in candidates.
9072 TypeSet BitIntTypes;
9073
9074 /// A flag indicating non-record types are viable candidates
9075 bool HasNonRecordTypes;
9076
9077 /// A flag indicating whether either arithmetic or enumeration types
9078 /// were present in the candidate set.
9079 bool HasArithmeticOrEnumeralTypes;
9080
9081 /// A flag indicating whether the nullptr type was present in the
9082 /// candidate set.
9083 bool HasNullPtrType;
9084
9085 /// Sema - The semantic analysis instance where we are building the
9086 /// candidate type set.
9087 Sema &SemaRef;
9088
9089 /// Context - The AST context in which we will build the type sets.
9090 ASTContext &Context;
9091
9092 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9093 const Qualifiers &VisibleQuals);
9094 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9095
9096public:
9097 /// iterator - Iterates through the types that are part of the set.
9098 typedef TypeSet::iterator iterator;
9099
9100 BuiltinCandidateTypeSet(Sema &SemaRef)
9101 : HasNonRecordTypes(false),
9102 HasArithmeticOrEnumeralTypes(false),
9103 HasNullPtrType(false),
9104 SemaRef(SemaRef),
9105 Context(SemaRef.Context) { }
9106
9107 void AddTypesConvertedFrom(QualType Ty,
9108 SourceLocation Loc,
9109 bool AllowUserConversions,
9110 bool AllowExplicitConversions,
9111 const Qualifiers &VisibleTypeConversionsQuals);
9112
9113 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9114 llvm::iterator_range<iterator> member_pointer_types() {
9115 return MemberPointerTypes;
9116 }
9117 llvm::iterator_range<iterator> enumeration_types() {
9118 return EnumerationTypes;
9119 }
9120 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9121 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9122 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9123
9124 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9125 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9126 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9127 bool hasNullPtrType() const { return HasNullPtrType; }
9128};
9129
9130} // end anonymous namespace
9131
9132/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9133/// the set of pointer types along with any more-qualified variants of
9134/// that type. For example, if @p Ty is "int const *", this routine
9135/// will add "int const *", "int const volatile *", "int const
9136/// restrict *", and "int const volatile restrict *" to the set of
9137/// pointer types. Returns true if the add of @p Ty itself succeeded,
9138/// false otherwise.
9139///
9140/// FIXME: what to do about extended qualifiers?
9141bool
9142BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9143 const Qualifiers &VisibleQuals) {
9144
9145 // Insert this type.
9146 if (!PointerTypes.insert(Ty))
9147 return false;
9148
9149 QualType PointeeTy;
9150 const PointerType *PointerTy = Ty->getAs<PointerType>();
9151 bool buildObjCPtr = false;
9152 if (!PointerTy) {
9153 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9154 PointeeTy = PTy->getPointeeType();
9155 buildObjCPtr = true;
9156 } else {
9157 PointeeTy = PointerTy->getPointeeType();
9158 }
9159
9160 // Don't add qualified variants of arrays. For one, they're not allowed
9161 // (the qualifier would sink to the element type), and for another, the
9162 // only overload situation where it matters is subscript or pointer +- int,
9163 // and those shouldn't have qualifier variants anyway.
9164 if (PointeeTy->isArrayType())
9165 return true;
9166
9167 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9168 bool hasVolatile = VisibleQuals.hasVolatile();
9169 bool hasRestrict = VisibleQuals.hasRestrict();
9170
9171 // Iterate through all strict supersets of BaseCVR.
9172 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9173 if ((CVR | BaseCVR) != CVR) continue;
9174 // Skip over volatile if no volatile found anywhere in the types.
9175 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9176
9177 // Skip over restrict if no restrict found anywhere in the types, or if
9178 // the type cannot be restrict-qualified.
9179 if ((CVR & Qualifiers::Restrict) &&
9180 (!hasRestrict ||
9181 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9182 continue;
9183
9184 // Build qualified pointee type.
9185 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9186
9187 // Build qualified pointer type.
9188 QualType QPointerTy;
9189 if (!buildObjCPtr)
9190 QPointerTy = Context.getPointerType(QPointeeTy);
9191 else
9192 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9193
9194 // Insert qualified pointer type.
9195 PointerTypes.insert(QPointerTy);
9196 }
9197
9198 return true;
9199}
9200
9201/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9202/// to the set of pointer types along with any more-qualified variants of
9203/// that type. For example, if @p Ty is "int const *", this routine
9204/// will add "int const *", "int const volatile *", "int const
9205/// restrict *", and "int const volatile restrict *" to the set of
9206/// pointer types. Returns true if the add of @p Ty itself succeeded,
9207/// false otherwise.
9208///
9209/// FIXME: what to do about extended qualifiers?
9210bool
9211BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9212 QualType Ty) {
9213 // Insert this type.
9214 if (!MemberPointerTypes.insert(Ty))
9215 return false;
9216
9217 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9218 assert(PointerTy && "type was not a member pointer type!");
9219
9220 QualType PointeeTy = PointerTy->getPointeeType();
9221 // Don't add qualified variants of arrays. For one, they're not allowed
9222 // (the qualifier would sink to the element type), and for another, the
9223 // only overload situation where it matters is subscript or pointer +- int,
9224 // and those shouldn't have qualifier variants anyway.
9225 if (PointeeTy->isArrayType())
9226 return true;
9227 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9228
9229 // Iterate through all strict supersets of the pointee type's CVR
9230 // qualifiers.
9231 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9232 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9233 if ((CVR | BaseCVR) != CVR) continue;
9234
9235 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9236 MemberPointerTypes.insert(Context.getMemberPointerType(
9237 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9238 }
9239
9240 return true;
9241}
9242
9243/// AddTypesConvertedFrom - Add each of the types to which the type @p
9244/// Ty can be implicit converted to the given set of @p Types. We're
9245/// primarily interested in pointer types and enumeration types. We also
9246/// take member pointer types, for the conditional operator.
9247/// AllowUserConversions is true if we should look at the conversion
9248/// functions of a class type, and AllowExplicitConversions if we
9249/// should also include the explicit conversion functions of a class
9250/// type.
9251void
9252BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9253 SourceLocation Loc,
9254 bool AllowUserConversions,
9255 bool AllowExplicitConversions,
9256 const Qualifiers &VisibleQuals) {
9257 // Only deal with canonical types.
9258 Ty = Context.getCanonicalType(Ty);
9259
9260 // Look through reference types; they aren't part of the type of an
9261 // expression for the purposes of conversions.
9262 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9263 Ty = RefTy->getPointeeType();
9264
9265 // If we're dealing with an array type, decay to the pointer.
9266 if (Ty->isArrayType())
9267 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9268
9269 // Otherwise, we don't care about qualifiers on the type.
9270 Ty = Ty.getLocalUnqualifiedType();
9271
9272 // Flag if we ever add a non-record type.
9273 bool TyIsRec = Ty->isRecordType();
9274 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9275
9276 // Flag if we encounter an arithmetic type.
9277 HasArithmeticOrEnumeralTypes =
9278 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9279
9280 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9281 PointerTypes.insert(Ty);
9282 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9283 // Insert our type, and its more-qualified variants, into the set
9284 // of types.
9285 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9286 return;
9287 } else if (Ty->isMemberPointerType()) {
9288 // Member pointers are far easier, since the pointee can't be converted.
9289 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9290 return;
9291 } else if (Ty->isEnumeralType()) {
9292 HasArithmeticOrEnumeralTypes = true;
9293 EnumerationTypes.insert(Ty);
9294 } else if (Ty->isBitIntType()) {
9295 HasArithmeticOrEnumeralTypes = true;
9296 BitIntTypes.insert(Ty);
9297 } else if (Ty->isVectorType()) {
9298 // We treat vector types as arithmetic types in many contexts as an
9299 // extension.
9300 HasArithmeticOrEnumeralTypes = true;
9301 VectorTypes.insert(Ty);
9302 } else if (Ty->isMatrixType()) {
9303 // Similar to vector types, we treat vector types as arithmetic types in
9304 // many contexts as an extension.
9305 HasArithmeticOrEnumeralTypes = true;
9306 MatrixTypes.insert(Ty);
9307 } else if (Ty->isNullPtrType()) {
9308 HasNullPtrType = true;
9309 } else if (AllowUserConversions && TyIsRec) {
9310 // No conversion functions in incomplete types.
9311 if (!SemaRef.isCompleteType(Loc, Ty))
9312 return;
9313
9314 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9315 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9316 if (isa<UsingShadowDecl>(D))
9317 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9318
9319 // Skip conversion function templates; they don't tell us anything
9320 // about which builtin types we can convert to.
9322 continue;
9323
9324 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9325 if (AllowExplicitConversions || !Conv->isExplicit()) {
9326 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9327 VisibleQuals);
9328 }
9329 }
9330 }
9331}
9332/// Helper function for adjusting address spaces for the pointer or reference
9333/// operands of builtin operators depending on the argument.
9338
9339/// Helper function for AddBuiltinOperatorCandidates() that adds
9340/// the volatile- and non-volatile-qualified assignment operators for the
9341/// given type to the candidate set.
9343 QualType T,
9344 ArrayRef<Expr *> Args,
9345 OverloadCandidateSet &CandidateSet) {
9346 QualType ParamTypes[2];
9347
9348 // T& operator=(T&, T)
9349 ParamTypes[0] = S.Context.getLValueReferenceType(
9351 ParamTypes[1] = T;
9352 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9353 /*IsAssignmentOperator=*/true);
9354
9356 // volatile T& operator=(volatile T&, T)
9357 ParamTypes[0] = S.Context.getLValueReferenceType(
9359 Args[0]));
9360 ParamTypes[1] = T;
9361 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9362 /*IsAssignmentOperator=*/true);
9363 }
9364}
9365
9366/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9367/// if any, found in visible type conversion functions found in ArgExpr's type.
9368static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9369 Qualifiers VRQuals;
9370 CXXRecordDecl *ClassDecl;
9371 if (const MemberPointerType *RHSMPType =
9372 ArgExpr->getType()->getAs<MemberPointerType>())
9373 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9374 else
9375 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9376 if (!ClassDecl) {
9377 // Just to be safe, assume the worst case.
9378 VRQuals.addVolatile();
9379 VRQuals.addRestrict();
9380 return VRQuals;
9381 }
9382 if (!ClassDecl->hasDefinition())
9383 return VRQuals;
9384
9385 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9386 if (isa<UsingShadowDecl>(D))
9387 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9388 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9389 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9390 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9391 CanTy = ResTypeRef->getPointeeType();
9392 // Need to go down the pointer/mempointer chain and add qualifiers
9393 // as see them.
9394 bool done = false;
9395 while (!done) {
9396 if (CanTy.isRestrictQualified())
9397 VRQuals.addRestrict();
9398 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9399 CanTy = ResTypePtr->getPointeeType();
9400 else if (const MemberPointerType *ResTypeMPtr =
9401 CanTy->getAs<MemberPointerType>())
9402 CanTy = ResTypeMPtr->getPointeeType();
9403 else
9404 done = true;
9405 if (CanTy.isVolatileQualified())
9406 VRQuals.addVolatile();
9407 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9408 return VRQuals;
9409 }
9410 }
9411 }
9412 return VRQuals;
9413}
9414
9415// Note: We're currently only handling qualifiers that are meaningful for the
9416// LHS of compound assignment overloading.
9418 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9419 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9420 // _Atomic
9421 if (Available.hasAtomic()) {
9422 Available.removeAtomic();
9423 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9424 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9425 return;
9426 }
9427
9428 // volatile
9429 if (Available.hasVolatile()) {
9430 Available.removeVolatile();
9431 assert(!Applied.hasVolatile());
9432 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9433 Callback);
9434 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9435 return;
9436 }
9437
9438 Callback(Applied);
9439}
9440
9442 QualifiersAndAtomic Quals,
9443 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9445 Callback);
9446}
9447
9449 QualifiersAndAtomic Quals,
9450 Sema &S) {
9451 if (Quals.hasAtomic())
9453 if (Quals.hasVolatile())
9456}
9457
9458namespace {
9459
9460/// Helper class to manage the addition of builtin operator overload
9461/// candidates. It provides shared state and utility methods used throughout
9462/// the process, as well as a helper method to add each group of builtin
9463/// operator overloads from the standard to a candidate set.
9464class BuiltinOperatorOverloadBuilder {
9465 // Common instance state available to all overload candidate addition methods.
9466 Sema &S;
9467 ArrayRef<Expr *> Args;
9468 QualifiersAndAtomic VisibleTypeConversionsQuals;
9469 bool HasArithmeticOrEnumeralCandidateType;
9470 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9471 OverloadCandidateSet &CandidateSet;
9472
9473 static constexpr int ArithmeticTypesCap = 26;
9474 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9475
9476 // Define some indices used to iterate over the arithmetic types in
9477 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9478 // types are that preserved by promotion (C++ [over.built]p2).
9479 unsigned FirstIntegralType,
9480 LastIntegralType;
9481 unsigned FirstPromotedIntegralType,
9482 LastPromotedIntegralType;
9483 unsigned FirstPromotedArithmeticType,
9484 LastPromotedArithmeticType;
9485 unsigned NumArithmeticTypes;
9486
9487 void InitArithmeticTypes() {
9488 // Start of promoted types.
9489 FirstPromotedArithmeticType = 0;
9490 ArithmeticTypes.push_back(S.Context.FloatTy);
9491 ArithmeticTypes.push_back(S.Context.DoubleTy);
9492 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9494 ArithmeticTypes.push_back(S.Context.Float128Ty);
9496 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9497
9498 // Start of integral types.
9499 FirstIntegralType = ArithmeticTypes.size();
9500 FirstPromotedIntegralType = ArithmeticTypes.size();
9501 ArithmeticTypes.push_back(S.Context.IntTy);
9502 ArithmeticTypes.push_back(S.Context.LongTy);
9503 ArithmeticTypes.push_back(S.Context.LongLongTy);
9507 ArithmeticTypes.push_back(S.Context.Int128Ty);
9508 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9509 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9510 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9514 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9515
9516 /// We add candidates for the unique, unqualified _BitInt types present in
9517 /// the candidate type set. The candidate set already handled ensuring the
9518 /// type is unqualified and canonical, but because we're adding from N
9519 /// different sets, we need to do some extra work to unique things. Insert
9520 /// the candidates into a unique set, then move from that set into the list
9521 /// of arithmetic types.
9522 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9523 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9524 for (QualType BitTy : Candidate.bitint_types())
9525 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9526 }
9527 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9528 LastPromotedIntegralType = ArithmeticTypes.size();
9529 LastPromotedArithmeticType = ArithmeticTypes.size();
9530 // End of promoted types.
9531
9532 ArithmeticTypes.push_back(S.Context.BoolTy);
9533 ArithmeticTypes.push_back(S.Context.CharTy);
9534 ArithmeticTypes.push_back(S.Context.WCharTy);
9535 if (S.Context.getLangOpts().Char8)
9536 ArithmeticTypes.push_back(S.Context.Char8Ty);
9537 ArithmeticTypes.push_back(S.Context.Char16Ty);
9538 ArithmeticTypes.push_back(S.Context.Char32Ty);
9539 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9540 ArithmeticTypes.push_back(S.Context.ShortTy);
9541 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9542 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9543 LastIntegralType = ArithmeticTypes.size();
9544 NumArithmeticTypes = ArithmeticTypes.size();
9545 // End of integral types.
9546 // FIXME: What about complex? What about half?
9547
9548 // We don't know for sure how many bit-precise candidates were involved, so
9549 // we subtract those from the total when testing whether we're under the
9550 // cap or not.
9551 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9552 ArithmeticTypesCap &&
9553 "Enough inline storage for all arithmetic types.");
9554 }
9555
9556 /// Helper method to factor out the common pattern of adding overloads
9557 /// for '++' and '--' builtin operators.
9558 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9559 bool HasVolatile,
9560 bool HasRestrict) {
9561 QualType ParamTypes[2] = {
9562 S.Context.getLValueReferenceType(CandidateTy),
9563 S.Context.IntTy
9564 };
9565
9566 // Non-volatile version.
9567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9568
9569 // Use a heuristic to reduce number of builtin candidates in the set:
9570 // add volatile version only if there are conversions to a volatile type.
9571 if (HasVolatile) {
9572 ParamTypes[0] =
9574 S.Context.getVolatileType(CandidateTy));
9575 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9576 }
9577
9578 // Add restrict version only if there are conversions to a restrict type
9579 // and our candidate type is a non-restrict-qualified pointer.
9580 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9581 !CandidateTy.isRestrictQualified()) {
9582 ParamTypes[0]
9585 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9586
9587 if (HasVolatile) {
9588 ParamTypes[0]
9590 S.Context.getCVRQualifiedType(CandidateTy,
9593 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9594 }
9595 }
9596
9597 }
9598
9599 /// Helper to add an overload candidate for a binary builtin with types \p L
9600 /// and \p R.
9601 void AddCandidate(QualType L, QualType R) {
9602 QualType LandR[2] = {L, R};
9603 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9604 }
9605
9606public:
9607 BuiltinOperatorOverloadBuilder(
9608 Sema &S, ArrayRef<Expr *> Args,
9609 QualifiersAndAtomic VisibleTypeConversionsQuals,
9610 bool HasArithmeticOrEnumeralCandidateType,
9611 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9612 OverloadCandidateSet &CandidateSet)
9613 : S(S), Args(Args),
9614 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9615 HasArithmeticOrEnumeralCandidateType(
9616 HasArithmeticOrEnumeralCandidateType),
9617 CandidateTypes(CandidateTypes),
9618 CandidateSet(CandidateSet) {
9619
9620 InitArithmeticTypes();
9621 }
9622
9623 // Increment is deprecated for bool since C++17.
9624 //
9625 // C++ [over.built]p3:
9626 //
9627 // For every pair (T, VQ), where T is an arithmetic type other
9628 // than bool, and VQ is either volatile or empty, there exist
9629 // candidate operator functions of the form
9630 //
9631 // VQ T& operator++(VQ T&);
9632 // T operator++(VQ T&, int);
9633 //
9634 // C++ [over.built]p4:
9635 //
9636 // For every pair (T, VQ), where T is an arithmetic type other
9637 // than bool, and VQ is either volatile or empty, there exist
9638 // candidate operator functions of the form
9639 //
9640 // VQ T& operator--(VQ T&);
9641 // T operator--(VQ T&, int);
9642 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9643 if (!HasArithmeticOrEnumeralCandidateType)
9644 return;
9645
9646 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9647 const auto TypeOfT = ArithmeticTypes[Arith];
9648 if (TypeOfT == S.Context.BoolTy) {
9649 if (Op == OO_MinusMinus)
9650 continue;
9651 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9652 continue;
9653 }
9654 addPlusPlusMinusMinusStyleOverloads(
9655 TypeOfT,
9656 VisibleTypeConversionsQuals.hasVolatile(),
9657 VisibleTypeConversionsQuals.hasRestrict());
9658 }
9659 }
9660
9661 // C++ [over.built]p5:
9662 //
9663 // For every pair (T, VQ), where T is a cv-qualified or
9664 // cv-unqualified object type, and VQ is either volatile or
9665 // empty, there exist candidate operator functions of the form
9666 //
9667 // T*VQ& operator++(T*VQ&);
9668 // T*VQ& operator--(T*VQ&);
9669 // T* operator++(T*VQ&, int);
9670 // T* operator--(T*VQ&, int);
9671 void addPlusPlusMinusMinusPointerOverloads() {
9672 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9673 // Skip pointer types that aren't pointers to object types.
9674 if (!PtrTy->getPointeeType()->isObjectType())
9675 continue;
9676
9677 addPlusPlusMinusMinusStyleOverloads(
9678 PtrTy,
9679 (!PtrTy.isVolatileQualified() &&
9680 VisibleTypeConversionsQuals.hasVolatile()),
9681 (!PtrTy.isRestrictQualified() &&
9682 VisibleTypeConversionsQuals.hasRestrict()));
9683 }
9684 }
9685
9686 // C++ [over.built]p6:
9687 // For every cv-qualified or cv-unqualified object type T, there
9688 // exist candidate operator functions of the form
9689 //
9690 // T& operator*(T*);
9691 //
9692 // C++ [over.built]p7:
9693 // For every function type T that does not have cv-qualifiers or a
9694 // ref-qualifier, there exist candidate operator functions of the form
9695 // T& operator*(T*);
9696 void addUnaryStarPointerOverloads() {
9697 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9698 QualType PointeeTy = ParamTy->getPointeeType();
9699 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9700 continue;
9701
9702 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9703 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9704 continue;
9705
9706 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9707 }
9708 }
9709
9710 // C++ [over.built]p9:
9711 // For every promoted arithmetic type T, there exist candidate
9712 // operator functions of the form
9713 //
9714 // T operator+(T);
9715 // T operator-(T);
9716 void addUnaryPlusOrMinusArithmeticOverloads() {
9717 if (!HasArithmeticOrEnumeralCandidateType)
9718 return;
9719
9720 for (unsigned Arith = FirstPromotedArithmeticType;
9721 Arith < LastPromotedArithmeticType; ++Arith) {
9722 QualType ArithTy = ArithmeticTypes[Arith];
9723 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9724 }
9725
9726 // Extension: We also add these operators for vector types.
9727 for (QualType VecTy : CandidateTypes[0].vector_types())
9728 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9729 }
9730
9731 // C++ [over.built]p8:
9732 // For every type T, there exist candidate operator functions of
9733 // the form
9734 //
9735 // T* operator+(T*);
9736 void addUnaryPlusPointerOverloads() {
9737 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9738 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9739 }
9740
9741 // C++ [over.built]p10:
9742 // For every promoted integral type T, there exist candidate
9743 // operator functions of the form
9744 //
9745 // T operator~(T);
9746 void addUnaryTildePromotedIntegralOverloads() {
9747 if (!HasArithmeticOrEnumeralCandidateType)
9748 return;
9749
9750 for (unsigned Int = FirstPromotedIntegralType;
9751 Int < LastPromotedIntegralType; ++Int) {
9752 QualType IntTy = ArithmeticTypes[Int];
9753 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9754 }
9755
9756 // Extension: We also add this operator for vector types.
9757 for (QualType VecTy : CandidateTypes[0].vector_types())
9758 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9759 }
9760
9761 // C++ [over.match.oper]p16:
9762 // For every pointer to member type T or type std::nullptr_t, there
9763 // exist candidate operator functions of the form
9764 //
9765 // bool operator==(T,T);
9766 // bool operator!=(T,T);
9767 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9768 /// Set of (canonical) types that we've already handled.
9769 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9770
9771 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9772 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9773 // Don't add the same builtin candidate twice.
9774 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9775 continue;
9776
9777 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9778 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9779 }
9780
9781 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9783 if (AddedTypes.insert(NullPtrTy).second) {
9784 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9785 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9786 }
9787 }
9788 }
9789 }
9790
9791 // C++ [over.built]p15:
9792 //
9793 // For every T, where T is an enumeration type or a pointer type,
9794 // there exist candidate operator functions of the form
9795 //
9796 // bool operator<(T, T);
9797 // bool operator>(T, T);
9798 // bool operator<=(T, T);
9799 // bool operator>=(T, T);
9800 // bool operator==(T, T);
9801 // bool operator!=(T, T);
9802 // R operator<=>(T, T)
9803 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9804 // C++ [over.match.oper]p3:
9805 // [...]the built-in candidates include all of the candidate operator
9806 // functions defined in 13.6 that, compared to the given operator, [...]
9807 // do not have the same parameter-type-list as any non-template non-member
9808 // candidate.
9809 //
9810 // Note that in practice, this only affects enumeration types because there
9811 // aren't any built-in candidates of record type, and a user-defined operator
9812 // must have an operand of record or enumeration type. Also, the only other
9813 // overloaded operator with enumeration arguments, operator=,
9814 // cannot be overloaded for enumeration types, so this is the only place
9815 // where we must suppress candidates like this.
9816 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9817 UserDefinedBinaryOperators;
9818
9819 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9820 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9821 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9822 CEnd = CandidateSet.end();
9823 C != CEnd; ++C) {
9824 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9825 continue;
9826
9827 if (C->Function->isFunctionTemplateSpecialization())
9828 continue;
9829
9830 // We interpret "same parameter-type-list" as applying to the
9831 // "synthesized candidate, with the order of the two parameters
9832 // reversed", not to the original function.
9833 bool Reversed = C->isReversed();
9834 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9835 ->getType()
9836 .getUnqualifiedType();
9837 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9838 ->getType()
9839 .getUnqualifiedType();
9840
9841 // Skip if either parameter isn't of enumeral type.
9842 if (!FirstParamType->isEnumeralType() ||
9843 !SecondParamType->isEnumeralType())
9844 continue;
9845
9846 // Add this operator to the set of known user-defined operators.
9847 UserDefinedBinaryOperators.insert(
9848 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9849 S.Context.getCanonicalType(SecondParamType)));
9850 }
9851 }
9852 }
9853
9854 /// Set of (canonical) types that we've already handled.
9855 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9856
9857 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9858 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9859 // Don't add the same builtin candidate twice.
9860 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9861 continue;
9862 if (IsSpaceship && PtrTy->isFunctionPointerType())
9863 continue;
9864
9865 QualType ParamTypes[2] = {PtrTy, PtrTy};
9866 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9867 }
9868 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9869 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9870
9871 // Don't add the same builtin candidate twice, or if a user defined
9872 // candidate exists.
9873 if (!AddedTypes.insert(CanonType).second ||
9874 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9875 CanonType)))
9876 continue;
9877 QualType ParamTypes[2] = {EnumTy, EnumTy};
9878 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9879 }
9880 }
9881 }
9882
9883 // C++ [over.built]p13:
9884 //
9885 // For every cv-qualified or cv-unqualified object type T
9886 // there exist candidate operator functions of the form
9887 //
9888 // T* operator+(T*, ptrdiff_t);
9889 // T& operator[](T*, ptrdiff_t); [BELOW]
9890 // T* operator-(T*, ptrdiff_t);
9891 // T* operator+(ptrdiff_t, T*);
9892 // T& operator[](ptrdiff_t, T*); [BELOW]
9893 //
9894 // C++ [over.built]p14:
9895 //
9896 // For every T, where T is a pointer to object type, there
9897 // exist candidate operator functions of the form
9898 //
9899 // ptrdiff_t operator-(T, T);
9900 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9901 /// Set of (canonical) types that we've already handled.
9902 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9903
9904 for (int Arg = 0; Arg < 2; ++Arg) {
9905 QualType AsymmetricParamTypes[2] = {
9908 };
9909 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9910 QualType PointeeTy = PtrTy->getPointeeType();
9911 if (!PointeeTy->isObjectType())
9912 continue;
9913
9914 AsymmetricParamTypes[Arg] = PtrTy;
9915 if (Arg == 0 || Op == OO_Plus) {
9916 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9917 // T* operator+(ptrdiff_t, T*);
9918 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9919 }
9920 if (Op == OO_Minus) {
9921 // ptrdiff_t operator-(T, T);
9922 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9923 continue;
9924
9925 QualType ParamTypes[2] = {PtrTy, PtrTy};
9926 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9927 }
9928 }
9929 }
9930 }
9931
9932 // C++ [over.built]p12:
9933 //
9934 // For every pair of promoted arithmetic types L and R, there
9935 // exist candidate operator functions of the form
9936 //
9937 // LR operator*(L, R);
9938 // LR operator/(L, R);
9939 // LR operator+(L, R);
9940 // LR operator-(L, R);
9941 // bool operator<(L, R);
9942 // bool operator>(L, R);
9943 // bool operator<=(L, R);
9944 // bool operator>=(L, R);
9945 // bool operator==(L, R);
9946 // bool operator!=(L, R);
9947 //
9948 // where LR is the result of the usual arithmetic conversions
9949 // between types L and R.
9950 //
9951 // C++ [over.built]p24:
9952 //
9953 // For every pair of promoted arithmetic types L and R, there exist
9954 // candidate operator functions of the form
9955 //
9956 // LR operator?(bool, L, R);
9957 //
9958 // where LR is the result of the usual arithmetic conversions
9959 // between types L and R.
9960 // Our candidates ignore the first parameter.
9961 void addGenericBinaryArithmeticOverloads() {
9962 if (!HasArithmeticOrEnumeralCandidateType)
9963 return;
9964
9965 for (unsigned Left = FirstPromotedArithmeticType;
9966 Left < LastPromotedArithmeticType; ++Left) {
9967 for (unsigned Right = FirstPromotedArithmeticType;
9968 Right < LastPromotedArithmeticType; ++Right) {
9969 QualType LandR[2] = { ArithmeticTypes[Left],
9970 ArithmeticTypes[Right] };
9971 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9972 }
9973 }
9974
9975 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9976 // conditional operator for vector types.
9977 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9978 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9979 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9980 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9981 }
9982 }
9983
9984 /// Add binary operator overloads for each candidate matrix type M1, M2:
9985 /// * (M1, M1) -> M1
9986 /// * (M1, M1.getElementType()) -> M1
9987 /// * (M2.getElementType(), M2) -> M2
9988 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9989 void addMatrixBinaryArithmeticOverloads() {
9990 if (!HasArithmeticOrEnumeralCandidateType)
9991 return;
9992
9993 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9994 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9995 AddCandidate(M1, M1);
9996 }
9997
9998 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9999 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10000 if (!CandidateTypes[0].containsMatrixType(M2))
10001 AddCandidate(M2, M2);
10002 }
10003 }
10004
10005 // C++2a [over.built]p14:
10006 //
10007 // For every integral type T there exists a candidate operator function
10008 // of the form
10009 //
10010 // std::strong_ordering operator<=>(T, T)
10011 //
10012 // C++2a [over.built]p15:
10013 //
10014 // For every pair of floating-point types L and R, there exists a candidate
10015 // operator function of the form
10016 //
10017 // std::partial_ordering operator<=>(L, R);
10018 //
10019 // FIXME: The current specification for integral types doesn't play nice with
10020 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10021 // comparisons. Under the current spec this can lead to ambiguity during
10022 // overload resolution. For example:
10023 //
10024 // enum A : int {a};
10025 // auto x = (a <=> (long)42);
10026 //
10027 // error: call is ambiguous for arguments 'A' and 'long'.
10028 // note: candidate operator<=>(int, int)
10029 // note: candidate operator<=>(long, long)
10030 //
10031 // To avoid this error, this function deviates from the specification and adds
10032 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10033 // arithmetic types (the same as the generic relational overloads).
10034 //
10035 // For now this function acts as a placeholder.
10036 void addThreeWayArithmeticOverloads() {
10037 addGenericBinaryArithmeticOverloads();
10038 }
10039
10040 // C++ [over.built]p17:
10041 //
10042 // For every pair of promoted integral types L and R, there
10043 // exist candidate operator functions of the form
10044 //
10045 // LR operator%(L, R);
10046 // LR operator&(L, R);
10047 // LR operator^(L, R);
10048 // LR operator|(L, R);
10049 // L operator<<(L, R);
10050 // L operator>>(L, R);
10051 //
10052 // where LR is the result of the usual arithmetic conversions
10053 // between types L and R.
10054 void addBinaryBitwiseArithmeticOverloads() {
10055 if (!HasArithmeticOrEnumeralCandidateType)
10056 return;
10057
10058 for (unsigned Left = FirstPromotedIntegralType;
10059 Left < LastPromotedIntegralType; ++Left) {
10060 for (unsigned Right = FirstPromotedIntegralType;
10061 Right < LastPromotedIntegralType; ++Right) {
10062 QualType LandR[2] = { ArithmeticTypes[Left],
10063 ArithmeticTypes[Right] };
10064 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10065 }
10066 }
10067 }
10068
10069 // C++ [over.built]p20:
10070 //
10071 // For every pair (T, VQ), where T is an enumeration or
10072 // pointer to member type and VQ is either volatile or
10073 // empty, there exist candidate operator functions of the form
10074 //
10075 // VQ T& operator=(VQ T&, T);
10076 void addAssignmentMemberPointerOrEnumeralOverloads() {
10077 /// Set of (canonical) types that we've already handled.
10078 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10079
10080 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10081 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10082 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10083 continue;
10084
10085 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10086 }
10087
10088 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10089 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10090 continue;
10091
10092 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10093 }
10094 }
10095 }
10096
10097 // C++ [over.built]p19:
10098 //
10099 // For every pair (T, VQ), where T is any type and VQ is either
10100 // volatile or empty, there exist candidate operator functions
10101 // of the form
10102 //
10103 // T*VQ& operator=(T*VQ&, T*);
10104 //
10105 // C++ [over.built]p21:
10106 //
10107 // For every pair (T, VQ), where T is a cv-qualified or
10108 // cv-unqualified object type and VQ is either volatile or
10109 // empty, there exist candidate operator functions of the form
10110 //
10111 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10112 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10113 void addAssignmentPointerOverloads(bool isEqualOp) {
10114 /// Set of (canonical) types that we've already handled.
10115 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10116
10117 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10118 // If this is operator=, keep track of the builtin candidates we added.
10119 if (isEqualOp)
10120 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10121 else if (!PtrTy->getPointeeType()->isObjectType())
10122 continue;
10123
10124 // non-volatile version
10125 QualType ParamTypes[2] = {
10127 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10128 };
10129 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10130 /*IsAssignmentOperator=*/ isEqualOp);
10131
10132 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10133 VisibleTypeConversionsQuals.hasVolatile();
10134 if (NeedVolatile) {
10135 // volatile version
10136 ParamTypes[0] =
10138 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10139 /*IsAssignmentOperator=*/isEqualOp);
10140 }
10141
10142 if (!PtrTy.isRestrictQualified() &&
10143 VisibleTypeConversionsQuals.hasRestrict()) {
10144 // restrict version
10145 ParamTypes[0] =
10147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10148 /*IsAssignmentOperator=*/isEqualOp);
10149
10150 if (NeedVolatile) {
10151 // volatile restrict version
10152 ParamTypes[0] =
10155 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10156 /*IsAssignmentOperator=*/isEqualOp);
10157 }
10158 }
10159 }
10160
10161 if (isEqualOp) {
10162 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10163 // Make sure we don't add the same candidate twice.
10164 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10165 continue;
10166
10167 QualType ParamTypes[2] = {
10169 PtrTy,
10170 };
10171
10172 // non-volatile version
10173 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10174 /*IsAssignmentOperator=*/true);
10175
10176 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10177 VisibleTypeConversionsQuals.hasVolatile();
10178 if (NeedVolatile) {
10179 // volatile version
10180 ParamTypes[0] = S.Context.getLValueReferenceType(
10181 S.Context.getVolatileType(PtrTy));
10182 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10183 /*IsAssignmentOperator=*/true);
10184 }
10185
10186 if (!PtrTy.isRestrictQualified() &&
10187 VisibleTypeConversionsQuals.hasRestrict()) {
10188 // restrict version
10189 ParamTypes[0] = S.Context.getLValueReferenceType(
10190 S.Context.getRestrictType(PtrTy));
10191 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10192 /*IsAssignmentOperator=*/true);
10193
10194 if (NeedVolatile) {
10195 // volatile restrict version
10196 ParamTypes[0] =
10199 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10200 /*IsAssignmentOperator=*/true);
10201 }
10202 }
10203 }
10204 }
10205 }
10206
10207 // C++ [over.built]p18:
10208 //
10209 // For every triple (L, VQ, R), where L is an arithmetic type,
10210 // VQ is either volatile or empty, and R is a promoted
10211 // arithmetic type, there exist candidate operator functions of
10212 // the form
10213 //
10214 // VQ L& operator=(VQ L&, R);
10215 // VQ L& operator*=(VQ L&, R);
10216 // VQ L& operator/=(VQ L&, R);
10217 // VQ L& operator+=(VQ L&, R);
10218 // VQ L& operator-=(VQ L&, R);
10219 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10220 if (!HasArithmeticOrEnumeralCandidateType)
10221 return;
10222
10223 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10224 for (unsigned Right = FirstPromotedArithmeticType;
10225 Right < LastPromotedArithmeticType; ++Right) {
10226 QualType ParamTypes[2];
10227 ParamTypes[1] = ArithmeticTypes[Right];
10229 S, ArithmeticTypes[Left], Args[0]);
10230
10232 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10233 ParamTypes[0] =
10234 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10235 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10236 /*IsAssignmentOperator=*/isEqualOp);
10237 });
10238 }
10239 }
10240
10241 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10242 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10243 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10244 QualType ParamTypes[2];
10245 ParamTypes[1] = Vec2Ty;
10246 // Add this built-in operator as a candidate (VQ is empty).
10247 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10248 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10249 /*IsAssignmentOperator=*/isEqualOp);
10250
10251 // Add this built-in operator as a candidate (VQ is 'volatile').
10252 if (VisibleTypeConversionsQuals.hasVolatile()) {
10253 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10254 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10255 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10256 /*IsAssignmentOperator=*/isEqualOp);
10257 }
10258 }
10259 }
10260
10261 // C++ [over.built]p22:
10262 //
10263 // For every triple (L, VQ, R), where L is an integral type, VQ
10264 // is either volatile or empty, and R is a promoted integral
10265 // type, there exist candidate operator functions of the form
10266 //
10267 // VQ L& operator%=(VQ L&, R);
10268 // VQ L& operator<<=(VQ L&, R);
10269 // VQ L& operator>>=(VQ L&, R);
10270 // VQ L& operator&=(VQ L&, R);
10271 // VQ L& operator^=(VQ L&, R);
10272 // VQ L& operator|=(VQ L&, R);
10273 void addAssignmentIntegralOverloads() {
10274 if (!HasArithmeticOrEnumeralCandidateType)
10275 return;
10276
10277 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10278 for (unsigned Right = FirstPromotedIntegralType;
10279 Right < LastPromotedIntegralType; ++Right) {
10280 QualType ParamTypes[2];
10281 ParamTypes[1] = ArithmeticTypes[Right];
10283 S, ArithmeticTypes[Left], Args[0]);
10284
10286 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10287 ParamTypes[0] =
10288 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10289 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10290 });
10291 }
10292 }
10293 }
10294
10295 // C++ [over.operator]p23:
10296 //
10297 // There also exist candidate operator functions of the form
10298 //
10299 // bool operator!(bool);
10300 // bool operator&&(bool, bool);
10301 // bool operator||(bool, bool);
10302 void addExclaimOverload() {
10303 QualType ParamTy = S.Context.BoolTy;
10304 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10305 /*IsAssignmentOperator=*/false,
10306 /*NumContextualBoolArguments=*/1);
10307 }
10308 void addAmpAmpOrPipePipeOverload() {
10309 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10310 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10311 /*IsAssignmentOperator=*/false,
10312 /*NumContextualBoolArguments=*/2);
10313 }
10314
10315 // C++ [over.built]p13:
10316 //
10317 // For every cv-qualified or cv-unqualified object type T there
10318 // exist candidate operator functions of the form
10319 //
10320 // T* operator+(T*, ptrdiff_t); [ABOVE]
10321 // T& operator[](T*, ptrdiff_t);
10322 // T* operator-(T*, ptrdiff_t); [ABOVE]
10323 // T* operator+(ptrdiff_t, T*); [ABOVE]
10324 // T& operator[](ptrdiff_t, T*);
10325 void addSubscriptOverloads() {
10326 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10327 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10328 QualType PointeeType = PtrTy->getPointeeType();
10329 if (!PointeeType->isObjectType())
10330 continue;
10331
10332 // T& operator[](T*, ptrdiff_t)
10333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10334 }
10335
10336 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10337 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10338 QualType PointeeType = PtrTy->getPointeeType();
10339 if (!PointeeType->isObjectType())
10340 continue;
10341
10342 // T& operator[](ptrdiff_t, T*)
10343 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10344 }
10345 }
10346
10347 // C++ [over.built]p11:
10348 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10349 // C1 is the same type as C2 or is a derived class of C2, T is an object
10350 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10351 // there exist candidate operator functions of the form
10352 //
10353 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10354 //
10355 // where CV12 is the union of CV1 and CV2.
10356 void addArrowStarOverloads() {
10357 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10358 QualType C1Ty = PtrTy;
10359 QualType C1;
10360 QualifierCollector Q1;
10361 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10362 if (!isa<RecordType>(C1))
10363 continue;
10364 // heuristic to reduce number of builtin candidates in the set.
10365 // Add volatile/restrict version only if there are conversions to a
10366 // volatile/restrict type.
10367 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10368 continue;
10369 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10370 continue;
10371 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10372 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10373 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10374 *D2 = mptr->getMostRecentCXXRecordDecl();
10375 if (!declaresSameEntity(D1, D2) &&
10376 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10377 break;
10378 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10379 // build CV12 T&
10380 QualType T = mptr->getPointeeType();
10381 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10383 continue;
10384 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10386 continue;
10387 T = Q1.apply(S.Context, T);
10388 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10389 }
10390 }
10391 }
10392
10393 // Note that we don't consider the first argument, since it has been
10394 // contextually converted to bool long ago. The candidates below are
10395 // therefore added as binary.
10396 //
10397 // C++ [over.built]p25:
10398 // For every type T, where T is a pointer, pointer-to-member, or scoped
10399 // enumeration type, there exist candidate operator functions of the form
10400 //
10401 // T operator?(bool, T, T);
10402 //
10403 void addConditionalOperatorOverloads() {
10404 /// Set of (canonical) types that we've already handled.
10405 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10406
10407 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10408 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10409 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10410 continue;
10411
10412 QualType ParamTypes[2] = {PtrTy, PtrTy};
10413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10414 }
10415
10416 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10417 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10418 continue;
10419
10420 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10421 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10422 }
10423
10424 if (S.getLangOpts().CPlusPlus11) {
10425 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10426 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10427 continue;
10428
10429 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10430 continue;
10431
10432 QualType ParamTypes[2] = {EnumTy, EnumTy};
10433 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10434 }
10435 }
10436 }
10437 }
10438};
10439
10440} // end anonymous namespace
10441
10443 SourceLocation OpLoc,
10444 ArrayRef<Expr *> Args,
10445 OverloadCandidateSet &CandidateSet) {
10446 // Find all of the types that the arguments can convert to, but only
10447 // if the operator we're looking at has built-in operator candidates
10448 // that make use of these types. Also record whether we encounter non-record
10449 // candidate types or either arithmetic or enumeral candidate types.
10450 QualifiersAndAtomic VisibleTypeConversionsQuals;
10451 VisibleTypeConversionsQuals.addConst();
10452 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10453 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10454 if (Args[ArgIdx]->getType()->isAtomicType())
10455 VisibleTypeConversionsQuals.addAtomic();
10456 }
10457
10458 bool HasNonRecordCandidateType = false;
10459 bool HasArithmeticOrEnumeralCandidateType = false;
10461 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10462 CandidateTypes.emplace_back(*this);
10463 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10464 OpLoc,
10465 true,
10466 (Op == OO_Exclaim ||
10467 Op == OO_AmpAmp ||
10468 Op == OO_PipePipe),
10469 VisibleTypeConversionsQuals);
10470 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10471 CandidateTypes[ArgIdx].hasNonRecordTypes();
10472 HasArithmeticOrEnumeralCandidateType =
10473 HasArithmeticOrEnumeralCandidateType ||
10474 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10475 }
10476
10477 // Exit early when no non-record types have been added to the candidate set
10478 // for any of the arguments to the operator.
10479 //
10480 // We can't exit early for !, ||, or &&, since there we have always have
10481 // 'bool' overloads.
10482 if (!HasNonRecordCandidateType &&
10483 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10484 return;
10485
10486 // Setup an object to manage the common state for building overloads.
10487 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10488 VisibleTypeConversionsQuals,
10489 HasArithmeticOrEnumeralCandidateType,
10490 CandidateTypes, CandidateSet);
10491
10492 // Dispatch over the operation to add in only those overloads which apply.
10493 switch (Op) {
10494 case OO_None:
10496 llvm_unreachable("Expected an overloaded operator");
10497
10498 case OO_New:
10499 case OO_Delete:
10500 case OO_Array_New:
10501 case OO_Array_Delete:
10502 case OO_Call:
10503 llvm_unreachable(
10504 "Special operators don't use AddBuiltinOperatorCandidates");
10505
10506 case OO_Comma:
10507 case OO_Arrow:
10508 case OO_Coawait:
10509 // C++ [over.match.oper]p3:
10510 // -- For the operator ',', the unary operator '&', the
10511 // operator '->', or the operator 'co_await', the
10512 // built-in candidates set is empty.
10513 break;
10514
10515 case OO_Plus: // '+' is either unary or binary
10516 if (Args.size() == 1)
10517 OpBuilder.addUnaryPlusPointerOverloads();
10518 [[fallthrough]];
10519
10520 case OO_Minus: // '-' is either unary or binary
10521 if (Args.size() == 1) {
10522 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10523 } else {
10524 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10525 OpBuilder.addGenericBinaryArithmeticOverloads();
10526 OpBuilder.addMatrixBinaryArithmeticOverloads();
10527 }
10528 break;
10529
10530 case OO_Star: // '*' is either unary or binary
10531 if (Args.size() == 1)
10532 OpBuilder.addUnaryStarPointerOverloads();
10533 else {
10534 OpBuilder.addGenericBinaryArithmeticOverloads();
10535 OpBuilder.addMatrixBinaryArithmeticOverloads();
10536 }
10537 break;
10538
10539 case OO_Slash:
10540 OpBuilder.addGenericBinaryArithmeticOverloads();
10541 break;
10542
10543 case OO_PlusPlus:
10544 case OO_MinusMinus:
10545 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10546 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10547 break;
10548
10549 case OO_EqualEqual:
10550 case OO_ExclaimEqual:
10551 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10552 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10553 OpBuilder.addGenericBinaryArithmeticOverloads();
10554 break;
10555
10556 case OO_Less:
10557 case OO_Greater:
10558 case OO_LessEqual:
10559 case OO_GreaterEqual:
10560 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10561 OpBuilder.addGenericBinaryArithmeticOverloads();
10562 break;
10563
10564 case OO_Spaceship:
10565 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10566 OpBuilder.addThreeWayArithmeticOverloads();
10567 break;
10568
10569 case OO_Percent:
10570 case OO_Caret:
10571 case OO_Pipe:
10572 case OO_LessLess:
10573 case OO_GreaterGreater:
10574 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10575 break;
10576
10577 case OO_Amp: // '&' is either unary or binary
10578 if (Args.size() == 1)
10579 // C++ [over.match.oper]p3:
10580 // -- For the operator ',', the unary operator '&', or the
10581 // operator '->', the built-in candidates set is empty.
10582 break;
10583
10584 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10585 break;
10586
10587 case OO_Tilde:
10588 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10589 break;
10590
10591 case OO_Equal:
10592 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10593 [[fallthrough]];
10594
10595 case OO_PlusEqual:
10596 case OO_MinusEqual:
10597 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10598 [[fallthrough]];
10599
10600 case OO_StarEqual:
10601 case OO_SlashEqual:
10602 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10603 break;
10604
10605 case OO_PercentEqual:
10606 case OO_LessLessEqual:
10607 case OO_GreaterGreaterEqual:
10608 case OO_AmpEqual:
10609 case OO_CaretEqual:
10610 case OO_PipeEqual:
10611 OpBuilder.addAssignmentIntegralOverloads();
10612 break;
10613
10614 case OO_Exclaim:
10615 OpBuilder.addExclaimOverload();
10616 break;
10617
10618 case OO_AmpAmp:
10619 case OO_PipePipe:
10620 OpBuilder.addAmpAmpOrPipePipeOverload();
10621 break;
10622
10623 case OO_Subscript:
10624 if (Args.size() == 2)
10625 OpBuilder.addSubscriptOverloads();
10626 break;
10627
10628 case OO_ArrowStar:
10629 OpBuilder.addArrowStarOverloads();
10630 break;
10631
10632 case OO_Conditional:
10633 OpBuilder.addConditionalOperatorOverloads();
10634 OpBuilder.addGenericBinaryArithmeticOverloads();
10635 break;
10636 }
10637}
10638
10639void
10641 SourceLocation Loc,
10642 ArrayRef<Expr *> Args,
10643 TemplateArgumentListInfo *ExplicitTemplateArgs,
10644 OverloadCandidateSet& CandidateSet,
10645 bool PartialOverloading) {
10646 ADLResult Fns;
10647
10648 // FIXME: This approach for uniquing ADL results (and removing
10649 // redundant candidates from the set) relies on pointer-equality,
10650 // which means we need to key off the canonical decl. However,
10651 // always going back to the canonical decl might not get us the
10652 // right set of default arguments. What default arguments are
10653 // we supposed to consider on ADL candidates, anyway?
10654
10655 // FIXME: Pass in the explicit template arguments?
10656 ArgumentDependentLookup(Name, Loc, Args, Fns);
10657
10658 ArrayRef<Expr *> ReversedArgs;
10659
10660 // Erase all of the candidates we already knew about.
10661 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10662 CandEnd = CandidateSet.end();
10663 Cand != CandEnd; ++Cand)
10664 if (Cand->Function) {
10665 FunctionDecl *Fn = Cand->Function;
10666 Fns.erase(Fn);
10667 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10668 Fns.erase(FunTmpl);
10669 }
10670
10671 // For each of the ADL candidates we found, add it to the overload
10672 // set.
10673 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10675
10676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10677 if (ExplicitTemplateArgs)
10678 continue;
10679
10681 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10682 PartialOverloading, /*AllowExplicit=*/true,
10683 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10684 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10686 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10687 /*SuppressUserConversions=*/false, PartialOverloading,
10688 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10689 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10690 }
10691 } else {
10692 auto *FTD = cast<FunctionTemplateDecl>(*I);
10694 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10695 /*SuppressUserConversions=*/false, PartialOverloading,
10696 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10697 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10698 *this, Args, FTD->getTemplatedDecl())) {
10699
10700 // As template candidates are not deduced immediately,
10701 // persist the array in the overload set.
10702 if (ReversedArgs.empty())
10703 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10704
10706 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10707 /*SuppressUserConversions=*/false, PartialOverloading,
10708 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10710 }
10711 }
10712 }
10713}
10714
10715namespace {
10716enum class Comparison { Equal, Better, Worse };
10717}
10718
10719/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10720/// overload resolution.
10721///
10722/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10723/// Cand1's first N enable_if attributes have precisely the same conditions as
10724/// Cand2's first N enable_if attributes (where N = the number of enable_if
10725/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10726///
10727/// Note that you can have a pair of candidates such that Cand1's enable_if
10728/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10729/// worse than Cand1's.
10730static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10731 const FunctionDecl *Cand2) {
10732 // Common case: One (or both) decls don't have enable_if attrs.
10733 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10734 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10735 if (!Cand1Attr || !Cand2Attr) {
10736 if (Cand1Attr == Cand2Attr)
10737 return Comparison::Equal;
10738 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10739 }
10740
10741 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10742 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10743
10744 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10745 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10746 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10747 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10748
10749 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10750 // has fewer enable_if attributes than Cand2, and vice versa.
10751 if (!Cand1A)
10752 return Comparison::Worse;
10753 if (!Cand2A)
10754 return Comparison::Better;
10755
10756 Cand1ID.clear();
10757 Cand2ID.clear();
10758
10759 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10760 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10761 if (Cand1ID != Cand2ID)
10762 return Comparison::Worse;
10763 }
10764
10765 return Comparison::Equal;
10766}
10767
10768static Comparison
10770 const OverloadCandidate &Cand2) {
10771 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10772 !Cand2.Function->isMultiVersion())
10773 return Comparison::Equal;
10774
10775 // If both are invalid, they are equal. If one of them is invalid, the other
10776 // is better.
10777 if (Cand1.Function->isInvalidDecl()) {
10778 if (Cand2.Function->isInvalidDecl())
10779 return Comparison::Equal;
10780 return Comparison::Worse;
10781 }
10782 if (Cand2.Function->isInvalidDecl())
10783 return Comparison::Better;
10784
10785 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10786 // cpu_dispatch, else arbitrarily based on the identifiers.
10787 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10788 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10789 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10790 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10791
10792 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10793 return Comparison::Equal;
10794
10795 if (Cand1CPUDisp && !Cand2CPUDisp)
10796 return Comparison::Better;
10797 if (Cand2CPUDisp && !Cand1CPUDisp)
10798 return Comparison::Worse;
10799
10800 if (Cand1CPUSpec && Cand2CPUSpec) {
10801 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10802 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10803 ? Comparison::Better
10804 : Comparison::Worse;
10805
10806 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10807 FirstDiff = std::mismatch(
10808 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10809 Cand2CPUSpec->cpus_begin(),
10810 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10811 return LHS->getName() == RHS->getName();
10812 });
10813
10814 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10815 "Two different cpu-specific versions should not have the same "
10816 "identifier list, otherwise they'd be the same decl!");
10817 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10818 ? Comparison::Better
10819 : Comparison::Worse;
10820 }
10821 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10822}
10823
10824/// Compute the type of the implicit object parameter for the given function,
10825/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10826/// null QualType if there is a 'matches anything' implicit object parameter.
10827static std::optional<QualType>
10830 return std::nullopt;
10831
10832 auto *M = cast<CXXMethodDecl>(F);
10833 // Static member functions' object parameters match all types.
10834 if (M->isStatic())
10835 return QualType();
10836 return M->getFunctionObjectParameterReferenceType();
10837}
10838
10839// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10840// represent the same entity.
10841static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10842 const FunctionDecl *F2) {
10843 if (declaresSameEntity(F1, F2))
10844 return true;
10845 auto PT1 = F1->getPrimaryTemplate();
10846 auto PT2 = F2->getPrimaryTemplate();
10847 if (PT1 && PT2) {
10848 if (declaresSameEntity(PT1, PT2) ||
10849 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10850 PT2->getInstantiatedFromMemberTemplate()))
10851 return true;
10852 }
10853 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10854 // different functions with same params). Consider removing this (as no test
10855 // fail w/o it).
10856 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10857 if (First) {
10858 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10859 return *T;
10860 }
10861 assert(I < F->getNumParams());
10862 return F->getParamDecl(I++)->getType();
10863 };
10864
10865 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10866 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10867
10868 if (F1NumParams != F2NumParams)
10869 return false;
10870
10871 unsigned I1 = 0, I2 = 0;
10872 for (unsigned I = 0; I != F1NumParams; ++I) {
10873 QualType T1 = NextParam(F1, I1, I == 0);
10874 QualType T2 = NextParam(F2, I2, I == 0);
10875 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10876 if (!Context.hasSameUnqualifiedType(T1, T2))
10877 return false;
10878 }
10879 return true;
10880}
10881
10882/// We're allowed to use constraints partial ordering only if the candidates
10883/// have the same parameter types:
10884/// [over.match.best.general]p2.6
10885/// F1 and F2 are non-template functions with the same
10886/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10888 FunctionDecl *Fn2,
10889 bool IsFn1Reversed,
10890 bool IsFn2Reversed) {
10891 assert(Fn1 && Fn2);
10892 if (Fn1->isVariadic() != Fn2->isVariadic())
10893 return false;
10894
10895 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10896 IsFn1Reversed ^ IsFn2Reversed))
10897 return false;
10898
10899 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10900 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10901 if (Mem1 && Mem2) {
10902 // if they are member functions, both are direct members of the same class,
10903 // and
10904 if (Mem1->getParent() != Mem2->getParent())
10905 return false;
10906 // if both are non-static member functions, they have the same types for
10907 // their object parameters
10908 if (Mem1->isInstance() && Mem2->isInstance() &&
10910 Mem1->getFunctionObjectParameterReferenceType(),
10911 Mem1->getFunctionObjectParameterReferenceType()))
10912 return false;
10913 }
10914 return true;
10915}
10916
10917static FunctionDecl *
10919 bool IsFn1Reversed, bool IsFn2Reversed) {
10920 if (!Fn1 || !Fn2)
10921 return nullptr;
10922
10923 // C++ [temp.constr.order]:
10924 // A non-template function F1 is more partial-ordering-constrained than a
10925 // non-template function F2 if:
10926 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10927 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10928
10929 if (Cand1IsSpecialization || Cand2IsSpecialization)
10930 return nullptr;
10931
10932 // - they have the same non-object-parameter-type-lists, and [...]
10933 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10934 IsFn2Reversed))
10935 return nullptr;
10936
10937 // - the declaration of F1 is more constrained than the declaration of F2.
10938 return S.getMoreConstrainedFunction(Fn1, Fn2);
10939}
10940
10941/// isBetterOverloadCandidate - Determines whether the first overload
10942/// candidate is a better candidate than the second (C++ 13.3.3p1).
10944 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10946 bool PartialOverloading) {
10947 // Define viable functions to be better candidates than non-viable
10948 // functions.
10949 if (!Cand2.Viable)
10950 return Cand1.Viable;
10951 else if (!Cand1.Viable)
10952 return false;
10953
10954 // [CUDA] A function with 'never' preference is marked not viable, therefore
10955 // is never shown up here. The worst preference shown up here is 'wrong side',
10956 // e.g. an H function called by a HD function in device compilation. This is
10957 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10958 // function which is called only by an H function. A deferred diagnostic will
10959 // be triggered if it is emitted. However a wrong-sided function is still
10960 // a viable candidate here.
10961 //
10962 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10963 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10964 // can be emitted, Cand1 is not better than Cand2. This rule should have
10965 // precedence over other rules.
10966 //
10967 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10968 // other rules should be used to determine which is better. This is because
10969 // host/device based overloading resolution is mostly for determining
10970 // viability of a function. If two functions are both viable, other factors
10971 // should take precedence in preference, e.g. the standard-defined preferences
10972 // like argument conversion ranks or enable_if partial-ordering. The
10973 // preference for pass-object-size parameters is probably most similar to a
10974 // type-based-overloading decision and so should take priority.
10975 //
10976 // If other rules cannot determine which is better, CUDA preference will be
10977 // used again to determine which is better.
10978 //
10979 // TODO: Currently IdentifyPreference does not return correct values
10980 // for functions called in global variable initializers due to missing
10981 // correct context about device/host. Therefore we can only enforce this
10982 // rule when there is a caller. We should enforce this rule for functions
10983 // in global variable initializers once proper context is added.
10984 //
10985 // TODO: We can only enable the hostness based overloading resolution when
10986 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10987 // overloading resolution diagnostics.
10988 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10989 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10990 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10991 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10992 bool IsCand1ImplicitHD =
10994 bool IsCand2ImplicitHD =
10996 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10997 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10998 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10999 // The implicit HD function may be a function in a system header which
11000 // is forced by pragma. In device compilation, if we prefer HD candidates
11001 // over wrong-sided candidates, overloading resolution may change, which
11002 // may result in non-deferrable diagnostics. As a workaround, we let
11003 // implicit HD candidates take equal preference as wrong-sided candidates.
11004 // This will preserve the overloading resolution.
11005 // TODO: We still need special handling of implicit HD functions since
11006 // they may incur other diagnostics to be deferred. We should make all
11007 // host/device related diagnostics deferrable and remove special handling
11008 // of implicit HD functions.
11009 auto EmitThreshold =
11010 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11011 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11014 auto Cand1Emittable = P1 > EmitThreshold;
11015 auto Cand2Emittable = P2 > EmitThreshold;
11016 if (Cand1Emittable && !Cand2Emittable)
11017 return true;
11018 if (!Cand1Emittable && Cand2Emittable)
11019 return false;
11020 }
11021 }
11022
11023 // C++ [over.match.best]p1: (Changed in C++23)
11024 //
11025 // -- if F is a static member function, ICS1(F) is defined such
11026 // that ICS1(F) is neither better nor worse than ICS1(G) for
11027 // any function G, and, symmetrically, ICS1(G) is neither
11028 // better nor worse than ICS1(F).
11029 unsigned StartArg = 0;
11030 if (!Cand1.TookAddressOfOverload &&
11032 StartArg = 1;
11033
11034 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11035 // We don't allow incompatible pointer conversions in C++.
11036 if (!S.getLangOpts().CPlusPlus)
11037 return ICS.isStandard() &&
11038 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11039
11040 // The only ill-formed conversion we allow in C++ is the string literal to
11041 // char* conversion, which is only considered ill-formed after C++11.
11042 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11044 };
11045
11046 // Define functions that don't require ill-formed conversions for a given
11047 // argument to be better candidates than functions that do.
11048 unsigned NumArgs = Cand1.Conversions.size();
11049 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11050 bool HasBetterConversion = false;
11051 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11052 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11053 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11054 if (Cand1Bad != Cand2Bad) {
11055 if (Cand1Bad)
11056 return false;
11057 HasBetterConversion = true;
11058 }
11059 }
11060
11061 if (HasBetterConversion)
11062 return true;
11063
11064 // C++ [over.match.best]p1:
11065 // A viable function F1 is defined to be a better function than another
11066 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11067 // conversion sequence than ICSi(F2), and then...
11068 bool HasWorseConversion = false;
11069 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11071 Cand1.Conversions[ArgIdx],
11072 Cand2.Conversions[ArgIdx])) {
11074 // Cand1 has a better conversion sequence.
11075 HasBetterConversion = true;
11076 break;
11077
11079 if (Cand1.Function && Cand2.Function &&
11080 Cand1.isReversed() != Cand2.isReversed() &&
11081 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11082 // Work around large-scale breakage caused by considering reversed
11083 // forms of operator== in C++20:
11084 //
11085 // When comparing a function against a reversed function, if we have a
11086 // better conversion for one argument and a worse conversion for the
11087 // other, the implicit conversion sequences are treated as being equally
11088 // good.
11089 //
11090 // This prevents a comparison function from being considered ambiguous
11091 // with a reversed form that is written in the same way.
11092 //
11093 // We diagnose this as an extension from CreateOverloadedBinOp.
11094 HasWorseConversion = true;
11095 break;
11096 }
11097
11098 // Cand1 can't be better than Cand2.
11099 return false;
11100
11102 // Do nothing.
11103 break;
11104 }
11105 }
11106
11107 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11108 // ICSj(F2), or, if not that,
11109 if (HasBetterConversion && !HasWorseConversion)
11110 return true;
11111
11112 // -- the context is an initialization by user-defined conversion
11113 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11114 // from the return type of F1 to the destination type (i.e.,
11115 // the type of the entity being initialized) is a better
11116 // conversion sequence than the standard conversion sequence
11117 // from the return type of F2 to the destination type.
11119 Cand1.Function && Cand2.Function &&
11122
11123 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11124 // First check whether we prefer one of the conversion functions over the
11125 // other. This only distinguishes the results in non-standard, extension
11126 // cases such as the conversion from a lambda closure type to a function
11127 // pointer or block.
11132 Cand1.FinalConversion,
11133 Cand2.FinalConversion);
11134
11137
11138 // FIXME: Compare kind of reference binding if conversion functions
11139 // convert to a reference type used in direct reference binding, per
11140 // C++14 [over.match.best]p1 section 2 bullet 3.
11141 }
11142
11143 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11144 // as combined with the resolution to CWG issue 243.
11145 //
11146 // When the context is initialization by constructor ([over.match.ctor] or
11147 // either phase of [over.match.list]), a constructor is preferred over
11148 // a conversion function.
11149 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11150 Cand1.Function && Cand2.Function &&
11153 return isa<CXXConstructorDecl>(Cand1.Function);
11154
11155 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11156 return Cand2.StrictPackMatch;
11157
11158 // -- F1 is a non-template function and F2 is a function template
11159 // specialization, or, if not that,
11160 bool Cand1IsSpecialization = Cand1.Function &&
11162 bool Cand2IsSpecialization = Cand2.Function &&
11164 if (Cand1IsSpecialization != Cand2IsSpecialization)
11165 return Cand2IsSpecialization;
11166
11167 // -- F1 and F2 are function template specializations, and the function
11168 // template for F1 is more specialized than the template for F2
11169 // according to the partial ordering rules described in 14.5.5.2, or,
11170 // if not that,
11171 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11172 const auto *Obj1Context =
11173 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11174 const auto *Obj2Context =
11175 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11176 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11178 Cand2.Function->getPrimaryTemplate(), Loc,
11180 : TPOC_Call,
11182 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11183 : QualType{},
11184 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11185 : QualType{},
11186 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11187 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11188 }
11189 }
11190
11191 // -— F1 and F2 are non-template functions and F1 is more
11192 // partial-ordering-constrained than F2 [...],
11194 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11195 Cand2.isReversed());
11196 F && F == Cand1.Function)
11197 return true;
11198
11199 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11200 // class B of D, and for all arguments the corresponding parameters of
11201 // F1 and F2 have the same type.
11202 // FIXME: Implement the "all parameters have the same type" check.
11203 bool Cand1IsInherited =
11204 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11205 bool Cand2IsInherited =
11206 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11207 if (Cand1IsInherited != Cand2IsInherited)
11208 return Cand2IsInherited;
11209 else if (Cand1IsInherited) {
11210 assert(Cand2IsInherited);
11211 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11212 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11213 if (Cand1Class->isDerivedFrom(Cand2Class))
11214 return true;
11215 if (Cand2Class->isDerivedFrom(Cand1Class))
11216 return false;
11217 // Inherited from sibling base classes: still ambiguous.
11218 }
11219
11220 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11221 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11222 // with reversed order of parameters and F1 is not
11223 //
11224 // We rank reversed + different operator as worse than just reversed, but
11225 // that comparison can never happen, because we only consider reversing for
11226 // the maximally-rewritten operator (== or <=>).
11227 if (Cand1.RewriteKind != Cand2.RewriteKind)
11228 return Cand1.RewriteKind < Cand2.RewriteKind;
11229
11230 // Check C++17 tie-breakers for deduction guides.
11231 {
11232 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11233 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11234 if (Guide1 && Guide2) {
11235 // -- F1 is generated from a deduction-guide and F2 is not
11236 if (Guide1->isImplicit() != Guide2->isImplicit())
11237 return Guide2->isImplicit();
11238
11239 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11240 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11241 return true;
11242 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11243 return false;
11244
11245 // --F1 is generated from a non-template constructor and F2 is generated
11246 // from a constructor template
11247 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11248 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11249 if (Constructor1 && Constructor2) {
11250 bool isC1Templated = Constructor1->getTemplatedKind() !=
11252 bool isC2Templated = Constructor2->getTemplatedKind() !=
11254 if (isC1Templated != isC2Templated)
11255 return isC2Templated;
11256 }
11257 }
11258 }
11259
11260 // Check for enable_if value-based overload resolution.
11261 if (Cand1.Function && Cand2.Function) {
11263 if (Cmp != Comparison::Equal)
11264 return Cmp == Comparison::Better;
11265 }
11266
11267 bool HasPS1 = Cand1.Function != nullptr &&
11269 bool HasPS2 = Cand2.Function != nullptr &&
11271 if (HasPS1 != HasPS2 && HasPS1)
11272 return true;
11273
11274 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11275 if (MV == Comparison::Better)
11276 return true;
11277 if (MV == Comparison::Worse)
11278 return false;
11279
11280 // If other rules cannot determine which is better, CUDA preference is used
11281 // to determine which is better.
11282 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11283 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11284 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11285 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11286 }
11287
11288 // General member function overloading is handled above, so this only handles
11289 // constructors with address spaces.
11290 // This only handles address spaces since C++ has no other
11291 // qualifier that can be used with constructors.
11292 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11293 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11294 if (CD1 && CD2) {
11295 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11296 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11297 if (AS1 != AS2) {
11299 return true;
11301 return false;
11302 }
11303 }
11304
11305 return false;
11306}
11307
11308/// Determine whether two declarations are "equivalent" for the purposes of
11309/// name lookup and overload resolution. This applies when the same internal/no
11310/// linkage entity is defined by two modules (probably by textually including
11311/// the same header). In such a case, we don't consider the declarations to
11312/// declare the same entity, but we also don't want lookups with both
11313/// declarations visible to be ambiguous in some cases (this happens when using
11314/// a modularized libstdc++).
11316 const NamedDecl *B) {
11317 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11318 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11319 if (!VA || !VB)
11320 return false;
11321
11322 // The declarations must be declaring the same name as an internal linkage
11323 // entity in different modules.
11324 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11325 VB->getDeclContext()->getRedeclContext()) ||
11326 getOwningModule(VA) == getOwningModule(VB) ||
11327 VA->isExternallyVisible() || VB->isExternallyVisible())
11328 return false;
11329
11330 // Check that the declarations appear to be equivalent.
11331 //
11332 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11333 // For constants and functions, we should check the initializer or body is
11334 // the same. For non-constant variables, we shouldn't allow it at all.
11335 if (Context.hasSameType(VA->getType(), VB->getType()))
11336 return true;
11337
11338 // Enum constants within unnamed enumerations will have different types, but
11339 // may still be similar enough to be interchangeable for our purposes.
11340 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11341 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11342 // Only handle anonymous enums. If the enumerations were named and
11343 // equivalent, they would have been merged to the same type.
11344 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11345 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11346 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11347 !Context.hasSameType(EnumA->getIntegerType(),
11348 EnumB->getIntegerType()))
11349 return false;
11350 // Allow this only if the value is the same for both enumerators.
11351 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11352 }
11353 }
11354
11355 // Nothing else is sufficiently similar.
11356 return false;
11357}
11358
11361 assert(D && "Unknown declaration");
11362 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11363
11364 Module *M = getOwningModule(D);
11365 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11366 << !M << (M ? M->getFullModuleName() : "");
11367
11368 for (auto *E : Equiv) {
11369 Module *M = getOwningModule(E);
11370 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11371 << !M << (M ? M->getFullModuleName() : "");
11372 }
11373}
11374
11377 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11379 static_cast<CNSInfo *>(DeductionFailure.Data)
11380 ->Satisfaction.ContainsErrors;
11381}
11382
11385 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11386 bool PartialOverloading, bool AllowExplicit,
11388 bool AggregateCandidateDeduction) {
11389
11390 auto *C =
11391 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11392
11395 /*AllowObjCConversionOnExplicit=*/false,
11396 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11397 PartialOverloading, AggregateCandidateDeduction},
11399 FoundDecl,
11400 Args,
11401 IsADLCandidate,
11402 PO};
11403
11404 HasDeferredTemplateConstructors |=
11405 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11406}
11407
11409 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11410 CXXRecordDecl *ActingContext, QualType ObjectType,
11411 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11412 bool SuppressUserConversions, bool PartialOverloading,
11414
11415 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11416
11417 auto *C =
11418 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11419
11422 /*AllowObjCConversionOnExplicit=*/false,
11423 /*AllowResultConversion=*/false,
11424 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11425 /*AggregateCandidateDeduction=*/false},
11426 MethodTmpl,
11427 FoundDecl,
11428 Args,
11429 ActingContext,
11430 ObjectClassification,
11431 ObjectType,
11432 PO};
11433}
11434
11437 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11438 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11439 bool AllowResultConversion) {
11440
11441 auto *C =
11442 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11443
11446 AllowObjCConversionOnExplicit, AllowResultConversion,
11447 /*AllowExplicit=*/false,
11448 /*SuppressUserConversions=*/false,
11449 /*PartialOverloading*/ false,
11450 /*AggregateCandidateDeduction=*/false},
11452 FoundDecl,
11453 ActingContext,
11454 From,
11455 ToType};
11456}
11457
11458static void
11461
11463 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11464 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11465 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11466}
11467
11468static void
11472 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11473 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11474 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11475 C.AggregateCandidateDeduction);
11476}
11477
11478static void
11482 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11483 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11484 C.AllowResultConversion);
11485}
11486
11488 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11489 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11490 while (Cand) {
11491 switch (Cand->Kind) {
11494 S, *this,
11495 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11496 break;
11499 S, *this,
11500 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11501 break;
11504 S, *this,
11505 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11506 break;
11507 }
11508 Cand = Cand->Next;
11509 }
11510 FirstDeferredCandidate = nullptr;
11511 DeferredCandidatesCount = 0;
11512}
11513
11515OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11516 Best->Best = true;
11517 if (Best->Function && Best->Function->isDeleted())
11518 return OR_Deleted;
11519 return OR_Success;
11520}
11521
11522void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11524 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11525 // are accepted by both clang and NVCC. However, during a particular
11526 // compilation mode only one call variant is viable. We need to
11527 // exclude non-viable overload candidates from consideration based
11528 // only on their host/device attributes. Specifically, if one
11529 // candidate call is WrongSide and the other is SameSide, we ignore
11530 // the WrongSide candidate.
11531 // We only need to remove wrong-sided candidates here if
11532 // -fgpu-exclude-wrong-side-overloads is off. When
11533 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11534 // uniformly in isBetterOverloadCandidate.
11535 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11536 return;
11537 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11538
11539 bool ContainsSameSideCandidate =
11540 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11541 // Check viable function only.
11542 return Cand->Viable && Cand->Function &&
11543 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11545 });
11546
11547 if (!ContainsSameSideCandidate)
11548 return;
11549
11550 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11551 // Check viable function only to avoid unnecessary data copying/moving.
11552 return Cand->Viable && Cand->Function &&
11553 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11555 };
11556 llvm::erase_if(Candidates, IsWrongSideCandidate);
11557}
11558
11559/// Computes the best viable function (C++ 13.3.3)
11560/// within an overload candidate set.
11561///
11562/// \param Loc The location of the function name (or operator symbol) for
11563/// which overload resolution occurs.
11564///
11565/// \param Best If overload resolution was successful or found a deleted
11566/// function, \p Best points to the candidate function found.
11567///
11568/// \returns The result of overload resolution.
11570 SourceLocation Loc,
11571 iterator &Best) {
11572
11574 DeferredCandidatesCount == 0) &&
11575 "Unexpected deferred template candidates");
11576
11577 bool TwoPhaseResolution =
11578 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11579
11580 if (TwoPhaseResolution) {
11581 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11582 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11583 if (!(HasDeferredTemplateConstructors &&
11584 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11585 return Res;
11586 }
11587 }
11588
11590 return BestViableFunctionImpl(S, Loc, Best);
11591}
11592
11593OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11595
11597 Candidates.reserve(this->Candidates.size());
11598 std::transform(this->Candidates.begin(), this->Candidates.end(),
11599 std::back_inserter(Candidates),
11600 [](OverloadCandidate &Cand) { return &Cand; });
11601
11602 if (S.getLangOpts().CUDA)
11603 CudaExcludeWrongSideCandidates(S, Candidates);
11604
11605 Best = end();
11606 for (auto *Cand : Candidates) {
11607 Cand->Best = false;
11608 if (Cand->Viable) {
11609 if (Best == end() ||
11610 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11611 Best = Cand;
11612 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11613 // This candidate has constraint that we were unable to evaluate because
11614 // it referenced an expression that contained an error. Rather than fall
11615 // back onto a potentially unintended candidate (made worse by
11616 // subsuming constraints), treat this as 'no viable candidate'.
11617 Best = end();
11618 return OR_No_Viable_Function;
11619 }
11620 }
11621
11622 // If we didn't find any viable functions, abort.
11623 if (Best == end())
11624 return OR_No_Viable_Function;
11625
11626 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11627 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11628 PendingBest.push_back(&*Best);
11629 Best->Best = true;
11630
11631 // Make sure that this function is better than every other viable
11632 // function. If not, we have an ambiguity.
11633 while (!PendingBest.empty()) {
11634 auto *Curr = PendingBest.pop_back_val();
11635 for (auto *Cand : Candidates) {
11636 if (Cand->Viable && !Cand->Best &&
11637 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11638 PendingBest.push_back(Cand);
11639 Cand->Best = true;
11640
11642 Curr->Function))
11643 EquivalentCands.push_back(Cand->Function);
11644 else
11645 Best = end();
11646 }
11647 }
11648 }
11649
11650 if (Best == end())
11651 return OR_Ambiguous;
11652
11653 OverloadingResult R = ResultForBestCandidate(Best);
11654
11655 if (!EquivalentCands.empty())
11657 EquivalentCands);
11658 return R;
11659}
11660
11661namespace {
11662
11663enum OverloadCandidateKind {
11664 oc_function,
11665 oc_method,
11666 oc_reversed_binary_operator,
11667 oc_constructor,
11668 oc_implicit_default_constructor,
11669 oc_implicit_copy_constructor,
11670 oc_implicit_move_constructor,
11671 oc_implicit_copy_assignment,
11672 oc_implicit_move_assignment,
11673 oc_implicit_equality_comparison,
11674 oc_inherited_constructor
11675};
11676
11677enum OverloadCandidateSelect {
11678 ocs_non_template,
11679 ocs_template,
11680 ocs_described_template,
11681};
11682
11683static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11684ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11685 const FunctionDecl *Fn,
11687 std::string &Description) {
11688
11689 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11690 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11691 isTemplate = true;
11692 Description = S.getTemplateArgumentBindingsText(
11693 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11694 }
11695
11696 OverloadCandidateSelect Select = [&]() {
11697 if (!Description.empty())
11698 return ocs_described_template;
11699 return isTemplate ? ocs_template : ocs_non_template;
11700 }();
11701
11702 OverloadCandidateKind Kind = [&]() {
11703 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11704 return oc_implicit_equality_comparison;
11705
11706 if (CRK & CRK_Reversed)
11707 return oc_reversed_binary_operator;
11708
11709 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11710 if (!Ctor->isImplicit()) {
11712 return oc_inherited_constructor;
11713 else
11714 return oc_constructor;
11715 }
11716
11717 if (Ctor->isDefaultConstructor())
11718 return oc_implicit_default_constructor;
11719
11720 if (Ctor->isMoveConstructor())
11721 return oc_implicit_move_constructor;
11722
11723 assert(Ctor->isCopyConstructor() &&
11724 "unexpected sort of implicit constructor");
11725 return oc_implicit_copy_constructor;
11726 }
11727
11728 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11729 // This actually gets spelled 'candidate function' for now, but
11730 // it doesn't hurt to split it out.
11731 if (!Meth->isImplicit())
11732 return oc_method;
11733
11734 if (Meth->isMoveAssignmentOperator())
11735 return oc_implicit_move_assignment;
11736
11737 if (Meth->isCopyAssignmentOperator())
11738 return oc_implicit_copy_assignment;
11739
11740 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11741 return oc_method;
11742 }
11743
11744 return oc_function;
11745 }();
11746
11747 return std::make_pair(Kind, Select);
11748}
11749
11750void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11751 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11752 // set.
11753 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11754 S.Diag(FoundDecl->getLocation(),
11755 diag::note_ovl_candidate_inherited_constructor)
11756 << Shadow->getNominatedBaseClass();
11757}
11758
11759} // end anonymous namespace
11760
11762 const FunctionDecl *FD) {
11763 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11764 bool AlwaysTrue;
11765 if (EnableIf->getCond()->isValueDependent() ||
11766 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11767 return false;
11768 if (!AlwaysTrue)
11769 return false;
11770 }
11771 return true;
11772}
11773
11774/// Returns true if we can take the address of the function.
11775///
11776/// \param Complain - If true, we'll emit a diagnostic
11777/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11778/// we in overload resolution?
11779/// \param Loc - The location of the statement we're complaining about. Ignored
11780/// if we're not complaining, or if we're in overload resolution.
11782 bool Complain,
11783 bool InOverloadResolution,
11784 SourceLocation Loc) {
11785 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11786 if (Complain) {
11787 if (InOverloadResolution)
11788 S.Diag(FD->getBeginLoc(),
11789 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11790 else
11791 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11792 }
11793 return false;
11794 }
11795
11796 if (FD->getTrailingRequiresClause()) {
11797 ConstraintSatisfaction Satisfaction;
11798 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11799 return false;
11800 if (!Satisfaction.IsSatisfied) {
11801 if (Complain) {
11802 if (InOverloadResolution) {
11803 SmallString<128> TemplateArgString;
11804 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11805 TemplateArgString += " ";
11806 TemplateArgString += S.getTemplateArgumentBindingsText(
11807 FunTmpl->getTemplateParameters(),
11809 }
11810
11811 S.Diag(FD->getBeginLoc(),
11812 diag::note_ovl_candidate_unsatisfied_constraints)
11813 << TemplateArgString;
11814 } else
11815 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11816 << FD;
11817 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11818 }
11819 return false;
11820 }
11821 }
11822
11823 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11824 return P->hasAttr<PassObjectSizeAttr>();
11825 });
11826 if (I == FD->param_end())
11827 return true;
11828
11829 if (Complain) {
11830 // Add one to ParamNo because it's user-facing
11831 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11832 if (InOverloadResolution)
11833 S.Diag(FD->getLocation(),
11834 diag::note_ovl_candidate_has_pass_object_size_params)
11835 << ParamNo;
11836 else
11837 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11838 << FD << ParamNo;
11839 }
11840 return false;
11841}
11842
11844 const FunctionDecl *FD) {
11845 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11846 /*InOverloadResolution=*/true,
11847 /*Loc=*/SourceLocation());
11848}
11849
11851 bool Complain,
11852 SourceLocation Loc) {
11853 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11854 /*InOverloadResolution=*/false,
11855 Loc);
11856}
11857
11858// Don't print candidates other than the one that matches the calling
11859// convention of the call operator, since that is guaranteed to exist.
11861 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11862
11863 if (!ConvD)
11864 return false;
11865 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11866 if (!RD->isLambda())
11867 return false;
11868
11869 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11870 CallingConv CallOpCC =
11871 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11872 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11873 CallingConv ConvToCC =
11874 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11875
11876 return ConvToCC != CallOpCC;
11877}
11878
11879// Notes the location of an overload candidate.
11881 OverloadCandidateRewriteKind RewriteKind,
11882 QualType DestType, bool TakingAddress) {
11883 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11884 return;
11885 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11886 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11887 return;
11888 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11889 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11890 return;
11892 return;
11893
11894 std::string FnDesc;
11895 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11896 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11897 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11898 << (unsigned)KSPair.first << (unsigned)KSPair.second
11899 << Fn << FnDesc;
11900
11901 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11902 Diag(Fn->getLocation(), PD);
11903 MaybeEmitInheritedConstructorNote(*this, Found);
11904}
11905
11906static void
11908 // Perhaps the ambiguity was caused by two atomic constraints that are
11909 // 'identical' but not equivalent:
11910 //
11911 // void foo() requires (sizeof(T) > 4) { } // #1
11912 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11913 //
11914 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11915 // #2 to subsume #1, but these constraint are not considered equivalent
11916 // according to the subsumption rules because they are not the same
11917 // source-level construct. This behavior is quite confusing and we should try
11918 // to help the user figure out what happened.
11919
11920 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11921 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11922 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11923 if (!I->Function)
11924 continue;
11926 if (auto *Template = I->Function->getPrimaryTemplate())
11927 Template->getAssociatedConstraints(AC);
11928 else
11929 I->Function->getAssociatedConstraints(AC);
11930 if (AC.empty())
11931 continue;
11932 if (FirstCand == nullptr) {
11933 FirstCand = I->Function;
11934 FirstAC = AC;
11935 } else if (SecondCand == nullptr) {
11936 SecondCand = I->Function;
11937 SecondAC = AC;
11938 } else {
11939 // We have more than one pair of constrained functions - this check is
11940 // expensive and we'd rather not try to diagnose it.
11941 return;
11942 }
11943 }
11944 if (!SecondCand)
11945 return;
11946 // The diagnostic can only happen if there are associated constraints on
11947 // both sides (there needs to be some identical atomic constraint).
11948 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11949 SecondCand, SecondAC))
11950 // Just show the user one diagnostic, they'll probably figure it out
11951 // from here.
11952 return;
11953}
11954
11955// Notes the location of all overload candidates designated through
11956// OverloadedExpr
11957void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11958 bool TakingAddress) {
11959 assert(OverloadedExpr->getType() == Context.OverloadTy);
11960
11961 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11962 OverloadExpr *OvlExpr = Ovl.Expression;
11963
11964 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11965 IEnd = OvlExpr->decls_end();
11966 I != IEnd; ++I) {
11967 if (FunctionTemplateDecl *FunTmpl =
11968 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11969 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11970 TakingAddress);
11971 } else if (FunctionDecl *Fun
11972 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11973 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11974 }
11975 }
11976}
11977
11978/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11979/// "lead" diagnostic; it will be given two arguments, the source and
11980/// target types of the conversion.
11982 Sema &S,
11983 SourceLocation CaretLoc,
11984 const PartialDiagnostic &PDiag) const {
11985 S.Diag(CaretLoc, PDiag)
11986 << Ambiguous.getFromType() << Ambiguous.getToType();
11987 unsigned CandsShown = 0;
11989 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11990 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11991 break;
11992 ++CandsShown;
11993 S.NoteOverloadCandidate(I->first, I->second);
11994 }
11995 S.Diags.overloadCandidatesShown(CandsShown);
11996 if (I != E)
11997 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11998}
11999
12001 unsigned I, bool TakingCandidateAddress) {
12002 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12003 assert(Conv.isBad());
12004 assert(Cand->Function && "for now, candidate must be a function");
12005 FunctionDecl *Fn = Cand->Function;
12006
12007 // There's a conversion slot for the object argument if this is a
12008 // non-constructor method. Note that 'I' corresponds the
12009 // conversion-slot index.
12010 bool isObjectArgument = false;
12011 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12013 if (I == 0)
12014 isObjectArgument = true;
12015 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12016 I--;
12017 }
12018
12019 std::string FnDesc;
12020 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12021 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12022 FnDesc);
12023
12024 Expr *FromExpr = Conv.Bad.FromExpr;
12025 QualType FromTy = Conv.Bad.getFromType();
12026 QualType ToTy = Conv.Bad.getToType();
12027 SourceRange ToParamRange;
12028
12029 // FIXME: In presence of parameter packs we can't determine parameter range
12030 // reliably, as we don't have access to instantiation.
12031 bool HasParamPack =
12032 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12033 return Parm->isParameterPack();
12034 });
12035 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12036 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12037
12038 if (FromTy == S.Context.OverloadTy) {
12039 assert(FromExpr && "overload set argument came from implicit argument?");
12040 Expr *E = FromExpr->IgnoreParens();
12041 if (isa<UnaryOperator>(E))
12042 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12043 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12044
12045 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12046 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12047 << ToParamRange << ToTy << Name << I + 1;
12048 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12049 return;
12050 }
12051
12052 // Do some hand-waving analysis to see if the non-viability is due
12053 // to a qualifier mismatch.
12054 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12055 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12056 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12057 CToTy = RT->getPointeeType();
12058 else {
12059 // TODO: detect and diagnose the full richness of const mismatches.
12060 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12061 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12062 CFromTy = FromPT->getPointeeType();
12063 CToTy = ToPT->getPointeeType();
12064 }
12065 }
12066
12067 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12068 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12069 Qualifiers FromQs = CFromTy.getQualifiers();
12070 Qualifiers ToQs = CToTy.getQualifiers();
12071
12072 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12073 if (isObjectArgument)
12074 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12075 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12076 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12077 else
12078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12079 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12080 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12081 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12082 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12083 return;
12084 }
12085
12086 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12088 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12089 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12090 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12091 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12092 return;
12093 }
12094
12095 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12097 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12098 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12099 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12100 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12101 return;
12102 }
12103
12104 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12106 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12107 << FromTy << !!FromQs.getPointerAuth()
12108 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12109 << ToQs.getPointerAuth().getAsString() << I + 1
12110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12111 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12112 return;
12113 }
12114
12115 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12116 assert(CVR && "expected qualifiers mismatch");
12117
12118 if (isObjectArgument) {
12119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12120 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12121 << FromTy << (CVR - 1);
12122 } else {
12123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12124 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12125 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12126 }
12127 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12128 return;
12129 }
12130
12133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12134 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12135 << (unsigned)isObjectArgument << I + 1
12137 << ToParamRange;
12138 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12139 return;
12140 }
12141
12142 // Special diagnostic for failure to convert an initializer list, since
12143 // telling the user that it has type void is not useful.
12144 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12146 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12147 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12150 ? 2
12151 : 0);
12152 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12153 return;
12154 }
12155
12156 // Diagnose references or pointers to incomplete types differently,
12157 // since it's far from impossible that the incompleteness triggered
12158 // the failure.
12159 QualType TempFromTy = FromTy.getNonReferenceType();
12160 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12161 TempFromTy = PTy->getPointeeType();
12162 if (TempFromTy->isIncompleteType()) {
12163 // Emit the generic diagnostic and, optionally, add the hints to it.
12164 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12165 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12166 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12167 << (unsigned)(Cand->Fix.Kind);
12168
12169 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12170 return;
12171 }
12172
12173 // Diagnose base -> derived pointer conversions.
12174 unsigned BaseToDerivedConversion = 0;
12175 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12176 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12177 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12178 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12179 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12180 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12181 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12182 FromPtrTy->getPointeeType()))
12183 BaseToDerivedConversion = 1;
12184 }
12185 } else if (const ObjCObjectPointerType *FromPtrTy
12186 = FromTy->getAs<ObjCObjectPointerType>()) {
12187 if (const ObjCObjectPointerType *ToPtrTy
12188 = ToTy->getAs<ObjCObjectPointerType>())
12189 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12190 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12191 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12192 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12193 FromIface->isSuperClassOf(ToIface))
12194 BaseToDerivedConversion = 2;
12195 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12196 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12197 S.getASTContext()) &&
12198 !FromTy->isIncompleteType() &&
12199 !ToRefTy->getPointeeType()->isIncompleteType() &&
12200 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12201 BaseToDerivedConversion = 3;
12202 }
12203 }
12204
12205 if (BaseToDerivedConversion) {
12206 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12207 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12208 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12209 << I + 1;
12210 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12211 return;
12212 }
12213
12214 if (isa<ObjCObjectPointerType>(CFromTy) &&
12215 isa<PointerType>(CToTy)) {
12216 Qualifiers FromQs = CFromTy.getQualifiers();
12217 Qualifiers ToQs = CToTy.getQualifiers();
12218 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12219 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12220 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12221 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12222 << I + 1;
12223 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12224 return;
12225 }
12226 }
12227
12228 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12229 return;
12230
12231 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12232 // although this is almost always an error and we advise against it.
12233 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12234 ToTy == S.Context.getLogicalOperationType()) {
12235 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12236 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12237 << Conv.Bad.FromExpr << ToTy;
12238 return;
12239 }
12240
12241 // Emit the generic diagnostic and, optionally, add the hints to it.
12242 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12243 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12244 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12245 << (unsigned)(Cand->Fix.Kind);
12246
12247 // Check that location of Fn is not in system header.
12248 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12249 // If we can fix the conversion, suggest the FixIts.
12250 for (const FixItHint &HI : Cand->Fix.Hints)
12251 FDiag << HI;
12252 }
12253
12254 S.Diag(Fn->getLocation(), FDiag);
12255
12256 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12257}
12258
12259/// Additional arity mismatch diagnosis specific to a function overload
12260/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12261/// over a candidate in any candidate set.
12263 unsigned NumArgs, bool IsAddressOf = false) {
12264 assert(Cand->Function && "Candidate is required to be a function.");
12265 FunctionDecl *Fn = Cand->Function;
12266 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12267 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12268
12269 // With invalid overloaded operators, it's possible that we think we
12270 // have an arity mismatch when in fact it looks like we have the
12271 // right number of arguments, because only overloaded operators have
12272 // the weird behavior of overloading member and non-member functions.
12273 // Just don't report anything.
12274 if (Fn->isInvalidDecl() &&
12275 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12276 return true;
12277
12278 if (NumArgs < MinParams) {
12279 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12281 Cand->DeductionFailure.getResult() ==
12283 } else {
12284 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12286 Cand->DeductionFailure.getResult() ==
12288 }
12289
12290 return false;
12291}
12292
12293/// General arity mismatch diagnosis over a candidate in a candidate set.
12295 unsigned NumFormalArgs,
12296 bool IsAddressOf = false) {
12297 assert(isa<FunctionDecl>(D) &&
12298 "The templated declaration should at least be a function"
12299 " when diagnosing bad template argument deduction due to too many"
12300 " or too few arguments");
12301
12303
12304 // TODO: treat calls to a missing default constructor as a special case
12305 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12306 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12307 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12308
12309 // at least / at most / exactly
12310 bool HasExplicitObjectParam =
12311 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12312
12313 unsigned ParamCount =
12314 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12315 unsigned mode, modeCount;
12316
12317 if (NumFormalArgs < MinParams) {
12318 if (MinParams != ParamCount || FnTy->isVariadic() ||
12319 FnTy->isTemplateVariadic())
12320 mode = 0; // "at least"
12321 else
12322 mode = 2; // "exactly"
12323 modeCount = MinParams;
12324 } else {
12325 if (MinParams != ParamCount)
12326 mode = 1; // "at most"
12327 else
12328 mode = 2; // "exactly"
12329 modeCount = ParamCount;
12330 }
12331
12332 std::string Description;
12333 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12334 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12335
12336 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12337 if (modeCount == 1 && !IsAddressOf &&
12338 FirstNonObjectParamIdx < Fn->getNumParams() &&
12339 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12340 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12341 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12342 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12343 << NumFormalArgs << HasExplicitObjectParam
12344 << Fn->getParametersSourceRange();
12345 else
12346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12347 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12348 << Description << mode << modeCount << NumFormalArgs
12349 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12350
12351 MaybeEmitInheritedConstructorNote(S, Found);
12352}
12353
12354/// Arity mismatch diagnosis specific to a function overload candidate.
12356 unsigned NumFormalArgs) {
12357 assert(Cand->Function && "Candidate must be a function");
12358 FunctionDecl *Fn = Cand->Function;
12359 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12360 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12361 Cand->TookAddressOfOverload);
12362}
12363
12365 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12366 return TD;
12367 llvm_unreachable("Unsupported: Getting the described template declaration"
12368 " for bad deduction diagnosis");
12369}
12370
12371/// Diagnose a failed template-argument deduction.
12372static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12373 DeductionFailureInfo &DeductionFailure,
12374 unsigned NumArgs,
12375 bool TakingCandidateAddress) {
12376 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12377 NamedDecl *ParamD;
12378 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12379 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12380 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12381 switch (DeductionFailure.getResult()) {
12383 llvm_unreachable(
12384 "TemplateDeductionResult::Success while diagnosing bad deduction");
12386 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12387 "while diagnosing bad deduction");
12390 return;
12391
12393 assert(ParamD && "no parameter found for incomplete deduction result");
12394 S.Diag(Templated->getLocation(),
12395 diag::note_ovl_candidate_incomplete_deduction)
12396 << ParamD->getDeclName();
12397 MaybeEmitInheritedConstructorNote(S, Found);
12398 return;
12399 }
12400
12402 assert(ParamD && "no parameter found for incomplete deduction result");
12403 S.Diag(Templated->getLocation(),
12404 diag::note_ovl_candidate_incomplete_deduction_pack)
12405 << ParamD->getDeclName()
12406 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12407 << *DeductionFailure.getFirstArg();
12408 MaybeEmitInheritedConstructorNote(S, Found);
12409 return;
12410 }
12411
12413 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12415
12416 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12417
12418 // Param will have been canonicalized, but it should just be a
12419 // qualified version of ParamD, so move the qualifiers to that.
12421 Qs.strip(Param);
12422 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12423 assert(S.Context.hasSameType(Param, NonCanonParam));
12424
12425 // Arg has also been canonicalized, but there's nothing we can do
12426 // about that. It also doesn't matter as much, because it won't
12427 // have any template parameters in it (because deduction isn't
12428 // done on dependent types).
12429 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12430
12431 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12432 << ParamD->getDeclName() << Arg << NonCanonParam;
12433 MaybeEmitInheritedConstructorNote(S, Found);
12434 return;
12435 }
12436
12438 assert(ParamD && "no parameter found for inconsistent deduction result");
12439 int which = 0;
12440 if (isa<TemplateTypeParmDecl>(ParamD))
12441 which = 0;
12442 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12443 // Deduction might have failed because we deduced arguments of two
12444 // different types for a non-type template parameter.
12445 // FIXME: Use a different TDK value for this.
12446 QualType T1 =
12447 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12448 QualType T2 =
12449 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12450 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12451 S.Diag(Templated->getLocation(),
12452 diag::note_ovl_candidate_inconsistent_deduction_types)
12453 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12454 << *DeductionFailure.getSecondArg() << T2;
12455 MaybeEmitInheritedConstructorNote(S, Found);
12456 return;
12457 }
12458
12459 which = 1;
12460 } else {
12461 which = 2;
12462 }
12463
12464 // Tweak the diagnostic if the problem is that we deduced packs of
12465 // different arities. We'll print the actual packs anyway in case that
12466 // includes additional useful information.
12467 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12468 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12469 DeductionFailure.getFirstArg()->pack_size() !=
12470 DeductionFailure.getSecondArg()->pack_size()) {
12471 which = 3;
12472 }
12473
12474 S.Diag(Templated->getLocation(),
12475 diag::note_ovl_candidate_inconsistent_deduction)
12476 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12477 << *DeductionFailure.getSecondArg();
12478 MaybeEmitInheritedConstructorNote(S, Found);
12479 return;
12480 }
12481
12483 assert(ParamD && "no parameter found for invalid explicit arguments");
12484 if (ParamD->getDeclName())
12485 S.Diag(Templated->getLocation(),
12486 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12487 << ParamD->getDeclName();
12488 else {
12489 int index = 0;
12490 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12491 index = TTP->getIndex();
12492 else if (NonTypeTemplateParmDecl *NTTP
12493 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12494 index = NTTP->getIndex();
12495 else
12496 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12497 S.Diag(Templated->getLocation(),
12498 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12499 << (index + 1);
12500 }
12501 MaybeEmitInheritedConstructorNote(S, Found);
12502 return;
12503
12505 // Format the template argument list into the argument string.
12506 SmallString<128> TemplateArgString;
12507 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12508 TemplateArgString = " ";
12509 TemplateArgString += S.getTemplateArgumentBindingsText(
12510 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12511 if (TemplateArgString.size() == 1)
12512 TemplateArgString.clear();
12513 S.Diag(Templated->getLocation(),
12514 diag::note_ovl_candidate_unsatisfied_constraints)
12515 << TemplateArgString;
12516
12518 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12519 return;
12520 }
12523 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12524 return;
12525
12527 S.Diag(Templated->getLocation(),
12528 diag::note_ovl_candidate_instantiation_depth);
12529 MaybeEmitInheritedConstructorNote(S, Found);
12530 return;
12531
12533 // Format the template argument list into the argument string.
12534 SmallString<128> TemplateArgString;
12535 if (TemplateArgumentList *Args =
12536 DeductionFailure.getTemplateArgumentList()) {
12537 TemplateArgString = " ";
12538 TemplateArgString += S.getTemplateArgumentBindingsText(
12539 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12540 if (TemplateArgString.size() == 1)
12541 TemplateArgString.clear();
12542 }
12543
12544 // If this candidate was disabled by enable_if, say so.
12545 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12546 if (PDiag && PDiag->second.getDiagID() ==
12547 diag::err_typename_nested_not_found_enable_if) {
12548 // FIXME: Use the source range of the condition, and the fully-qualified
12549 // name of the enable_if template. These are both present in PDiag.
12550 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12551 << "'enable_if'" << TemplateArgString;
12552 return;
12553 }
12554
12555 // We found a specific requirement that disabled the enable_if.
12556 if (PDiag && PDiag->second.getDiagID() ==
12557 diag::err_typename_nested_not_found_requirement) {
12558 S.Diag(Templated->getLocation(),
12559 diag::note_ovl_candidate_disabled_by_requirement)
12560 << PDiag->second.getStringArg(0) << TemplateArgString;
12561 return;
12562 }
12563
12564 // Format the SFINAE diagnostic into the argument string.
12565 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12566 // formatted message in another diagnostic.
12567 SmallString<128> SFINAEArgString;
12568 SourceRange R;
12569 if (PDiag) {
12570 SFINAEArgString = ": ";
12571 R = SourceRange(PDiag->first, PDiag->first);
12572 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12573 }
12574
12575 S.Diag(Templated->getLocation(),
12576 diag::note_ovl_candidate_substitution_failure)
12577 << TemplateArgString << SFINAEArgString << R;
12578 MaybeEmitInheritedConstructorNote(S, Found);
12579 return;
12580 }
12581
12584 // Format the template argument list into the argument string.
12585 SmallString<128> TemplateArgString;
12586 if (TemplateArgumentList *Args =
12587 DeductionFailure.getTemplateArgumentList()) {
12588 TemplateArgString = " ";
12589 TemplateArgString += S.getTemplateArgumentBindingsText(
12590 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12591 if (TemplateArgString.size() == 1)
12592 TemplateArgString.clear();
12593 }
12594
12595 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12596 << (*DeductionFailure.getCallArgIndex() + 1)
12597 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12598 << TemplateArgString
12599 << (DeductionFailure.getResult() ==
12601 break;
12602 }
12603
12605 // FIXME: Provide a source location to indicate what we couldn't match.
12606 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12607 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12608 if (FirstTA.getKind() == TemplateArgument::Template &&
12609 SecondTA.getKind() == TemplateArgument::Template) {
12610 TemplateName FirstTN = FirstTA.getAsTemplate();
12611 TemplateName SecondTN = SecondTA.getAsTemplate();
12612 if (FirstTN.getKind() == TemplateName::Template &&
12613 SecondTN.getKind() == TemplateName::Template) {
12614 if (FirstTN.getAsTemplateDecl()->getName() ==
12615 SecondTN.getAsTemplateDecl()->getName()) {
12616 // FIXME: This fixes a bad diagnostic where both templates are named
12617 // the same. This particular case is a bit difficult since:
12618 // 1) It is passed as a string to the diagnostic printer.
12619 // 2) The diagnostic printer only attempts to find a better
12620 // name for types, not decls.
12621 // Ideally, this should folded into the diagnostic printer.
12622 S.Diag(Templated->getLocation(),
12623 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12624 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12625 return;
12626 }
12627 }
12628 }
12629
12630 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12632 return;
12633
12634 // FIXME: For generic lambda parameters, check if the function is a lambda
12635 // call operator, and if so, emit a prettier and more informative
12636 // diagnostic that mentions 'auto' and lambda in addition to
12637 // (or instead of?) the canonical template type parameters.
12638 S.Diag(Templated->getLocation(),
12639 diag::note_ovl_candidate_non_deduced_mismatch)
12640 << FirstTA << SecondTA;
12641 return;
12642 }
12643 // TODO: diagnose these individually, then kill off
12644 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12646 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12647 MaybeEmitInheritedConstructorNote(S, Found);
12648 return;
12650 S.Diag(Templated->getLocation(),
12651 diag::note_cuda_ovl_candidate_target_mismatch);
12652 return;
12653 }
12654}
12655
12656/// Diagnose a failed template-argument deduction, for function calls.
12658 unsigned NumArgs,
12659 bool TakingCandidateAddress) {
12660 assert(Cand->Function && "Candidate must be a function");
12661 FunctionDecl *Fn = Cand->Function;
12665 if (CheckArityMismatch(S, Cand, NumArgs))
12666 return;
12667 }
12668 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12669 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12670}
12671
12672/// CUDA: diagnose an invalid call across targets.
12674 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12675 assert(Cand->Function && "Candidate must be a Function.");
12676 FunctionDecl *Callee = Cand->Function;
12677
12678 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12679 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12680
12681 std::string FnDesc;
12682 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12683 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12684 Cand->getRewriteKind(), FnDesc);
12685
12686 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12687 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12688 << FnDesc /* Ignored */
12689 << CalleeTarget << CallerTarget;
12690
12691 // This could be an implicit constructor for which we could not infer the
12692 // target due to a collsion. Diagnose that case.
12693 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12694 if (Meth != nullptr && Meth->isImplicit()) {
12695 CXXRecordDecl *ParentClass = Meth->getParent();
12697
12698 switch (FnKindPair.first) {
12699 default:
12700 return;
12701 case oc_implicit_default_constructor:
12703 break;
12704 case oc_implicit_copy_constructor:
12706 break;
12707 case oc_implicit_move_constructor:
12709 break;
12710 case oc_implicit_copy_assignment:
12712 break;
12713 case oc_implicit_move_assignment:
12715 break;
12716 };
12717
12718 bool ConstRHS = false;
12719 if (Meth->getNumParams()) {
12720 if (const ReferenceType *RT =
12721 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12722 ConstRHS = RT->getPointeeType().isConstQualified();
12723 }
12724 }
12725
12726 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12727 /* ConstRHS */ ConstRHS,
12728 /* Diagnose */ true);
12729 }
12730}
12731
12733 assert(Cand->Function && "Candidate must be a function");
12734 FunctionDecl *Callee = Cand->Function;
12735 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12736
12737 S.Diag(Callee->getLocation(),
12738 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12739 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12740}
12741
12743 assert(Cand->Function && "Candidate must be a function");
12744 FunctionDecl *Fn = Cand->Function;
12746 assert(ES.isExplicit() && "not an explicit candidate");
12747
12748 unsigned Kind;
12749 switch (Fn->getDeclKind()) {
12750 case Decl::Kind::CXXConstructor:
12751 Kind = 0;
12752 break;
12753 case Decl::Kind::CXXConversion:
12754 Kind = 1;
12755 break;
12756 case Decl::Kind::CXXDeductionGuide:
12757 Kind = Fn->isImplicit() ? 0 : 2;
12758 break;
12759 default:
12760 llvm_unreachable("invalid Decl");
12761 }
12762
12763 // Note the location of the first (in-class) declaration; a redeclaration
12764 // (particularly an out-of-class definition) will typically lack the
12765 // 'explicit' specifier.
12766 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12767 FunctionDecl *First = Fn->getFirstDecl();
12768 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12769 First = Pattern->getFirstDecl();
12770
12771 S.Diag(First->getLocation(),
12772 diag::note_ovl_candidate_explicit)
12773 << Kind << (ES.getExpr() ? 1 : 0)
12774 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12775}
12776
12778 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12779 if (!DG)
12780 return;
12781 TemplateDecl *OriginTemplate =
12783 // We want to always print synthesized deduction guides for type aliases.
12784 // They would retain the explicit bit of the corresponding constructor.
12785 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12786 return;
12787 std::string FunctionProto;
12788 llvm::raw_string_ostream OS(FunctionProto);
12789 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12790 if (!Template) {
12791 // This also could be an instantiation. Find out the primary template.
12792 FunctionDecl *Pattern =
12793 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12794 if (!Pattern) {
12795 // The implicit deduction guide is built on an explicit non-template
12796 // deduction guide. Currently, this might be the case only for type
12797 // aliases.
12798 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12799 // gets merged.
12800 assert(OriginTemplate->isTypeAlias() &&
12801 "Non-template implicit deduction guides are only possible for "
12802 "type aliases");
12803 DG->print(OS);
12804 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12805 << FunctionProto;
12806 return;
12807 }
12809 assert(Template && "Cannot find the associated function template of "
12810 "CXXDeductionGuideDecl?");
12811 }
12812 Template->print(OS);
12813 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12814 << FunctionProto;
12815}
12816
12817/// Generates a 'note' diagnostic for an overload candidate. We've
12818/// already generated a primary error at the call site.
12819///
12820/// It really does need to be a single diagnostic with its caret
12821/// pointed at the candidate declaration. Yes, this creates some
12822/// major challenges of technical writing. Yes, this makes pointing
12823/// out problems with specific arguments quite awkward. It's still
12824/// better than generating twenty screens of text for every failed
12825/// overload.
12826///
12827/// It would be great to be able to express per-candidate problems
12828/// more richly for those diagnostic clients that cared, but we'd
12829/// still have to be just as careful with the default diagnostics.
12830/// \param CtorDestAS Addr space of object being constructed (for ctor
12831/// candidates only).
12833 unsigned NumArgs,
12834 bool TakingCandidateAddress,
12835 LangAS CtorDestAS = LangAS::Default) {
12836 assert(Cand->Function && "Candidate must be a function");
12837 FunctionDecl *Fn = Cand->Function;
12839 return;
12840
12841 // There is no physical candidate declaration to point to for OpenCL builtins.
12842 // Except for failed conversions, the notes are identical for each candidate,
12843 // so do not generate such notes.
12844 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12846 return;
12847
12848 // Skip implicit member functions when trying to resolve
12849 // the address of a an overload set for a function pointer.
12850 if (Cand->TookAddressOfOverload &&
12851 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12852 return;
12853
12854 // Note deleted candidates, but only if they're viable.
12855 if (Cand->Viable) {
12856 if (Fn->isDeleted()) {
12857 std::string FnDesc;
12858 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12859 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12860 Cand->getRewriteKind(), FnDesc);
12861
12862 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12863 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12864 << (Fn->isDeleted()
12865 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12866 : 0);
12867 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12868 return;
12869 }
12870
12871 // We don't really have anything else to say about viable candidates.
12872 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12873 return;
12874 }
12875
12876 // If this is a synthesized deduction guide we're deducing against, add a note
12877 // for it. These deduction guides are not explicitly spelled in the source
12878 // code, so simply printing a deduction failure note mentioning synthesized
12879 // template parameters or pointing to the header of the surrounding RecordDecl
12880 // would be confusing.
12881 //
12882 // We prefer adding such notes at the end of the deduction failure because
12883 // duplicate code snippets appearing in the diagnostic would likely become
12884 // noisy.
12885 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12886
12887 switch (Cand->FailureKind) {
12890 return DiagnoseArityMismatch(S, Cand, NumArgs);
12891
12893 return DiagnoseBadDeduction(S, Cand, NumArgs,
12894 TakingCandidateAddress);
12895
12897 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12898 << (Fn->getPrimaryTemplate() ? 1 : 0);
12899 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12900 return;
12901 }
12902
12904 Qualifiers QualsForPrinting;
12905 QualsForPrinting.setAddressSpace(CtorDestAS);
12906 S.Diag(Fn->getLocation(),
12907 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12908 << QualsForPrinting;
12909 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12910 return;
12911 }
12912
12916 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12917
12919 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12920 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12921 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12922 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12923
12924 // FIXME: this currently happens when we're called from SemaInit
12925 // when user-conversion overload fails. Figure out how to handle
12926 // those conditions and diagnose them well.
12927 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12928 }
12929
12931 return DiagnoseBadTarget(S, Cand);
12932
12933 case ovl_fail_enable_if:
12934 return DiagnoseFailedEnableIfAttr(S, Cand);
12935
12936 case ovl_fail_explicit:
12937 return DiagnoseFailedExplicitSpec(S, Cand);
12938
12940 // It's generally not interesting to note copy/move constructors here.
12941 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12942 return;
12943 S.Diag(Fn->getLocation(),
12944 diag::note_ovl_candidate_inherited_constructor_slice)
12945 << (Fn->getPrimaryTemplate() ? 1 : 0)
12946 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12947 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12948 return;
12949
12951 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12952 (void)Available;
12953 assert(!Available);
12954 break;
12955 }
12957 // Do nothing, these should simply be ignored.
12958 break;
12959
12961 std::string FnDesc;
12962 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12963 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12964 Cand->getRewriteKind(), FnDesc);
12965
12966 S.Diag(Fn->getLocation(),
12967 diag::note_ovl_candidate_constraints_not_satisfied)
12968 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12969 << FnDesc /* Ignored */;
12970 ConstraintSatisfaction Satisfaction;
12971 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12972 /*ForOverloadResolution=*/true))
12973 break;
12974 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12975 }
12976 }
12977}
12978
12981 return;
12982
12983 // Desugar the type of the surrogate down to a function type,
12984 // retaining as many typedefs as possible while still showing
12985 // the function type (and, therefore, its parameter types).
12986 QualType FnType = Cand->Surrogate->getConversionType();
12987 bool isLValueReference = false;
12988 bool isRValueReference = false;
12989 bool isPointer = false;
12990 if (const LValueReferenceType *FnTypeRef =
12991 FnType->getAs<LValueReferenceType>()) {
12992 FnType = FnTypeRef->getPointeeType();
12993 isLValueReference = true;
12994 } else if (const RValueReferenceType *FnTypeRef =
12995 FnType->getAs<RValueReferenceType>()) {
12996 FnType = FnTypeRef->getPointeeType();
12997 isRValueReference = true;
12998 }
12999 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13000 FnType = FnTypePtr->getPointeeType();
13001 isPointer = true;
13002 }
13003 // Desugar down to a function type.
13004 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13005 // Reconstruct the pointer/reference as appropriate.
13006 if (isPointer) FnType = S.Context.getPointerType(FnType);
13007 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13008 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13009
13010 if (!Cand->Viable &&
13012 S.Diag(Cand->Surrogate->getLocation(),
13013 diag::note_ovl_surrogate_constraints_not_satisfied)
13014 << Cand->Surrogate;
13015 ConstraintSatisfaction Satisfaction;
13016 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13017 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13018 } else {
13019 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13020 << FnType;
13021 }
13022}
13023
13024static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13025 SourceLocation OpLoc,
13026 OverloadCandidate *Cand) {
13027 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13028 std::string TypeStr("operator");
13029 TypeStr += Opc;
13030 TypeStr += "(";
13031 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13032 if (Cand->Conversions.size() == 1) {
13033 TypeStr += ")";
13034 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13035 } else {
13036 TypeStr += ", ";
13037 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13038 TypeStr += ")";
13039 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13040 }
13041}
13042
13044 OverloadCandidate *Cand) {
13045 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13046 if (ICS.isBad()) break; // all meaningless after first invalid
13047 if (!ICS.isAmbiguous()) continue;
13048
13050 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13051 }
13052}
13053
13055 if (Cand->Function)
13056 return Cand->Function->getLocation();
13057 if (Cand->IsSurrogate)
13058 return Cand->Surrogate->getLocation();
13059 return SourceLocation();
13060}
13061
13062static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13063 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13067 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13068
13072 return 1;
13073
13076 return 2;
13077
13085 return 3;
13086
13088 return 4;
13089
13091 return 5;
13092
13095 return 6;
13096 }
13097 llvm_unreachable("Unhandled deduction result");
13098}
13099
13100namespace {
13101
13102struct CompareOverloadCandidatesForDisplay {
13103 Sema &S;
13104 SourceLocation Loc;
13105 size_t NumArgs;
13107
13108 CompareOverloadCandidatesForDisplay(
13109 Sema &S, SourceLocation Loc, size_t NArgs,
13111 : S(S), NumArgs(NArgs), CSK(CSK) {}
13112
13113 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13114 // If there are too many or too few arguments, that's the high-order bit we
13115 // want to sort by, even if the immediate failure kind was something else.
13116 if (C->FailureKind == ovl_fail_too_many_arguments ||
13117 C->FailureKind == ovl_fail_too_few_arguments)
13118 return static_cast<OverloadFailureKind>(C->FailureKind);
13119
13120 if (C->Function) {
13121 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13123 if (NumArgs < C->Function->getMinRequiredArguments())
13125 }
13126
13127 return static_cast<OverloadFailureKind>(C->FailureKind);
13128 }
13129
13130 bool operator()(const OverloadCandidate *L,
13131 const OverloadCandidate *R) {
13132 // Fast-path this check.
13133 if (L == R) return false;
13134
13135 // Order first by viability.
13136 if (L->Viable) {
13137 if (!R->Viable) return true;
13138
13139 if (int Ord = CompareConversions(*L, *R))
13140 return Ord < 0;
13141 // Use other tie breakers.
13142 } else if (R->Viable)
13143 return false;
13144
13145 assert(L->Viable == R->Viable);
13146
13147 // Criteria by which we can sort non-viable candidates:
13148 if (!L->Viable) {
13149 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13150 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13151
13152 // 1. Arity mismatches come after other candidates.
13153 if (LFailureKind == ovl_fail_too_many_arguments ||
13154 LFailureKind == ovl_fail_too_few_arguments) {
13155 if (RFailureKind == ovl_fail_too_many_arguments ||
13156 RFailureKind == ovl_fail_too_few_arguments) {
13157 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13158 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13159 if (LDist == RDist) {
13160 if (LFailureKind == RFailureKind)
13161 // Sort non-surrogates before surrogates.
13162 return !L->IsSurrogate && R->IsSurrogate;
13163 // Sort candidates requiring fewer parameters than there were
13164 // arguments given after candidates requiring more parameters
13165 // than there were arguments given.
13166 return LFailureKind == ovl_fail_too_many_arguments;
13167 }
13168 return LDist < RDist;
13169 }
13170 return false;
13171 }
13172 if (RFailureKind == ovl_fail_too_many_arguments ||
13173 RFailureKind == ovl_fail_too_few_arguments)
13174 return true;
13175
13176 // 2. Bad conversions come first and are ordered by the number
13177 // of bad conversions and quality of good conversions.
13178 if (LFailureKind == ovl_fail_bad_conversion) {
13179 if (RFailureKind != ovl_fail_bad_conversion)
13180 return true;
13181
13182 // The conversion that can be fixed with a smaller number of changes,
13183 // comes first.
13184 unsigned numLFixes = L->Fix.NumConversionsFixed;
13185 unsigned numRFixes = R->Fix.NumConversionsFixed;
13186 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13187 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13188 if (numLFixes != numRFixes) {
13189 return numLFixes < numRFixes;
13190 }
13191
13192 // If there's any ordering between the defined conversions...
13193 if (int Ord = CompareConversions(*L, *R))
13194 return Ord < 0;
13195 } else if (RFailureKind == ovl_fail_bad_conversion)
13196 return false;
13197
13198 if (LFailureKind == ovl_fail_bad_deduction) {
13199 if (RFailureKind != ovl_fail_bad_deduction)
13200 return true;
13201
13202 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13203 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13204 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13205 if (LRank != RRank)
13206 return LRank < RRank;
13207 }
13208 } else if (RFailureKind == ovl_fail_bad_deduction)
13209 return false;
13210
13211 // TODO: others?
13212 }
13213
13214 // Sort everything else by location.
13215 SourceLocation LLoc = GetLocationForCandidate(L);
13216 SourceLocation RLoc = GetLocationForCandidate(R);
13217
13218 // Put candidates without locations (e.g. builtins) at the end.
13219 if (LLoc.isValid() && RLoc.isValid())
13220 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13221 if (LLoc.isValid() && !RLoc.isValid())
13222 return true;
13223 if (RLoc.isValid() && !LLoc.isValid())
13224 return false;
13225 assert(!LLoc.isValid() && !RLoc.isValid());
13226 // For builtins and other functions without locations, fallback to the order
13227 // in which they were added into the candidate set.
13228 return L < R;
13229 }
13230
13231private:
13232 struct ConversionSignals {
13233 unsigned KindRank = 0;
13235
13236 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13237 ConversionSignals Sig;
13238 Sig.KindRank = Seq.getKindRank();
13239 if (Seq.isStandard())
13240 Sig.Rank = Seq.Standard.getRank();
13241 else if (Seq.isUserDefined())
13242 Sig.Rank = Seq.UserDefined.After.getRank();
13243 // We intend StaticObjectArgumentConversion to compare the same as
13244 // StandardConversion with ICR_ExactMatch rank.
13245 return Sig;
13246 }
13247
13248 static ConversionSignals ForObjectArgument() {
13249 // We intend StaticObjectArgumentConversion to compare the same as
13250 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13251 return {};
13252 }
13253 };
13254
13255 // Returns -1 if conversions in L are considered better.
13256 // 0 if they are considered indistinguishable.
13257 // 1 if conversions in R are better.
13258 int CompareConversions(const OverloadCandidate &L,
13259 const OverloadCandidate &R) {
13260 // We cannot use `isBetterOverloadCandidate` because it is defined
13261 // according to the C++ standard and provides a partial order, but we need
13262 // a total order as this function is used in sort.
13263 assert(L.Conversions.size() == R.Conversions.size());
13264 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13265 auto LS = L.IgnoreObjectArgument && I == 0
13266 ? ConversionSignals::ForObjectArgument()
13267 : ConversionSignals::ForSequence(L.Conversions[I]);
13268 auto RS = R.IgnoreObjectArgument
13269 ? ConversionSignals::ForObjectArgument()
13270 : ConversionSignals::ForSequence(R.Conversions[I]);
13271 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13272 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13273 ? -1
13274 : 1;
13275 }
13276 // FIXME: find a way to compare templates for being more or less
13277 // specialized that provides a strict weak ordering.
13278 return 0;
13279 }
13280};
13281}
13282
13283/// CompleteNonViableCandidate - Normally, overload resolution only
13284/// computes up to the first bad conversion. Produces the FixIt set if
13285/// possible.
13286static void
13288 ArrayRef<Expr *> Args,
13290 assert(!Cand->Viable);
13291
13292 // Don't do anything on failures other than bad conversion.
13294 return;
13295
13296 // We only want the FixIts if all the arguments can be corrected.
13297 bool Unfixable = false;
13298 // Use a implicit copy initialization to check conversion fixes.
13300
13301 // Attempt to fix the bad conversion.
13302 unsigned ConvCount = Cand->Conversions.size();
13303 for (unsigned ConvIdx =
13304 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13305 : 0);
13306 /**/; ++ConvIdx) {
13307 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13308 if (Cand->Conversions[ConvIdx].isInitialized() &&
13309 Cand->Conversions[ConvIdx].isBad()) {
13310 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13311 break;
13312 }
13313 }
13314
13315 // FIXME: this should probably be preserved from the overload
13316 // operation somehow.
13317 bool SuppressUserConversions = false;
13318
13319 unsigned ConvIdx = 0;
13320 unsigned ArgIdx = 0;
13321 ArrayRef<QualType> ParamTypes;
13322 bool Reversed = Cand->isReversed();
13323
13324 if (Cand->IsSurrogate) {
13325 QualType ConvType
13327 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13328 ConvType = ConvPtrType->getPointeeType();
13329 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13330 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13331 ConvIdx = 1;
13332 } else if (Cand->Function) {
13333 ParamTypes =
13334 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13335 if (isa<CXXMethodDecl>(Cand->Function) &&
13338 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13339 ConvIdx = 1;
13341 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13343 OO_Subscript)
13344 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13345 ArgIdx = 1;
13346 }
13347 } else {
13348 // Builtin operator.
13349 assert(ConvCount <= 3);
13350 ParamTypes = Cand->BuiltinParamTypes;
13351 }
13352
13353 // Fill in the rest of the conversions.
13354 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13355 ConvIdx != ConvCount && ArgIdx < Args.size();
13356 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13357 if (Cand->Conversions[ConvIdx].isInitialized()) {
13358 // We've already checked this conversion.
13359 } else if (ParamIdx < ParamTypes.size()) {
13360 if (ParamTypes[ParamIdx]->isDependentType())
13361 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13362 Args[ArgIdx]->getType());
13363 else {
13364 Cand->Conversions[ConvIdx] =
13365 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13366 SuppressUserConversions,
13367 /*InOverloadResolution=*/true,
13368 /*AllowObjCWritebackConversion=*/
13369 S.getLangOpts().ObjCAutoRefCount);
13370 // Store the FixIt in the candidate if it exists.
13371 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13372 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13373 }
13374 } else
13375 Cand->Conversions[ConvIdx].setEllipsis();
13376 }
13377}
13378
13381 SourceLocation OpLoc,
13382 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13383
13385
13386 // Sort the candidates by viability and position. Sorting directly would
13387 // be prohibitive, so we make a set of pointers and sort those.
13389 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13390 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13391 Cand != LastCand; ++Cand) {
13392 if (!Filter(*Cand))
13393 continue;
13394 switch (OCD) {
13395 case OCD_AllCandidates:
13396 if (!Cand->Viable) {
13397 if (!Cand->Function && !Cand->IsSurrogate) {
13398 // This a non-viable builtin candidate. We do not, in general,
13399 // want to list every possible builtin candidate.
13400 continue;
13401 }
13402 CompleteNonViableCandidate(S, Cand, Args, Kind);
13403 }
13404 break;
13405
13407 if (!Cand->Viable)
13408 continue;
13409 break;
13410
13412 if (!Cand->Best)
13413 continue;
13414 break;
13415 }
13416
13417 Cands.push_back(Cand);
13418 }
13419
13420 llvm::stable_sort(
13421 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13422
13423 return Cands;
13424}
13425
13427 SourceLocation OpLoc) {
13428 bool DeferHint = false;
13429 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13430 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13431 // host device candidates.
13432 auto WrongSidedCands =
13433 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13434 return (Cand.Viable == false &&
13436 (Cand.Function &&
13437 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13438 Cand.Function->template hasAttr<CUDADeviceAttr>());
13439 });
13440 DeferHint = !WrongSidedCands.empty();
13441 }
13442 return DeferHint;
13443}
13444
13445/// When overload resolution fails, prints diagnostic messages containing the
13446/// candidates in the candidate set.
13449 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13450 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13451
13452 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13453
13454 {
13455 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13456 S.Diag(PD.first, PD.second);
13457 }
13458
13459 // In WebAssembly we don't want to emit further diagnostics if a table is
13460 // passed as an argument to a function.
13461 bool NoteCands = true;
13462 for (const Expr *Arg : Args) {
13463 if (Arg->getType()->isWebAssemblyTableType())
13464 NoteCands = false;
13465 }
13466
13467 if (NoteCands)
13468 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13469
13470 if (OCD == OCD_AmbiguousCandidates)
13472 {Candidates.begin(), Candidates.end()});
13473}
13474
13477 StringRef Opc, SourceLocation OpLoc) {
13478 bool ReportedAmbiguousConversions = false;
13479
13480 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13481 unsigned CandsShown = 0;
13482 auto I = Cands.begin(), E = Cands.end();
13483 for (; I != E; ++I) {
13484 OverloadCandidate *Cand = *I;
13485
13486 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13487 ShowOverloads == Ovl_Best) {
13488 break;
13489 }
13490 ++CandsShown;
13491
13492 if (Cand->Function)
13493 NoteFunctionCandidate(S, Cand, Args.size(),
13494 Kind == CSK_AddressOfOverloadSet, DestAS);
13495 else if (Cand->IsSurrogate)
13496 NoteSurrogateCandidate(S, Cand);
13497 else {
13498 assert(Cand->Viable &&
13499 "Non-viable built-in candidates are not added to Cands.");
13500 // Generally we only see ambiguities including viable builtin
13501 // operators if overload resolution got screwed up by an
13502 // ambiguous user-defined conversion.
13503 //
13504 // FIXME: It's quite possible for different conversions to see
13505 // different ambiguities, though.
13506 if (!ReportedAmbiguousConversions) {
13507 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13508 ReportedAmbiguousConversions = true;
13509 }
13510
13511 // If this is a viable builtin, print it.
13512 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13513 }
13514 }
13515
13516 // Inform S.Diags that we've shown an overload set with N elements. This may
13517 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13518 S.Diags.overloadCandidatesShown(CandsShown);
13519
13520 if (I != E) {
13521 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13522 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13523 }
13524}
13525
13526static SourceLocation
13528 return Cand->Specialization ? Cand->Specialization->getLocation()
13529 : SourceLocation();
13530}
13531
13532namespace {
13533struct CompareTemplateSpecCandidatesForDisplay {
13534 Sema &S;
13535 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13536
13537 bool operator()(const TemplateSpecCandidate *L,
13538 const TemplateSpecCandidate *R) {
13539 // Fast-path this check.
13540 if (L == R)
13541 return false;
13542
13543 // Assuming that both candidates are not matches...
13544
13545 // Sort by the ranking of deduction failures.
13546 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13548 RankDeductionFailure(R->DeductionFailure);
13549
13550 // Sort everything else by location.
13551 SourceLocation LLoc = GetLocationForCandidate(L);
13552 SourceLocation RLoc = GetLocationForCandidate(R);
13553
13554 // Put candidates without locations (e.g. builtins) at the end.
13555 if (LLoc.isInvalid())
13556 return false;
13557 if (RLoc.isInvalid())
13558 return true;
13559
13560 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13561 }
13562};
13563}
13564
13565/// Diagnose a template argument deduction failure.
13566/// We are treating these failures as overload failures due to bad
13567/// deductions.
13569 bool ForTakingAddress) {
13571 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13572}
13573
13574void TemplateSpecCandidateSet::destroyCandidates() {
13575 for (iterator i = begin(), e = end(); i != e; ++i) {
13576 i->DeductionFailure.Destroy();
13577 }
13578}
13579
13581 destroyCandidates();
13582 Candidates.clear();
13583}
13584
13585/// NoteCandidates - When no template specialization match is found, prints
13586/// diagnostic messages containing the non-matching specializations that form
13587/// the candidate set.
13588/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13589/// OCD == OCD_AllCandidates and Cand->Viable == false.
13591 // Sort the candidates by position (assuming no candidate is a match).
13592 // Sorting directly would be prohibitive, so we make a set of pointers
13593 // and sort those.
13595 Cands.reserve(size());
13596 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13597 if (Cand->Specialization)
13598 Cands.push_back(Cand);
13599 // Otherwise, this is a non-matching builtin candidate. We do not,
13600 // in general, want to list every possible builtin candidate.
13601 }
13602
13603 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13604
13605 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13606 // for generalization purposes (?).
13607 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13608
13610 unsigned CandsShown = 0;
13611 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13612 TemplateSpecCandidate *Cand = *I;
13613
13614 // Set an arbitrary limit on the number of candidates we'll spam
13615 // the user with. FIXME: This limit should depend on details of the
13616 // candidate list.
13617 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13618 break;
13619 ++CandsShown;
13620
13621 assert(Cand->Specialization &&
13622 "Non-matching built-in candidates are not added to Cands.");
13623 Cand->NoteDeductionFailure(S, ForTakingAddress);
13624 }
13625
13626 if (I != E)
13627 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13628}
13629
13630// [PossiblyAFunctionType] --> [Return]
13631// NonFunctionType --> NonFunctionType
13632// R (A) --> R(A)
13633// R (*)(A) --> R (A)
13634// R (&)(A) --> R (A)
13635// R (S::*)(A) --> R (A)
13637 QualType Ret = PossiblyAFunctionType;
13638 if (const PointerType *ToTypePtr =
13639 PossiblyAFunctionType->getAs<PointerType>())
13640 Ret = ToTypePtr->getPointeeType();
13641 else if (const ReferenceType *ToTypeRef =
13642 PossiblyAFunctionType->getAs<ReferenceType>())
13643 Ret = ToTypeRef->getPointeeType();
13644 else if (const MemberPointerType *MemTypePtr =
13645 PossiblyAFunctionType->getAs<MemberPointerType>())
13646 Ret = MemTypePtr->getPointeeType();
13647 Ret =
13648 Context.getCanonicalType(Ret).getUnqualifiedType();
13649 return Ret;
13650}
13651
13653 bool Complain = true) {
13654 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13655 S.DeduceReturnType(FD, Loc, Complain))
13656 return true;
13657
13658 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13659 if (S.getLangOpts().CPlusPlus17 &&
13660 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13661 !S.ResolveExceptionSpec(Loc, FPT))
13662 return true;
13663
13664 return false;
13665}
13666
13667namespace {
13668// A helper class to help with address of function resolution
13669// - allows us to avoid passing around all those ugly parameters
13670class AddressOfFunctionResolver {
13671 Sema& S;
13672 Expr* SourceExpr;
13673 const QualType& TargetType;
13674 QualType TargetFunctionType; // Extracted function type from target type
13675
13676 bool Complain;
13677 //DeclAccessPair& ResultFunctionAccessPair;
13678 ASTContext& Context;
13679
13680 bool TargetTypeIsNonStaticMemberFunction;
13681 bool FoundNonTemplateFunction;
13682 bool StaticMemberFunctionFromBoundPointer;
13683 bool HasComplained;
13684
13685 OverloadExpr::FindResult OvlExprInfo;
13686 OverloadExpr *OvlExpr;
13687 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13688 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13689 TemplateSpecCandidateSet FailedCandidates;
13690
13691public:
13692 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13693 const QualType &TargetType, bool Complain)
13694 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13695 Complain(Complain), Context(S.getASTContext()),
13696 TargetTypeIsNonStaticMemberFunction(
13697 !!TargetType->getAs<MemberPointerType>()),
13698 FoundNonTemplateFunction(false),
13699 StaticMemberFunctionFromBoundPointer(false),
13700 HasComplained(false),
13701 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13702 OvlExpr(OvlExprInfo.Expression),
13703 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13704 ExtractUnqualifiedFunctionTypeFromTargetType();
13705
13706 if (TargetFunctionType->isFunctionType()) {
13707 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13708 if (!UME->isImplicitAccess() &&
13710 StaticMemberFunctionFromBoundPointer = true;
13711 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13712 DeclAccessPair dap;
13713 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13714 OvlExpr, false, &dap)) {
13715 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13716 if (!Method->isStatic()) {
13717 // If the target type is a non-function type and the function found
13718 // is a non-static member function, pretend as if that was the
13719 // target, it's the only possible type to end up with.
13720 TargetTypeIsNonStaticMemberFunction = true;
13721
13722 // And skip adding the function if its not in the proper form.
13723 // We'll diagnose this due to an empty set of functions.
13724 if (!OvlExprInfo.HasFormOfMemberPointer)
13725 return;
13726 }
13727
13728 Matches.push_back(std::make_pair(dap, Fn));
13729 }
13730 return;
13731 }
13732
13733 if (OvlExpr->hasExplicitTemplateArgs())
13734 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13735
13736 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13737 // C++ [over.over]p4:
13738 // If more than one function is selected, [...]
13739 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13740 if (FoundNonTemplateFunction) {
13741 EliminateAllTemplateMatches();
13742 EliminateLessPartialOrderingConstrainedMatches();
13743 } else
13744 EliminateAllExceptMostSpecializedTemplate();
13745 }
13746 }
13747
13748 if (S.getLangOpts().CUDA && Matches.size() > 1)
13749 EliminateSuboptimalCudaMatches();
13750 }
13751
13752 bool hasComplained() const { return HasComplained; }
13753
13754private:
13755 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13756 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13757 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13758 }
13759
13760 /// \return true if A is considered a better overload candidate for the
13761 /// desired type than B.
13762 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13763 // If A doesn't have exactly the correct type, we don't want to classify it
13764 // as "better" than anything else. This way, the user is required to
13765 // disambiguate for us if there are multiple candidates and no exact match.
13766 return candidateHasExactlyCorrectType(A) &&
13767 (!candidateHasExactlyCorrectType(B) ||
13768 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13769 }
13770
13771 /// \return true if we were able to eliminate all but one overload candidate,
13772 /// false otherwise.
13773 bool eliminiateSuboptimalOverloadCandidates() {
13774 // Same algorithm as overload resolution -- one pass to pick the "best",
13775 // another pass to be sure that nothing is better than the best.
13776 auto Best = Matches.begin();
13777 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13778 if (isBetterCandidate(I->second, Best->second))
13779 Best = I;
13780
13781 const FunctionDecl *BestFn = Best->second;
13782 auto IsBestOrInferiorToBest = [this, BestFn](
13783 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13784 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13785 };
13786
13787 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13788 // option, so we can potentially give the user a better error
13789 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13790 return false;
13791 Matches[0] = *Best;
13792 Matches.resize(1);
13793 return true;
13794 }
13795
13796 bool isTargetTypeAFunction() const {
13797 return TargetFunctionType->isFunctionType();
13798 }
13799
13800 // [ToType] [Return]
13801
13802 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13803 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13804 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13805 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13806 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13807 }
13808
13809 // return true if any matching specializations were found
13810 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13811 const DeclAccessPair& CurAccessFunPair) {
13812 if (CXXMethodDecl *Method
13813 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13814 // Skip non-static function templates when converting to pointer, and
13815 // static when converting to member pointer.
13816 bool CanConvertToFunctionPointer =
13817 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13818 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13819 return false;
13820 }
13821 else if (TargetTypeIsNonStaticMemberFunction)
13822 return false;
13823
13824 // C++ [over.over]p2:
13825 // If the name is a function template, template argument deduction is
13826 // done (14.8.2.2), and if the argument deduction succeeds, the
13827 // resulting template argument list is used to generate a single
13828 // function template specialization, which is added to the set of
13829 // overloaded functions considered.
13830 FunctionDecl *Specialization = nullptr;
13831 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13833 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13834 Specialization, Info, /*IsAddressOfFunction*/ true);
13835 Result != TemplateDeductionResult::Success) {
13836 // Make a note of the failed deduction for diagnostics.
13837 FailedCandidates.addCandidate()
13838 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13839 MakeDeductionFailureInfo(Context, Result, Info));
13840 return false;
13841 }
13842
13843 // Template argument deduction ensures that we have an exact match or
13844 // compatible pointer-to-function arguments that would be adjusted by ICS.
13845 // This function template specicalization works.
13847 Context.getCanonicalType(Specialization->getType()),
13848 Context.getCanonicalType(TargetFunctionType)));
13849
13851 return false;
13852
13853 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13854 return true;
13855 }
13856
13857 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13858 const DeclAccessPair& CurAccessFunPair) {
13859 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13860 // Skip non-static functions when converting to pointer, and static
13861 // when converting to member pointer.
13862 bool CanConvertToFunctionPointer =
13863 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13864 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13865 return false;
13866 }
13867 else if (TargetTypeIsNonStaticMemberFunction)
13868 return false;
13869
13870 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13871 if (S.getLangOpts().CUDA) {
13872 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13873 if (!(Caller && Caller->isImplicit()) &&
13874 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13875 return false;
13876 }
13877 if (FunDecl->isMultiVersion()) {
13878 const auto *TA = FunDecl->getAttr<TargetAttr>();
13879 if (TA && !TA->isDefaultVersion())
13880 return false;
13881 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13882 if (TVA && !TVA->isDefaultVersion())
13883 return false;
13884 }
13885
13886 // If any candidate has a placeholder return type, trigger its deduction
13887 // now.
13888 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13889 Complain)) {
13890 HasComplained |= Complain;
13891 return false;
13892 }
13893
13894 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13895 return false;
13896
13897 // If we're in C, we need to support types that aren't exactly identical.
13898 if (!S.getLangOpts().CPlusPlus ||
13899 candidateHasExactlyCorrectType(FunDecl)) {
13900 Matches.push_back(std::make_pair(
13901 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13902 FoundNonTemplateFunction = true;
13903 return true;
13904 }
13905 }
13906
13907 return false;
13908 }
13909
13910 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13911 bool Ret = false;
13912
13913 // If the overload expression doesn't have the form of a pointer to
13914 // member, don't try to convert it to a pointer-to-member type.
13915 if (IsInvalidFormOfPointerToMemberFunction())
13916 return false;
13917
13918 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13919 E = OvlExpr->decls_end();
13920 I != E; ++I) {
13921 // Look through any using declarations to find the underlying function.
13922 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13923
13924 // C++ [over.over]p3:
13925 // Non-member functions and static member functions match
13926 // targets of type "pointer-to-function" or "reference-to-function."
13927 // Nonstatic member functions match targets of
13928 // type "pointer-to-member-function."
13929 // Note that according to DR 247, the containing class does not matter.
13930 if (FunctionTemplateDecl *FunctionTemplate
13931 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13932 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13933 Ret = true;
13934 }
13935 // If we have explicit template arguments supplied, skip non-templates.
13936 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13937 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13938 Ret = true;
13939 }
13940 assert(Ret || Matches.empty());
13941 return Ret;
13942 }
13943
13944 void EliminateAllExceptMostSpecializedTemplate() {
13945 // [...] and any given function template specialization F1 is
13946 // eliminated if the set contains a second function template
13947 // specialization whose function template is more specialized
13948 // than the function template of F1 according to the partial
13949 // ordering rules of 14.5.5.2.
13950
13951 // The algorithm specified above is quadratic. We instead use a
13952 // two-pass algorithm (similar to the one used to identify the
13953 // best viable function in an overload set) that identifies the
13954 // best function template (if it exists).
13955
13956 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13957 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13958 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13959
13960 // TODO: It looks like FailedCandidates does not serve much purpose
13961 // here, since the no_viable diagnostic has index 0.
13962 UnresolvedSetIterator Result = S.getMostSpecialized(
13963 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13964 SourceExpr->getBeginLoc(), S.PDiag(),
13965 S.PDiag(diag::err_addr_ovl_ambiguous)
13966 << Matches[0].second->getDeclName(),
13967 S.PDiag(diag::note_ovl_candidate)
13968 << (unsigned)oc_function << (unsigned)ocs_described_template,
13969 Complain, TargetFunctionType);
13970
13971 if (Result != MatchesCopy.end()) {
13972 // Make it the first and only element
13973 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13974 Matches[0].second = cast<FunctionDecl>(*Result);
13975 Matches.resize(1);
13976 } else
13977 HasComplained |= Complain;
13978 }
13979
13980 void EliminateAllTemplateMatches() {
13981 // [...] any function template specializations in the set are
13982 // eliminated if the set also contains a non-template function, [...]
13983 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13984 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13985 ++I;
13986 else {
13987 Matches[I] = Matches[--N];
13988 Matches.resize(N);
13989 }
13990 }
13991 }
13992
13993 void EliminateLessPartialOrderingConstrainedMatches() {
13994 // C++ [over.over]p5:
13995 // [...] Any given non-template function F0 is eliminated if the set
13996 // contains a second non-template function that is more
13997 // partial-ordering-constrained than F0. [...]
13998 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13999 "Call EliminateAllTemplateMatches() first");
14000 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14001 Results.push_back(Matches[0]);
14002 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14003 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14004 FunctionDecl *F = getMorePartialOrderingConstrained(
14005 S, Matches[I].second, Results[0].second,
14006 /*IsFn1Reversed=*/false,
14007 /*IsFn2Reversed=*/false);
14008 if (!F) {
14009 Results.push_back(Matches[I]);
14010 continue;
14011 }
14012 if (F == Matches[I].second) {
14013 Results.clear();
14014 Results.push_back(Matches[I]);
14015 }
14016 }
14017 std::swap(Matches, Results);
14018 }
14019
14020 void EliminateSuboptimalCudaMatches() {
14021 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14022 Matches);
14023 }
14024
14025public:
14026 void ComplainNoMatchesFound() const {
14027 assert(Matches.empty());
14028 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14029 << OvlExpr->getName() << TargetFunctionType
14030 << OvlExpr->getSourceRange();
14031 if (FailedCandidates.empty())
14032 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14033 /*TakingAddress=*/true);
14034 else {
14035 // We have some deduction failure messages. Use them to diagnose
14036 // the function templates, and diagnose the non-template candidates
14037 // normally.
14038 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14039 IEnd = OvlExpr->decls_end();
14040 I != IEnd; ++I)
14041 if (FunctionDecl *Fun =
14042 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14044 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14045 /*TakingAddress=*/true);
14046 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14047 }
14048 }
14049
14050 bool IsInvalidFormOfPointerToMemberFunction() const {
14051 return TargetTypeIsNonStaticMemberFunction &&
14052 !OvlExprInfo.HasFormOfMemberPointer;
14053 }
14054
14055 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14056 // TODO: Should we condition this on whether any functions might
14057 // have matched, or is it more appropriate to do that in callers?
14058 // TODO: a fixit wouldn't hurt.
14059 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14060 << TargetType << OvlExpr->getSourceRange();
14061 }
14062
14063 bool IsStaticMemberFunctionFromBoundPointer() const {
14064 return StaticMemberFunctionFromBoundPointer;
14065 }
14066
14067 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14068 S.Diag(OvlExpr->getBeginLoc(),
14069 diag::err_invalid_form_pointer_member_function)
14070 << OvlExpr->getSourceRange();
14071 }
14072
14073 void ComplainOfInvalidConversion() const {
14074 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14075 << OvlExpr->getName() << TargetType;
14076 }
14077
14078 void ComplainMultipleMatchesFound() const {
14079 assert(Matches.size() > 1);
14080 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14081 << OvlExpr->getName() << OvlExpr->getSourceRange();
14082 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14083 /*TakingAddress=*/true);
14084 }
14085
14086 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14087
14088 int getNumMatches() const { return Matches.size(); }
14089
14090 FunctionDecl* getMatchingFunctionDecl() const {
14091 if (Matches.size() != 1) return nullptr;
14092 return Matches[0].second;
14093 }
14094
14095 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14096 if (Matches.size() != 1) return nullptr;
14097 return &Matches[0].first;
14098 }
14099};
14100}
14101
14102FunctionDecl *
14104 QualType TargetType,
14105 bool Complain,
14106 DeclAccessPair &FoundResult,
14107 bool *pHadMultipleCandidates) {
14108 assert(AddressOfExpr->getType() == Context.OverloadTy);
14109
14110 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14111 Complain);
14112 int NumMatches = Resolver.getNumMatches();
14113 FunctionDecl *Fn = nullptr;
14114 bool ShouldComplain = Complain && !Resolver.hasComplained();
14115 if (NumMatches == 0 && ShouldComplain) {
14116 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14117 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14118 else
14119 Resolver.ComplainNoMatchesFound();
14120 }
14121 else if (NumMatches > 1 && ShouldComplain)
14122 Resolver.ComplainMultipleMatchesFound();
14123 else if (NumMatches == 1) {
14124 Fn = Resolver.getMatchingFunctionDecl();
14125 assert(Fn);
14126 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14127 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14128 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14129 if (Complain) {
14130 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14131 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14132 else
14133 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14134 }
14135 }
14136
14137 if (pHadMultipleCandidates)
14138 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14139 return Fn;
14140}
14141
14145 OverloadExpr *Ovl = R.Expression;
14146 bool IsResultAmbiguous = false;
14147 FunctionDecl *Result = nullptr;
14148 DeclAccessPair DAP;
14149 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14150
14151 // Return positive for better, negative for worse, 0 for equal preference.
14152 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14153 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14154 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14155 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14156 };
14157
14158 // Don't use the AddressOfResolver because we're specifically looking for
14159 // cases where we have one overload candidate that lacks
14160 // enable_if/pass_object_size/...
14161 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14162 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14163 if (!FD)
14164 return nullptr;
14165
14167 continue;
14168
14169 // If we found a better result, update Result.
14170 auto FoundBetter = [&]() {
14171 IsResultAmbiguous = false;
14172 DAP = I.getPair();
14173 Result = FD;
14174 };
14175
14176 // We have more than one result - see if it is more
14177 // partial-ordering-constrained than the previous one.
14178 if (Result) {
14179 // Check CUDA preference first. If the candidates have differennt CUDA
14180 // preference, choose the one with higher CUDA preference. Otherwise,
14181 // choose the one with more constraints.
14182 if (getLangOpts().CUDA) {
14183 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14184 // FD has different preference than Result.
14185 if (PreferenceByCUDA != 0) {
14186 // FD is more preferable than Result.
14187 if (PreferenceByCUDA > 0)
14188 FoundBetter();
14189 continue;
14190 }
14191 }
14192 // FD has the same CUDA preference than Result. Continue to check
14193 // constraints.
14194
14195 // C++ [over.over]p5:
14196 // [...] Any given non-template function F0 is eliminated if the set
14197 // contains a second non-template function that is more
14198 // partial-ordering-constrained than F0 [...]
14199 FunctionDecl *MoreConstrained =
14201 /*IsFn1Reversed=*/false,
14202 /*IsFn2Reversed=*/false);
14203 if (MoreConstrained != FD) {
14204 if (!MoreConstrained) {
14205 IsResultAmbiguous = true;
14206 AmbiguousDecls.push_back(FD);
14207 }
14208 continue;
14209 }
14210 // FD is more constrained - replace Result with it.
14211 }
14212 FoundBetter();
14213 }
14214
14215 if (IsResultAmbiguous)
14216 return nullptr;
14217
14218 if (Result) {
14219 // We skipped over some ambiguous declarations which might be ambiguous with
14220 // the selected result.
14221 for (FunctionDecl *Skipped : AmbiguousDecls) {
14222 // If skipped candidate has different CUDA preference than the result,
14223 // there is no ambiguity. Otherwise check whether they have different
14224 // constraints.
14225 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14226 continue;
14227 if (!getMoreConstrainedFunction(Skipped, Result))
14228 return nullptr;
14229 }
14230 Pair = DAP;
14231 }
14232 return Result;
14233}
14234
14236 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14237 Expr *E = SrcExpr.get();
14238 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14239
14240 DeclAccessPair DAP;
14242 if (!Found || Found->isCPUDispatchMultiVersion() ||
14243 Found->isCPUSpecificMultiVersion())
14244 return false;
14245
14246 // Emitting multiple diagnostics for a function that is both inaccessible and
14247 // unavailable is consistent with our behavior elsewhere. So, always check
14248 // for both.
14252 if (Res.isInvalid())
14253 return false;
14254 Expr *Fixed = Res.get();
14255 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14256 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14257 else
14258 SrcExpr = Fixed;
14259 return true;
14260}
14261
14263 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14264 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14265 // C++ [over.over]p1:
14266 // [...] [Note: any redundant set of parentheses surrounding the
14267 // overloaded function name is ignored (5.1). ]
14268 // C++ [over.over]p1:
14269 // [...] The overloaded function name can be preceded by the &
14270 // operator.
14271
14272 // If we didn't actually find any template-ids, we're done.
14273 if (!ovl->hasExplicitTemplateArgs())
14274 return nullptr;
14275
14276 TemplateArgumentListInfo ExplicitTemplateArgs;
14277 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14278
14279 // Look through all of the overloaded functions, searching for one
14280 // whose type matches exactly.
14281 FunctionDecl *Matched = nullptr;
14282 for (UnresolvedSetIterator I = ovl->decls_begin(),
14283 E = ovl->decls_end(); I != E; ++I) {
14284 // C++0x [temp.arg.explicit]p3:
14285 // [...] In contexts where deduction is done and fails, or in contexts
14286 // where deduction is not done, if a template argument list is
14287 // specified and it, along with any default template arguments,
14288 // identifies a single function template specialization, then the
14289 // template-id is an lvalue for the function template specialization.
14291 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14292 if (!FunctionTemplate)
14293 continue;
14294
14295 // C++ [over.over]p2:
14296 // If the name is a function template, template argument deduction is
14297 // done (14.8.2.2), and if the argument deduction succeeds, the
14298 // resulting template argument list is used to generate a single
14299 // function template specialization, which is added to the set of
14300 // overloaded functions considered.
14301 FunctionDecl *Specialization = nullptr;
14302 TemplateDeductionInfo Info(ovl->getNameLoc());
14304 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14305 /*IsAddressOfFunction*/ true);
14307 // Make a note of the failed deduction for diagnostics.
14308 if (FailedTSC)
14309 FailedTSC->addCandidate().set(
14310 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14312 continue;
14313 }
14314
14315 assert(Specialization && "no specialization and no error?");
14316
14317 // C++ [temp.deduct.call]p6:
14318 // [...] If all successful deductions yield the same deduced A, that
14319 // deduced A is the result of deduction; otherwise, the parameter is
14320 // treated as a non-deduced context.
14321 if (Matched) {
14322 if (ForTypeDeduction &&
14324 Specialization->getType()))
14325 continue;
14326 // Multiple matches; we can't resolve to a single declaration.
14327 if (Complain) {
14328 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14329 << ovl->getName();
14331 }
14332 return nullptr;
14333 }
14334
14335 Matched = Specialization;
14336 if (FoundResult) *FoundResult = I.getPair();
14337 }
14338
14339 if (Matched &&
14340 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14341 return nullptr;
14342
14343 return Matched;
14344}
14345
14347 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14348 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14349 unsigned DiagIDForComplaining) {
14350 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14351
14353
14354 DeclAccessPair found;
14355 ExprResult SingleFunctionExpression;
14357 ovl.Expression, /*complain*/ false, &found)) {
14358 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14359 SrcExpr = ExprError();
14360 return true;
14361 }
14362
14363 // It is only correct to resolve to an instance method if we're
14364 // resolving a form that's permitted to be a pointer to member.
14365 // Otherwise we'll end up making a bound member expression, which
14366 // is illegal in all the contexts we resolve like this.
14367 if (!ovl.HasFormOfMemberPointer &&
14368 isa<CXXMethodDecl>(fn) &&
14369 cast<CXXMethodDecl>(fn)->isInstance()) {
14370 if (!complain) return false;
14371
14372 Diag(ovl.Expression->getExprLoc(),
14373 diag::err_bound_member_function)
14374 << 0 << ovl.Expression->getSourceRange();
14375
14376 // TODO: I believe we only end up here if there's a mix of
14377 // static and non-static candidates (otherwise the expression
14378 // would have 'bound member' type, not 'overload' type).
14379 // Ideally we would note which candidate was chosen and why
14380 // the static candidates were rejected.
14381 SrcExpr = ExprError();
14382 return true;
14383 }
14384
14385 // Fix the expression to refer to 'fn'.
14386 SingleFunctionExpression =
14387 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14388
14389 // If desired, do function-to-pointer decay.
14390 if (doFunctionPointerConversion) {
14391 SingleFunctionExpression =
14392 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14393 if (SingleFunctionExpression.isInvalid()) {
14394 SrcExpr = ExprError();
14395 return true;
14396 }
14397 }
14398 }
14399
14400 if (!SingleFunctionExpression.isUsable()) {
14401 if (complain) {
14402 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14403 << ovl.Expression->getName()
14404 << DestTypeForComplaining
14405 << OpRangeForComplaining
14407 NoteAllOverloadCandidates(SrcExpr.get());
14408
14409 SrcExpr = ExprError();
14410 return true;
14411 }
14412
14413 return false;
14414 }
14415
14416 SrcExpr = SingleFunctionExpression;
14417 return true;
14418}
14419
14420/// Add a single candidate to the overload set.
14422 DeclAccessPair FoundDecl,
14423 TemplateArgumentListInfo *ExplicitTemplateArgs,
14424 ArrayRef<Expr *> Args,
14425 OverloadCandidateSet &CandidateSet,
14426 bool PartialOverloading,
14427 bool KnownValid) {
14428 NamedDecl *Callee = FoundDecl.getDecl();
14429 if (isa<UsingShadowDecl>(Callee))
14430 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14431
14432 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14433 if (ExplicitTemplateArgs) {
14434 assert(!KnownValid && "Explicit template arguments?");
14435 return;
14436 }
14437 // Prevent ill-formed function decls to be added as overload candidates.
14438 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14439 return;
14440
14441 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14442 /*SuppressUserConversions=*/false,
14443 PartialOverloading);
14444 return;
14445 }
14446
14447 if (FunctionTemplateDecl *FuncTemplate
14448 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14449 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14450 ExplicitTemplateArgs, Args, CandidateSet,
14451 /*SuppressUserConversions=*/false,
14452 PartialOverloading);
14453 return;
14454 }
14455
14456 assert(!KnownValid && "unhandled case in overloaded call candidate");
14457}
14458
14460 ArrayRef<Expr *> Args,
14461 OverloadCandidateSet &CandidateSet,
14462 bool PartialOverloading) {
14463
14464#ifndef NDEBUG
14465 // Verify that ArgumentDependentLookup is consistent with the rules
14466 // in C++0x [basic.lookup.argdep]p3:
14467 //
14468 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14469 // and let Y be the lookup set produced by argument dependent
14470 // lookup (defined as follows). If X contains
14471 //
14472 // -- a declaration of a class member, or
14473 //
14474 // -- a block-scope function declaration that is not a
14475 // using-declaration, or
14476 //
14477 // -- a declaration that is neither a function or a function
14478 // template
14479 //
14480 // then Y is empty.
14481
14482 if (ULE->requiresADL()) {
14484 E = ULE->decls_end(); I != E; ++I) {
14485 assert(!(*I)->getDeclContext()->isRecord());
14486 assert(isa<UsingShadowDecl>(*I) ||
14487 !(*I)->getDeclContext()->isFunctionOrMethod());
14488 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14489 }
14490 }
14491#endif
14492
14493 // It would be nice to avoid this copy.
14494 TemplateArgumentListInfo TABuffer;
14495 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14496 if (ULE->hasExplicitTemplateArgs()) {
14497 ULE->copyTemplateArgumentsInto(TABuffer);
14498 ExplicitTemplateArgs = &TABuffer;
14499 }
14500
14502 E = ULE->decls_end(); I != E; ++I)
14503 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14504 CandidateSet, PartialOverloading,
14505 /*KnownValid*/ true);
14506
14507 if (ULE->requiresADL())
14509 Args, ExplicitTemplateArgs,
14510 CandidateSet, PartialOverloading);
14511}
14512
14514 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14515 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14516 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14517 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14518 CandidateSet, false, /*KnownValid*/ false);
14519}
14520
14521/// Determine whether a declaration with the specified name could be moved into
14522/// a different namespace.
14524 switch (Name.getCXXOverloadedOperator()) {
14525 case OO_New: case OO_Array_New:
14526 case OO_Delete: case OO_Array_Delete:
14527 return false;
14528
14529 default:
14530 return true;
14531 }
14532}
14533
14534/// Attempt to recover from an ill-formed use of a non-dependent name in a
14535/// template, where the non-dependent name was declared after the template
14536/// was defined. This is common in code written for a compilers which do not
14537/// correctly implement two-stage name lookup.
14538///
14539/// Returns true if a viable candidate was found and a diagnostic was issued.
14541 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14543 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14544 CXXRecordDecl **FoundInClass = nullptr) {
14545 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14546 return false;
14547
14548 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14549 if (DC->isTransparentContext())
14550 continue;
14551
14552 SemaRef.LookupQualifiedName(R, DC);
14553
14554 if (!R.empty()) {
14555 R.suppressDiagnostics();
14556
14557 OverloadCandidateSet Candidates(FnLoc, CSK);
14558 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14559 Candidates);
14560
14563 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14564
14565 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14566 // We either found non-function declarations or a best viable function
14567 // at class scope. A class-scope lookup result disables ADL. Don't
14568 // look past this, but let the caller know that we found something that
14569 // either is, or might be, usable in this class.
14570 if (FoundInClass) {
14571 *FoundInClass = RD;
14572 if (OR == OR_Success) {
14573 R.clear();
14574 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14575 R.resolveKind();
14576 }
14577 }
14578 return false;
14579 }
14580
14581 if (OR != OR_Success) {
14582 // There wasn't a unique best function or function template.
14583 return false;
14584 }
14585
14586 // Find the namespaces where ADL would have looked, and suggest
14587 // declaring the function there instead.
14588 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14589 Sema::AssociatedClassSet AssociatedClasses;
14590 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14591 AssociatedNamespaces,
14592 AssociatedClasses);
14593 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14594 if (canBeDeclaredInNamespace(R.getLookupName())) {
14595 DeclContext *Std = SemaRef.getStdNamespace();
14596 for (Sema::AssociatedNamespaceSet::iterator
14597 it = AssociatedNamespaces.begin(),
14598 end = AssociatedNamespaces.end(); it != end; ++it) {
14599 // Never suggest declaring a function within namespace 'std'.
14600 if (Std && Std->Encloses(*it))
14601 continue;
14602
14603 // Never suggest declaring a function within a namespace with a
14604 // reserved name, like __gnu_cxx.
14605 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14606 if (NS &&
14607 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14608 continue;
14609
14610 SuggestedNamespaces.insert(*it);
14611 }
14612 }
14613
14614 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14615 << R.getLookupName();
14616 if (SuggestedNamespaces.empty()) {
14617 SemaRef.Diag(Best->Function->getLocation(),
14618 diag::note_not_found_by_two_phase_lookup)
14619 << R.getLookupName() << 0;
14620 } else if (SuggestedNamespaces.size() == 1) {
14621 SemaRef.Diag(Best->Function->getLocation(),
14622 diag::note_not_found_by_two_phase_lookup)
14623 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14624 } else {
14625 // FIXME: It would be useful to list the associated namespaces here,
14626 // but the diagnostics infrastructure doesn't provide a way to produce
14627 // a localized representation of a list of items.
14628 SemaRef.Diag(Best->Function->getLocation(),
14629 diag::note_not_found_by_two_phase_lookup)
14630 << R.getLookupName() << 2;
14631 }
14632
14633 // Try to recover by calling this function.
14634 return true;
14635 }
14636
14637 R.clear();
14638 }
14639
14640 return false;
14641}
14642
14643/// Attempt to recover from ill-formed use of a non-dependent operator in a
14644/// template, where the non-dependent operator was declared after the template
14645/// was defined.
14646///
14647/// Returns true if a viable candidate was found and a diagnostic was issued.
14648static bool
14650 SourceLocation OpLoc,
14651 ArrayRef<Expr *> Args) {
14652 DeclarationName OpName =
14654 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14655 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14657 /*ExplicitTemplateArgs=*/nullptr, Args);
14658}
14659
14660namespace {
14661class BuildRecoveryCallExprRAII {
14662 Sema &SemaRef;
14663 Sema::SatisfactionStackResetRAII SatStack;
14664
14665public:
14666 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14667 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14668 SemaRef.IsBuildingRecoveryCallExpr = true;
14669 }
14670
14671 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14672};
14673}
14674
14675/// Attempts to recover from a call where no functions were found.
14676///
14677/// This function will do one of three things:
14678/// * Diagnose, recover, and return a recovery expression.
14679/// * Diagnose, fail to recover, and return ExprError().
14680/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14681/// expected to diagnose as appropriate.
14682static ExprResult
14685 SourceLocation LParenLoc,
14687 SourceLocation RParenLoc,
14688 bool EmptyLookup, bool AllowTypoCorrection) {
14689 // Do not try to recover if it is already building a recovery call.
14690 // This stops infinite loops for template instantiations like
14691 //
14692 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14693 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14694 if (SemaRef.IsBuildingRecoveryCallExpr)
14695 return ExprResult();
14696 BuildRecoveryCallExprRAII RCE(SemaRef);
14697
14698 CXXScopeSpec SS;
14699 SS.Adopt(ULE->getQualifierLoc());
14700 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14701
14702 TemplateArgumentListInfo TABuffer;
14703 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14704 if (ULE->hasExplicitTemplateArgs()) {
14705 ULE->copyTemplateArgumentsInto(TABuffer);
14706 ExplicitTemplateArgs = &TABuffer;
14707 }
14708
14709 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14711 CXXRecordDecl *FoundInClass = nullptr;
14712 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14714 ExplicitTemplateArgs, Args, &FoundInClass)) {
14715 // OK, diagnosed a two-phase lookup issue.
14716 } else if (EmptyLookup) {
14717 // Try to recover from an empty lookup with typo correction.
14718 R.clear();
14719 NoTypoCorrectionCCC NoTypoValidator{};
14720 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14721 ExplicitTemplateArgs != nullptr,
14722 dyn_cast<MemberExpr>(Fn));
14723 CorrectionCandidateCallback &Validator =
14724 AllowTypoCorrection
14725 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14726 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14727 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14728 Args))
14729 return ExprError();
14730 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14731 // We found a usable declaration of the name in a dependent base of some
14732 // enclosing class.
14733 // FIXME: We should also explain why the candidates found by name lookup
14734 // were not viable.
14735 if (SemaRef.DiagnoseDependentMemberLookup(R))
14736 return ExprError();
14737 } else {
14738 // We had viable candidates and couldn't recover; let the caller diagnose
14739 // this.
14740 return ExprResult();
14741 }
14742
14743 // If we get here, we should have issued a diagnostic and formed a recovery
14744 // lookup result.
14745 assert(!R.empty() && "lookup results empty despite recovery");
14746
14747 // If recovery created an ambiguity, just bail out.
14748 if (R.isAmbiguous()) {
14749 R.suppressDiagnostics();
14750 return ExprError();
14751 }
14752
14753 // Build an implicit member call if appropriate. Just drop the
14754 // casts and such from the call, we don't really care.
14755 ExprResult NewFn = ExprError();
14756 if ((*R.begin())->isCXXClassMember())
14757 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14758 ExplicitTemplateArgs, S);
14759 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14760 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14761 ExplicitTemplateArgs);
14762 else
14763 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14764
14765 if (NewFn.isInvalid())
14766 return ExprError();
14767
14768 // This shouldn't cause an infinite loop because we're giving it
14769 // an expression with viable lookup results, which should never
14770 // end up here.
14771 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14772 MultiExprArg(Args.data(), Args.size()),
14773 RParenLoc);
14774}
14775
14778 MultiExprArg Args,
14779 SourceLocation RParenLoc,
14780 OverloadCandidateSet *CandidateSet,
14781 ExprResult *Result) {
14782#ifndef NDEBUG
14783 if (ULE->requiresADL()) {
14784 // To do ADL, we must have found an unqualified name.
14785 assert(!ULE->getQualifier() && "qualified name with ADL");
14786
14787 // We don't perform ADL for implicit declarations of builtins.
14788 // Verify that this was correctly set up.
14789 FunctionDecl *F;
14790 if (ULE->decls_begin() != ULE->decls_end() &&
14791 ULE->decls_begin() + 1 == ULE->decls_end() &&
14792 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14793 F->getBuiltinID() && F->isImplicit())
14794 llvm_unreachable("performing ADL for builtin");
14795
14796 // We don't perform ADL in C.
14797 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14798 }
14799#endif
14800
14801 UnbridgedCastsSet UnbridgedCasts;
14802 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14803 *Result = ExprError();
14804 return true;
14805 }
14806
14807 // Add the functions denoted by the callee to the set of candidate
14808 // functions, including those from argument-dependent lookup.
14809 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14810
14811 if (getLangOpts().MSVCCompat &&
14812 CurContext->isDependentContext() && !isSFINAEContext() &&
14814
14816 if (CandidateSet->empty() ||
14817 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14819 // In Microsoft mode, if we are inside a template class member function
14820 // then create a type dependent CallExpr. The goal is to postpone name
14821 // lookup to instantiation time to be able to search into type dependent
14822 // base classes.
14823 CallExpr *CE =
14824 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14825 RParenLoc, CurFPFeatureOverrides());
14827 *Result = CE;
14828 return true;
14829 }
14830 }
14831
14832 if (CandidateSet->empty())
14833 return false;
14834
14835 UnbridgedCasts.restore();
14836 return false;
14837}
14838
14839// Guess at what the return type for an unresolvable overload should be.
14842 std::optional<QualType> Result;
14843 // Adjust Type after seeing a candidate.
14844 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14845 if (!Candidate.Function)
14846 return;
14847 if (Candidate.Function->isInvalidDecl())
14848 return;
14849 QualType T = Candidate.Function->getReturnType();
14850 if (T.isNull())
14851 return;
14852 if (!Result)
14853 Result = T;
14854 else if (Result != T)
14855 Result = QualType();
14856 };
14857
14858 // Look for an unambiguous type from a progressively larger subset.
14859 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14860 //
14861 // First, consider only the best candidate.
14862 if (Best && *Best != CS.end())
14863 ConsiderCandidate(**Best);
14864 // Next, consider only viable candidates.
14865 if (!Result)
14866 for (const auto &C : CS)
14867 if (C.Viable)
14868 ConsiderCandidate(C);
14869 // Finally, consider all candidates.
14870 if (!Result)
14871 for (const auto &C : CS)
14872 ConsiderCandidate(C);
14873
14874 if (!Result)
14875 return QualType();
14876 auto Value = *Result;
14877 if (Value.isNull() || Value->isUndeducedType())
14878 return QualType();
14879 return Value;
14880}
14881
14882/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14883/// the completed call expression. If overload resolution fails, emits
14884/// diagnostics and returns ExprError()
14887 SourceLocation LParenLoc,
14888 MultiExprArg Args,
14889 SourceLocation RParenLoc,
14890 Expr *ExecConfig,
14891 OverloadCandidateSet *CandidateSet,
14893 OverloadingResult OverloadResult,
14894 bool AllowTypoCorrection) {
14895 switch (OverloadResult) {
14896 case OR_Success: {
14897 FunctionDecl *FDecl = (*Best)->Function;
14898 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14899 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14900 return ExprError();
14901 ExprResult Res =
14902 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14903 if (Res.isInvalid())
14904 return ExprError();
14905 return SemaRef.BuildResolvedCallExpr(
14906 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14907 /*IsExecConfig=*/false,
14908 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14909 }
14910
14911 case OR_No_Viable_Function: {
14912 if (*Best != CandidateSet->end() &&
14913 CandidateSet->getKind() ==
14915 if (CXXMethodDecl *M =
14916 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14918 CandidateSet->NoteCandidates(
14920 Fn->getBeginLoc(),
14921 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14922 SemaRef, OCD_AmbiguousCandidates, Args);
14923 return ExprError();
14924 }
14925 }
14926
14927 // Try to recover by looking for viable functions which the user might
14928 // have meant to call.
14929 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14930 Args, RParenLoc,
14931 CandidateSet->empty(),
14932 AllowTypoCorrection);
14933 if (Recovery.isInvalid() || Recovery.isUsable())
14934 return Recovery;
14935
14936 // If the user passes in a function that we can't take the address of, we
14937 // generally end up emitting really bad error messages. Here, we attempt to
14938 // emit better ones.
14939 for (const Expr *Arg : Args) {
14940 if (!Arg->getType()->isFunctionType())
14941 continue;
14942 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14943 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14944 if (FD &&
14945 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14946 Arg->getExprLoc()))
14947 return ExprError();
14948 }
14949 }
14950
14951 CandidateSet->NoteCandidates(
14953 Fn->getBeginLoc(),
14954 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14955 << ULE->getName() << Fn->getSourceRange()),
14956 SemaRef, OCD_AllCandidates, Args);
14957 break;
14958 }
14959
14960 case OR_Ambiguous:
14961 CandidateSet->NoteCandidates(
14962 PartialDiagnosticAt(Fn->getBeginLoc(),
14963 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14964 << ULE->getName() << Fn->getSourceRange()),
14965 SemaRef, OCD_AmbiguousCandidates, Args);
14966 break;
14967
14968 case OR_Deleted: {
14969 FunctionDecl *FDecl = (*Best)->Function;
14970 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14971 Fn->getSourceRange(), ULE->getName(),
14972 *CandidateSet, FDecl, Args);
14973
14974 // We emitted an error for the unavailable/deleted function call but keep
14975 // the call in the AST.
14976 ExprResult Res =
14977 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14978 if (Res.isInvalid())
14979 return ExprError();
14980 return SemaRef.BuildResolvedCallExpr(
14981 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14982 /*IsExecConfig=*/false,
14983 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14984 }
14985 }
14986
14987 // Overload resolution failed, try to recover.
14988 SmallVector<Expr *, 8> SubExprs = {Fn};
14989 SubExprs.append(Args.begin(), Args.end());
14990 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14991 chooseRecoveryType(*CandidateSet, Best));
14992}
14993
14996 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14997 if (I->Viable &&
14998 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14999 I->Viable = false;
15000 I->FailureKind = ovl_fail_addr_not_available;
15001 }
15002 }
15003}
15004
15007 SourceLocation LParenLoc,
15008 MultiExprArg Args,
15009 SourceLocation RParenLoc,
15010 Expr *ExecConfig,
15011 bool AllowTypoCorrection,
15012 bool CalleesAddressIsTaken) {
15013
15017
15018 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15019 ExprResult result;
15020
15021 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15022 &result))
15023 return result;
15024
15025 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15026 // functions that aren't addressible are considered unviable.
15027 if (CalleesAddressIsTaken)
15028 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15029
15031 OverloadingResult OverloadResult =
15032 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15033
15034 // [C++23][over.call.func]
15035 // if overload resolution selects a non-static member function,
15036 // the call is ill-formed;
15038 Best != CandidateSet.end()) {
15039 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15040 M && M->isImplicitObjectMemberFunction()) {
15041 OverloadResult = OR_No_Viable_Function;
15042 }
15043 }
15044
15045 // Model the case with a call to a templated function whose definition
15046 // encloses the call and whose return type contains a placeholder type as if
15047 // the UnresolvedLookupExpr was type-dependent.
15048 if (OverloadResult == OR_Success) {
15049 const FunctionDecl *FDecl = Best->Function;
15050 if (LangOpts.CUDA)
15051 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15052 if (FDecl && FDecl->isTemplateInstantiation() &&
15053 FDecl->getReturnType()->isUndeducedType()) {
15054
15055 // Creating dependent CallExpr is not okay if the enclosing context itself
15056 // is not dependent. This situation notably arises if a non-dependent
15057 // member function calls the later-defined overloaded static function.
15058 //
15059 // For example, in
15060 // class A {
15061 // void c() { callee(1); }
15062 // static auto callee(auto x) { }
15063 // };
15064 //
15065 // Here callee(1) is unresolved at the call site, but is not inside a
15066 // dependent context. There will be no further attempt to resolve this
15067 // call if it is made dependent.
15068
15069 if (const auto *TP =
15070 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15071 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15072 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15073 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15074 }
15075 }
15076 }
15077
15078 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15079 ExecConfig, &CandidateSet, &Best,
15080 OverloadResult, AllowTypoCorrection);
15081}
15082
15086 const UnresolvedSetImpl &Fns,
15087 bool PerformADL) {
15089 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15090 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15091}
15092
15095 bool HadMultipleCandidates) {
15096 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15097 // the FoundDecl as it impedes TransformMemberExpr.
15098 // We go a bit further here: if there's no difference in UnderlyingDecl,
15099 // then using FoundDecl vs Method shouldn't make a difference either.
15100 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15101 FoundDecl = Method;
15102 // Convert the expression to match the conversion function's implicit object
15103 // parameter.
15104 ExprResult Exp;
15105 if (Method->isExplicitObjectMemberFunction())
15107 else
15109 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15110 if (Exp.isInvalid())
15111 return true;
15112
15113 if (Method->getParent()->isLambda() &&
15114 Method->getConversionType()->isBlockPointerType()) {
15115 // This is a lambda conversion to block pointer; check if the argument
15116 // was a LambdaExpr.
15117 Expr *SubE = E;
15118 auto *CE = dyn_cast<CastExpr>(SubE);
15119 if (CE && CE->getCastKind() == CK_NoOp)
15120 SubE = CE->getSubExpr();
15121 SubE = SubE->IgnoreParens();
15122 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15123 SubE = BE->getSubExpr();
15124 if (isa<LambdaExpr>(SubE)) {
15125 // For the conversion to block pointer on a lambda expression, we
15126 // construct a special BlockLiteral instead; this doesn't really make
15127 // a difference in ARC, but outside of ARC the resulting block literal
15128 // follows the normal lifetime rules for block literals instead of being
15129 // autoreleased.
15133 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15135
15136 // FIXME: This note should be produced by a CodeSynthesisContext.
15137 if (BlockExp.isInvalid())
15138 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15139 return BlockExp;
15140 }
15141 }
15142 CallExpr *CE;
15143 QualType ResultType = Method->getReturnType();
15145 ResultType = ResultType.getNonLValueExprType(Context);
15146 if (Method->isExplicitObjectMemberFunction()) {
15147 ExprResult FnExpr =
15148 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15149 HadMultipleCandidates, E->getBeginLoc());
15150 if (FnExpr.isInvalid())
15151 return ExprError();
15152 Expr *ObjectParam = Exp.get();
15153 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15154 ResultType, VK, Exp.get()->getEndLoc(),
15156 CE->setUsesMemberSyntax(true);
15157 } else {
15158 MemberExpr *ME =
15159 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15161 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15162 HadMultipleCandidates, DeclarationNameInfo(),
15163 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15164
15165 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15166 Exp.get()->getEndLoc(),
15168 }
15169
15170 if (CheckFunctionCall(Method, CE,
15171 Method->getType()->castAs<FunctionProtoType>()))
15172 return ExprError();
15173
15175}
15176
15179 const UnresolvedSetImpl &Fns,
15180 Expr *Input, bool PerformADL) {
15182 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15183 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15184 // TODO: provide better source location info.
15185 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15186
15187 if (checkPlaceholderForOverload(*this, Input))
15188 return ExprError();
15189
15190 Expr *Args[2] = { Input, nullptr };
15191 unsigned NumArgs = 1;
15192
15193 // For post-increment and post-decrement, add the implicit '0' as
15194 // the second argument, so that we know this is a post-increment or
15195 // post-decrement.
15196 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15197 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15198 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15199 SourceLocation());
15200 NumArgs = 2;
15201 }
15202
15203 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15204
15205 if (Input->isTypeDependent()) {
15207 // [C++26][expr.unary.op][expr.pre.incr]
15208 // The * operator yields an lvalue of type
15209 // The pre/post increment operators yied an lvalue.
15210 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15211 VK = VK_LValue;
15212
15213 if (Fns.empty())
15214 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15215 OK_Ordinary, OpLoc, false,
15217
15218 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15220 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15221 if (Fn.isInvalid())
15222 return ExprError();
15223 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15224 Context.DependentTy, VK_PRValue, OpLoc,
15226 }
15227
15228 // Build an empty overload set.
15230
15231 // Add the candidates from the given function set.
15232 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15233
15234 // Add operator candidates that are member functions.
15235 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15236
15237 // Add candidates from ADL.
15238 if (PerformADL) {
15239 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15240 /*ExplicitTemplateArgs*/nullptr,
15241 CandidateSet);
15242 }
15243
15244 // Add builtin operator candidates.
15245 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15246
15247 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15248
15249 // Perform overload resolution.
15251 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15252 case OR_Success: {
15253 // We found a built-in operator or an overloaded operator.
15254 FunctionDecl *FnDecl = Best->Function;
15255
15256 if (FnDecl) {
15257 Expr *Base = nullptr;
15258 // We matched an overloaded operator. Build a call to that
15259 // operator.
15260
15261 // Convert the arguments.
15262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15263 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15264
15265 ExprResult InputInit;
15266 if (Method->isExplicitObjectMemberFunction())
15267 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15268 else
15270 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15271 if (InputInit.isInvalid())
15272 return ExprError();
15273 Base = Input = InputInit.get();
15274 } else {
15275 // Convert the arguments.
15276 ExprResult InputInit
15278 Context,
15279 FnDecl->getParamDecl(0)),
15281 Input);
15282 if (InputInit.isInvalid())
15283 return ExprError();
15284 Input = InputInit.get();
15285 }
15286
15287 // Build the actual expression node.
15288 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15289 Base, HadMultipleCandidates,
15290 OpLoc);
15291 if (FnExpr.isInvalid())
15292 return ExprError();
15293
15294 // Determine the result type.
15295 QualType ResultTy = FnDecl->getReturnType();
15297 ResultTy = ResultTy.getNonLValueExprType(Context);
15298
15299 Args[0] = Input;
15301 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15303 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15304
15305 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15306 return ExprError();
15307
15308 if (CheckFunctionCall(FnDecl, TheCall,
15309 FnDecl->getType()->castAs<FunctionProtoType>()))
15310 return ExprError();
15311 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15312 } else {
15313 // We matched a built-in operator. Convert the arguments, then
15314 // break out so that we will build the appropriate built-in
15315 // operator node.
15317 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15320 if (InputRes.isInvalid())
15321 return ExprError();
15322 Input = InputRes.get();
15323 break;
15324 }
15325 }
15326
15328 // This is an erroneous use of an operator which can be overloaded by
15329 // a non-member function. Check for non-member operators which were
15330 // defined too late to be candidates.
15331 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15332 // FIXME: Recover by calling the found function.
15333 return ExprError();
15334
15335 // No viable function; fall through to handling this as a
15336 // built-in operator, which will produce an error message for us.
15337 break;
15338
15339 case OR_Ambiguous:
15340 CandidateSet.NoteCandidates(
15341 PartialDiagnosticAt(OpLoc,
15342 PDiag(diag::err_ovl_ambiguous_oper_unary)
15344 << Input->getType() << Input->getSourceRange()),
15345 *this, OCD_AmbiguousCandidates, ArgsArray,
15346 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15347 return ExprError();
15348
15349 case OR_Deleted: {
15350 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15351 // object whose method was called. Later in NoteCandidates size of ArgsArray
15352 // is passed further and it eventually ends up compared to number of
15353 // function candidate parameters which never includes the object parameter,
15354 // so slice ArgsArray to make sure apples are compared to apples.
15355 StringLiteral *Msg = Best->Function->getDeletedMessage();
15356 CandidateSet.NoteCandidates(
15357 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15359 << (Msg != nullptr)
15360 << (Msg ? Msg->getString() : StringRef())
15361 << Input->getSourceRange()),
15362 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15363 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15364 return ExprError();
15365 }
15366 }
15367
15368 // Either we found no viable overloaded operator or we matched a
15369 // built-in operator. In either case, fall through to trying to
15370 // build a built-in operation.
15371 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15372}
15373
15376 const UnresolvedSetImpl &Fns,
15377 ArrayRef<Expr *> Args, bool PerformADL) {
15378 SourceLocation OpLoc = CandidateSet.getLocation();
15379
15380 OverloadedOperatorKind ExtraOp =
15383 : OO_None;
15384
15385 // Add the candidates from the given function set. This also adds the
15386 // rewritten candidates using these functions if necessary.
15387 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15388
15389 // As template candidates are not deduced immediately,
15390 // persist the array in the overload set.
15391 ArrayRef<Expr *> ReversedArgs;
15392 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15393 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15394 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15395
15396 // Add operator candidates that are member functions.
15397 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15398 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15399 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15401
15402 // In C++20, also add any rewritten member candidates.
15403 if (ExtraOp) {
15404 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15405 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15406 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15408 }
15409
15410 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15411 // performed for an assignment operator (nor for operator[] nor operator->,
15412 // which don't get here).
15413 if (Op != OO_Equal && PerformADL) {
15414 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15415 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15416 /*ExplicitTemplateArgs*/ nullptr,
15417 CandidateSet);
15418 if (ExtraOp) {
15419 DeclarationName ExtraOpName =
15420 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15421 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15422 /*ExplicitTemplateArgs*/ nullptr,
15423 CandidateSet);
15424 }
15425 }
15426
15427 // Add builtin operator candidates.
15428 //
15429 // FIXME: We don't add any rewritten candidates here. This is strictly
15430 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15431 // resulting in our selecting a rewritten builtin candidate. For example:
15432 //
15433 // enum class E { e };
15434 // bool operator!=(E, E) requires false;
15435 // bool k = E::e != E::e;
15436 //
15437 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15438 // it seems unreasonable to consider rewritten builtin candidates. A core
15439 // issue has been filed proposing to removed this requirement.
15440 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15441}
15442
15445 const UnresolvedSetImpl &Fns, Expr *LHS,
15446 Expr *RHS, bool PerformADL,
15447 bool AllowRewrittenCandidates,
15448 FunctionDecl *DefaultedFn) {
15449 Expr *Args[2] = { LHS, RHS };
15450 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15451
15452 if (!getLangOpts().CPlusPlus20)
15453 AllowRewrittenCandidates = false;
15454
15456
15457 // If either side is type-dependent, create an appropriate dependent
15458 // expression.
15459 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15460 if (Fns.empty()) {
15461 // If there are no functions to store, just build a dependent
15462 // BinaryOperator or CompoundAssignment.
15465 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15466 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15467 Context.DependentTy);
15469 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15471 }
15472
15473 // FIXME: save results of ADL from here?
15474 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15475 // TODO: provide better source location info in DNLoc component.
15476 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15477 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15479 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15480 if (Fn.isInvalid())
15481 return ExprError();
15482 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15483 Context.DependentTy, VK_PRValue, OpLoc,
15485 }
15486
15487 // If this is the .* operator, which is not overloadable, just
15488 // create a built-in binary operator.
15489 if (Opc == BO_PtrMemD) {
15490 auto CheckPlaceholder = [&](Expr *&Arg) {
15492 if (Res.isUsable())
15493 Arg = Res.get();
15494 return !Res.isUsable();
15495 };
15496
15497 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15498 // expression that contains placeholders (in either the LHS or RHS).
15499 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15500 return ExprError();
15501 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15502 }
15503
15504 // Always do placeholder-like conversions on the RHS.
15505 if (checkPlaceholderForOverload(*this, Args[1]))
15506 return ExprError();
15507
15508 // Do placeholder-like conversion on the LHS; note that we should
15509 // not get here with a PseudoObject LHS.
15510 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15511 if (checkPlaceholderForOverload(*this, Args[0]))
15512 return ExprError();
15513
15514 // If this is the assignment operator, we only perform overload resolution
15515 // if the left-hand side is a class or enumeration type. This is actually
15516 // a hack. The standard requires that we do overload resolution between the
15517 // various built-in candidates, but as DR507 points out, this can lead to
15518 // problems. So we do it this way, which pretty much follows what GCC does.
15519 // Note that we go the traditional code path for compound assignment forms.
15520 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15521 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15522
15523 // Build the overload set.
15526 Op, OpLoc, AllowRewrittenCandidates));
15527 if (DefaultedFn)
15528 CandidateSet.exclude(DefaultedFn);
15529 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15530
15531 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15532
15533 // Perform overload resolution.
15535 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15536 case OR_Success: {
15537 // We found a built-in operator or an overloaded operator.
15538 FunctionDecl *FnDecl = Best->Function;
15539
15540 bool IsReversed = Best->isReversed();
15541 if (IsReversed)
15542 std::swap(Args[0], Args[1]);
15543
15544 if (FnDecl) {
15545
15546 if (FnDecl->isInvalidDecl())
15547 return ExprError();
15548
15549 Expr *Base = nullptr;
15550 // We matched an overloaded operator. Build a call to that
15551 // operator.
15552
15553 OverloadedOperatorKind ChosenOp =
15555
15556 // C++2a [over.match.oper]p9:
15557 // If a rewritten operator== candidate is selected by overload
15558 // resolution for an operator@, its return type shall be cv bool
15559 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15560 !FnDecl->getReturnType()->isBooleanType()) {
15561 bool IsExtension =
15563 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15564 : diag::err_ovl_rewrite_equalequal_not_bool)
15565 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15566 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15567 Diag(FnDecl->getLocation(), diag::note_declared_at);
15568 if (!IsExtension)
15569 return ExprError();
15570 }
15571
15572 if (AllowRewrittenCandidates && !IsReversed &&
15573 CandidateSet.getRewriteInfo().isReversible()) {
15574 // We could have reversed this operator, but didn't. Check if some
15575 // reversed form was a viable candidate, and if so, if it had a
15576 // better conversion for either parameter. If so, this call is
15577 // formally ambiguous, and allowing it is an extension.
15579 for (OverloadCandidate &Cand : CandidateSet) {
15580 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15581 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15582 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15584 *this, OpLoc, Cand.Conversions[ArgIdx],
15585 Best->Conversions[ArgIdx]) ==
15587 AmbiguousWith.push_back(Cand.Function);
15588 break;
15589 }
15590 }
15591 }
15592 }
15593
15594 if (!AmbiguousWith.empty()) {
15595 bool AmbiguousWithSelf =
15596 AmbiguousWith.size() == 1 &&
15597 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15598 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15600 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15601 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15602 if (AmbiguousWithSelf) {
15603 Diag(FnDecl->getLocation(),
15604 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15605 // Mark member== const or provide matching != to disallow reversed
15606 // args. Eg.
15607 // struct S { bool operator==(const S&); };
15608 // S()==S();
15609 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15610 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15611 !MD->isConst() &&
15612 !MD->hasCXXExplicitFunctionObjectParameter() &&
15613 Context.hasSameUnqualifiedType(
15614 MD->getFunctionObjectParameterType(),
15615 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15616 Context.hasSameUnqualifiedType(
15617 MD->getFunctionObjectParameterType(),
15618 Args[0]->getType()) &&
15619 Context.hasSameUnqualifiedType(
15620 MD->getFunctionObjectParameterType(),
15621 Args[1]->getType()))
15622 Diag(FnDecl->getLocation(),
15623 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15624 } else {
15625 Diag(FnDecl->getLocation(),
15626 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15627 for (auto *F : AmbiguousWith)
15628 Diag(F->getLocation(),
15629 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15630 }
15631 }
15632 }
15633
15634 // Check for nonnull = nullable.
15635 // This won't be caught in the arg's initialization: the parameter to
15636 // the assignment operator is not marked nonnull.
15637 if (Op == OO_Equal)
15639 Args[1]->getType(), OpLoc);
15640
15641 // Convert the arguments.
15642 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15643 // Best->Access is only meaningful for class members.
15644 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15645
15646 ExprResult Arg0, Arg1;
15647 unsigned ParamIdx = 0;
15648 if (Method->isExplicitObjectMemberFunction()) {
15649 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15650 ParamIdx = 1;
15651 } else {
15653 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15654 }
15657 Context, FnDecl->getParamDecl(ParamIdx)),
15658 SourceLocation(), Args[1]);
15659 if (Arg0.isInvalid() || Arg1.isInvalid())
15660 return ExprError();
15661
15662 Base = Args[0] = Arg0.getAs<Expr>();
15663 Args[1] = RHS = Arg1.getAs<Expr>();
15664 } else {
15665 // Convert the arguments.
15668 FnDecl->getParamDecl(0)),
15669 SourceLocation(), Args[0]);
15670 if (Arg0.isInvalid())
15671 return ExprError();
15672
15673 ExprResult Arg1 =
15676 FnDecl->getParamDecl(1)),
15677 SourceLocation(), Args[1]);
15678 if (Arg1.isInvalid())
15679 return ExprError();
15680 Args[0] = LHS = Arg0.getAs<Expr>();
15681 Args[1] = RHS = Arg1.getAs<Expr>();
15682 }
15683
15684 // Build the actual expression node.
15685 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15686 Best->FoundDecl, Base,
15687 HadMultipleCandidates, OpLoc);
15688 if (FnExpr.isInvalid())
15689 return ExprError();
15690
15691 // Determine the result type.
15692 QualType ResultTy = FnDecl->getReturnType();
15694 ResultTy = ResultTy.getNonLValueExprType(Context);
15695
15696 CallExpr *TheCall;
15697 ArrayRef<const Expr *> ArgsArray(Args, 2);
15698 const Expr *ImplicitThis = nullptr;
15699
15700 // We always create a CXXOperatorCallExpr, even for explicit object
15701 // members; CodeGen should take care not to emit the this pointer.
15703 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15705 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15706 IsReversed);
15707
15708 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15709 Method && Method->isImplicitObjectMemberFunction()) {
15710 // Cut off the implicit 'this'.
15711 ImplicitThis = ArgsArray[0];
15712 ArgsArray = ArgsArray.slice(1);
15713 }
15714
15715 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15716 FnDecl))
15717 return ExprError();
15718
15719 if (Op == OO_Equal) {
15720 // Check for a self move.
15721 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15722 // lifetime check.
15724 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15725 Args[1]);
15726 }
15727 if (ImplicitThis) {
15728 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15729 QualType ThisTypeFromDecl = Context.getPointerType(
15730 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15731
15732 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15733 ThisTypeFromDecl);
15734 }
15735
15736 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15737 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15739
15740 ExprResult R = MaybeBindToTemporary(TheCall);
15741 if (R.isInvalid())
15742 return ExprError();
15743
15744 R = CheckForImmediateInvocation(R, FnDecl);
15745 if (R.isInvalid())
15746 return ExprError();
15747
15748 // For a rewritten candidate, we've already reversed the arguments
15749 // if needed. Perform the rest of the rewrite now.
15750 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15751 (Op == OO_Spaceship && IsReversed)) {
15752 if (Op == OO_ExclaimEqual) {
15753 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15754 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15755 } else {
15756 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15757 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15758 Expr *ZeroLiteral =
15760
15763 Ctx.Entity = FnDecl;
15765
15767 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15768 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15769 /*AllowRewrittenCandidates=*/false);
15770
15772 }
15773 if (R.isInvalid())
15774 return ExprError();
15775 } else {
15776 assert(ChosenOp == Op && "unexpected operator name");
15777 }
15778
15779 // Make a note in the AST if we did any rewriting.
15780 if (Best->RewriteKind != CRK_None)
15781 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15782
15783 return R;
15784 } else {
15785 // We matched a built-in operator. Convert the arguments, then
15786 // break out so that we will build the appropriate built-in
15787 // operator node.
15789 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15792 if (ArgsRes0.isInvalid())
15793 return ExprError();
15794 Args[0] = ArgsRes0.get();
15795
15797 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15800 if (ArgsRes1.isInvalid())
15801 return ExprError();
15802 Args[1] = ArgsRes1.get();
15803 break;
15804 }
15805 }
15806
15807 case OR_No_Viable_Function: {
15808 // C++ [over.match.oper]p9:
15809 // If the operator is the operator , [...] and there are no
15810 // viable functions, then the operator is assumed to be the
15811 // built-in operator and interpreted according to clause 5.
15812 if (Opc == BO_Comma)
15813 break;
15814
15815 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15816 // compare result using '==' and '<'.
15817 if (DefaultedFn && Opc == BO_Cmp) {
15818 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15819 Args[1], DefaultedFn);
15820 if (E.isInvalid() || E.isUsable())
15821 return E;
15822 }
15823
15824 // For class as left operand for assignment or compound assignment
15825 // operator do not fall through to handling in built-in, but report that
15826 // no overloaded assignment operator found
15828 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15829 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15830 Args, OpLoc);
15831 DeferDiagsRAII DDR(*this,
15832 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15833 if (Args[0]->getType()->isRecordType() &&
15834 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15835 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15837 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15838 if (Args[0]->getType()->isIncompleteType()) {
15839 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15840 << Args[0]->getType()
15841 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15842 }
15843 } else {
15844 // This is an erroneous use of an operator which can be overloaded by
15845 // a non-member function. Check for non-member operators which were
15846 // defined too late to be candidates.
15847 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15848 // FIXME: Recover by calling the found function.
15849 return ExprError();
15850
15851 // No viable function; try to create a built-in operation, which will
15852 // produce an error. Then, show the non-viable candidates.
15853 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15854 }
15855 assert(Result.isInvalid() &&
15856 "C++ binary operator overloading is missing candidates!");
15857 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15858 return Result;
15859 }
15860
15861 case OR_Ambiguous:
15862 CandidateSet.NoteCandidates(
15863 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15865 << Args[0]->getType()
15866 << Args[1]->getType()
15867 << Args[0]->getSourceRange()
15868 << Args[1]->getSourceRange()),
15870 OpLoc);
15871 return ExprError();
15872
15873 case OR_Deleted: {
15874 if (isImplicitlyDeleted(Best->Function)) {
15875 FunctionDecl *DeletedFD = Best->Function;
15877 if (DFK.isSpecialMember()) {
15878 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15879 << Args[0]->getType() << DFK.asSpecialMember();
15880 } else {
15881 assert(DFK.isComparison());
15882 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15883 << Args[0]->getType() << DeletedFD;
15884 }
15885
15886 // The user probably meant to call this special member. Just
15887 // explain why it's deleted.
15888 NoteDeletedFunction(DeletedFD);
15889 return ExprError();
15890 }
15891
15892 StringLiteral *Msg = Best->Function->getDeletedMessage();
15893 CandidateSet.NoteCandidates(
15895 OpLoc,
15896 PDiag(diag::err_ovl_deleted_oper)
15897 << getOperatorSpelling(Best->Function->getDeclName()
15898 .getCXXOverloadedOperator())
15899 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15900 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15902 OpLoc);
15903 return ExprError();
15904 }
15905 }
15906
15907 // We matched a built-in operator; build it.
15908 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15909}
15910
15912 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15913 FunctionDecl *DefaultedFn) {
15914 const ComparisonCategoryInfo *Info =
15915 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15916 // If we're not producing a known comparison category type, we can't
15917 // synthesize a three-way comparison. Let the caller diagnose this.
15918 if (!Info)
15919 return ExprResult((Expr*)nullptr);
15920
15921 // If we ever want to perform this synthesis more generally, we will need to
15922 // apply the temporary materialization conversion to the operands.
15923 assert(LHS->isGLValue() && RHS->isGLValue() &&
15924 "cannot use prvalue expressions more than once");
15925 Expr *OrigLHS = LHS;
15926 Expr *OrigRHS = RHS;
15927
15928 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15929 // each of them multiple times below.
15930 LHS = new (Context)
15931 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15932 LHS->getObjectKind(), LHS);
15933 RHS = new (Context)
15934 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15935 RHS->getObjectKind(), RHS);
15936
15937 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15938 DefaultedFn);
15939 if (Eq.isInvalid())
15940 return ExprError();
15941
15942 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15943 true, DefaultedFn);
15944 if (Less.isInvalid())
15945 return ExprError();
15946
15948 if (Info->isPartial()) {
15949 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15950 DefaultedFn);
15951 if (Greater.isInvalid())
15952 return ExprError();
15953 }
15954
15955 // Form the list of comparisons we're going to perform.
15956 struct Comparison {
15959 } Comparisons[4] =
15965 };
15966
15967 int I = Info->isPartial() ? 3 : 2;
15968
15969 // Combine the comparisons with suitable conditional expressions.
15971 for (; I >= 0; --I) {
15972 // Build a reference to the comparison category constant.
15973 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15974 // FIXME: Missing a constant for a comparison category. Diagnose this?
15975 if (!VI)
15976 return ExprResult((Expr*)nullptr);
15977 ExprResult ThisResult =
15979 if (ThisResult.isInvalid())
15980 return ExprError();
15981
15982 // Build a conditional unless this is the final case.
15983 if (Result.get()) {
15984 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15985 ThisResult.get(), Result.get());
15986 if (Result.isInvalid())
15987 return ExprError();
15988 } else {
15989 Result = ThisResult;
15990 }
15991 }
15992
15993 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15994 // bind the OpaqueValueExprs before they're (repeatedly) used.
15995 Expr *SyntacticForm = BinaryOperator::Create(
15996 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15997 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15999 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16000 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16001}
16002
16004 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16005 MultiExprArg Args, SourceLocation LParenLoc) {
16006
16007 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16008 unsigned NumParams = Proto->getNumParams();
16009 unsigned NumArgsSlots =
16010 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16011 // Build the full argument list for the method call (the implicit object
16012 // parameter is placed at the beginning of the list).
16013 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16014 bool IsError = false;
16015 // Initialize the implicit object parameter.
16016 // Check the argument types.
16017 for (unsigned i = 0; i != NumParams; i++) {
16018 Expr *Arg;
16019 if (i < Args.size()) {
16020 Arg = Args[i];
16021 ExprResult InputInit =
16023 S.Context, Method->getParamDecl(i)),
16024 SourceLocation(), Arg);
16025 IsError |= InputInit.isInvalid();
16026 Arg = InputInit.getAs<Expr>();
16027 } else {
16028 ExprResult DefArg =
16029 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16030 if (DefArg.isInvalid()) {
16031 IsError = true;
16032 break;
16033 }
16034 Arg = DefArg.getAs<Expr>();
16035 }
16036
16037 MethodArgs.push_back(Arg);
16038 }
16039 return IsError;
16040}
16041
16043 SourceLocation RLoc,
16044 Expr *Base,
16045 MultiExprArg ArgExpr) {
16047 Args.push_back(Base);
16048 for (auto *e : ArgExpr) {
16049 Args.push_back(e);
16050 }
16051 DeclarationName OpName =
16052 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16053
16054 SourceRange Range = ArgExpr.empty()
16055 ? SourceRange{}
16056 : SourceRange(ArgExpr.front()->getBeginLoc(),
16057 ArgExpr.back()->getEndLoc());
16058
16059 // If either side is type-dependent, create an appropriate dependent
16060 // expression.
16062
16063 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16064 // CHECKME: no 'operator' keyword?
16065 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16066 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16068 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16069 if (Fn.isInvalid())
16070 return ExprError();
16071 // Can't add any actual overloads yet
16072
16073 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16074 Context.DependentTy, VK_PRValue, RLoc,
16076 }
16077
16078 // Handle placeholders
16079 UnbridgedCastsSet UnbridgedCasts;
16080 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16081 return ExprError();
16082 }
16083 // Build an empty overload set.
16085
16086 // Subscript can only be overloaded as a member function.
16087
16088 // Add operator candidates that are member functions.
16089 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16090
16091 // Add builtin operator candidates.
16092 if (Args.size() == 2)
16093 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16094
16095 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16096
16097 // Perform overload resolution.
16099 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16100 case OR_Success: {
16101 // We found a built-in operator or an overloaded operator.
16102 FunctionDecl *FnDecl = Best->Function;
16103
16104 if (FnDecl) {
16105 // We matched an overloaded operator. Build a call to that
16106 // operator.
16107
16108 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16109
16110 // Convert the arguments.
16112 SmallVector<Expr *, 2> MethodArgs;
16113
16114 // Initialize the object parameter.
16115 if (Method->isExplicitObjectMemberFunction()) {
16116 ExprResult Res =
16118 if (Res.isInvalid())
16119 return ExprError();
16120 Args[0] = Res.get();
16121 ArgExpr = Args;
16122 } else {
16124 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16125 if (Arg0.isInvalid())
16126 return ExprError();
16127
16128 MethodArgs.push_back(Arg0.get());
16129 }
16130
16132 *this, MethodArgs, Method, ArgExpr, LLoc);
16133 if (IsError)
16134 return ExprError();
16135
16136 // Build the actual expression node.
16137 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16138 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16140 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16141 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16142 if (FnExpr.isInvalid())
16143 return ExprError();
16144
16145 // Determine the result type
16146 QualType ResultTy = FnDecl->getReturnType();
16148 ResultTy = ResultTy.getNonLValueExprType(Context);
16149
16151 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16153
16154 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16155 return ExprError();
16156
16157 if (CheckFunctionCall(Method, TheCall,
16158 Method->getType()->castAs<FunctionProtoType>()))
16159 return ExprError();
16160
16162 FnDecl);
16163 } else {
16164 // We matched a built-in operator. Convert the arguments, then
16165 // break out so that we will build the appropriate built-in
16166 // operator node.
16168 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16171 if (ArgsRes0.isInvalid())
16172 return ExprError();
16173 Args[0] = ArgsRes0.get();
16174
16176 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16179 if (ArgsRes1.isInvalid())
16180 return ExprError();
16181 Args[1] = ArgsRes1.get();
16182
16183 break;
16184 }
16185 }
16186
16187 case OR_No_Viable_Function: {
16189 CandidateSet.empty()
16190 ? (PDiag(diag::err_ovl_no_oper)
16191 << Args[0]->getType() << /*subscript*/ 0
16192 << Args[0]->getSourceRange() << Range)
16193 : (PDiag(diag::err_ovl_no_viable_subscript)
16194 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16195 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16196 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16197 return ExprError();
16198 }
16199
16200 case OR_Ambiguous:
16201 if (Args.size() == 2) {
16202 CandidateSet.NoteCandidates(
16204 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16205 << "[]" << Args[0]->getType() << Args[1]->getType()
16206 << Args[0]->getSourceRange() << Range),
16207 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16208 } else {
16209 CandidateSet.NoteCandidates(
16211 PDiag(diag::err_ovl_ambiguous_subscript_call)
16212 << Args[0]->getType()
16213 << Args[0]->getSourceRange() << Range),
16214 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16215 }
16216 return ExprError();
16217
16218 case OR_Deleted: {
16219 StringLiteral *Msg = Best->Function->getDeletedMessage();
16220 CandidateSet.NoteCandidates(
16222 PDiag(diag::err_ovl_deleted_oper)
16223 << "[]" << (Msg != nullptr)
16224 << (Msg ? Msg->getString() : StringRef())
16225 << Args[0]->getSourceRange() << Range),
16226 *this, OCD_AllCandidates, Args, "[]", LLoc);
16227 return ExprError();
16228 }
16229 }
16230
16231 // We matched a built-in operator; build it.
16232 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16233}
16234
16236 SourceLocation LParenLoc,
16237 MultiExprArg Args,
16238 SourceLocation RParenLoc,
16239 Expr *ExecConfig, bool IsExecConfig,
16240 bool AllowRecovery) {
16241 assert(MemExprE->getType() == Context.BoundMemberTy ||
16242 MemExprE->getType() == Context.OverloadTy);
16243
16244 // Dig out the member expression. This holds both the object
16245 // argument and the member function we're referring to.
16246 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16247
16248 // Determine whether this is a call to a pointer-to-member function.
16249 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16250 assert(op->getType() == Context.BoundMemberTy);
16251 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16252
16253 QualType fnType =
16254 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16255
16256 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16257 QualType resultType = proto->getCallResultType(Context);
16259
16260 // Check that the object type isn't more qualified than the
16261 // member function we're calling.
16262 Qualifiers funcQuals = proto->getMethodQuals();
16263
16264 QualType objectType = op->getLHS()->getType();
16265 if (op->getOpcode() == BO_PtrMemI)
16266 objectType = objectType->castAs<PointerType>()->getPointeeType();
16267 Qualifiers objectQuals = objectType.getQualifiers();
16268
16269 Qualifiers difference = objectQuals - funcQuals;
16270 difference.removeObjCGCAttr();
16271 difference.removeAddressSpace();
16272 if (difference) {
16273 std::string qualsString = difference.getAsString();
16274 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16275 << fnType.getUnqualifiedType()
16276 << qualsString
16277 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16278 }
16279
16281 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16283
16284 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16285 call, nullptr))
16286 return ExprError();
16287
16288 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16289 return ExprError();
16290
16291 if (CheckOtherCall(call, proto))
16292 return ExprError();
16293
16294 return MaybeBindToTemporary(call);
16295 }
16296
16297 // We only try to build a recovery expr at this level if we can preserve
16298 // the return type, otherwise we return ExprError() and let the caller
16299 // recover.
16300 auto BuildRecoveryExpr = [&](QualType Type) {
16301 if (!AllowRecovery)
16302 return ExprError();
16303 std::vector<Expr *> SubExprs = {MemExprE};
16304 llvm::append_range(SubExprs, Args);
16305 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16306 Type);
16307 };
16308 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16309 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16310 RParenLoc, CurFPFeatureOverrides());
16311
16312 UnbridgedCastsSet UnbridgedCasts;
16313 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16314 return ExprError();
16315
16316 MemberExpr *MemExpr;
16317 CXXMethodDecl *Method = nullptr;
16318 bool HadMultipleCandidates = false;
16319 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16320 NestedNameSpecifier Qualifier = std::nullopt;
16321 if (isa<MemberExpr>(NakedMemExpr)) {
16322 MemExpr = cast<MemberExpr>(NakedMemExpr);
16324 FoundDecl = MemExpr->getFoundDecl();
16325 Qualifier = MemExpr->getQualifier();
16326 UnbridgedCasts.restore();
16327 } else {
16328 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16329 Qualifier = UnresExpr->getQualifier();
16330
16331 QualType ObjectType = UnresExpr->getBaseType();
16332 Expr::Classification ObjectClassification
16334 : UnresExpr->getBase()->Classify(Context);
16335
16336 // Add overload candidates
16337 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16339
16340 // FIXME: avoid copy.
16341 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16342 if (UnresExpr->hasExplicitTemplateArgs()) {
16343 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16344 TemplateArgs = &TemplateArgsBuffer;
16345 }
16346
16348 E = UnresExpr->decls_end(); I != E; ++I) {
16349
16350 QualType ExplicitObjectType = ObjectType;
16351
16352 NamedDecl *Func = *I;
16353 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16355 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16356
16357 bool HasExplicitParameter = false;
16358 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16359 M && M->hasCXXExplicitFunctionObjectParameter())
16360 HasExplicitParameter = true;
16361 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16362 M &&
16363 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16364 HasExplicitParameter = true;
16365
16366 if (HasExplicitParameter)
16367 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16368
16369 // Microsoft supports direct constructor calls.
16370 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16372 CandidateSet,
16373 /*SuppressUserConversions*/ false);
16374 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16375 // If explicit template arguments were provided, we can't call a
16376 // non-template member function.
16377 if (TemplateArgs)
16378 continue;
16379
16380 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16381 ObjectClassification, Args, CandidateSet,
16382 /*SuppressUserConversions=*/false);
16383 } else {
16385 I.getPair(), ActingDC, TemplateArgs,
16386 ExplicitObjectType, ObjectClassification,
16387 Args, CandidateSet,
16388 /*SuppressUserConversions=*/false);
16389 }
16390 }
16391
16392 HadMultipleCandidates = (CandidateSet.size() > 1);
16393
16394 DeclarationName DeclName = UnresExpr->getMemberName();
16395
16396 UnbridgedCasts.restore();
16397
16399 bool Succeeded = false;
16400 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16401 Best)) {
16402 case OR_Success:
16403 Method = cast<CXXMethodDecl>(Best->Function);
16404 FoundDecl = Best->FoundDecl;
16405 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16406 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16407 break;
16408 // If FoundDecl is different from Method (such as if one is a template
16409 // and the other a specialization), make sure DiagnoseUseOfDecl is
16410 // called on both.
16411 // FIXME: This would be more comprehensively addressed by modifying
16412 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16413 // being used.
16414 if (Method != FoundDecl.getDecl() &&
16416 break;
16417 Succeeded = true;
16418 break;
16419
16421 CandidateSet.NoteCandidates(
16423 UnresExpr->getMemberLoc(),
16424 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16425 << DeclName << MemExprE->getSourceRange()),
16426 *this, OCD_AllCandidates, Args);
16427 break;
16428 case OR_Ambiguous:
16429 CandidateSet.NoteCandidates(
16430 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16431 PDiag(diag::err_ovl_ambiguous_member_call)
16432 << DeclName << MemExprE->getSourceRange()),
16433 *this, OCD_AmbiguousCandidates, Args);
16434 break;
16435 case OR_Deleted:
16437 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16438 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16439 break;
16440 }
16441 // Overload resolution fails, try to recover.
16442 if (!Succeeded)
16443 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16444
16445 ExprResult Res =
16446 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16447 if (Res.isInvalid())
16448 return ExprError();
16449 MemExprE = Res.get();
16450
16451 // If overload resolution picked a static member
16452 // build a non-member call based on that function.
16453 if (Method->isStatic()) {
16454 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16455 ExecConfig, IsExecConfig);
16456 }
16457
16458 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16459 }
16460
16461 QualType ResultType = Method->getReturnType();
16463 ResultType = ResultType.getNonLValueExprType(Context);
16464
16465 assert(Method && "Member call to something that isn't a method?");
16466 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16467
16468 CallExpr *TheCall = nullptr;
16470 if (Method->isExplicitObjectMemberFunction()) {
16471 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16472 NewArgs))
16473 return ExprError();
16474
16475 // Build the actual expression node.
16476 ExprResult FnExpr =
16477 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16478 HadMultipleCandidates, MemExpr->getExprLoc());
16479 if (FnExpr.isInvalid())
16480 return ExprError();
16481
16482 TheCall =
16483 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16484 CurFPFeatureOverrides(), Proto->getNumParams());
16485 TheCall->setUsesMemberSyntax(true);
16486 } else {
16487 // Convert the object argument (for a non-static member function call).
16489 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16490 if (ObjectArg.isInvalid())
16491 return ExprError();
16492 MemExpr->setBase(ObjectArg.get());
16493 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16494 RParenLoc, CurFPFeatureOverrides(),
16495 Proto->getNumParams());
16496 }
16497
16498 // Check for a valid return type.
16499 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16500 TheCall, Method))
16501 return BuildRecoveryExpr(ResultType);
16502
16503 // Convert the rest of the arguments
16504 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16505 RParenLoc))
16506 return BuildRecoveryExpr(ResultType);
16507
16508 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16509
16510 if (CheckFunctionCall(Method, TheCall, Proto))
16511 return ExprError();
16512
16513 // In the case the method to call was not selected by the overloading
16514 // resolution process, we still need to handle the enable_if attribute. Do
16515 // that here, so it will not hide previous -- and more relevant -- errors.
16516 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16517 if (const EnableIfAttr *Attr =
16518 CheckEnableIf(Method, LParenLoc, Args, true)) {
16519 Diag(MemE->getMemberLoc(),
16520 diag::err_ovl_no_viable_member_function_in_call)
16521 << Method << Method->getSourceRange();
16522 Diag(Method->getLocation(),
16523 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16524 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16525 return ExprError();
16526 }
16527 }
16528
16530 TheCall->getDirectCallee()->isPureVirtual()) {
16531 const FunctionDecl *MD = TheCall->getDirectCallee();
16532
16533 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16535 Diag(MemExpr->getBeginLoc(),
16536 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16538 << MD->getParent();
16539
16540 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16541 if (getLangOpts().AppleKext)
16542 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16543 << MD->getParent() << MD->getDeclName();
16544 }
16545 }
16546
16547 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16548 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16549 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16550 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16551 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16552 MemExpr->getMemberLoc());
16553 }
16554
16556 TheCall->getDirectCallee());
16557}
16558
16561 SourceLocation LParenLoc,
16562 MultiExprArg Args,
16563 SourceLocation RParenLoc) {
16564 if (checkPlaceholderForOverload(*this, Obj))
16565 return ExprError();
16566 ExprResult Object = Obj;
16567
16568 UnbridgedCastsSet UnbridgedCasts;
16569 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16570 return ExprError();
16571
16572 assert(Object.get()->getType()->isRecordType() &&
16573 "Requires object type argument");
16574
16575 // C++ [over.call.object]p1:
16576 // If the primary-expression E in the function call syntax
16577 // evaluates to a class object of type "cv T", then the set of
16578 // candidate functions includes at least the function call
16579 // operators of T. The function call operators of T are obtained by
16580 // ordinary lookup of the name operator() in the context of
16581 // (E).operator().
16582 OverloadCandidateSet CandidateSet(LParenLoc,
16584 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16585
16586 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16587 diag::err_incomplete_object_call, Object.get()))
16588 return true;
16589
16590 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16591 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16593 R.suppressAccessDiagnostics();
16594
16595 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16596 Oper != OperEnd; ++Oper) {
16597 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16598 Object.get()->Classify(Context), Args, CandidateSet,
16599 /*SuppressUserConversion=*/false);
16600 }
16601
16602 // When calling a lambda, both the call operator, and
16603 // the conversion operator to function pointer
16604 // are considered. But when constraint checking
16605 // on the call operator fails, it will also fail on the
16606 // conversion operator as the constraints are always the same.
16607 // As the user probably does not intend to perform a surrogate call,
16608 // we filter them out to produce better error diagnostics, ie to avoid
16609 // showing 2 failed overloads instead of one.
16610 bool IgnoreSurrogateFunctions = false;
16611 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16612 const OverloadCandidate &Candidate = *CandidateSet.begin();
16613 if (!Candidate.Viable &&
16615 IgnoreSurrogateFunctions = true;
16616 }
16617
16618 // C++ [over.call.object]p2:
16619 // In addition, for each (non-explicit in C++0x) conversion function
16620 // declared in T of the form
16621 //
16622 // operator conversion-type-id () cv-qualifier;
16623 //
16624 // where cv-qualifier is the same cv-qualification as, or a
16625 // greater cv-qualification than, cv, and where conversion-type-id
16626 // denotes the type "pointer to function of (P1,...,Pn) returning
16627 // R", or the type "reference to pointer to function of
16628 // (P1,...,Pn) returning R", or the type "reference to function
16629 // of (P1,...,Pn) returning R", a surrogate call function [...]
16630 // is also considered as a candidate function. Similarly,
16631 // surrogate call functions are added to the set of candidate
16632 // functions for each conversion function declared in an
16633 // accessible base class provided the function is not hidden
16634 // within T by another intervening declaration.
16635 const auto &Conversions = Record->getVisibleConversionFunctions();
16636 for (auto I = Conversions.begin(), E = Conversions.end();
16637 !IgnoreSurrogateFunctions && I != E; ++I) {
16638 NamedDecl *D = *I;
16639 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16640 if (isa<UsingShadowDecl>(D))
16641 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16642
16643 // Skip over templated conversion functions; they aren't
16644 // surrogates.
16646 continue;
16647
16649 if (!Conv->isExplicit()) {
16650 // Strip the reference type (if any) and then the pointer type (if
16651 // any) to get down to what might be a function type.
16652 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16653 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16654 ConvType = ConvPtrType->getPointeeType();
16655
16656 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16657 {
16658 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16659 Object.get(), Args, CandidateSet);
16660 }
16661 }
16662 }
16663
16664 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16665
16666 // Perform overload resolution.
16668 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16669 Best)) {
16670 case OR_Success:
16671 // Overload resolution succeeded; we'll build the appropriate call
16672 // below.
16673 break;
16674
16675 case OR_No_Viable_Function: {
16677 CandidateSet.empty()
16678 ? (PDiag(diag::err_ovl_no_oper)
16679 << Object.get()->getType() << /*call*/ 1
16680 << Object.get()->getSourceRange())
16681 : (PDiag(diag::err_ovl_no_viable_object_call)
16682 << Object.get()->getType() << Object.get()->getSourceRange());
16683 CandidateSet.NoteCandidates(
16684 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16685 OCD_AllCandidates, Args);
16686 break;
16687 }
16688 case OR_Ambiguous:
16689 if (!R.isAmbiguous())
16690 CandidateSet.NoteCandidates(
16691 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16692 PDiag(diag::err_ovl_ambiguous_object_call)
16693 << Object.get()->getType()
16694 << Object.get()->getSourceRange()),
16695 *this, OCD_AmbiguousCandidates, Args);
16696 break;
16697
16698 case OR_Deleted: {
16699 // FIXME: Is this diagnostic here really necessary? It seems that
16700 // 1. we don't have any tests for this diagnostic, and
16701 // 2. we already issue err_deleted_function_use for this later on anyway.
16702 StringLiteral *Msg = Best->Function->getDeletedMessage();
16703 CandidateSet.NoteCandidates(
16704 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16705 PDiag(diag::err_ovl_deleted_object_call)
16706 << Object.get()->getType() << (Msg != nullptr)
16707 << (Msg ? Msg->getString() : StringRef())
16708 << Object.get()->getSourceRange()),
16709 *this, OCD_AllCandidates, Args);
16710 break;
16711 }
16712 }
16713
16714 if (Best == CandidateSet.end())
16715 return true;
16716
16717 UnbridgedCasts.restore();
16718
16719 if (Best->Function == nullptr) {
16720 // Since there is no function declaration, this is one of the
16721 // surrogate candidates. Dig out the conversion function.
16722 CXXConversionDecl *Conv
16724 Best->Conversions[0].UserDefined.ConversionFunction);
16725
16726 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16727 Best->FoundDecl);
16728 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16729 return ExprError();
16730 assert(Conv == Best->FoundDecl.getDecl() &&
16731 "Found Decl & conversion-to-functionptr should be same, right?!");
16732 // We selected one of the surrogate functions that converts the
16733 // object parameter to a function pointer. Perform the conversion
16734 // on the object argument, then let BuildCallExpr finish the job.
16735
16736 // Create an implicit member expr to refer to the conversion operator.
16737 // and then call it.
16738 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16739 Conv, HadMultipleCandidates);
16740 if (Call.isInvalid())
16741 return ExprError();
16742 // Record usage of conversion in an implicit cast.
16744 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16745 nullptr, VK_PRValue, CurFPFeatureOverrides());
16746
16747 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16748 }
16749
16750 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16751
16752 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16753 // that calls this method, using Object for the implicit object
16754 // parameter and passing along the remaining arguments.
16755 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16756
16757 // An error diagnostic has already been printed when parsing the declaration.
16758 if (Method->isInvalidDecl())
16759 return ExprError();
16760
16761 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16762 unsigned NumParams = Proto->getNumParams();
16763
16764 DeclarationNameInfo OpLocInfo(
16765 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16766 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16767 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16768 Obj, HadMultipleCandidates,
16769 OpLocInfo.getLoc(),
16770 OpLocInfo.getInfo());
16771 if (NewFn.isInvalid())
16772 return true;
16773
16774 SmallVector<Expr *, 8> MethodArgs;
16775 MethodArgs.reserve(NumParams + 1);
16776
16777 bool IsError = false;
16778
16779 // Initialize the object parameter.
16781 if (Method->isExplicitObjectMemberFunction()) {
16782 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16783 } else {
16785 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16786 if (ObjRes.isInvalid())
16787 IsError = true;
16788 else
16789 Object = ObjRes;
16790 MethodArgs.push_back(Object.get());
16791 }
16792
16794 *this, MethodArgs, Method, Args, LParenLoc);
16795
16796 // If this is a variadic call, handle args passed through "...".
16797 if (Proto->isVariadic()) {
16798 // Promote the arguments (C99 6.5.2.2p7).
16799 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16801 Args[i], VariadicCallType::Method, nullptr);
16802 IsError |= Arg.isInvalid();
16803 MethodArgs.push_back(Arg.get());
16804 }
16805 }
16806
16807 if (IsError)
16808 return true;
16809
16810 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16811
16812 // Once we've built TheCall, all of the expressions are properly owned.
16813 QualType ResultTy = Method->getReturnType();
16815 ResultTy = ResultTy.getNonLValueExprType(Context);
16816
16818 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16820
16821 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16822 return true;
16823
16824 if (CheckFunctionCall(Method, TheCall, Proto))
16825 return true;
16826
16828}
16829
16831 SourceLocation OpLoc,
16832 bool *NoArrowOperatorFound) {
16833 assert(Base->getType()->isRecordType() &&
16834 "left-hand side must have class type");
16835
16837 return ExprError();
16838
16839 SourceLocation Loc = Base->getExprLoc();
16840
16841 // C++ [over.ref]p1:
16842 //
16843 // [...] An expression x->m is interpreted as (x.operator->())->m
16844 // for a class object x of type T if T::operator->() exists and if
16845 // the operator is selected as the best match function by the
16846 // overload resolution mechanism (13.3).
16847 DeclarationName OpName =
16848 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16850
16851 if (RequireCompleteType(Loc, Base->getType(),
16852 diag::err_typecheck_incomplete_tag, Base))
16853 return ExprError();
16854
16855 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16856 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16857 R.suppressAccessDiagnostics();
16858
16859 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16860 Oper != OperEnd; ++Oper) {
16861 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16862 {}, CandidateSet,
16863 /*SuppressUserConversion=*/false);
16864 }
16865
16866 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16867
16868 // Perform overload resolution.
16870 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16871 case OR_Success:
16872 // Overload resolution succeeded; we'll build the call below.
16873 break;
16874
16875 case OR_No_Viable_Function: {
16876 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16877 if (CandidateSet.empty()) {
16878 QualType BaseType = Base->getType();
16879 if (NoArrowOperatorFound) {
16880 // Report this specific error to the caller instead of emitting a
16881 // diagnostic, as requested.
16882 *NoArrowOperatorFound = true;
16883 return ExprError();
16884 }
16885 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16886 << BaseType << Base->getSourceRange();
16887 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16888 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16889 << FixItHint::CreateReplacement(OpLoc, ".");
16890 }
16891 } else
16892 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16893 << "operator->" << Base->getSourceRange();
16894 CandidateSet.NoteCandidates(*this, Base, Cands);
16895 return ExprError();
16896 }
16897 case OR_Ambiguous:
16898 if (!R.isAmbiguous())
16899 CandidateSet.NoteCandidates(
16900 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16901 << "->" << Base->getType()
16902 << Base->getSourceRange()),
16904 return ExprError();
16905
16906 case OR_Deleted: {
16907 StringLiteral *Msg = Best->Function->getDeletedMessage();
16908 CandidateSet.NoteCandidates(
16909 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16910 << "->" << (Msg != nullptr)
16911 << (Msg ? Msg->getString() : StringRef())
16912 << Base->getSourceRange()),
16913 *this, OCD_AllCandidates, Base);
16914 return ExprError();
16915 }
16916 }
16917
16918 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16919
16920 // Convert the object parameter.
16921 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16922
16923 if (Method->isExplicitObjectMemberFunction()) {
16925 if (R.isInvalid())
16926 return ExprError();
16927 Base = R.get();
16928 } else {
16930 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16931 if (BaseResult.isInvalid())
16932 return ExprError();
16933 Base = BaseResult.get();
16934 }
16935
16936 // Build the operator call.
16937 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16938 Base, HadMultipleCandidates, OpLoc);
16939 if (FnExpr.isInvalid())
16940 return ExprError();
16941
16942 QualType ResultTy = Method->getReturnType();
16944 ResultTy = ResultTy.getNonLValueExprType(Context);
16945
16946 CallExpr *TheCall =
16947 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16948 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16949
16950 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16951 return ExprError();
16952
16953 if (CheckFunctionCall(Method, TheCall,
16954 Method->getType()->castAs<FunctionProtoType>()))
16955 return ExprError();
16956
16958}
16959
16961 DeclarationNameInfo &SuffixInfo,
16962 ArrayRef<Expr*> Args,
16963 SourceLocation LitEndLoc,
16964 TemplateArgumentListInfo *TemplateArgs) {
16965 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16966
16967 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16969 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16970 TemplateArgs);
16971
16972 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16973
16974 // Perform overload resolution. This will usually be trivial, but might need
16975 // to perform substitutions for a literal operator template.
16977 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16978 case OR_Success:
16979 case OR_Deleted:
16980 break;
16981
16983 CandidateSet.NoteCandidates(
16984 PartialDiagnosticAt(UDSuffixLoc,
16985 PDiag(diag::err_ovl_no_viable_function_in_call)
16986 << R.getLookupName()),
16987 *this, OCD_AllCandidates, Args);
16988 return ExprError();
16989
16990 case OR_Ambiguous:
16991 CandidateSet.NoteCandidates(
16992 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16993 << R.getLookupName()),
16994 *this, OCD_AmbiguousCandidates, Args);
16995 return ExprError();
16996 }
16997
16998 FunctionDecl *FD = Best->Function;
16999 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
17000 nullptr, HadMultipleCandidates,
17001 SuffixInfo.getLoc(),
17002 SuffixInfo.getInfo());
17003 if (Fn.isInvalid())
17004 return true;
17005
17006 // Check the argument types. This should almost always be a no-op, except
17007 // that array-to-pointer decay is applied to string literals.
17008 Expr *ConvArgs[2];
17009 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17012 SourceLocation(), Args[ArgIdx]);
17013 if (InputInit.isInvalid())
17014 return true;
17015 ConvArgs[ArgIdx] = InputInit.get();
17016 }
17017
17018 QualType ResultTy = FD->getReturnType();
17020 ResultTy = ResultTy.getNonLValueExprType(Context);
17021
17023 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17024 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17025
17026 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17027 return ExprError();
17028
17029 if (CheckFunctionCall(FD, UDL, nullptr))
17030 return ExprError();
17031
17033}
17034
17037 SourceLocation RangeLoc,
17038 const DeclarationNameInfo &NameInfo,
17039 LookupResult &MemberLookup,
17040 OverloadCandidateSet *CandidateSet,
17041 Expr *Range, ExprResult *CallExpr) {
17042 Scope *S = nullptr;
17043
17045 if (!MemberLookup.empty()) {
17046 ExprResult MemberRef =
17047 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17048 /*IsPtr=*/false, CXXScopeSpec(),
17049 /*TemplateKWLoc=*/SourceLocation(),
17050 /*FirstQualifierInScope=*/nullptr,
17051 MemberLookup,
17052 /*TemplateArgs=*/nullptr, S);
17053 if (MemberRef.isInvalid()) {
17054 *CallExpr = ExprError();
17055 return FRS_DiagnosticIssued;
17056 }
17057 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17058 if (CallExpr->isInvalid()) {
17059 *CallExpr = ExprError();
17060 return FRS_DiagnosticIssued;
17061 }
17062 } else {
17063 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17065 NameInfo, UnresolvedSet<0>());
17066 if (FnR.isInvalid())
17067 return FRS_DiagnosticIssued;
17069
17070 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17071 CandidateSet, CallExpr);
17072 if (CandidateSet->empty() || CandidateSetError) {
17073 *CallExpr = ExprError();
17074 return FRS_NoViableFunction;
17075 }
17077 OverloadingResult OverloadResult =
17078 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17079
17080 if (OverloadResult == OR_No_Viable_Function) {
17081 *CallExpr = ExprError();
17082 return FRS_NoViableFunction;
17083 }
17084 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17085 Loc, nullptr, CandidateSet, &Best,
17086 OverloadResult,
17087 /*AllowTypoCorrection=*/false);
17088 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17089 *CallExpr = ExprError();
17090 return FRS_DiagnosticIssued;
17091 }
17092 }
17093 return FRS_Success;
17094}
17095
17097 FunctionDecl *Fn) {
17098 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17099 ExprResult SubExpr =
17100 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17101 if (SubExpr.isInvalid())
17102 return ExprError();
17103 if (SubExpr.get() == PE->getSubExpr())
17104 return PE;
17105
17106 return new (Context)
17107 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17108 }
17109
17110 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17111 ExprResult SubExpr =
17112 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17113 if (SubExpr.isInvalid())
17114 return ExprError();
17115 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17116 SubExpr.get()->getType()) &&
17117 "Implicit cast type cannot be determined from overload");
17118 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17119 if (SubExpr.get() == ICE->getSubExpr())
17120 return ICE;
17121
17122 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17123 SubExpr.get(), nullptr, ICE->getValueKind(),
17125 }
17126
17127 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17128 if (!GSE->isResultDependent()) {
17129 ExprResult SubExpr =
17130 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17131 if (SubExpr.isInvalid())
17132 return ExprError();
17133 if (SubExpr.get() == GSE->getResultExpr())
17134 return GSE;
17135
17136 // Replace the resulting type information before rebuilding the generic
17137 // selection expression.
17138 ArrayRef<Expr *> A = GSE->getAssocExprs();
17139 SmallVector<Expr *, 4> AssocExprs(A);
17140 unsigned ResultIdx = GSE->getResultIndex();
17141 AssocExprs[ResultIdx] = SubExpr.get();
17142
17143 if (GSE->isExprPredicate())
17145 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17146 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17147 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17148 ResultIdx);
17150 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17151 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17152 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17153 ResultIdx);
17154 }
17155 // Rather than fall through to the unreachable, return the original generic
17156 // selection expression.
17157 return GSE;
17158 }
17159
17160 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17161 assert(UnOp->getOpcode() == UO_AddrOf &&
17162 "Can only take the address of an overloaded function");
17163 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17164 if (!Method->isImplicitObjectMemberFunction()) {
17165 // Do nothing: the address of static and
17166 // explicit object member functions is a (non-member) function pointer.
17167 } else {
17168 // Fix the subexpression, which really has to be an
17169 // UnresolvedLookupExpr holding an overloaded member function
17170 // or template.
17171 ExprResult SubExpr =
17172 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17173 if (SubExpr.isInvalid())
17174 return ExprError();
17175 if (SubExpr.get() == UnOp->getSubExpr())
17176 return UnOp;
17177
17178 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17179 SubExpr.get(), Method))
17180 return ExprError();
17181
17182 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17183 "fixed to something other than a decl ref");
17184 NestedNameSpecifier Qualifier =
17185 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17186 assert(Qualifier &&
17187 "fixed to a member ref with no nested name qualifier");
17188
17189 // We have taken the address of a pointer to member
17190 // function. Perform the computation here so that we get the
17191 // appropriate pointer to member type.
17192 QualType MemPtrType = Context.getMemberPointerType(
17193 Fn->getType(), Qualifier,
17194 cast<CXXRecordDecl>(Method->getDeclContext()));
17195 // Under the MS ABI, lock down the inheritance model now.
17196 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17197 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17198
17199 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17200 MemPtrType, VK_PRValue, OK_Ordinary,
17201 UnOp->getOperatorLoc(), false,
17203 }
17204 }
17205 ExprResult SubExpr =
17206 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17207 if (SubExpr.isInvalid())
17208 return ExprError();
17209 if (SubExpr.get() == UnOp->getSubExpr())
17210 return UnOp;
17211
17212 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17213 SubExpr.get());
17214 }
17215
17216 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17217 if (Found.getAccess() == AS_none) {
17219 }
17220 // FIXME: avoid copy.
17221 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17222 if (ULE->hasExplicitTemplateArgs()) {
17223 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17224 TemplateArgs = &TemplateArgsBuffer;
17225 }
17226
17227 QualType Type = Fn->getType();
17228 ExprValueKind ValueKind =
17229 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17230 ? VK_LValue
17231 : VK_PRValue;
17232
17233 // FIXME: Duplicated from BuildDeclarationNameExpr.
17234 if (unsigned BID = Fn->getBuiltinID()) {
17235 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17236 Type = Context.BuiltinFnTy;
17237 ValueKind = VK_PRValue;
17238 }
17239 }
17240
17242 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17243 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17244 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17245 return DRE;
17246 }
17247
17248 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17249 // FIXME: avoid copy.
17250 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17251 if (MemExpr->hasExplicitTemplateArgs()) {
17252 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17253 TemplateArgs = &TemplateArgsBuffer;
17254 }
17255
17256 Expr *Base;
17257
17258 // If we're filling in a static method where we used to have an
17259 // implicit member access, rewrite to a simple decl ref.
17260 if (MemExpr->isImplicitAccess()) {
17261 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17263 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17264 MemExpr->getQualifierLoc(), Found.getDecl(),
17265 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17266 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17267 return DRE;
17268 } else {
17269 SourceLocation Loc = MemExpr->getMemberLoc();
17270 if (MemExpr->getQualifier())
17271 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17272 Base =
17273 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17274 }
17275 } else
17276 Base = MemExpr->getBase();
17277
17278 ExprValueKind valueKind;
17279 QualType type;
17280 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17281 valueKind = VK_LValue;
17282 type = Fn->getType();
17283 } else {
17284 valueKind = VK_PRValue;
17285 type = Context.BoundMemberTy;
17286 }
17287
17288 return BuildMemberExpr(
17289 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17290 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17291 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17292 type, valueKind, OK_Ordinary, TemplateArgs);
17293 }
17294
17295 llvm_unreachable("Invalid reference to overloaded function");
17296}
17297
17303
17304bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17306 if (!PartialOverloading || !Function)
17307 return true;
17308 if (Function->isVariadic())
17309 return false;
17310 if (const auto *Proto =
17311 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17312 if (Proto->isTemplateVariadic())
17313 return false;
17314 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17315 if (const auto *Proto =
17316 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17317 if (Proto->isTemplateVariadic())
17318 return false;
17319 return true;
17320}
17321
17323 DeclarationName Name,
17324 OverloadCandidateSet &CandidateSet,
17325 FunctionDecl *Fn, MultiExprArg Args,
17326 bool IsMember) {
17327 StringLiteral *Msg = Fn->getDeletedMessage();
17328 CandidateSet.NoteCandidates(
17329 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17330 << IsMember << Name << (Msg != nullptr)
17331 << (Msg ? Msg->getString() : StringRef())
17332 << Range),
17333 *this, OCD_AllCandidates, Args);
17334}
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.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
llvm::json::Object Object
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid matrix conversion.
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
__device__ __2f16 b
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:481
bool isFloat() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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:802
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType NullPtrTy
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:918
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:917
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:3942
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:281
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
QualType getElementType() const
Definition TypeBase.h:3784
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8230
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2180
StringRef getOpcodeStr() const
Definition Expr.h:4107
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2133
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5094
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
Pointer to a block type.
Definition TypeBase.h:3592
This class is used for builtin types like 'int'.
Definition TypeBase.h:3214
Kind getKind() const
Definition TypeBase.h:3262
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:2624
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3071
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3108
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2959
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2995
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2999
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:694
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2721
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2728
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2872
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2275
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Definition ExprCXX.cpp:624
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1987
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1517
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3110
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3328
Represents a canonical, potentially-qualified type.
bool isAtLeastAsQualifiedAs(CanQual< T > Other, const ASTContext &Ctx) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
static CanQual< Type > CreateUnsafe(QualType Other)
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isVolatileQualified() const
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
QualType getElementType() const
Definition TypeBase.h:3335
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:5116
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4456
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4453
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition Expr.h:1466
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:786
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:771
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:762
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:598
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4028
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4246
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4144
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1955
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1939
const Expr * getExpr() const
Definition DeclCXX.h:1940
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2372
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1466
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:398
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3095
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3339
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4229
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:814
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4068
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3175
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:141
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:104
Represents a function declaration or definition.
Definition Decl.h:2015
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2704
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4195
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3764
param_iterator param_end()
Definition Decl.h:2802
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3668
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3867
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
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:4266
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4315
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3749
param_iterator param_begin()
Definition Decl.h:2801
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3135
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4331
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4259
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3871
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2485
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4132
bool isConsteval() const
Definition Decl.h:2497
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3712
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:2877
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:3717
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3828
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2700
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5861
unsigned getNumParams() const
Definition TypeBase.h:5635
Qualifiers getMethodQuals() const
Definition TypeBase.h:5783
QualType getParamType(unsigned i) const
Definition TypeBase.h:5637
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5761
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5797
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:4664
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4735
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4592
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
ExtInfo getExtInfo() const
Definition TypeBase.h:4909
CallingConv getCallConv() const
Definition TypeBase.h:4908
QualType getReturnType() const
Definition TypeBase.h:4893
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4921
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition Expr.cpp:4716
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:673
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:770
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:827
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:681
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:812
bool hasInitializerListContainerType() const
Definition Overload.h:809
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:734
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:816
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:685
QualType getInitializerListContainerType() const
Definition Overload.h:819
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5417
unsigned getNumInits() const
Definition Expr.h:5332
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2496
const Expr * getInit(unsigned Init) const
Definition Expr.h:5356
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2514
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3667
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:4401
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3478
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3464
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3585
Expr * getBase() const
Definition Expr.h:3444
void setBase(Expr *E)
Definition Expr.h:3443
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1794
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3562
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3454
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3735
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5535
QualType getPointeeType() const
Definition TypeBase.h:3721
Describes a module or submodule.
Definition Module.h:246
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:259
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1681
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7993
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8049
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8138
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8107
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8061
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8101
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1854
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8113
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void AddDeferredTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition Overload.h:1360
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1458
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1392
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1408
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1350
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1549
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1185
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition Overload.h:1368
SourceLocation getLocation() const
Definition Overload.h:1348
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1349
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1383
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3132
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3284
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3248
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3245
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3223
decls_iterator decls_begin() const
Definition ExprCXX.h:3225
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3236
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3258
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3254
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3342
decls_iterator decls_end() const
Definition ExprCXX.h:3228
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3242
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
Represents a parameter to a function.
Definition Decl.h:1805
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3060
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5188
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8509
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8520
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3630
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1231
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
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:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8585
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8552
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8477
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
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:8596
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8463
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8371
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8378
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4740
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:860
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
bool hasOnlyConst() const
Definition TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasRestrict() const
Definition TypeBase.h:477
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeUnaligned()
Definition TypeBase.h:515
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3685
Represents a struct/union/class.
Definition Decl.h:4342
field_range fields() const
Definition Decl.h:4545
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3623
QualType getPointeeType() const
Definition TypeBase.h:3641
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
Definition SemaARM.cpp:1505
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1550
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:187
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp: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:459
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:406
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp: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:10404
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6435
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6464
RAII class to control scope of DeferDiags.
Definition Sema.h:10127
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1386
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1421
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12551
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12585
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10145
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9442
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9427
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:416
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:170
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
SemaCUDA & CUDA()
Definition Sema.h:1473
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10487
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10490
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10496
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10494
@ AR_dependent
Definition Sema.h:1688
@ AR_accessible
Definition Sema.h:1686
@ AR_inaccessible
Definition Sema.h:1687
@ AR_delayed
Definition Sema.h:1689
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1308
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:686
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition Sema.h:1518
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:759
ASTContext & getASTContext() const
Definition Sema.h:939
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
@ FRS_Success
Definition Sema.h:10875
@ FRS_DiagnosticIssued
Definition Sema.h:10877
@ FRS_NoViableFunction
Definition Sema.h:10876
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9408
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10196
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3637
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12249
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:932
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1306
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
SemaHLSL & HLSL()
Definition Sema.h:1483
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9407
MemberPointerConversionDirection
Definition Sema.h:10328
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10515
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15616
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7057
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8261
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14060
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7555
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13793
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:15571
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:125
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6820
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6789
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
MemberPointerConversionResult
Definition Sema.h:10320
SourceManager & SourceMgr
Definition Sema.h:1311
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1310
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6497
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
SemaARM & ARM()
Definition Sema.h:1453
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8743
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:392
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:362
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:339
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition Overload.h:324
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:391
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:334
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:367
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:318
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:329
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition Overload.h:384
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
StringRef getString() const
Definition Expr.h:1870
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:679
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:733
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:718
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3553
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2533
bool isBlockPointerType() const
Definition TypeBase.h:8688
bool isVoidType() const
Definition TypeBase.h:9034
bool isBooleanType() const
Definition TypeBase.h:9171
bool isObjCBuiltinType() const
Definition TypeBase.h:8898
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
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:1965
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:789
bool isIncompleteArrayType() const
Definition TypeBase.h:8775
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
bool isFloat16Type() const
Definition TypeBase.h:9043
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:726
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2138
bool isRValueReferenceType() const
Definition TypeBase.h:8700
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:8771
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9201
bool isArrayType() const
Definition TypeBase.h:8767
bool isCharType() const
Definition Type.cpp:2158
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9106
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2375
bool isPointerType() const
Definition TypeBase.h:8668
bool isArrayParameterType() const
Definition TypeBase.h:8783
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2620
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2121
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8868
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2194
bool isExtVectorBoolType() const
Definition TypeBase.h:8815
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8855
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2840
bool isLValueReferenceType() const
Definition TypeBase.h:8696
bool isBitIntType() const
Definition TypeBase.h:8943
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2456
bool isAnyComplexType() const
Definition TypeBase.h:8803
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9094
bool isHalfType() const
Definition TypeBase.h:9038
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9016
bool isQueueT() const
Definition TypeBase.h:8924
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isObjCIdType() const
Definition TypeBase.h:8880
bool isMatrixType() const
Definition TypeBase.h:8831
bool isOverflowBehaviorType() const
Definition TypeBase.h:8839
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2558
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8916
bool isBFloat16Type() const
Definition TypeBase.h:9055
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isObjCObjectPointerType() const
Definition TypeBase.h:8847
bool isVectorType() const
Definition TypeBase.h:8807
bool isObjCClassType() const
Definition TypeBase.h:8886
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2641
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8991
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:2285
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
bool isSamplerT() const
Definition TypeBase.h:8912
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:655
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1430
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5151
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1406
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3459
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4234
QualType getBaseType() const
Definition ExprCXX.h:4208
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4218
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4199
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4244
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4238
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:644
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:968
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4240
QualType getElementType() const
Definition TypeBase.h:4239
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:252
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:61
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind, bool PartialOverloading=false)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition Overload.h:859
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:887
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:896
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:879
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:883
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition Overload.h:924
@ ovl_fail_too_few_arguments
Definition Overload.h:861
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:903
@ ovl_fail_too_many_arguments
Definition Overload.h:860
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:911
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:892
@ ovl_fail_bad_deduction
Definition Overload.h:863
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:907
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:916
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:900
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:868
@ Comparison
A comparison.
Definition Sema.h:667
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1788
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1791
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1794
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:221
@ ICR_Conversion
Conversion.
Definition Overload.h:235
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:247
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:257
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:263
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:250
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:238
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:244
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:260
@ ICR_Promotion
Promotion.
Definition Overload.h:229
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:223
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:254
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:232
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1045
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:929
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
OptionalUnsigned< unsigned > UnsignedOrNone
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:587
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:216
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:150
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:274
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:310
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:448
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h:522
ConversionSet::const_iterator const_iterator
Definition Overload.h:558
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:523
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:549
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:607
QualType getFromType() const
Definition Overload.h:606
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
DeferredTemplateOverloadCandidate * Next
Definition Overload.h:1102
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
Extra information about a function prototype.
Definition TypeBase.h:5442
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5447
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1195
bool allowsReversed(OverloadedOperatorKind Op) const
Determine whether reversing parameter order is allowed for operator Op.
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD) const
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool isAcceptableCandidate(const FunctionDecl *FD) const
Definition Overload.h:1217
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1244
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1206
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1208
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1234
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:998
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:989
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1063
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1037
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1002
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:979
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:947
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:943
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:938
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1010
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:959
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:973
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1028
unsigned getNumParams() const
Definition Overload.h:1076
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1006
unsigned TookAddressOfOverload
Definition Overload.h:992
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1019
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
DeductionFailureInfo DeductionFailure
Definition Overload.h:1022
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:951
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1033
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10607
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10614
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13287
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13333
Abstract class used to diagnose incomplete types.
Definition Sema.h:8342
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
DeclAccessPair FoundDecl
The declaration that was looked up, together with its access.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:477
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:489
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:511
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:502
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:497
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:516
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.