clang 22.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"
33#include "clang/Sema/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.h"
36#include "clang/Sema/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
169 };
170 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
171 return Rank[(int)Kind];
172}
173
192
193/// GetImplicitConversionName - Return the name of this kind of
194/// implicit conversion.
196 static const char *const Name[] = {
197 "No conversion",
198 "Lvalue-to-rvalue",
199 "Array-to-pointer",
200 "Function-to-pointer",
201 "Function pointer conversion",
202 "Qualification",
203 "Integral promotion",
204 "Floating point promotion",
205 "Complex promotion",
206 "Integral conversion",
207 "Floating conversion",
208 "Complex conversion",
209 "Floating-integral conversion",
210 "Pointer conversion",
211 "Pointer-to-member conversion",
212 "Boolean conversion",
213 "Compatible-types conversion",
214 "Derived-to-base conversion",
215 "Vector conversion",
216 "SVE Vector conversion",
217 "RVV Vector conversion",
218 "Vector splat",
219 "Complex-real conversion",
220 "Block Pointer conversion",
221 "Transparent Union Conversion",
222 "Writeback conversion",
223 "OpenCL Zero Event Conversion",
224 "OpenCL Zero Queue Conversion",
225 "C specific type conversion",
226 "Incompatible pointer conversion",
227 "Fixed point conversion",
228 "HLSL vector truncation",
229 "HLSL matrix truncation",
230 "Non-decaying array conversion",
231 "HLSL vector splat",
232 "HLSL matrix splat",
233 };
234 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
235 return Name[Kind];
236}
237
238/// StandardConversionSequence - Set the standard conversion
239/// sequence to the identity conversion.
257
258/// getRank - Retrieve the rank of this standard conversion sequence
259/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
260/// implicit conversions.
273
274/// isPointerConversionToBool - Determines whether this conversion is
275/// a conversion of a pointer or pointer-to-member to bool. This is
276/// used as part of the ranking of standard conversion sequences
277/// (C++ 13.3.3.2p4).
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer or function-to-pointer implicit conversions, so
281 // check for their presence as well as checking whether FromType is
282 // a pointer.
283 if (getToType(1)->isBooleanType() &&
284 (getFromType()->isPointerType() ||
285 getFromType()->isMemberPointerType() ||
286 getFromType()->isObjCObjectPointerType() ||
287 getFromType()->isBlockPointerType() ||
289 return true;
290
291 return false;
292}
293
294/// isPointerConversionToVoidPointer - Determines whether this
295/// conversion is a conversion of a pointer to a void pointer. This is
296/// used as part of the ranking of standard conversion sequences (C++
297/// 13.3.3.2p4).
298bool
301 QualType FromType = getFromType();
302 QualType ToType = getToType(1);
303
304 // Note that FromType has not necessarily been transformed by the
305 // array-to-pointer implicit conversion, so check for its presence
306 // and redo the conversion to get a pointer.
308 FromType = Context.getArrayDecayedType(FromType);
309
310 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
311 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
312 return ToPtrType->getPointeeType()->isVoidType();
313
314 return false;
315}
316
317/// Skip any implicit casts which could be either part of a narrowing conversion
318/// or after one in an implicit conversion.
320 const Expr *Converted) {
321 // We can have cleanups wrapping the converted expression; these need to be
322 // preserved so that destructors run if necessary.
323 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
324 Expr *Inner =
325 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
326 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
327 EWC->getObjects());
328 }
329
330 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
331 switch (ICE->getCastKind()) {
332 case CK_NoOp:
333 case CK_IntegralCast:
334 case CK_IntegralToBoolean:
335 case CK_IntegralToFloating:
336 case CK_BooleanToSignedIntegral:
337 case CK_FloatingToIntegral:
338 case CK_FloatingToBoolean:
339 case CK_FloatingCast:
340 Converted = ICE->getSubExpr();
341 continue;
342
343 default:
344 return Converted;
345 }
346 }
347
348 return Converted;
349}
350
351/// Check if this standard conversion sequence represents a narrowing
352/// conversion, according to C++11 [dcl.init.list]p7.
353///
354/// \param Ctx The AST context.
355/// \param Converted The result of applying this standard conversion sequence.
356/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
357/// value of the expression prior to the narrowing conversion.
358/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
359/// type of the expression prior to the narrowing conversion.
360/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
361/// from floating point types to integral types should be ignored.
363 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
364 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
365 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
366 "narrowing check outside C++");
367
368 // C++11 [dcl.init.list]p7:
369 // A narrowing conversion is an implicit conversion ...
370 QualType FromType = getToType(0);
371 QualType ToType = getToType(1);
372
373 // A conversion to an enumeration type is narrowing if the conversion to
374 // the underlying type is narrowing. This only arises for expressions of
375 // the form 'Enum{init}'.
376 if (const auto *ED = ToType->getAsEnumDecl())
377 ToType = ED->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
385 goto IntegralConversion;
386 // -- from a pointer type or pointer-to-member type to bool, or
387 return NK_Type_Narrowing;
388
389 // -- from a floating-point type to an integer type, or
390 //
391 // -- from an integer type or unscoped enumeration type to a floating-point
392 // type, except where the source is a constant expression and the actual
393 // value after conversion will fit into the target type and will produce
394 // the original value when converted back to the original type, or
396 FloatingIntegralConversion:
397 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
398 return NK_Type_Narrowing;
399 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
400 ToType->isRealFloatingType()) {
401 if (IgnoreFloatToIntegralConversion)
402 return NK_Not_Narrowing;
403 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 assert(Initializer && "Unknown conversion expression");
405
406 // If it's value-dependent, we can't tell whether it's narrowing.
407 if (Initializer->isValueDependent())
409
410 if (std::optional<llvm::APSInt> IntConstantValue =
411 Initializer->getIntegerConstantExpr(Ctx)) {
412 // Convert the integer to the floating type.
413 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
414 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
415 llvm::APFloat::rmNearestTiesToEven);
416 // And back.
417 llvm::APSInt ConvertedValue = *IntConstantValue;
418 bool ignored;
419 llvm::APFloat::opStatus Status = Result.convertToInteger(
420 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
421 // If the converted-back integer has unspecified value, or if the
422 // resulting value is different, this was a narrowing conversion.
423 if (Status == llvm::APFloat::opInvalidOp ||
424 *IntConstantValue != ConvertedValue) {
425 ConstantValue = APValue(*IntConstantValue);
426 ConstantType = Initializer->getType();
428 }
429 } else {
430 // Variables are always narrowings.
432 }
433 }
434 return NK_Not_Narrowing;
435
436 // -- from long double to double or float, or from double to float, except
437 // where the source is a constant expression and the actual value after
438 // conversion is within the range of values that can be represented (even
439 // if it cannot be represented exactly), or
441 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
442 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
443 // FromType is larger than ToType.
444 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
445
446 // If it's value-dependent, we can't tell whether it's narrowing.
447 if (Initializer->isValueDependent())
449
451 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
452 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
453 // Constant!
454 if (Ctx.getLangOpts().C23)
455 ConstantValue = R.Val;
456 assert(ConstantValue.isFloat());
457 llvm::APFloat FloatVal = ConstantValue.getFloat();
458 // Convert the source value into the target type.
459 bool ignored;
460 llvm::APFloat Converted = FloatVal;
461 llvm::APFloat::opStatus ConvertStatus =
462 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
463 llvm::APFloat::rmNearestTiesToEven, &ignored);
464 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
465 llvm::APFloat::rmNearestTiesToEven, &ignored);
466 if (Ctx.getLangOpts().C23) {
467 if (FloatVal.isNaN() && Converted.isNaN() &&
468 !FloatVal.isSignaling() && !Converted.isSignaling()) {
469 // Quiet NaNs are considered the same value, regardless of
470 // payloads.
471 return NK_Not_Narrowing;
472 }
473 // For normal values, check exact equality.
474 if (!Converted.bitwiseIsEqual(FloatVal)) {
475 ConstantType = Initializer->getType();
477 }
478 } else {
479 // If there was no overflow, the source value is within the range of
480 // values that can be represented.
481 if (ConvertStatus & llvm::APFloat::opOverflow) {
482 ConstantType = Initializer->getType();
484 }
485 }
486 } else {
488 }
489 }
490 return NK_Not_Narrowing;
491
492 // -- from an integer type or unscoped enumeration type to an integer type
493 // that cannot represent all the values of the original type, except where
494 // (CWG2627) -- the source is a bit-field whose width w is less than that
495 // of its type (or, for an enumeration type, its underlying type) and the
496 // target type can represent all the values of a hypothetical extended
497 // integer type with width w and with the same signedness as the original
498 // type or
499 // -- the source is a constant expression and the actual value after
500 // conversion will fit into the target type and will produce the original
501 // value when converted back to the original type.
503 IntegralConversion: {
504 assert(FromType->isIntegralOrUnscopedEnumerationType());
505 assert(ToType->isIntegralOrUnscopedEnumerationType());
506 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
507 unsigned FromWidth = Ctx.getIntWidth(FromType);
508 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
509 const unsigned ToWidth = Ctx.getIntWidth(ToType);
510
511 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
512 bool ToSigned, unsigned ToWidth) {
513 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
514 !(FromSigned && !ToSigned);
515 };
516
517 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
518 return NK_Not_Narrowing;
519
520 // Not all values of FromType can be represented in ToType.
521 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
522
523 bool DependentBitField = false;
524 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
525 if (BitField->getBitWidth()->isValueDependent())
526 DependentBitField = true;
527 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
528 BitFieldWidth < FromWidth) {
529 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
530 return NK_Not_Narrowing;
531
532 // The initializer will be truncated to the bit-field width
533 FromWidth = BitFieldWidth;
534 }
535 }
536
537 // If it's value-dependent, we can't tell whether it's narrowing.
538 if (Initializer->isValueDependent())
540
541 std::optional<llvm::APSInt> OptInitializerValue =
542 Initializer->getIntegerConstantExpr(Ctx);
543 if (!OptInitializerValue) {
544 // If the bit-field width was dependent, it might end up being small
545 // enough to fit in the target type (unless the target type is unsigned
546 // and the source type is signed, in which case it will never fit)
547 if (DependentBitField && !(FromSigned && !ToSigned))
549
550 // Otherwise, such a conversion is always narrowing
552 }
553 llvm::APSInt &InitializerValue = *OptInitializerValue;
554 bool Narrowing = false;
555 if (FromWidth < ToWidth) {
556 // Negative -> unsigned is narrowing. Otherwise, more bits is never
557 // narrowing.
558 if (InitializerValue.isSigned() && InitializerValue.isNegative())
559 Narrowing = true;
560 } else {
561 // Add a bit to the InitializerValue so we don't have to worry about
562 // signed vs. unsigned comparisons.
563 InitializerValue =
564 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
565 // Convert the initializer to and from the target width and signed-ness.
566 llvm::APSInt ConvertedValue = InitializerValue;
567 ConvertedValue = ConvertedValue.trunc(ToWidth);
568 ConvertedValue.setIsSigned(ToSigned);
569 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
570 ConvertedValue.setIsSigned(InitializerValue.isSigned());
571 // If the result is different, this was a narrowing conversion.
572 if (ConvertedValue != InitializerValue)
573 Narrowing = true;
574 }
575 if (Narrowing) {
576 ConstantType = Initializer->getType();
577 ConstantValue = APValue(InitializerValue);
579 }
580
581 return NK_Not_Narrowing;
582 }
583 case ICK_Complex_Real:
584 if (FromType->isComplexType() && !ToType->isComplexType())
585 return NK_Type_Narrowing;
586 return NK_Not_Narrowing;
587
589 if (Ctx.getLangOpts().C23) {
590 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
592 if (Initializer->EvaluateAsRValue(R, Ctx)) {
593 ConstantValue = R.Val;
594 assert(ConstantValue.isFloat());
595 llvm::APFloat FloatVal = ConstantValue.getFloat();
596 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
597 // value, the unqualified versions of the type of the initializer and
598 // the corresponding real type of the object declared shall be
599 // compatible.
600 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
601 ConstantType = Initializer->getType();
603 }
604 }
605 }
606 return NK_Not_Narrowing;
607 default:
608 // Other kinds of conversions are not narrowings.
609 return NK_Not_Narrowing;
610 }
611}
612
613/// dump - Print this standard conversion sequence to standard
614/// error. Useful for debugging overloading issues.
615LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
616 raw_ostream &OS = llvm::errs();
617 bool PrintedSomething = false;
618 if (First != ICK_Identity) {
620 PrintedSomething = true;
621 }
622
623 if (Second != ICK_Identity) {
624 if (PrintedSomething) {
625 OS << " -> ";
626 }
628
629 if (CopyConstructor) {
630 OS << " (by copy constructor)";
631 } else if (DirectBinding) {
632 OS << " (direct reference binding)";
633 } else if (ReferenceBinding) {
634 OS << " (reference binding)";
635 }
636 PrintedSomething = true;
637 }
638
639 if (Third != ICK_Identity) {
640 if (PrintedSomething) {
641 OS << " -> ";
642 }
644 PrintedSomething = true;
645 }
646
647 if (!PrintedSomething) {
648 OS << "No conversions required";
649 }
650}
651
652/// dump - Print this user-defined conversion sequence to standard
653/// error. Useful for debugging overloading issues.
655 raw_ostream &OS = llvm::errs();
656 if (Before.First || Before.Second || Before.Third) {
657 Before.dump();
658 OS << " -> ";
659 }
661 OS << '\'' << *ConversionFunction << '\'';
662 else
663 OS << "aggregate initialization";
664 if (After.First || After.Second || After.Third) {
665 OS << " -> ";
666 After.dump();
667 }
668}
669
670/// dump - Print this implicit conversion sequence to standard
671/// error. Useful for debugging overloading issues.
673 raw_ostream &OS = llvm::errs();
675 OS << "Worst list element conversion: ";
676 switch (ConversionKind) {
678 OS << "Standard conversion: ";
679 Standard.dump();
680 break;
682 OS << "User-defined conversion: ";
683 UserDefined.dump();
684 break;
686 OS << "Ellipsis conversion";
687 break;
689 OS << "Ambiguous conversion";
690 break;
691 case BadConversion:
692 OS << "Bad conversion";
693 break;
694 }
695
696 OS << "\n";
697}
698
702
704 conversions().~ConversionSet();
705}
706
707void
713
714namespace {
715 // Structure used by DeductionFailureInfo to store
716 // template argument information.
717 struct DFIArguments {
718 TemplateArgument FirstArg;
719 TemplateArgument SecondArg;
720 };
721 // Structure used by DeductionFailureInfo to store
722 // template parameter and template argument information.
723 struct DFIParamWithArguments : DFIArguments {
724 TemplateParameter Param;
725 };
726 // Structure used by DeductionFailureInfo to store template argument
727 // information and the index of the problematic call argument.
728 struct DFIDeducedMismatchArgs : DFIArguments {
729 TemplateArgumentList *TemplateArgs;
730 unsigned CallArgIndex;
731 };
732 // Structure used by DeductionFailureInfo to store information about
733 // unsatisfied constraints.
734 struct CNSInfo {
735 TemplateArgumentList *TemplateArgs;
736 ConstraintSatisfaction Satisfaction;
737 };
738}
739
740/// Convert from Sema's representation of template deduction information
741/// to the form used in overload-candidate information.
745 TemplateDeductionInfo &Info) {
747 Result.Result = static_cast<unsigned>(TDK);
748 Result.HasDiagnostic = false;
749 switch (TDK) {
756 Result.Data = nullptr;
757 break;
758
761 Result.Data = Info.Param.getOpaqueValue();
762 break;
763
766 // FIXME: Should allocate from normal heap so that we can free this later.
767 auto *Saved = new (Context) DFIDeducedMismatchArgs;
768 Saved->FirstArg = Info.FirstArg;
769 Saved->SecondArg = Info.SecondArg;
770 Saved->TemplateArgs = Info.takeSugared();
771 Saved->CallArgIndex = Info.CallArgIndex;
772 Result.Data = Saved;
773 break;
774 }
775
777 // FIXME: Should allocate from normal heap so that we can free this later.
778 DFIArguments *Saved = new (Context) DFIArguments;
779 Saved->FirstArg = Info.FirstArg;
780 Saved->SecondArg = Info.SecondArg;
781 Result.Data = Saved;
782 break;
783 }
784
786 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
789 // FIXME: Should allocate from normal heap so that we can free this later.
790 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
791 Saved->Param = Info.Param;
792 Saved->FirstArg = Info.FirstArg;
793 Saved->SecondArg = Info.SecondArg;
794 Result.Data = Saved;
795 break;
796 }
797
799 Result.Data = Info.takeSugared();
800 if (Info.hasSFINAEDiagnostic()) {
804 Result.HasDiagnostic = true;
805 }
806 break;
807
809 CNSInfo *Saved = new (Context) CNSInfo;
810 Saved->TemplateArgs = Info.takeSugared();
811 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
812 Result.Data = Saved;
813 break;
814 }
815
819 llvm_unreachable("not a deduction failure");
820 }
821
822 return Result;
823}
824
826 switch (static_cast<TemplateDeductionResult>(Result)) {
836 break;
837
844 // FIXME: Destroy the data?
845 Data = nullptr;
846 break;
847
849 // FIXME: Destroy the template argument list?
850 Data = nullptr;
852 Diag->~PartialDiagnosticAt();
853 HasDiagnostic = false;
854 }
855 break;
856
858 // FIXME: Destroy the template argument list?
859 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
860 Data = nullptr;
862 Diag->~PartialDiagnosticAt();
863 HasDiagnostic = false;
864 }
865 break;
866
867 // Unhandled
870 break;
871 }
872}
873
875 if (HasDiagnostic)
876 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
877 return nullptr;
878}
879
913
949
981
1013
1015 switch (static_cast<TemplateDeductionResult>(Result)) {
1018 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1019
1020 default:
1021 return std::nullopt;
1022 }
1023}
1024
1026 const FunctionDecl *Y) {
1027 if (!X || !Y)
1028 return false;
1029 if (X->getNumParams() != Y->getNumParams())
1030 return false;
1031 // FIXME: when do rewritten comparison operators
1032 // with explicit object parameters correspond?
1033 // https://cplusplus.github.io/CWG/issues/2797.html
1034 for (unsigned I = 0; I < X->getNumParams(); ++I)
1035 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1036 Y->getParamDecl(I)->getType()))
1037 return false;
1038 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1039 auto *FTY = Y->getDescribedFunctionTemplate();
1040 if (!FTY)
1041 return false;
1042 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1043 FTY->getTemplateParameters()))
1044 return false;
1045 }
1046 return true;
1047}
1048
1050 Expr *FirstOperand, FunctionDecl *EqFD) {
1051 assert(EqFD->getOverloadedOperator() ==
1052 OverloadedOperatorKind::OO_EqualEqual);
1053 // C++2a [over.match.oper]p4:
1054 // A non-template function or function template F named operator== is a
1055 // rewrite target with first operand o unless a search for the name operator!=
1056 // in the scope S from the instantiation context of the operator expression
1057 // finds a function or function template that would correspond
1058 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1059 // scope of the class type of o if F is a class member, and the namespace
1060 // scope of which F is a member otherwise. A function template specialization
1061 // named operator== is a rewrite target if its function template is a rewrite
1062 // target.
1064 OverloadedOperatorKind::OO_ExclaimEqual);
1065 if (isa<CXXMethodDecl>(EqFD)) {
1066 // If F is a class member, search scope is class type of first operand.
1067 QualType RHS = FirstOperand->getType();
1068 auto *RHSRec = RHS->getAsCXXRecordDecl();
1069 if (!RHSRec)
1070 return true;
1071 LookupResult Members(S, NotEqOp, OpLoc,
1073 S.LookupQualifiedName(Members, RHSRec);
1074 Members.suppressAccessDiagnostics();
1075 for (NamedDecl *Op : Members)
1076 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1077 return false;
1078 return true;
1079 }
1080 // Otherwise the search scope is the namespace scope of which F is a member.
1081 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1082 auto *NotEqFD = Op->getAsFunction();
1083 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1084 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1085 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1087 cast<Decl>(Op->getLexicalDeclContext())))
1088 return false;
1089 }
1090 return true;
1091}
1092
1094 OverloadedOperatorKind Op) const {
1096 return false;
1097 return Op == OO_EqualEqual || Op == OO_Spaceship;
1098}
1099
1101 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1102 auto Op = FD->getOverloadedOperator();
1103 if (!allowsReversed(Op))
1104 return false;
1105 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1106 assert(OriginalArgs.size() == 2);
1108 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1109 return false;
1110 }
1111 // Don't bother adding a reversed candidate that can never be a better
1112 // match than the non-reversed version.
1113 return FD->getNumNonObjectParams() != 2 ||
1115 FD->getParamDecl(1)->getType()) ||
1116 FD->hasAttr<EnableIfAttr>();
1117}
1118
1119void OverloadCandidateSet::destroyCandidates() {
1120 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1121 for (auto &C : i->Conversions)
1122 C.~ImplicitConversionSequence();
1123 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1124 i->DeductionFailure.Destroy();
1125 }
1126}
1127
1129 destroyCandidates();
1130 SlabAllocator.Reset();
1131 NumInlineBytesUsed = 0;
1132 Candidates.clear();
1133 Functions.clear();
1134 Kind = CSK;
1135 FirstDeferredCandidate = nullptr;
1136 DeferredCandidatesCount = 0;
1137 HasDeferredTemplateConstructors = false;
1138 ResolutionByPerfectCandidateIsDisabled = false;
1139}
1140
1141namespace {
1142 class UnbridgedCastsSet {
1143 struct Entry {
1144 Expr **Addr;
1145 Expr *Saved;
1146 };
1147 SmallVector<Entry, 2> Entries;
1148
1149 public:
1150 void save(Sema &S, Expr *&E) {
1151 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1152 Entry entry = { &E, E };
1153 Entries.push_back(entry);
1154 E = S.ObjC().stripARCUnbridgedCast(E);
1155 }
1156
1157 void restore() {
1158 for (SmallVectorImpl<Entry>::iterator
1159 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1160 *i->Addr = i->Saved;
1161 }
1162 };
1163}
1164
1165/// checkPlaceholderForOverload - Do any interesting placeholder-like
1166/// preprocessing on the given expression.
1167///
1168/// \param unbridgedCasts a collection to which to add unbridged casts;
1169/// without this, they will be immediately diagnosed as errors
1170///
1171/// Return true on unrecoverable error.
1172static bool
1174 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1175 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1176 // We can't handle overloaded expressions here because overload
1177 // resolution might reasonably tweak them.
1178 if (placeholder->getKind() == BuiltinType::Overload) return false;
1179
1180 // If the context potentially accepts unbridged ARC casts, strip
1181 // the unbridged cast and add it to the collection for later restoration.
1182 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1183 unbridgedCasts) {
1184 unbridgedCasts->save(S, E);
1185 return false;
1186 }
1187
1188 // Go ahead and check everything else.
1189 ExprResult result = S.CheckPlaceholderExpr(E);
1190 if (result.isInvalid())
1191 return true;
1192
1193 E = result.get();
1194 return false;
1195 }
1196
1197 // Nothing to do.
1198 return false;
1199}
1200
1201/// checkArgPlaceholdersForOverload - Check a set of call operands for
1202/// placeholders.
1204 UnbridgedCastsSet &unbridged) {
1205 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1206 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1207 return true;
1208
1209 return false;
1210}
1211
1213 const LookupResult &Old, NamedDecl *&Match,
1214 bool NewIsUsingDecl) {
1215 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1216 I != E; ++I) {
1217 NamedDecl *OldD = *I;
1218
1219 bool OldIsUsingDecl = false;
1220 if (isa<UsingShadowDecl>(OldD)) {
1221 OldIsUsingDecl = true;
1222
1223 // We can always introduce two using declarations into the same
1224 // context, even if they have identical signatures.
1225 if (NewIsUsingDecl) continue;
1226
1227 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1228 }
1229
1230 // A using-declaration does not conflict with another declaration
1231 // if one of them is hidden.
1232 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1233 continue;
1234
1235 // If either declaration was introduced by a using declaration,
1236 // we'll need to use slightly different rules for matching.
1237 // Essentially, these rules are the normal rules, except that
1238 // function templates hide function templates with different
1239 // return types or template parameter lists.
1240 bool UseMemberUsingDeclRules =
1241 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1242 !New->getFriendObjectKind();
1243
1244 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1245 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1246 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1248 continue;
1249 }
1250
1251 if (!isa<FunctionTemplateDecl>(OldD) &&
1252 !shouldLinkPossiblyHiddenDecl(*I, New))
1253 continue;
1254
1255 Match = *I;
1256 return OverloadKind::Match;
1257 }
1258
1259 // Builtins that have custom typechecking or have a reference should
1260 // not be overloadable or redeclarable.
1261 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1262 Match = *I;
1264 }
1265 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1266 // We can overload with these, which can show up when doing
1267 // redeclaration checks for UsingDecls.
1268 assert(Old.getLookupKind() == LookupUsingDeclName);
1269 } else if (isa<TagDecl>(OldD)) {
1270 // We can always overload with tags by hiding them.
1271 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1272 // Optimistically assume that an unresolved using decl will
1273 // overload; if it doesn't, we'll have to diagnose during
1274 // template instantiation.
1275 //
1276 // Exception: if the scope is dependent and this is not a class
1277 // member, the using declaration can only introduce an enumerator.
1278 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1279 Match = *I;
1281 }
1282 } else {
1283 // (C++ 13p1):
1284 // Only function declarations can be overloaded; object and type
1285 // declarations cannot be overloaded.
1286 Match = *I;
1288 }
1289 }
1290
1291 // C++ [temp.friend]p1:
1292 // For a friend function declaration that is not a template declaration:
1293 // -- if the name of the friend is a qualified or unqualified template-id,
1294 // [...], otherwise
1295 // -- if the name of the friend is a qualified-id and a matching
1296 // non-template function is found in the specified class or namespace,
1297 // the friend declaration refers to that function, otherwise,
1298 // -- if the name of the friend is a qualified-id and a matching function
1299 // template is found in the specified class or namespace, the friend
1300 // declaration refers to the deduced specialization of that function
1301 // template, otherwise
1302 // -- the name shall be an unqualified-id [...]
1303 // If we get here for a qualified friend declaration, we've just reached the
1304 // third bullet. If the type of the friend is dependent, skip this lookup
1305 // until instantiation.
1306 if (New->getFriendObjectKind() && New->getQualifier() &&
1307 !New->getDescribedFunctionTemplate() &&
1308 !New->getDependentSpecializationInfo() &&
1309 !New->getType()->isDependentType()) {
1310 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1311 TemplateSpecResult.addAllDecls(Old);
1312 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1313 /*QualifiedFriend*/true)) {
1314 New->setInvalidDecl();
1316 }
1317
1318 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1319 return OverloadKind::Match;
1320 }
1321
1323}
1324
1325template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1326 assert(D && "function decl should not be null");
1327 if (auto *A = D->getAttr<AttrT>())
1328 return !A->isImplicit();
1329 return false;
1330}
1331
1333 FunctionDecl *Old,
1334 bool UseMemberUsingDeclRules,
1335 bool ConsiderCudaAttrs,
1336 bool UseOverrideRules = false) {
1337 // C++ [basic.start.main]p2: This function shall not be overloaded.
1338 if (New->isMain())
1339 return false;
1340
1341 // MSVCRT user defined entry points cannot be overloaded.
1342 if (New->isMSVCRTEntryPoint())
1343 return false;
1344
1345 NamedDecl *OldDecl = Old;
1346 NamedDecl *NewDecl = New;
1348 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1349
1350 // C++ [temp.fct]p2:
1351 // A function template can be overloaded with other function templates
1352 // and with normal (non-template) functions.
1353 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1354 return true;
1355
1356 // Is the function New an overload of the function Old?
1357 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1358 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1359
1360 // Compare the signatures (C++ 1.3.10) of the two functions to
1361 // determine whether they are overloads. If we find any mismatch
1362 // in the signature, they are overloads.
1363
1364 // If either of these functions is a K&R-style function (no
1365 // prototype), then we consider them to have matching signatures.
1366 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1368 return false;
1369
1370 const auto *OldType = cast<FunctionProtoType>(OldQType);
1371 const auto *NewType = cast<FunctionProtoType>(NewQType);
1372
1373 // The signature of a function includes the types of its
1374 // parameters (C++ 1.3.10), which includes the presence or absence
1375 // of the ellipsis; see C++ DR 357).
1376 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1377 return true;
1378
1379 // For member-like friends, the enclosing class is part of the signature.
1380 if ((New->isMemberLikeConstrainedFriend() ||
1382 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1383 return true;
1384
1385 // Compare the parameter lists.
1386 // This can only be done once we have establish that friend functions
1387 // inhabit the same context, otherwise we might tried to instantiate
1388 // references to non-instantiated entities during constraint substitution.
1389 // GH78101.
1390 if (NewTemplate) {
1391 OldDecl = OldTemplate;
1392 NewDecl = NewTemplate;
1393 // C++ [temp.over.link]p4:
1394 // The signature of a function template consists of its function
1395 // signature, its return type and its template parameter list. The names
1396 // of the template parameters are significant only for establishing the
1397 // relationship between the template parameters and the rest of the
1398 // signature.
1399 //
1400 // We check the return type and template parameter lists for function
1401 // templates first; the remaining checks follow.
1402 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1403 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1404 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1405 bool SameReturnType = SemaRef.Context.hasSameType(
1406 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1407 // FIXME(GH58571): Match template parameter list even for non-constrained
1408 // template heads. This currently ensures that the code prior to C++20 is
1409 // not newly broken.
1410 bool ConstraintsInTemplateHead =
1413 // C++ [namespace.udecl]p11:
1414 // The set of declarations named by a using-declarator that inhabits a
1415 // class C does not include member functions and member function
1416 // templates of a base class that "correspond" to (and thus would
1417 // conflict with) a declaration of a function or function template in
1418 // C.
1419 // Comparing return types is not required for the "correspond" check to
1420 // decide whether a member introduced by a shadow declaration is hidden.
1421 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1422 !SameTemplateParameterList)
1423 return true;
1424 if (!UseMemberUsingDeclRules &&
1425 (!SameTemplateParameterList || !SameReturnType))
1426 return true;
1427 }
1428
1429 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1430 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1431
1432 int OldParamsOffset = 0;
1433 int NewParamsOffset = 0;
1434
1435 // When determining if a method is an overload from a base class, act as if
1436 // the implicit object parameter are of the same type.
1437
1438 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1440 auto ThisType = M->getFunctionObjectParameterReferenceType();
1441 if (ThisType.isConstQualified())
1442 Q.removeConst();
1443 return Q;
1444 }
1445
1446 // We do not allow overloading based off of '__restrict'.
1447 Q.removeRestrict();
1448
1449 // We may not have applied the implicit const for a constexpr member
1450 // function yet (because we haven't yet resolved whether this is a static
1451 // or non-static member function). Add it now, on the assumption that this
1452 // is a redeclaration of OldMethod.
1453 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1454 (M->isConstexpr() || M->isConsteval()) &&
1455 !isa<CXXConstructorDecl>(NewMethod))
1456 Q.addConst();
1457 return Q;
1458 };
1459
1460 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1461 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1462 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1463
1464 if (OldMethod->isExplicitObjectMemberFunction()) {
1465 BS.Quals.removeVolatile();
1466 DS.Quals.removeVolatile();
1467 }
1468
1469 return BS.Quals == DS.Quals;
1470 };
1471
1472 auto CompareType = [&](QualType Base, QualType D) {
1473 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1474 auto DS = D.getNonReferenceType().getCanonicalType().split();
1475
1476 if (!AreQualifiersEqual(BS, DS))
1477 return false;
1478
1479 if (OldMethod->isImplicitObjectMemberFunction() &&
1480 OldMethod->getParent() != NewMethod->getParent()) {
1481 CanQualType ParentType =
1482 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1483 if (ParentType.getTypePtr() != BS.Ty)
1484 return false;
1485 BS.Ty = DS.Ty;
1486 }
1487
1488 // FIXME: should we ignore some type attributes here?
1489 if (BS.Ty != DS.Ty)
1490 return false;
1491
1492 if (Base->isLValueReferenceType())
1493 return D->isLValueReferenceType();
1494 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1495 };
1496
1497 // If the function is a class member, its signature includes the
1498 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1499 auto DiagnoseInconsistentRefQualifiers = [&]() {
1500 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1501 return false;
1502 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1503 return false;
1504 if (OldMethod->isExplicitObjectMemberFunction() ||
1505 NewMethod->isExplicitObjectMemberFunction())
1506 return false;
1507 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1508 NewMethod->getRefQualifier() == RQ_None)) {
1509 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1510 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1511 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1512 return true;
1513 }
1514 return false;
1515 };
1516
1517 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1518 OldParamsOffset++;
1519 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1520 NewParamsOffset++;
1521
1522 if (OldType->getNumParams() - OldParamsOffset !=
1523 NewType->getNumParams() - NewParamsOffset ||
1525 {OldType->param_type_begin() + OldParamsOffset,
1526 OldType->param_type_end()},
1527 {NewType->param_type_begin() + NewParamsOffset,
1528 NewType->param_type_end()},
1529 nullptr)) {
1530 return true;
1531 }
1532
1533 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1534 !NewMethod->isStatic()) {
1535 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1536 const CXXMethodDecl *New) {
1537 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1538 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1539
1540 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1541 return F->getRefQualifier() == RQ_None &&
1542 !F->isExplicitObjectMemberFunction();
1543 };
1544
1545 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1546 CompareType(OldObjectType.getNonReferenceType(),
1547 NewObjectType.getNonReferenceType()))
1548 return true;
1549 return CompareType(OldObjectType, NewObjectType);
1550 }(OldMethod, NewMethod);
1551
1552 if (!HaveCorrespondingObjectParameters) {
1553 if (DiagnoseInconsistentRefQualifiers())
1554 return true;
1555 // CWG2554
1556 // and, if at least one is an explicit object member function, ignoring
1557 // object parameters
1558 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1559 !OldMethod->isExplicitObjectMemberFunction()))
1560 return true;
1561 }
1562 }
1563
1564 if (!UseOverrideRules &&
1565 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1566 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1567 OldRC = Old->getTrailingRequiresClause();
1568 if (!NewRC != !OldRC)
1569 return true;
1570 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1571 return true;
1572 if (NewRC &&
1573 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1574 NewDecl, NewRC.ConstraintExpr))
1575 return true;
1576 }
1577
1578 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1579 NewMethod->isImplicitObjectMemberFunction()) {
1580 if (DiagnoseInconsistentRefQualifiers())
1581 return true;
1582 }
1583
1584 // Though pass_object_size is placed on parameters and takes an argument, we
1585 // consider it to be a function-level modifier for the sake of function
1586 // identity. Either the function has one or more parameters with
1587 // pass_object_size or it doesn't.
1590 return true;
1591
1592 // enable_if attributes are an order-sensitive part of the signature.
1594 NewI = New->specific_attr_begin<EnableIfAttr>(),
1595 NewE = New->specific_attr_end<EnableIfAttr>(),
1596 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1597 OldE = Old->specific_attr_end<EnableIfAttr>();
1598 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1599 if (NewI == NewE || OldI == OldE)
1600 return true;
1601 llvm::FoldingSetNodeID NewID, OldID;
1602 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1603 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1604 if (NewID != OldID)
1605 return true;
1606 }
1607
1608 // At this point, it is known that the two functions have the same signature.
1609 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1610 // Don't allow overloading of destructors. (In theory we could, but it
1611 // would be a giant change to clang.)
1613 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1614 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1615 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1616 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1617 "Unexpected invalid target.");
1618
1619 // Allow overloading of functions with same signature and different CUDA
1620 // target attributes.
1621 if (NewTarget != OldTarget) {
1622 // Special case: non-constexpr function is allowed to override
1623 // constexpr virtual function
1624 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1625 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1630 return false;
1631 }
1632 return true;
1633 }
1634 }
1635 }
1636 }
1637
1638 // The signatures match; this is not an overload.
1639 return false;
1640}
1641
1643 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1644 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1645 ConsiderCudaAttrs);
1646}
1647
1649 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1650 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1651 /*UseMemberUsingDeclRules=*/false,
1652 /*ConsiderCudaAttrs=*/true,
1653 /*UseOverrideRules=*/true);
1654}
1655
1656/// Tries a user-defined conversion from From to ToType.
1657///
1658/// Produces an implicit conversion sequence for when a standard conversion
1659/// is not an option. See TryImplicitConversion for more information.
1662 bool SuppressUserConversions,
1663 AllowedExplicit AllowExplicit,
1664 bool InOverloadResolution,
1665 bool CStyle,
1666 bool AllowObjCWritebackConversion,
1667 bool AllowObjCConversionOnExplicit) {
1669
1670 if (SuppressUserConversions) {
1671 // We're not in the case above, so there is no conversion that
1672 // we can perform.
1674 return ICS;
1675 }
1676
1677 // Attempt user-defined conversion.
1678 OverloadCandidateSet Conversions(From->getExprLoc(),
1680 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1681 Conversions, AllowExplicit,
1682 AllowObjCConversionOnExplicit)) {
1683 case OR_Success:
1684 case OR_Deleted:
1685 ICS.setUserDefined();
1686 // C++ [over.ics.user]p4:
1687 // A conversion of an expression of class type to the same class
1688 // type is given Exact Match rank, and a conversion of an
1689 // expression of class type to a base class of that type is
1690 // given Conversion rank, in spite of the fact that a copy
1691 // constructor (i.e., a user-defined conversion function) is
1692 // called for those cases.
1694 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1695 QualType FromType;
1696 SourceLocation FromLoc;
1697 // C++11 [over.ics.list]p6, per DR2137:
1698 // C++17 [over.ics.list]p6:
1699 // If C is not an initializer-list constructor and the initializer list
1700 // has a single element of type cv U, where U is X or a class derived
1701 // from X, the implicit conversion sequence has Exact Match rank if U is
1702 // X, or Conversion rank if U is derived from X.
1703 bool FromListInit = false;
1704 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1705 InitList && InitList->getNumInits() == 1 &&
1707 const Expr *SingleInit = InitList->getInit(0);
1708 FromType = SingleInit->getType();
1709 FromLoc = SingleInit->getBeginLoc();
1710 FromListInit = true;
1711 } else {
1712 FromType = From->getType();
1713 FromLoc = From->getBeginLoc();
1714 }
1715 QualType FromCanon =
1717 QualType ToCanon
1719 if ((FromCanon == ToCanon ||
1720 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1721 // Turn this into a "standard" conversion sequence, so that it
1722 // gets ranked with standard conversion sequences.
1724 ICS.setStandard();
1726 ICS.Standard.setFromType(FromType);
1727 ICS.Standard.setAllToTypes(ToType);
1728 ICS.Standard.FromBracedInitList = FromListInit;
1731 if (ToCanon != FromCanon)
1733 }
1734 }
1735 break;
1736
1737 case OR_Ambiguous:
1738 ICS.setAmbiguous();
1739 ICS.Ambiguous.setFromType(From->getType());
1740 ICS.Ambiguous.setToType(ToType);
1741 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1742 Cand != Conversions.end(); ++Cand)
1743 if (Cand->Best)
1744 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1745 break;
1746
1747 // Fall through.
1750 break;
1751 }
1752
1753 return ICS;
1754}
1755
1756/// TryImplicitConversion - Attempt to perform an implicit conversion
1757/// from the given expression (Expr) to the given type (ToType). This
1758/// function returns an implicit conversion sequence that can be used
1759/// to perform the initialization. Given
1760///
1761/// void f(float f);
1762/// void g(int i) { f(i); }
1763///
1764/// this routine would produce an implicit conversion sequence to
1765/// describe the initialization of f from i, which will be a standard
1766/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1767/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1768//
1769/// Note that this routine only determines how the conversion can be
1770/// performed; it does not actually perform the conversion. As such,
1771/// it will not produce any diagnostics if no conversion is available,
1772/// but will instead return an implicit conversion sequence of kind
1773/// "BadConversion".
1774///
1775/// If @p SuppressUserConversions, then user-defined conversions are
1776/// not permitted.
1777/// If @p AllowExplicit, then explicit user-defined conversions are
1778/// permitted.
1779///
1780/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1781/// writeback conversion, which allows __autoreleasing id* parameters to
1782/// be initialized with __strong id* or __weak id* arguments.
1783static ImplicitConversionSequence
1785 bool SuppressUserConversions,
1786 AllowedExplicit AllowExplicit,
1787 bool InOverloadResolution,
1788 bool CStyle,
1789 bool AllowObjCWritebackConversion,
1790 bool AllowObjCConversionOnExplicit) {
1792 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1793 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1794 ICS.setStandard();
1795 return ICS;
1796 }
1797
1798 if (!S.getLangOpts().CPlusPlus) {
1800 return ICS;
1801 }
1802
1803 // C++ [over.ics.user]p4:
1804 // A conversion of an expression of class type to the same class
1805 // type is given Exact Match rank, and a conversion of an
1806 // expression of class type to a base class of that type is
1807 // given Conversion rank, in spite of the fact that a copy/move
1808 // constructor (i.e., a user-defined conversion function) is
1809 // called for those cases.
1810 QualType FromType = From->getType();
1811 if (ToType->isRecordType() &&
1812 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1813 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1814 ICS.setStandard();
1816 ICS.Standard.setFromType(FromType);
1817 ICS.Standard.setAllToTypes(ToType);
1818
1819 // We don't actually check at this point whether there is a valid
1820 // copy/move constructor, since overloading just assumes that it
1821 // exists. When we actually perform initialization, we'll find the
1822 // appropriate constructor to copy the returned object, if needed.
1823 ICS.Standard.CopyConstructor = nullptr;
1824
1825 // Determine whether this is considered a derived-to-base conversion.
1826 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1828
1829 return ICS;
1830 }
1831
1832 if (S.getLangOpts().HLSL) {
1833 // Handle conversion of the HLSL resource types.
1834 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1835 if (FromTy->isHLSLAttributedResourceType()) {
1836 // Attributed resource types can convert to other attributed
1837 // resource types with the same attributes and contained types,
1838 // or to __hlsl_resource_t without any attributes.
1839 bool CanConvert = false;
1840 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1841 if (ToTy->isHLSLAttributedResourceType()) {
1842 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1843 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1844 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1845 FromResType->getWrappedType()) &&
1846 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1847 FromResType->getContainedType()) &&
1848 ToResType->getAttrs() == FromResType->getAttrs())
1849 CanConvert = true;
1850 } else if (ToTy->isHLSLResourceType()) {
1851 CanConvert = true;
1852 }
1853 if (CanConvert) {
1854 ICS.setStandard();
1856 ICS.Standard.setFromType(FromType);
1857 ICS.Standard.setAllToTypes(ToType);
1858 return ICS;
1859 }
1860 }
1861 }
1862
1863 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1864 AllowExplicit, InOverloadResolution, CStyle,
1865 AllowObjCWritebackConversion,
1866 AllowObjCConversionOnExplicit);
1867}
1868
1869ImplicitConversionSequence
1871 bool SuppressUserConversions,
1872 AllowedExplicit AllowExplicit,
1873 bool InOverloadResolution,
1874 bool CStyle,
1875 bool AllowObjCWritebackConversion) {
1876 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1877 AllowExplicit, InOverloadResolution, CStyle,
1878 AllowObjCWritebackConversion,
1879 /*AllowObjCConversionOnExplicit=*/false);
1880}
1881
1883 AssignmentAction Action,
1884 bool AllowExplicit) {
1885 if (checkPlaceholderForOverload(*this, From))
1886 return ExprError();
1887
1888 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1889 bool AllowObjCWritebackConversion =
1890 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1891 Action == AssignmentAction::Sending);
1892 if (getLangOpts().ObjC)
1893 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1894 From->getType(), From);
1896 *this, From, ToType,
1897 /*SuppressUserConversions=*/false,
1898 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1899 /*InOverloadResolution=*/false,
1900 /*CStyle=*/false, AllowObjCWritebackConversion,
1901 /*AllowObjCConversionOnExplicit=*/false);
1902 return PerformImplicitConversion(From, ToType, ICS, Action);
1903}
1904
1906 QualType &ResultTy) const {
1907 bool Changed = IsFunctionConversion(FromType, ToType);
1908 if (Changed)
1909 ResultTy = ToType;
1910 return Changed;
1911}
1912
1913bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1914 if (Context.hasSameUnqualifiedType(FromType, ToType))
1915 return false;
1916
1917 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1918 // or F(t noexcept) -> F(t)
1919 // where F adds one of the following at most once:
1920 // - a pointer
1921 // - a member pointer
1922 // - a block pointer
1923 // Changes here need matching changes in FindCompositePointerType.
1924 CanQualType CanTo = Context.getCanonicalType(ToType);
1925 CanQualType CanFrom = Context.getCanonicalType(FromType);
1926 Type::TypeClass TyClass = CanTo->getTypeClass();
1927 if (TyClass != CanFrom->getTypeClass()) return false;
1928 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1929 if (TyClass == Type::Pointer) {
1930 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1931 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1932 } else if (TyClass == Type::BlockPointer) {
1933 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1934 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1935 } else if (TyClass == Type::MemberPointer) {
1936 auto ToMPT = CanTo.castAs<MemberPointerType>();
1937 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1938 // A function pointer conversion cannot change the class of the function.
1939 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1940 FromMPT->getMostRecentCXXRecordDecl()))
1941 return false;
1942 CanTo = ToMPT->getPointeeType();
1943 CanFrom = FromMPT->getPointeeType();
1944 } else {
1945 return false;
1946 }
1947
1948 TyClass = CanTo->getTypeClass();
1949 if (TyClass != CanFrom->getTypeClass()) return false;
1950 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1951 return false;
1952 }
1953
1954 const auto *FromFn = cast<FunctionType>(CanFrom);
1955 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1956
1957 const auto *ToFn = cast<FunctionType>(CanTo);
1958 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1959
1960 bool Changed = false;
1961
1962 // Drop 'noreturn' if not present in target type.
1963 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1964 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1965 Changed = true;
1966 }
1967
1968 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1969 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1970
1971 if (FromFPT && ToFPT) {
1972 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1973 QualType NewTy = Context.getFunctionType(
1974 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1975 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1976 ToFPT->hasCFIUncheckedCallee()));
1977 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1978 FromFn = FromFPT;
1979 Changed = true;
1980 }
1981 }
1982
1983 // Drop 'noexcept' if not present in target type.
1984 if (FromFPT && ToFPT) {
1985 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1986 FromFn = cast<FunctionType>(
1987 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1988 EST_None)
1989 .getTypePtr());
1990 Changed = true;
1991 }
1992
1993 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1994 // only if the ExtParameterInfo lists of the two function prototypes can be
1995 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1997 bool CanUseToFPT, CanUseFromFPT;
1998 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1999 CanUseFromFPT, NewParamInfos) &&
2000 CanUseToFPT && !CanUseFromFPT) {
2001 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2002 ExtInfo.ExtParameterInfos =
2003 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2004 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2005 FromFPT->getParamTypes(), ExtInfo);
2006 FromFn = QT->getAs<FunctionType>();
2007 Changed = true;
2008 }
2009
2010 if (Context.hasAnyFunctionEffects()) {
2011 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2012
2013 // Transparently add/drop effects; here we are concerned with
2014 // language rules/canonicalization. Adding/dropping effects is a warning.
2015 const auto FromFX = FromFPT->getFunctionEffects();
2016 const auto ToFX = ToFPT->getFunctionEffects();
2017 if (FromFX != ToFX) {
2018 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2019 ExtInfo.FunctionEffects = ToFX;
2020 QualType QT = Context.getFunctionType(
2021 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2022 FromFn = QT->getAs<FunctionType>();
2023 Changed = true;
2024 }
2025 }
2026 }
2027
2028 if (!Changed)
2029 return false;
2030
2031 assert(QualType(FromFn, 0).isCanonical());
2032 if (QualType(FromFn, 0) != CanTo) return false;
2033
2034 return true;
2035}
2036
2037/// Determine whether the conversion from FromType to ToType is a valid
2038/// floating point conversion.
2039///
2040static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2041 QualType ToType) {
2042 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2043 return false;
2044 // FIXME: disable conversions between long double, __ibm128 and __float128
2045 // if their representation is different until there is back end support
2046 // We of course allow this conversion if long double is really double.
2047
2048 // Conversions between bfloat16 and float16 are currently not supported.
2049 if ((FromType->isBFloat16Type() &&
2050 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2051 (ToType->isBFloat16Type() &&
2052 (FromType->isFloat16Type() || FromType->isHalfType())))
2053 return false;
2054
2055 // Conversions between IEEE-quad and IBM-extended semantics are not
2056 // permitted.
2057 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2058 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2059 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2060 &ToSem == &llvm::APFloat::IEEEquad()) ||
2061 (&FromSem == &llvm::APFloat::IEEEquad() &&
2062 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2063 return false;
2064 return true;
2065}
2066
2068 QualType ToType,
2070 Expr *From) {
2071 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2072 return true;
2073
2074 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2076 return true;
2077 }
2078
2079 if (IsFloatingPointConversion(S, FromType, ToType)) {
2081 return true;
2082 }
2083
2084 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2086 return true;
2087 }
2088
2089 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2091 ToType->isRealFloatingType())) {
2093 return true;
2094 }
2095
2096 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2098 return true;
2099 }
2100
2101 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2102 ToType->isIntegralType(S.Context)) {
2104 return true;
2105 }
2106
2107 return false;
2108}
2109
2110/// Determine whether the conversion from FromType to ToType is a valid
2111/// matrix conversion.
2112///
2113/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2114/// conversion.
2115static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2117 ImplicitConversionKind &ElConv, Expr *From,
2118 bool InOverloadResolution, bool CStyle) {
2119 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2120 if (!S.getLangOpts().HLSL)
2121 return false;
2122
2123 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2124 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2125
2126 // If both arguments are matrix, handle possible matrix truncation and
2127 // element conversion.
2128 if (ToMatrixType && FromMatrixType) {
2129 unsigned FromCols = FromMatrixType->getNumColumns();
2130 unsigned ToCols = ToMatrixType->getNumColumns();
2131 if (FromCols < ToCols)
2132 return false;
2133
2134 unsigned FromRows = FromMatrixType->getNumRows();
2135 unsigned ToRows = ToMatrixType->getNumRows();
2136 if (FromRows < ToRows)
2137 return false;
2138
2139 if (FromRows == ToRows && FromCols == ToCols)
2140 ElConv = ICK_Identity;
2141 else
2143
2144 QualType FromElTy = FromMatrixType->getElementType();
2145 QualType ToElTy = ToMatrixType->getElementType();
2146 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2147 return true;
2148 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2149 }
2150
2151 // Matrix splat from any arithmetic type to a matrix.
2152 if (ToMatrixType && FromType->isArithmeticType()) {
2153 ElConv = ICK_HLSL_Matrix_Splat;
2154 QualType ToElTy = ToMatrixType->getElementType();
2155 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2157 return true;
2158 }
2159 if (FromMatrixType && !ToMatrixType) {
2161 QualType FromElTy = FromMatrixType->getElementType();
2162 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2163 return true;
2164 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2165 }
2166
2167 return false;
2168}
2169
2170/// Determine whether the conversion from FromType to ToType is a valid
2171/// vector conversion.
2172///
2173/// \param ICK Will be set to the vector conversion kind, if this is a vector
2174/// conversion.
2175static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2177 ImplicitConversionKind &ElConv, Expr *From,
2178 bool InOverloadResolution, bool CStyle) {
2179 // We need at least one of these types to be a vector type to have a vector
2180 // conversion.
2181 if (!ToType->isVectorType() && !FromType->isVectorType())
2182 return false;
2183
2184 // Identical types require no conversions.
2185 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2186 return false;
2187
2188 // HLSL allows implicit truncation of vector types.
2189 if (S.getLangOpts().HLSL) {
2190 auto *ToExtType = ToType->getAs<ExtVectorType>();
2191 auto *FromExtType = FromType->getAs<ExtVectorType>();
2192
2193 // If both arguments are vectors, handle possible vector truncation and
2194 // element conversion.
2195 if (ToExtType && FromExtType) {
2196 unsigned FromElts = FromExtType->getNumElements();
2197 unsigned ToElts = ToExtType->getNumElements();
2198 if (FromElts < ToElts)
2199 return false;
2200 if (FromElts == ToElts)
2201 ElConv = ICK_Identity;
2202 else
2204
2205 QualType FromElTy = FromExtType->getElementType();
2206 QualType ToElTy = ToExtType->getElementType();
2207 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2208 return true;
2209 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2210 }
2211 if (FromExtType && !ToExtType) {
2213 QualType FromElTy = FromExtType->getElementType();
2214 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2215 return true;
2216 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2217 }
2218 // Fallthrough for the case where ToType is a vector and FromType is not.
2219 }
2220
2221 // There are no conversions between extended vector types, only identity.
2222 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2223 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2224 // Implicit conversions require the same number of elements.
2225 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2226 return false;
2227
2228 // Permit implicit conversions from integral values to boolean vectors.
2229 if (ToType->isExtVectorBoolType() &&
2230 FromExtType->getElementType()->isIntegerType()) {
2232 return true;
2233 }
2234 // There are no other conversions between extended vector types.
2235 return false;
2236 }
2237
2238 // Vector splat from any arithmetic type to a vector.
2239 if (FromType->isArithmeticType()) {
2240 if (S.getLangOpts().HLSL) {
2241 ElConv = ICK_HLSL_Vector_Splat;
2242 QualType ToElTy = ToExtType->getElementType();
2243 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2244 From);
2245 }
2246 ICK = ICK_Vector_Splat;
2247 return true;
2248 }
2249 }
2250
2251 if (ToType->isSVESizelessBuiltinType() ||
2252 FromType->isSVESizelessBuiltinType())
2253 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2254 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2256 return true;
2257 }
2258
2259 if (ToType->isRVVSizelessBuiltinType() ||
2260 FromType->isRVVSizelessBuiltinType())
2261 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2262 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2264 return true;
2265 }
2266
2267 // We can perform the conversion between vector types in the following cases:
2268 // 1)vector types are equivalent AltiVec and GCC vector types
2269 // 2)lax vector conversions are permitted and the vector types are of the
2270 // same size
2271 // 3)the destination type does not have the ARM MVE strict-polymorphism
2272 // attribute, which inhibits lax vector conversion for overload resolution
2273 // only
2274 if (ToType->isVectorType() && FromType->isVectorType()) {
2275 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2276 (S.isLaxVectorConversion(FromType, ToType) &&
2277 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2278 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2279 S.isLaxVectorConversion(FromType, ToType) &&
2280 S.anyAltivecTypes(FromType, ToType) &&
2281 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2282 !InOverloadResolution && !CStyle) {
2283 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2284 << FromType << ToType;
2285 }
2287 return true;
2288 }
2289 }
2290
2291 return false;
2292}
2293
2294static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2295 bool InOverloadResolution,
2296 StandardConversionSequence &SCS,
2297 bool CStyle);
2298
2299/// IsStandardConversion - Determines whether there is a standard
2300/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2301/// expression From to the type ToType. Standard conversion sequences
2302/// only consider non-class types; for conversions that involve class
2303/// types, use TryImplicitConversion. If a conversion exists, SCS will
2304/// contain the standard conversion sequence required to perform this
2305/// conversion and this routine will return true. Otherwise, this
2306/// routine will return false and the value of SCS is unspecified.
2307static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2308 bool InOverloadResolution,
2310 bool CStyle,
2311 bool AllowObjCWritebackConversion) {
2312 QualType FromType = From->getType();
2313
2314 // Standard conversions (C++ [conv])
2316 SCS.IncompatibleObjC = false;
2317 SCS.setFromType(FromType);
2318 SCS.CopyConstructor = nullptr;
2319
2320 // There are no standard conversions for class types in C++, so
2321 // abort early. When overloading in C, however, we do permit them.
2322 if (S.getLangOpts().CPlusPlus &&
2323 (FromType->isRecordType() || ToType->isRecordType()))
2324 return false;
2325
2326 // The first conversion can be an lvalue-to-rvalue conversion,
2327 // array-to-pointer conversion, or function-to-pointer conversion
2328 // (C++ 4p1).
2329
2330 if (FromType == S.Context.OverloadTy) {
2331 DeclAccessPair AccessPair;
2332 if (FunctionDecl *Fn
2333 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2334 AccessPair)) {
2335 // We were able to resolve the address of the overloaded function,
2336 // so we can convert to the type of that function.
2337 FromType = Fn->getType();
2338 SCS.setFromType(FromType);
2339
2340 // we can sometimes resolve &foo<int> regardless of ToType, so check
2341 // if the type matches (identity) or we are converting to bool
2343 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2344 // if the function type matches except for [[noreturn]], it's ok
2345 if (!S.IsFunctionConversion(FromType,
2347 // otherwise, only a boolean conversion is standard
2348 if (!ToType->isBooleanType())
2349 return false;
2350 }
2351
2352 // Check if the "from" expression is taking the address of an overloaded
2353 // function and recompute the FromType accordingly. Take advantage of the
2354 // fact that non-static member functions *must* have such an address-of
2355 // expression.
2356 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2357 if (Method && !Method->isStatic() &&
2358 !Method->isExplicitObjectMemberFunction()) {
2359 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2360 "Non-unary operator on non-static member address");
2361 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2362 == UO_AddrOf &&
2363 "Non-address-of operator on non-static member address");
2364 FromType = S.Context.getMemberPointerType(
2365 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2366 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2367 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2368 UO_AddrOf &&
2369 "Non-address-of operator for overloaded function expression");
2370 FromType = S.Context.getPointerType(FromType);
2371 }
2372 } else {
2373 return false;
2374 }
2375 }
2376
2377 bool argIsLValue = From->isGLValue();
2378 // To handle conversion from ArrayParameterType to ConstantArrayType
2379 // this block must be above the one below because Array parameters
2380 // do not decay and when handling HLSLOutArgExprs and
2381 // the From expression is an LValue.
2382 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2383 ToType->isConstantArrayType()) {
2384 // HLSL constant array parameters do not decay, so if the argument is a
2385 // constant array and the parameter is an ArrayParameterType we have special
2386 // handling here.
2387 if (ToType->isArrayParameterType()) {
2388 FromType = S.Context.getArrayParameterType(FromType);
2389 } else if (FromType->isArrayParameterType()) {
2390 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2391 FromType = APT->getConstantArrayType(S.Context);
2392 }
2393
2395
2396 // Don't consider qualifiers, which include things like address spaces
2397 if (FromType.getCanonicalType().getUnqualifiedType() !=
2399 return false;
2400
2401 SCS.setAllToTypes(ToType);
2402 return true;
2403 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2404 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2405 // Lvalue-to-rvalue conversion (C++11 4.1):
2406 // A glvalue (3.10) of a non-function, non-array type T can
2407 // be converted to a prvalue.
2408
2410
2411 // C11 6.3.2.1p2:
2412 // ... if the lvalue has atomic type, the value has the non-atomic version
2413 // of the type of the lvalue ...
2414 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2415 FromType = Atomic->getValueType();
2416
2417 // If T is a non-class type, the type of the rvalue is the
2418 // cv-unqualified version of T. Otherwise, the type of the rvalue
2419 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2420 // just strip the qualifiers because they don't matter.
2421 FromType = FromType.getUnqualifiedType();
2422 } else if (FromType->isArrayType()) {
2423 // Array-to-pointer conversion (C++ 4.2)
2425
2426 // An lvalue or rvalue of type "array of N T" or "array of unknown
2427 // bound of T" can be converted to an rvalue of type "pointer to
2428 // T" (C++ 4.2p1).
2429 FromType = S.Context.getArrayDecayedType(FromType);
2430
2431 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2432 // This conversion is deprecated in C++03 (D.4)
2434
2435 // For the purpose of ranking in overload resolution
2436 // (13.3.3.1.1), this conversion is considered an
2437 // array-to-pointer conversion followed by a qualification
2438 // conversion (4.4). (C++ 4.2p2)
2439 SCS.Second = ICK_Identity;
2442 SCS.setAllToTypes(FromType);
2443 return true;
2444 }
2445 } else if (FromType->isFunctionType() && argIsLValue) {
2446 // Function-to-pointer conversion (C++ 4.3).
2448
2449 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2450 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2452 return false;
2453
2454 // An lvalue of function type T can be converted to an rvalue of
2455 // type "pointer to T." The result is a pointer to the
2456 // function. (C++ 4.3p1).
2457 FromType = S.Context.getPointerType(FromType);
2458 } else {
2459 // We don't require any conversions for the first step.
2460 SCS.First = ICK_Identity;
2461 }
2462 SCS.setToType(0, FromType);
2463
2464 // The second conversion can be an integral promotion, floating
2465 // point promotion, integral conversion, floating point conversion,
2466 // floating-integral conversion, pointer conversion,
2467 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2468 // For overloading in C, this can also be a "compatible-type"
2469 // conversion.
2470 bool IncompatibleObjC = false;
2472 ImplicitConversionKind DimensionICK = ICK_Identity;
2473 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2474 // The unqualified versions of the types are the same: there's no
2475 // conversion to do.
2476 SCS.Second = ICK_Identity;
2477 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2478 // Integral promotion (C++ 4.5).
2480 FromType = ToType.getUnqualifiedType();
2481 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2482 // Floating point promotion (C++ 4.6).
2484 FromType = ToType.getUnqualifiedType();
2485 } else if (S.IsComplexPromotion(FromType, ToType)) {
2486 // Complex promotion (Clang extension)
2488 FromType = ToType.getUnqualifiedType();
2489 } else if (ToType->isBooleanType() &&
2490 (FromType->isArithmeticType() ||
2491 FromType->isAnyPointerType() ||
2492 FromType->isBlockPointerType() ||
2493 FromType->isMemberPointerType())) {
2494 // Boolean conversions (C++ 4.12).
2496 FromType = S.Context.BoolTy;
2497 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2498 ToType->isIntegralType(S.Context)) {
2499 // Integral conversions (C++ 4.7).
2501 FromType = ToType.getUnqualifiedType();
2502 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2503 // Complex conversions (C99 6.3.1.6)
2505 FromType = ToType.getUnqualifiedType();
2506 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2507 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2508 // Complex-real conversions (C99 6.3.1.7)
2510 FromType = ToType.getUnqualifiedType();
2511 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2512 // Floating point conversions (C++ 4.8).
2514 FromType = ToType.getUnqualifiedType();
2515 } else if ((FromType->isRealFloatingType() &&
2516 ToType->isIntegralType(S.Context)) ||
2518 ToType->isRealFloatingType())) {
2519
2520 // Floating-integral conversions (C++ 4.9).
2522 FromType = ToType.getUnqualifiedType();
2523 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2525 } else if (AllowObjCWritebackConversion &&
2526 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2528 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2529 FromType, IncompatibleObjC)) {
2530 // Pointer conversions (C++ 4.10).
2532 SCS.IncompatibleObjC = IncompatibleObjC;
2533 FromType = FromType.getUnqualifiedType();
2534 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2535 InOverloadResolution, FromType)) {
2536 // Pointer to member conversions (4.11).
2538 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2539 From, InOverloadResolution, CStyle)) {
2540 SCS.Second = SecondICK;
2541 SCS.Dimension = DimensionICK;
2542 FromType = ToType.getUnqualifiedType();
2543 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2544 From, InOverloadResolution, CStyle)) {
2545 SCS.Second = SecondICK;
2546 SCS.Dimension = DimensionICK;
2547 FromType = ToType.getUnqualifiedType();
2548 } else if (!S.getLangOpts().CPlusPlus &&
2549 S.Context.typesAreCompatible(ToType, FromType)) {
2550 // Compatible conversions (Clang extension for C function overloading)
2552 FromType = ToType.getUnqualifiedType();
2554 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2556 FromType = ToType;
2557 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2558 CStyle)) {
2559 // tryAtomicConversion has updated the standard conversion sequence
2560 // appropriately.
2561 return true;
2562 } else if (ToType->isEventT() &&
2564 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2566 FromType = ToType;
2567 } else if (ToType->isQueueT() &&
2569 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2571 FromType = ToType;
2572 } else if (ToType->isSamplerT() &&
2575 FromType = ToType;
2576 } else if ((ToType->isFixedPointType() &&
2577 FromType->isConvertibleToFixedPointType()) ||
2578 (FromType->isFixedPointType() &&
2579 ToType->isConvertibleToFixedPointType())) {
2581 FromType = ToType;
2582 } else {
2583 // No second conversion required.
2584 SCS.Second = ICK_Identity;
2585 }
2586 SCS.setToType(1, FromType);
2587
2588 // The third conversion can be a function pointer conversion or a
2589 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2590 bool ObjCLifetimeConversion;
2591 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2592 // Function pointer conversions (removing 'noexcept') including removal of
2593 // 'noreturn' (Clang extension).
2595 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2596 ObjCLifetimeConversion)) {
2598 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2599 FromType = ToType;
2600 } else {
2601 // No conversion required
2602 SCS.Third = ICK_Identity;
2603 }
2604
2605 // C++ [over.best.ics]p6:
2606 // [...] Any difference in top-level cv-qualification is
2607 // subsumed by the initialization itself and does not constitute
2608 // a conversion. [...]
2609 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2610 QualType CanonTo = S.Context.getCanonicalType(ToType);
2611 if (CanonFrom.getLocalUnqualifiedType()
2612 == CanonTo.getLocalUnqualifiedType() &&
2613 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2614 FromType = ToType;
2615 CanonFrom = CanonTo;
2616 }
2617
2618 SCS.setToType(2, FromType);
2619
2620 if (CanonFrom == CanonTo)
2621 return true;
2622
2623 // If we have not converted the argument type to the parameter type,
2624 // this is a bad conversion sequence, unless we're resolving an overload in C.
2625 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2626 return false;
2627
2628 ExprResult ER = ExprResult{From};
2629 AssignConvertType Conv =
2631 /*Diagnose=*/false,
2632 /*DiagnoseCFAudited=*/false,
2633 /*ConvertRHS=*/false);
2634 ImplicitConversionKind SecondConv;
2635 switch (Conv) {
2637 case AssignConvertType::
2638 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2639 SecondConv = ICK_C_Only_Conversion;
2640 break;
2641 // For our purposes, discarding qualifiers is just as bad as using an
2642 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2643 // qualifiers, as well.
2648 break;
2649 default:
2650 return false;
2651 }
2652
2653 // First can only be an lvalue conversion, so we pretend that this was the
2654 // second conversion. First should already be valid from earlier in the
2655 // function.
2656 SCS.Second = SecondConv;
2657 SCS.setToType(1, ToType);
2658
2659 // Third is Identity, because Second should rank us worse than any other
2660 // conversion. This could also be ICK_Qualification, but it's simpler to just
2661 // lump everything in with the second conversion, and we don't gain anything
2662 // from making this ICK_Qualification.
2663 SCS.Third = ICK_Identity;
2664 SCS.setToType(2, ToType);
2665 return true;
2666}
2667
2668static bool
2670 QualType &ToType,
2671 bool InOverloadResolution,
2673 bool CStyle) {
2674
2675 const RecordType *UT = ToType->getAsUnionType();
2676 if (!UT)
2677 return false;
2678 // The field to initialize within the transparent union.
2679 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2680 if (!UD->hasAttr<TransparentUnionAttr>())
2681 return false;
2682 // It's compatible if the expression matches any of the fields.
2683 for (const auto *it : UD->fields()) {
2684 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2685 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2686 ToType = it->getType();
2687 return true;
2688 }
2689 }
2690 return false;
2691}
2692
2693bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2694 const BuiltinType *To = ToType->getAs<BuiltinType>();
2695 // All integers are built-in.
2696 if (!To) {
2697 return false;
2698 }
2699
2700 // An rvalue of type char, signed char, unsigned char, short int, or
2701 // unsigned short int can be converted to an rvalue of type int if
2702 // int can represent all the values of the source type; otherwise,
2703 // the source rvalue can be converted to an rvalue of type unsigned
2704 // int (C++ 4.5p1).
2705 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2706 !FromType->isEnumeralType()) {
2707 if ( // We can promote any signed, promotable integer type to an int
2708 (FromType->isSignedIntegerType() ||
2709 // We can promote any unsigned integer type whose size is
2710 // less than int to an int.
2711 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2712 return To->getKind() == BuiltinType::Int;
2713 }
2714
2715 return To->getKind() == BuiltinType::UInt;
2716 }
2717
2718 // C++11 [conv.prom]p3:
2719 // A prvalue of an unscoped enumeration type whose underlying type is not
2720 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2721 // following types that can represent all the values of the enumeration
2722 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2723 // unsigned int, long int, unsigned long int, long long int, or unsigned
2724 // long long int. If none of the types in that list can represent all the
2725 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2726 // type can be converted to an rvalue a prvalue of the extended integer type
2727 // with lowest integer conversion rank (4.13) greater than the rank of long
2728 // long in which all the values of the enumeration can be represented. If
2729 // there are two such extended types, the signed one is chosen.
2730 // C++11 [conv.prom]p4:
2731 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2732 // can be converted to a prvalue of its underlying type. Moreover, if
2733 // integral promotion can be applied to its underlying type, a prvalue of an
2734 // unscoped enumeration type whose underlying type is fixed can also be
2735 // converted to a prvalue of the promoted underlying type.
2736 if (const auto *FromED = FromType->getAsEnumDecl()) {
2737 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2738 // provided for a scoped enumeration.
2739 if (FromED->isScoped())
2740 return false;
2741
2742 // We can perform an integral promotion to the underlying type of the enum,
2743 // even if that's not the promoted type. Note that the check for promoting
2744 // the underlying type is based on the type alone, and does not consider
2745 // the bitfield-ness of the actual source expression.
2746 if (FromED->isFixed()) {
2747 QualType Underlying = FromED->getIntegerType();
2748 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2749 IsIntegralPromotion(nullptr, Underlying, ToType);
2750 }
2751
2752 // We have already pre-calculated the promotion type, so this is trivial.
2753 if (ToType->isIntegerType() &&
2754 isCompleteType(From->getBeginLoc(), FromType))
2755 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2756
2757 // C++ [conv.prom]p5:
2758 // If the bit-field has an enumerated type, it is treated as any other
2759 // value of that type for promotion purposes.
2760 //
2761 // ... so do not fall through into the bit-field checks below in C++.
2762 if (getLangOpts().CPlusPlus)
2763 return false;
2764 }
2765
2766 // C++0x [conv.prom]p2:
2767 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2768 // to an rvalue a prvalue of the first of the following types that can
2769 // represent all the values of its underlying type: int, unsigned int,
2770 // long int, unsigned long int, long long int, or unsigned long long int.
2771 // If none of the types in that list can represent all the values of its
2772 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2773 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2774 // type.
2775 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2776 ToType->isIntegerType()) {
2777 // Determine whether the type we're converting from is signed or
2778 // unsigned.
2779 bool FromIsSigned = FromType->isSignedIntegerType();
2780 uint64_t FromSize = Context.getTypeSize(FromType);
2781
2782 // The types we'll try to promote to, in the appropriate
2783 // order. Try each of these types.
2784 QualType PromoteTypes[6] = {
2785 Context.IntTy, Context.UnsignedIntTy,
2786 Context.LongTy, Context.UnsignedLongTy ,
2787 Context.LongLongTy, Context.UnsignedLongLongTy
2788 };
2789 for (int Idx = 0; Idx < 6; ++Idx) {
2790 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2791 if (FromSize < ToSize ||
2792 (FromSize == ToSize &&
2793 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2794 // We found the type that we can promote to. If this is the
2795 // type we wanted, we have a promotion. Otherwise, no
2796 // promotion.
2797 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2798 }
2799 }
2800 }
2801
2802 // An rvalue for an integral bit-field (9.6) can be converted to an
2803 // rvalue of type int if int can represent all the values of the
2804 // bit-field; otherwise, it can be converted to unsigned int if
2805 // unsigned int can represent all the values of the bit-field. If
2806 // the bit-field is larger yet, no integral promotion applies to
2807 // it. If the bit-field has an enumerated type, it is treated as any
2808 // other value of that type for promotion purposes (C++ 4.5p3).
2809 // FIXME: We should delay checking of bit-fields until we actually perform the
2810 // conversion.
2811 //
2812 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2813 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2814 // bit-fields and those whose underlying type is larger than int) for GCC
2815 // compatibility.
2816 if (From) {
2817 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2818 std::optional<llvm::APSInt> BitWidth;
2819 if (FromType->isIntegralType(Context) &&
2820 (BitWidth =
2821 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2822 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2823 ToSize = Context.getTypeSize(ToType);
2824
2825 // Are we promoting to an int from a bitfield that fits in an int?
2826 if (*BitWidth < ToSize ||
2827 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2828 return To->getKind() == BuiltinType::Int;
2829 }
2830
2831 // Are we promoting to an unsigned int from an unsigned bitfield
2832 // that fits into an unsigned int?
2833 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2834 return To->getKind() == BuiltinType::UInt;
2835 }
2836
2837 return false;
2838 }
2839 }
2840 }
2841
2842 // An rvalue of type bool can be converted to an rvalue of type int,
2843 // with false becoming zero and true becoming one (C++ 4.5p4).
2844 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2845 return true;
2846 }
2847
2848 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2849 // integral type.
2850 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2851 ToType->isIntegerType())
2852 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2853
2854 return false;
2855}
2856
2858 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2859 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2860 /// An rvalue of type float can be converted to an rvalue of type
2861 /// double. (C++ 4.6p1).
2862 if (FromBuiltin->getKind() == BuiltinType::Float &&
2863 ToBuiltin->getKind() == BuiltinType::Double)
2864 return true;
2865
2866 // C99 6.3.1.5p1:
2867 // When a float is promoted to double or long double, or a
2868 // double is promoted to long double [...].
2869 if (!getLangOpts().CPlusPlus &&
2870 (FromBuiltin->getKind() == BuiltinType::Float ||
2871 FromBuiltin->getKind() == BuiltinType::Double) &&
2872 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2873 ToBuiltin->getKind() == BuiltinType::Float128 ||
2874 ToBuiltin->getKind() == BuiltinType::Ibm128))
2875 return true;
2876
2877 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2878 // or not native half types are enabled.
2879 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2880 (ToBuiltin->getKind() == BuiltinType::Float ||
2881 ToBuiltin->getKind() == BuiltinType::Double))
2882 return true;
2883
2884 // Half can be promoted to float.
2885 if (!getLangOpts().NativeHalfType &&
2886 FromBuiltin->getKind() == BuiltinType::Half &&
2887 ToBuiltin->getKind() == BuiltinType::Float)
2888 return true;
2889 }
2890
2891 return false;
2892}
2893
2895 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2896 if (!FromComplex)
2897 return false;
2898
2899 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2900 if (!ToComplex)
2901 return false;
2902
2903 return IsFloatingPointPromotion(FromComplex->getElementType(),
2904 ToComplex->getElementType()) ||
2905 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2906 ToComplex->getElementType());
2907}
2908
2909/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2910/// the pointer type FromPtr to a pointer to type ToPointee, with the
2911/// same type qualifiers as FromPtr has on its pointee type. ToType,
2912/// if non-empty, will be a pointer to ToType that may or may not have
2913/// the right set of qualifiers on its pointee.
2914///
2915static QualType
2917 QualType ToPointee, QualType ToType,
2918 ASTContext &Context,
2919 bool StripObjCLifetime = false) {
2920 assert((FromPtr->getTypeClass() == Type::Pointer ||
2921 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2922 "Invalid similarly-qualified pointer type");
2923
2924 /// Conversions to 'id' subsume cv-qualifier conversions.
2925 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2926 return ToType.getUnqualifiedType();
2927
2928 QualType CanonFromPointee
2929 = Context.getCanonicalType(FromPtr->getPointeeType());
2930 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2931 Qualifiers Quals = CanonFromPointee.getQualifiers();
2932
2933 if (StripObjCLifetime)
2934 Quals.removeObjCLifetime();
2935
2936 // Exact qualifier match -> return the pointer type we're converting to.
2937 if (CanonToPointee.getLocalQualifiers() == Quals) {
2938 // ToType is exactly what we need. Return it.
2939 if (!ToType.isNull())
2940 return ToType.getUnqualifiedType();
2941
2942 // Build a pointer to ToPointee. It has the right qualifiers
2943 // already.
2944 if (isa<ObjCObjectPointerType>(ToType))
2945 return Context.getObjCObjectPointerType(ToPointee);
2946 return Context.getPointerType(ToPointee);
2947 }
2948
2949 // Just build a canonical type that has the right qualifiers.
2950 QualType QualifiedCanonToPointee
2951 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2952
2953 if (isa<ObjCObjectPointerType>(ToType))
2954 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2955 return Context.getPointerType(QualifiedCanonToPointee);
2956}
2957
2959 bool InOverloadResolution,
2960 ASTContext &Context) {
2961 // Handle value-dependent integral null pointer constants correctly.
2962 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2963 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2965 return !InOverloadResolution;
2966
2967 return Expr->isNullPointerConstant(Context,
2968 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2970}
2971
2973 bool InOverloadResolution,
2974 QualType& ConvertedType,
2975 bool &IncompatibleObjC) {
2976 IncompatibleObjC = false;
2977 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2978 IncompatibleObjC))
2979 return true;
2980
2981 // Conversion from a null pointer constant to any Objective-C pointer type.
2982 if (ToType->isObjCObjectPointerType() &&
2983 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2984 ConvertedType = ToType;
2985 return true;
2986 }
2987
2988 // Blocks: Block pointers can be converted to void*.
2989 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2990 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2991 ConvertedType = ToType;
2992 return true;
2993 }
2994 // Blocks: A null pointer constant can be converted to a block
2995 // pointer type.
2996 if (ToType->isBlockPointerType() &&
2997 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2998 ConvertedType = ToType;
2999 return true;
3000 }
3001
3002 // If the left-hand-side is nullptr_t, the right side can be a null
3003 // pointer constant.
3004 if (ToType->isNullPtrType() &&
3005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3006 ConvertedType = ToType;
3007 return true;
3008 }
3009
3010 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3011 if (!ToTypePtr)
3012 return false;
3013
3014 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3015 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3016 ConvertedType = ToType;
3017 return true;
3018 }
3019
3020 // Beyond this point, both types need to be pointers
3021 // , including objective-c pointers.
3022 QualType ToPointeeType = ToTypePtr->getPointeeType();
3023 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3024 !getLangOpts().ObjCAutoRefCount) {
3025 ConvertedType = BuildSimilarlyQualifiedPointerType(
3026 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3027 Context);
3028 return true;
3029 }
3030 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3031 if (!FromTypePtr)
3032 return false;
3033
3034 QualType FromPointeeType = FromTypePtr->getPointeeType();
3035
3036 // If the unqualified pointee types are the same, this can't be a
3037 // pointer conversion, so don't do all of the work below.
3038 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3039 return false;
3040
3041 // An rvalue of type "pointer to cv T," where T is an object type,
3042 // can be converted to an rvalue of type "pointer to cv void" (C++
3043 // 4.10p2).
3044 if (FromPointeeType->isIncompleteOrObjectType() &&
3045 ToPointeeType->isVoidType()) {
3046 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3047 ToPointeeType,
3048 ToType, Context,
3049 /*StripObjCLifetime=*/true);
3050 return true;
3051 }
3052
3053 // MSVC allows implicit function to void* type conversion.
3054 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3055 ToPointeeType->isVoidType()) {
3056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3057 ToPointeeType,
3058 ToType, Context);
3059 return true;
3060 }
3061
3062 // When we're overloading in C, we allow a special kind of pointer
3063 // conversion for compatible-but-not-identical pointee types.
3064 if (!getLangOpts().CPlusPlus &&
3065 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3067 ToPointeeType,
3068 ToType, Context);
3069 return true;
3070 }
3071
3072 // C++ [conv.ptr]p3:
3073 //
3074 // An rvalue of type "pointer to cv D," where D is a class type,
3075 // can be converted to an rvalue of type "pointer to cv B," where
3076 // B is a base class (clause 10) of D. If B is an inaccessible
3077 // (clause 11) or ambiguous (10.2) base class of D, a program that
3078 // necessitates this conversion is ill-formed. The result of the
3079 // conversion is a pointer to the base class sub-object of the
3080 // derived class object. The null pointer value is converted to
3081 // the null pointer value of the destination type.
3082 //
3083 // Note that we do not check for ambiguity or inaccessibility
3084 // here. That is handled by CheckPointerConversion.
3085 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3086 ToPointeeType->isRecordType() &&
3087 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3088 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3089 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3090 ToPointeeType,
3091 ToType, Context);
3092 return true;
3093 }
3094
3095 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3096 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3098 ToPointeeType,
3099 ToType, Context);
3100 return true;
3101 }
3102
3103 return false;
3104}
3105
3106/// Adopt the given qualifiers for the given type.
3108 Qualifiers TQs = T.getQualifiers();
3109
3110 // Check whether qualifiers already match.
3111 if (TQs == Qs)
3112 return T;
3113
3114 if (Qs.compatiblyIncludes(TQs, Context))
3115 return Context.getQualifiedType(T, Qs);
3116
3117 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3118}
3119
3121 QualType& ConvertedType,
3122 bool &IncompatibleObjC) {
3123 if (!getLangOpts().ObjC)
3124 return false;
3125
3126 // The set of qualifiers on the type we're converting from.
3127 Qualifiers FromQualifiers = FromType.getQualifiers();
3128
3129 // First, we handle all conversions on ObjC object pointer types.
3130 const ObjCObjectPointerType* ToObjCPtr =
3131 ToType->getAs<ObjCObjectPointerType>();
3132 const ObjCObjectPointerType *FromObjCPtr =
3133 FromType->getAs<ObjCObjectPointerType>();
3134
3135 if (ToObjCPtr && FromObjCPtr) {
3136 // If the pointee types are the same (ignoring qualifications),
3137 // then this is not a pointer conversion.
3138 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3139 FromObjCPtr->getPointeeType()))
3140 return false;
3141
3142 // Conversion between Objective-C pointers.
3143 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3144 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3145 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3146 if (getLangOpts().CPlusPlus && LHS && RHS &&
3148 FromObjCPtr->getPointeeType(), getASTContext()))
3149 return false;
3150 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3151 ToObjCPtr->getPointeeType(),
3152 ToType, Context);
3153 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3154 return true;
3155 }
3156
3157 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3158 // Okay: this is some kind of implicit downcast of Objective-C
3159 // interfaces, which is permitted. However, we're going to
3160 // complain about it.
3161 IncompatibleObjC = true;
3162 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3163 ToObjCPtr->getPointeeType(),
3164 ToType, Context);
3165 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3166 return true;
3167 }
3168 }
3169 // Beyond this point, both types need to be C pointers or block pointers.
3170 QualType ToPointeeType;
3171 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3172 ToPointeeType = ToCPtr->getPointeeType();
3173 else if (const BlockPointerType *ToBlockPtr =
3174 ToType->getAs<BlockPointerType>()) {
3175 // Objective C++: We're able to convert from a pointer to any object
3176 // to a block pointer type.
3177 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3178 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3179 return true;
3180 }
3181 ToPointeeType = ToBlockPtr->getPointeeType();
3182 }
3183 else if (FromType->getAs<BlockPointerType>() &&
3184 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3185 // Objective C++: We're able to convert from a block pointer type to a
3186 // pointer to any object.
3187 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3188 return true;
3189 }
3190 else
3191 return false;
3192
3193 QualType FromPointeeType;
3194 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3195 FromPointeeType = FromCPtr->getPointeeType();
3196 else if (const BlockPointerType *FromBlockPtr =
3197 FromType->getAs<BlockPointerType>())
3198 FromPointeeType = FromBlockPtr->getPointeeType();
3199 else
3200 return false;
3201
3202 // If we have pointers to pointers, recursively check whether this
3203 // is an Objective-C conversion.
3204 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3205 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3206 IncompatibleObjC)) {
3207 // We always complain about this conversion.
3208 IncompatibleObjC = true;
3209 ConvertedType = Context.getPointerType(ConvertedType);
3210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3211 return true;
3212 }
3213 // Allow conversion of pointee being objective-c pointer to another one;
3214 // as in I* to id.
3215 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3216 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3217 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3218 IncompatibleObjC)) {
3219
3220 ConvertedType = Context.getPointerType(ConvertedType);
3221 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3222 return true;
3223 }
3224
3225 // If we have pointers to functions or blocks, check whether the only
3226 // differences in the argument and result types are in Objective-C
3227 // pointer conversions. If so, we permit the conversion (but
3228 // complain about it).
3229 const FunctionProtoType *FromFunctionType
3230 = FromPointeeType->getAs<FunctionProtoType>();
3231 const FunctionProtoType *ToFunctionType
3232 = ToPointeeType->getAs<FunctionProtoType>();
3233 if (FromFunctionType && ToFunctionType) {
3234 // If the function types are exactly the same, this isn't an
3235 // Objective-C pointer conversion.
3236 if (Context.getCanonicalType(FromPointeeType)
3237 == Context.getCanonicalType(ToPointeeType))
3238 return false;
3239
3240 // Perform the quick checks that will tell us whether these
3241 // function types are obviously different.
3242 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3243 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3244 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3245 return false;
3246
3247 bool HasObjCConversion = false;
3248 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3249 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3250 // Okay, the types match exactly. Nothing to do.
3251 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3252 ToFunctionType->getReturnType(),
3253 ConvertedType, IncompatibleObjC)) {
3254 // Okay, we have an Objective-C pointer conversion.
3255 HasObjCConversion = true;
3256 } else {
3257 // Function types are too different. Abort.
3258 return false;
3259 }
3260
3261 // Check argument types.
3262 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3263 ArgIdx != NumArgs; ++ArgIdx) {
3264 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3265 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3266 if (Context.getCanonicalType(FromArgType)
3267 == Context.getCanonicalType(ToArgType)) {
3268 // Okay, the types match exactly. Nothing to do.
3269 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3270 ConvertedType, IncompatibleObjC)) {
3271 // Okay, we have an Objective-C pointer conversion.
3272 HasObjCConversion = true;
3273 } else {
3274 // Argument types are too different. Abort.
3275 return false;
3276 }
3277 }
3278
3279 if (HasObjCConversion) {
3280 // We had an Objective-C conversion. Allow this pointer
3281 // conversion, but complain about it.
3282 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3283 IncompatibleObjC = true;
3284 return true;
3285 }
3286 }
3287
3288 return false;
3289}
3290
3292 QualType& ConvertedType) {
3293 QualType ToPointeeType;
3294 if (const BlockPointerType *ToBlockPtr =
3295 ToType->getAs<BlockPointerType>())
3296 ToPointeeType = ToBlockPtr->getPointeeType();
3297 else
3298 return false;
3299
3300 QualType FromPointeeType;
3301 if (const BlockPointerType *FromBlockPtr =
3302 FromType->getAs<BlockPointerType>())
3303 FromPointeeType = FromBlockPtr->getPointeeType();
3304 else
3305 return false;
3306 // We have pointer to blocks, check whether the only
3307 // differences in the argument and result types are in Objective-C
3308 // pointer conversions. If so, we permit the conversion.
3309
3310 const FunctionProtoType *FromFunctionType
3311 = FromPointeeType->getAs<FunctionProtoType>();
3312 const FunctionProtoType *ToFunctionType
3313 = ToPointeeType->getAs<FunctionProtoType>();
3314
3315 if (!FromFunctionType || !ToFunctionType)
3316 return false;
3317
3318 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3319 return true;
3320
3321 // Perform the quick checks that will tell us whether these
3322 // function types are obviously different.
3323 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3324 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3325 return false;
3326
3327 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3328 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3329 if (FromEInfo != ToEInfo)
3330 return false;
3331
3332 bool IncompatibleObjC = false;
3333 if (Context.hasSameType(FromFunctionType->getReturnType(),
3334 ToFunctionType->getReturnType())) {
3335 // Okay, the types match exactly. Nothing to do.
3336 } else {
3337 QualType RHS = FromFunctionType->getReturnType();
3338 QualType LHS = ToFunctionType->getReturnType();
3339 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3340 !RHS.hasQualifiers() && LHS.hasQualifiers())
3341 LHS = LHS.getUnqualifiedType();
3342
3343 if (Context.hasSameType(RHS,LHS)) {
3344 // OK exact match.
3345 } else if (isObjCPointerConversion(RHS, LHS,
3346 ConvertedType, IncompatibleObjC)) {
3347 if (IncompatibleObjC)
3348 return false;
3349 // Okay, we have an Objective-C pointer conversion.
3350 }
3351 else
3352 return false;
3353 }
3354
3355 // Check argument types.
3356 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3357 ArgIdx != NumArgs; ++ArgIdx) {
3358 IncompatibleObjC = false;
3359 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3360 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3361 if (Context.hasSameType(FromArgType, ToArgType)) {
3362 // Okay, the types match exactly. Nothing to do.
3363 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3364 ConvertedType, IncompatibleObjC)) {
3365 if (IncompatibleObjC)
3366 return false;
3367 // Okay, we have an Objective-C pointer conversion.
3368 } else
3369 // Argument types are too different. Abort.
3370 return false;
3371 }
3372
3374 bool CanUseToFPT, CanUseFromFPT;
3375 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3376 CanUseToFPT, CanUseFromFPT,
3377 NewParamInfos))
3378 return false;
3379
3380 ConvertedType = ToType;
3381 return true;
3382}
3383
3384enum {
3392};
3393
3394/// Attempts to get the FunctionProtoType from a Type. Handles
3395/// MemberFunctionPointers properly.
3397 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3398 return FPT;
3399
3400 if (auto *MPT = FromType->getAs<MemberPointerType>())
3401 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3402
3403 return nullptr;
3404}
3405
3407 QualType FromType, QualType ToType) {
3408 // If either type is not valid, include no extra info.
3409 if (FromType.isNull() || ToType.isNull()) {
3410 PDiag << ft_default;
3411 return;
3412 }
3413
3414 // Get the function type from the pointers.
3415 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3416 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3417 *ToMember = ToType->castAs<MemberPointerType>();
3418 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3419 ToMember->getMostRecentCXXRecordDecl())) {
3421 if (ToMember->isSugared())
3422 PDiag << Context.getCanonicalTagType(
3423 ToMember->getMostRecentCXXRecordDecl());
3424 else
3425 PDiag << ToMember->getQualifier();
3426 if (FromMember->isSugared())
3427 PDiag << Context.getCanonicalTagType(
3428 FromMember->getMostRecentCXXRecordDecl());
3429 else
3430 PDiag << FromMember->getQualifier();
3431 return;
3432 }
3433 FromType = FromMember->getPointeeType();
3434 ToType = ToMember->getPointeeType();
3435 }
3436
3437 if (FromType->isPointerType())
3438 FromType = FromType->getPointeeType();
3439 if (ToType->isPointerType())
3440 ToType = ToType->getPointeeType();
3441
3442 // Remove references.
3443 FromType = FromType.getNonReferenceType();
3444 ToType = ToType.getNonReferenceType();
3445
3446 // Don't print extra info for non-specialized template functions.
3447 if (FromType->isInstantiationDependentType() &&
3448 !FromType->getAs<TemplateSpecializationType>()) {
3449 PDiag << ft_default;
3450 return;
3451 }
3452
3453 // No extra info for same types.
3454 if (Context.hasSameType(FromType, ToType)) {
3455 PDiag << ft_default;
3456 return;
3457 }
3458
3459 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3460 *ToFunction = tryGetFunctionProtoType(ToType);
3461
3462 // Both types need to be function types.
3463 if (!FromFunction || !ToFunction) {
3464 PDiag << ft_default;
3465 return;
3466 }
3467
3468 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3469 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3470 << FromFunction->getNumParams();
3471 return;
3472 }
3473
3474 // Handle different parameter types.
3475 unsigned ArgPos;
3476 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3477 PDiag << ft_parameter_mismatch << ArgPos + 1
3478 << ToFunction->getParamType(ArgPos)
3479 << FromFunction->getParamType(ArgPos);
3480 return;
3481 }
3482
3483 // Handle different return type.
3484 if (!Context.hasSameType(FromFunction->getReturnType(),
3485 ToFunction->getReturnType())) {
3486 PDiag << ft_return_type << ToFunction->getReturnType()
3487 << FromFunction->getReturnType();
3488 return;
3489 }
3490
3491 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3492 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3493 << FromFunction->getMethodQuals();
3494 return;
3495 }
3496
3497 // Handle exception specification differences on canonical type (in C++17
3498 // onwards).
3500 ->isNothrow() !=
3501 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3502 ->isNothrow()) {
3503 PDiag << ft_noexcept;
3504 return;
3505 }
3506
3507 // Unable to find a difference, so add no extra info.
3508 PDiag << ft_default;
3509}
3510
3512 ArrayRef<QualType> New, unsigned *ArgPos,
3513 bool Reversed) {
3514 assert(llvm::size(Old) == llvm::size(New) &&
3515 "Can't compare parameters of functions with different number of "
3516 "parameters!");
3517
3518 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3519 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3520 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3521
3522 // Ignore address spaces in pointee type. This is to disallow overloading
3523 // on __ptr32/__ptr64 address spaces.
3524 QualType OldType =
3525 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3526 QualType NewType =
3527 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3528
3529 if (!Context.hasSameType(OldType, NewType)) {
3530 if (ArgPos)
3531 *ArgPos = Idx;
3532 return false;
3533 }
3534 }
3535 return true;
3536}
3537
3539 const FunctionProtoType *NewType,
3540 unsigned *ArgPos, bool Reversed) {
3541 return FunctionParamTypesAreEqual(OldType->param_types(),
3542 NewType->param_types(), ArgPos, Reversed);
3543}
3544
3546 const FunctionDecl *NewFunction,
3547 unsigned *ArgPos,
3548 bool Reversed) {
3549
3550 if (OldFunction->getNumNonObjectParams() !=
3551 NewFunction->getNumNonObjectParams())
3552 return false;
3553
3554 unsigned OldIgnore =
3556 unsigned NewIgnore =
3558
3559 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3560 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3561
3562 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3563 NewPT->param_types().slice(NewIgnore),
3564 ArgPos, Reversed);
3565}
3566
3568 CastKind &Kind,
3569 CXXCastPath& BasePath,
3570 bool IgnoreBaseAccess,
3571 bool Diagnose) {
3572 QualType FromType = From->getType();
3573 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3574
3575 Kind = CK_BitCast;
3576
3577 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3580 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3581 DiagRuntimeBehavior(From->getExprLoc(), From,
3582 PDiag(diag::warn_impcast_bool_to_null_pointer)
3583 << ToType << From->getSourceRange());
3584 else if (!isUnevaluatedContext())
3585 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3586 << ToType << From->getSourceRange();
3587 }
3588 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3589 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3590 QualType FromPointeeType = FromPtrType->getPointeeType(),
3591 ToPointeeType = ToPtrType->getPointeeType();
3592
3593 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3594 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3595 // We must have a derived-to-base conversion. Check an
3596 // ambiguous or inaccessible conversion.
3597 unsigned InaccessibleID = 0;
3598 unsigned AmbiguousID = 0;
3599 if (Diagnose) {
3600 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3601 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3602 }
3604 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3605 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3606 &BasePath, IgnoreBaseAccess))
3607 return true;
3608
3609 // The conversion was successful.
3610 Kind = CK_DerivedToBase;
3611 }
3612
3613 if (Diagnose && !IsCStyleOrFunctionalCast &&
3614 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3615 assert(getLangOpts().MSVCCompat &&
3616 "this should only be possible with MSVCCompat!");
3617 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3618 << From->getSourceRange();
3619 }
3620 }
3621 } else if (const ObjCObjectPointerType *ToPtrType =
3622 ToType->getAs<ObjCObjectPointerType>()) {
3623 if (const ObjCObjectPointerType *FromPtrType =
3624 FromType->getAs<ObjCObjectPointerType>()) {
3625 // Objective-C++ conversions are always okay.
3626 // FIXME: We should have a different class of conversions for the
3627 // Objective-C++ implicit conversions.
3628 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3629 return false;
3630 } else if (FromType->isBlockPointerType()) {
3631 Kind = CK_BlockPointerToObjCPointerCast;
3632 } else {
3633 Kind = CK_CPointerToObjCPointerCast;
3634 }
3635 } else if (ToType->isBlockPointerType()) {
3636 if (!FromType->isBlockPointerType())
3637 Kind = CK_AnyPointerToBlockPointerCast;
3638 }
3639
3640 // We shouldn't fall into this case unless it's valid for other
3641 // reasons.
3643 Kind = CK_NullToPointer;
3644
3645 return false;
3646}
3647
3649 QualType ToType,
3650 bool InOverloadResolution,
3651 QualType &ConvertedType) {
3652 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3653 if (!ToTypePtr)
3654 return false;
3655
3656 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3658 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3660 ConvertedType = ToType;
3661 return true;
3662 }
3663
3664 // Otherwise, both types have to be member pointers.
3665 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3666 if (!FromTypePtr)
3667 return false;
3668
3669 // A pointer to member of B can be converted to a pointer to member of D,
3670 // where D is derived from B (C++ 4.11p2).
3671 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3672 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3673
3674 if (!declaresSameEntity(FromClass, ToClass) &&
3675 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3676 ConvertedType = Context.getMemberPointerType(
3677 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3678 return true;
3679 }
3680
3681 return false;
3682}
3683
3685 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3686 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3687 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3688 // Lock down the inheritance model right now in MS ABI, whether or not the
3689 // pointee types are the same.
3690 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3691 (void)isCompleteType(CheckLoc, FromType);
3692 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3693 }
3694
3695 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3696 if (!FromPtrType) {
3697 // This must be a null pointer to member pointer conversion
3698 Kind = CK_NullToMemberPointer;
3700 }
3701
3702 // T == T, modulo cv
3704 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3705 ToPtrType->getPointeeType()))
3707
3708 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3709 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3710
3711 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3712 const CXXRecordDecl *Cls) {
3713 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3714 PD << Qual;
3715 else
3716 PD << Context.getCanonicalTagType(Cls);
3717 };
3718 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3719 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3720 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3721 return PD;
3722 };
3723
3724 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3726 std::swap(Base, Derived);
3727
3728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3729 /*DetectVirtual=*/true);
3730 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3732
3733 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3734 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3735 PD << int(Direction);
3736 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3737 Diag(CheckLoc, PD);
3739 }
3740
3741 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3742 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3743 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3744 Diag(CheckLoc, PD);
3746 }
3747
3748 // Must be a base to derived member conversion.
3749 BuildBasePathArray(Paths, BasePath);
3751 ? CK_DerivedToBaseMemberPointer
3752 : CK_BaseToDerivedMemberPointer;
3753
3754 if (!IgnoreBaseAccess)
3755 switch (CheckBaseClassAccess(
3756 CheckLoc, Base, Derived, Paths.front(),
3758 ? diag::err_upcast_to_inaccessible_base
3759 : diag::err_downcast_from_inaccessible_base,
3760 [&](PartialDiagnostic &PD) {
3761 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3762 DerivedQual = ToPtrType->getQualifier();
3763 if (Direction == MemberPointerConversionDirection::Upcast)
3764 std::swap(BaseQual, DerivedQual);
3765 DiagCls(PD, DerivedQual, Derived);
3766 DiagCls(PD, BaseQual, Base);
3767 })) {
3769 case Sema::AR_delayed:
3770 case Sema::AR_dependent:
3771 // Optimistically assume that the delayed and dependent cases
3772 // will work out.
3773 break;
3774
3777 }
3778
3780}
3781
3782/// Determine whether the lifetime conversion between the two given
3783/// qualifiers sets is nontrivial.
3785 Qualifiers ToQuals) {
3786 // Converting anything to const __unsafe_unretained is trivial.
3787 if (ToQuals.hasConst() &&
3789 return false;
3790
3791 return true;
3792}
3793
3794/// Perform a single iteration of the loop for checking if a qualification
3795/// conversion is valid.
3796///
3797/// Specifically, check whether any change between the qualifiers of \p
3798/// FromType and \p ToType is permissible, given knowledge about whether every
3799/// outer layer is const-qualified.
3801 bool CStyle, bool IsTopLevel,
3802 bool &PreviousToQualsIncludeConst,
3803 bool &ObjCLifetimeConversion,
3804 const ASTContext &Ctx) {
3805 Qualifiers FromQuals = FromType.getQualifiers();
3806 Qualifiers ToQuals = ToType.getQualifiers();
3807
3808 // Ignore __unaligned qualifier.
3809 FromQuals.removeUnaligned();
3810
3811 // Objective-C ARC:
3812 // Check Objective-C lifetime conversions.
3813 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3814 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3815 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3816 ObjCLifetimeConversion = true;
3817 FromQuals.removeObjCLifetime();
3818 ToQuals.removeObjCLifetime();
3819 } else {
3820 // Qualification conversions cannot cast between different
3821 // Objective-C lifetime qualifiers.
3822 return false;
3823 }
3824 }
3825
3826 // Allow addition/removal of GC attributes but not changing GC attributes.
3827 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3828 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3829 FromQuals.removeObjCGCAttr();
3830 ToQuals.removeObjCGCAttr();
3831 }
3832
3833 // __ptrauth qualifiers must match exactly.
3834 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3835 return false;
3836
3837 // -- for every j > 0, if const is in cv 1,j then const is in cv
3838 // 2,j, and similarly for volatile.
3839 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3840 return false;
3841
3842 // If address spaces mismatch:
3843 // - in top level it is only valid to convert to addr space that is a
3844 // superset in all cases apart from C-style casts where we allow
3845 // conversions between overlapping address spaces.
3846 // - in non-top levels it is not a valid conversion.
3847 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3848 (!IsTopLevel ||
3849 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3850 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3851 return false;
3852
3853 // -- if the cv 1,j and cv 2,j are different, then const is in
3854 // every cv for 0 < k < j.
3855 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3856 !PreviousToQualsIncludeConst)
3857 return false;
3858
3859 // The following wording is from C++20, where the result of the conversion
3860 // is T3, not T2.
3861 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3862 // "array of unknown bound of"
3863 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3864 return false;
3865
3866 // -- if the resulting P3,i is different from P1,i [...], then const is
3867 // added to every cv 3_k for 0 < k < i.
3868 if (!CStyle && FromType->isConstantArrayType() &&
3869 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3870 return false;
3871
3872 // Keep track of whether all prior cv-qualifiers in the "to" type
3873 // include const.
3874 PreviousToQualsIncludeConst =
3875 PreviousToQualsIncludeConst && ToQuals.hasConst();
3876 return true;
3877}
3878
3879bool
3881 bool CStyle, bool &ObjCLifetimeConversion) {
3882 FromType = Context.getCanonicalType(FromType);
3883 ToType = Context.getCanonicalType(ToType);
3884 ObjCLifetimeConversion = false;
3885
3886 // If FromType and ToType are the same type, this is not a
3887 // qualification conversion.
3888 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3889 return false;
3890
3891 // (C++ 4.4p4):
3892 // A conversion can add cv-qualifiers at levels other than the first
3893 // in multi-level pointers, subject to the following rules: [...]
3894 bool PreviousToQualsIncludeConst = true;
3895 bool UnwrappedAnyPointer = false;
3896 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3897 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3898 !UnwrappedAnyPointer,
3899 PreviousToQualsIncludeConst,
3900 ObjCLifetimeConversion, getASTContext()))
3901 return false;
3902 UnwrappedAnyPointer = true;
3903 }
3904
3905 // We are left with FromType and ToType being the pointee types
3906 // after unwrapping the original FromType and ToType the same number
3907 // of times. If we unwrapped any pointers, and if FromType and
3908 // ToType have the same unqualified type (since we checked
3909 // qualifiers above), then this is a qualification conversion.
3910 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3911}
3912
3913/// - Determine whether this is a conversion from a scalar type to an
3914/// atomic type.
3915///
3916/// If successful, updates \c SCS's second and third steps in the conversion
3917/// sequence to finish the conversion.
3918static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3919 bool InOverloadResolution,
3921 bool CStyle) {
3922 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3923 if (!ToAtomic)
3924 return false;
3925
3927 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3928 InOverloadResolution, InnerSCS,
3929 CStyle, /*AllowObjCWritebackConversion=*/false))
3930 return false;
3931
3932 SCS.Second = InnerSCS.Second;
3933 SCS.setToType(1, InnerSCS.getToType(1));
3934 SCS.Third = InnerSCS.Third;
3937 SCS.setToType(2, InnerSCS.getToType(2));
3938 return true;
3939}
3940
3943 QualType Type) {
3944 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3945 if (CtorType->getNumParams() > 0) {
3946 QualType FirstArg = CtorType->getParamType(0);
3947 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3948 return true;
3949 }
3950 return false;
3951}
3952
3953static OverloadingResult
3955 CXXRecordDecl *To,
3957 OverloadCandidateSet &CandidateSet,
3958 bool AllowExplicit) {
3960 for (auto *D : S.LookupConstructors(To)) {
3961 auto Info = getConstructorInfo(D);
3962 if (!Info)
3963 continue;
3964
3965 bool Usable = !Info.Constructor->isInvalidDecl() &&
3966 S.isInitListConstructor(Info.Constructor);
3967 if (Usable) {
3968 bool SuppressUserConversions = false;
3969 if (Info.ConstructorTmpl)
3970 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3971 /*ExplicitArgs*/ nullptr, From,
3972 CandidateSet, SuppressUserConversions,
3973 /*PartialOverloading*/ false,
3974 AllowExplicit);
3975 else
3976 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3977 CandidateSet, SuppressUserConversions,
3978 /*PartialOverloading*/ false, AllowExplicit);
3979 }
3980 }
3981
3982 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3983
3985 switch (auto Result =
3986 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3987 case OR_Deleted:
3988 case OR_Success: {
3989 // Record the standard conversion we used and the conversion function.
3991 QualType ThisType = Constructor->getFunctionObjectParameterType();
3992 // Initializer lists don't have conversions as such.
3994 User.HadMultipleCandidates = HadMultipleCandidates;
3996 User.FoundConversionFunction = Best->FoundDecl;
3998 User.After.setFromType(ThisType);
3999 User.After.setAllToTypes(ToType);
4000 return Result;
4001 }
4002
4004 return OR_No_Viable_Function;
4005 case OR_Ambiguous:
4006 return OR_Ambiguous;
4007 }
4008
4009 llvm_unreachable("Invalid OverloadResult!");
4010}
4011
4012/// Determines whether there is a user-defined conversion sequence
4013/// (C++ [over.ics.user]) that converts expression From to the type
4014/// ToType. If such a conversion exists, User will contain the
4015/// user-defined conversion sequence that performs such a conversion
4016/// and this routine will return true. Otherwise, this routine returns
4017/// false and User is unspecified.
4018///
4019/// \param AllowExplicit true if the conversion should consider C++0x
4020/// "explicit" conversion functions as well as non-explicit conversion
4021/// functions (C++0x [class.conv.fct]p2).
4022///
4023/// \param AllowObjCConversionOnExplicit true if the conversion should
4024/// allow an extra Objective-C pointer conversion on uses of explicit
4025/// constructors. Requires \c AllowExplicit to also be set.
4026static OverloadingResult
4029 OverloadCandidateSet &CandidateSet,
4030 AllowedExplicit AllowExplicit,
4031 bool AllowObjCConversionOnExplicit) {
4032 assert(AllowExplicit != AllowedExplicit::None ||
4033 !AllowObjCConversionOnExplicit);
4035
4036 // Whether we will only visit constructors.
4037 bool ConstructorsOnly = false;
4038
4039 // If the type we are conversion to is a class type, enumerate its
4040 // constructors.
4041 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4042 // C++ [over.match.ctor]p1:
4043 // When objects of class type are direct-initialized (8.5), or
4044 // copy-initialized from an expression of the same or a
4045 // derived class type (8.5), overload resolution selects the
4046 // constructor. [...] For copy-initialization, the candidate
4047 // functions are all the converting constructors (12.3.1) of
4048 // that class. The argument list is the expression-list within
4049 // the parentheses of the initializer.
4050 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4051 (From->getType()->isRecordType() &&
4052 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4053 ConstructorsOnly = true;
4054
4055 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4056 // We're not going to find any constructors.
4057 } else if (auto *ToRecordDecl =
4058 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4059 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4060
4061 Expr **Args = &From;
4062 unsigned NumArgs = 1;
4063 bool ListInitializing = false;
4064 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4065 // But first, see if there is an init-list-constructor that will work.
4067 S, From, ToType, ToRecordDecl, User, CandidateSet,
4068 AllowExplicit == AllowedExplicit::All);
4069 if (Result != OR_No_Viable_Function)
4070 return Result;
4071 // Never mind.
4072 CandidateSet.clear(
4074
4075 // If we're list-initializing, we pass the individual elements as
4076 // arguments, not the entire list.
4077 Args = InitList->getInits();
4078 NumArgs = InitList->getNumInits();
4079 ListInitializing = true;
4080 }
4081
4082 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4083 auto Info = getConstructorInfo(D);
4084 if (!Info)
4085 continue;
4086
4087 bool Usable = !Info.Constructor->isInvalidDecl();
4088 if (!ListInitializing)
4089 Usable = Usable && Info.Constructor->isConvertingConstructor(
4090 /*AllowExplicit*/ true);
4091 if (Usable) {
4092 bool SuppressUserConversions = !ConstructorsOnly;
4093 // C++20 [over.best.ics.general]/4.5:
4094 // if the target is the first parameter of a constructor [of class
4095 // X] and the constructor [...] is a candidate by [...] the second
4096 // phase of [over.match.list] when the initializer list has exactly
4097 // one element that is itself an initializer list, [...] and the
4098 // conversion is to X or reference to cv X, user-defined conversion
4099 // sequences are not considered.
4100 if (SuppressUserConversions && ListInitializing) {
4101 SuppressUserConversions =
4102 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4103 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4104 ToType);
4105 }
4106 if (Info.ConstructorTmpl)
4108 Info.ConstructorTmpl, Info.FoundDecl,
4109 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4110 CandidateSet, SuppressUserConversions,
4111 /*PartialOverloading*/ false,
4112 AllowExplicit == AllowedExplicit::All);
4113 else
4114 // Allow one user-defined conversion when user specifies a
4115 // From->ToType conversion via an static cast (c-style, etc).
4116 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4117 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4118 SuppressUserConversions,
4119 /*PartialOverloading*/ false,
4120 AllowExplicit == AllowedExplicit::All);
4121 }
4122 }
4123 }
4124 }
4125
4126 // Enumerate conversion functions, if we're allowed to.
4127 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4128 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4129 // No conversion functions from incomplete types.
4130 } else if (const RecordType *FromRecordType =
4131 From->getType()->getAsCanonical<RecordType>()) {
4132 if (auto *FromRecordDecl =
4133 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4134 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4135 // Add all of the conversion functions as candidates.
4136 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4137 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4138 DeclAccessPair FoundDecl = I.getPair();
4139 NamedDecl *D = FoundDecl.getDecl();
4140 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4141 if (isa<UsingShadowDecl>(D))
4142 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4143
4144 CXXConversionDecl *Conv;
4145 FunctionTemplateDecl *ConvTemplate;
4146 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4147 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4148 else
4149 Conv = cast<CXXConversionDecl>(D);
4150
4151 if (ConvTemplate)
4153 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4154 CandidateSet, AllowObjCConversionOnExplicit,
4155 AllowExplicit != AllowedExplicit::None);
4156 else
4157 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4158 CandidateSet, AllowObjCConversionOnExplicit,
4159 AllowExplicit != AllowedExplicit::None);
4160 }
4161 }
4162 }
4163
4164 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4165
4167 switch (auto Result =
4168 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4169 case OR_Success:
4170 case OR_Deleted:
4171 // Record the standard conversion we used and the conversion function.
4173 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4174 // C++ [over.ics.user]p1:
4175 // If the user-defined conversion is specified by a
4176 // constructor (12.3.1), the initial standard conversion
4177 // sequence converts the source type to the type required by
4178 // the argument of the constructor.
4179 //
4180 if (isa<InitListExpr>(From)) {
4181 // Initializer lists don't have conversions as such.
4183 User.Before.FromBracedInitList = true;
4184 } else {
4185 if (Best->Conversions[0].isEllipsis())
4186 User.EllipsisConversion = true;
4187 else {
4188 User.Before = Best->Conversions[0].Standard;
4189 User.EllipsisConversion = false;
4190 }
4191 }
4192 User.HadMultipleCandidates = HadMultipleCandidates;
4194 User.FoundConversionFunction = Best->FoundDecl;
4196 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4197 User.After.setAllToTypes(ToType);
4198 return Result;
4199 }
4200 if (CXXConversionDecl *Conversion
4201 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4202
4203 assert(Best->HasFinalConversion);
4204
4205 // C++ [over.ics.user]p1:
4206 //
4207 // [...] If the user-defined conversion is specified by a
4208 // conversion function (12.3.2), the initial standard
4209 // conversion sequence converts the source type to the
4210 // implicit object parameter of the conversion function.
4211 User.Before = Best->Conversions[0].Standard;
4212 User.HadMultipleCandidates = HadMultipleCandidates;
4213 User.ConversionFunction = Conversion;
4214 User.FoundConversionFunction = Best->FoundDecl;
4215 User.EllipsisConversion = false;
4216
4217 // C++ [over.ics.user]p2:
4218 // The second standard conversion sequence converts the
4219 // result of the user-defined conversion to the target type
4220 // for the sequence. Since an implicit conversion sequence
4221 // is an initialization, the special rules for
4222 // initialization by user-defined conversion apply when
4223 // selecting the best user-defined conversion for a
4224 // user-defined conversion sequence (see 13.3.3 and
4225 // 13.3.3.1).
4226 User.After = Best->FinalConversion;
4227 return Result;
4228 }
4229 llvm_unreachable("Not a constructor or conversion function?");
4230
4232 return OR_No_Viable_Function;
4233
4234 case OR_Ambiguous:
4235 return OR_Ambiguous;
4236 }
4237
4238 llvm_unreachable("Invalid OverloadResult!");
4239}
4240
4241bool
4244 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4246 OverloadingResult OvResult =
4247 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4248 CandidateSet, AllowedExplicit::None, false);
4249
4250 if (!(OvResult == OR_Ambiguous ||
4251 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4252 return false;
4253
4254 auto Cands = CandidateSet.CompleteCandidates(
4255 *this,
4257 From);
4258 if (OvResult == OR_Ambiguous)
4259 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4260 << From->getType() << ToType << From->getSourceRange();
4261 else { // OR_No_Viable_Function && !CandidateSet.empty()
4262 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4263 diag::err_typecheck_nonviable_condition_incomplete,
4264 From->getType(), From->getSourceRange()))
4265 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4266 << false << From->getType() << From->getSourceRange() << ToType;
4267 }
4268
4269 CandidateSet.NoteCandidates(
4270 *this, From, Cands);
4271 return true;
4272}
4273
4274// Helper for compareConversionFunctions that gets the FunctionType that the
4275// conversion-operator return value 'points' to, or nullptr.
4276static const FunctionType *
4278 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4279 const PointerType *RetPtrTy =
4280 ConvFuncTy->getReturnType()->getAs<PointerType>();
4281
4282 if (!RetPtrTy)
4283 return nullptr;
4284
4285 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4286}
4287
4288/// Compare the user-defined conversion functions or constructors
4289/// of two user-defined conversion sequences to determine whether any ordering
4290/// is possible.
4293 FunctionDecl *Function2) {
4294 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4295 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4296 if (!Conv1 || !Conv2)
4298
4299 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4301
4302 // Objective-C++:
4303 // If both conversion functions are implicitly-declared conversions from
4304 // a lambda closure type to a function pointer and a block pointer,
4305 // respectively, always prefer the conversion to a function pointer,
4306 // because the function pointer is more lightweight and is more likely
4307 // to keep code working.
4308 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4309 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4310 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4311 if (Block1 != Block2)
4312 return Block1 ? ImplicitConversionSequence::Worse
4314 }
4315
4316 // In order to support multiple calling conventions for the lambda conversion
4317 // operator (such as when the free and member function calling convention is
4318 // different), prefer the 'free' mechanism, followed by the calling-convention
4319 // of operator(). The latter is in place to support the MSVC-like solution of
4320 // defining ALL of the possible conversions in regards to calling-convention.
4321 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4322 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4323
4324 if (Conv1FuncRet && Conv2FuncRet &&
4325 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4326 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4327 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4328
4329 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4330 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4331
4332 CallingConv CallOpCC =
4333 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4335 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4337 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4338
4339 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4340 for (CallingConv CC : PrefOrder) {
4341 if (Conv1CC == CC)
4343 if (Conv2CC == CC)
4345 }
4346 }
4347
4349}
4350
4357
4358/// CompareImplicitConversionSequences - Compare two implicit
4359/// conversion sequences to determine whether one is better than the
4360/// other or if they are indistinguishable (C++ 13.3.3.2).
4363 const ImplicitConversionSequence& ICS1,
4364 const ImplicitConversionSequence& ICS2)
4365{
4366 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4367 // conversion sequences (as defined in 13.3.3.1)
4368 // -- a standard conversion sequence (13.3.3.1.1) is a better
4369 // conversion sequence than a user-defined conversion sequence or
4370 // an ellipsis conversion sequence, and
4371 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4372 // conversion sequence than an ellipsis conversion sequence
4373 // (13.3.3.1.3).
4374 //
4375 // C++0x [over.best.ics]p10:
4376 // For the purpose of ranking implicit conversion sequences as
4377 // described in 13.3.3.2, the ambiguous conversion sequence is
4378 // treated as a user-defined sequence that is indistinguishable
4379 // from any other user-defined conversion sequence.
4380
4381 // String literal to 'char *' conversion has been deprecated in C++03. It has
4382 // been removed from C++11. We still accept this conversion, if it happens at
4383 // the best viable function. Otherwise, this conversion is considered worse
4384 // than ellipsis conversion. Consider this as an extension; this is not in the
4385 // standard. For example:
4386 //
4387 // int &f(...); // #1
4388 // void f(char*); // #2
4389 // void g() { int &r = f("foo"); }
4390 //
4391 // In C++03, we pick #2 as the best viable function.
4392 // In C++11, we pick #1 as the best viable function, because ellipsis
4393 // conversion is better than string-literal to char* conversion (since there
4394 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4395 // convert arguments, #2 would be the best viable function in C++11.
4396 // If the best viable function has this conversion, a warning will be issued
4397 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4398
4399 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4402 // Ill-formedness must not differ
4403 ICS1.isBad() == ICS2.isBad())
4407
4408 if (ICS1.getKindRank() < ICS2.getKindRank())
4410 if (ICS2.getKindRank() < ICS1.getKindRank())
4412
4413 // The following checks require both conversion sequences to be of
4414 // the same kind.
4415 if (ICS1.getKind() != ICS2.getKind())
4417
4420
4421 // Two implicit conversion sequences of the same form are
4422 // indistinguishable conversion sequences unless one of the
4423 // following rules apply: (C++ 13.3.3.2p3):
4424
4425 // List-initialization sequence L1 is a better conversion sequence than
4426 // list-initialization sequence L2 if:
4427 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4428 // if not that,
4429 // — L1 and L2 convert to arrays of the same element type, and either the
4430 // number of elements n_1 initialized by L1 is less than the number of
4431 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4432 // an array of unknown bound and L1 does not,
4433 // even if one of the other rules in this paragraph would otherwise apply.
4434 if (!ICS1.isBad()) {
4435 bool StdInit1 = false, StdInit2 = false;
4438 nullptr);
4441 nullptr);
4442 if (StdInit1 != StdInit2)
4443 return StdInit1 ? ImplicitConversionSequence::Better
4445
4448 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4450 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4452 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4453 CAT2->getElementType())) {
4454 // Both to arrays of the same element type
4455 if (CAT1->getSize() != CAT2->getSize())
4456 // Different sized, the smaller wins
4457 return CAT1->getSize().ult(CAT2->getSize())
4462 // One is incomplete, it loses
4466 }
4467 }
4468 }
4469
4470 if (ICS1.isStandard())
4471 // Standard conversion sequence S1 is a better conversion sequence than
4472 // standard conversion sequence S2 if [...]
4473 Result = CompareStandardConversionSequences(S, Loc,
4474 ICS1.Standard, ICS2.Standard);
4475 else if (ICS1.isUserDefined()) {
4476 // With lazy template loading, it is possible to find non-canonical
4477 // FunctionDecls, depending on when redecl chains are completed. Make sure
4478 // to compare the canonical decls of conversion functions. This avoids
4479 // ambiguity problems for templated conversion operators.
4480 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4481 if (ConvFunc1)
4482 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4483 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4484 if (ConvFunc2)
4485 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4486 // User-defined conversion sequence U1 is a better conversion
4487 // sequence than another user-defined conversion sequence U2 if
4488 // they contain the same user-defined conversion function or
4489 // constructor and if the second standard conversion sequence of
4490 // U1 is better than the second standard conversion sequence of
4491 // U2 (C++ 13.3.3.2p3).
4492 if (ConvFunc1 == ConvFunc2)
4493 Result = CompareStandardConversionSequences(S, Loc,
4494 ICS1.UserDefined.After,
4495 ICS2.UserDefined.After);
4496 else
4497 Result = compareConversionFunctions(S,
4500 }
4501
4502 return Result;
4503}
4504
4505// Per 13.3.3.2p3, compare the given standard conversion sequences to
4506// determine if one is a proper subset of the other.
4509 const StandardConversionSequence& SCS1,
4510 const StandardConversionSequence& SCS2) {
4513
4514 // the identity conversion sequence is considered to be a subsequence of
4515 // any non-identity conversion sequence
4516 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4518 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4520
4521 if (SCS1.Second != SCS2.Second) {
4522 if (SCS1.Second == ICK_Identity)
4524 else if (SCS2.Second == ICK_Identity)
4526 else
4528 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4530
4531 if (SCS1.Third == SCS2.Third) {
4532 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4534 }
4535
4536 if (SCS1.Third == ICK_Identity)
4537 return Result == ImplicitConversionSequence::Worse
4540
4541 if (SCS2.Third == ICK_Identity)
4542 return Result == ImplicitConversionSequence::Better
4545
4547}
4548
4549/// Determine whether one of the given reference bindings is better
4550/// than the other based on what kind of bindings they are.
4551static bool
4553 const StandardConversionSequence &SCS2) {
4554 // C++0x [over.ics.rank]p3b4:
4555 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4556 // implicit object parameter of a non-static member function declared
4557 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4558 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4559 // lvalue reference to a function lvalue and S2 binds an rvalue
4560 // reference*.
4561 //
4562 // FIXME: Rvalue references. We're going rogue with the above edits,
4563 // because the semantics in the current C++0x working paper (N3225 at the
4564 // time of this writing) break the standard definition of std::forward
4565 // and std::reference_wrapper when dealing with references to functions.
4566 // Proposed wording changes submitted to CWG for consideration.
4569 return false;
4570
4571 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4572 SCS2.IsLvalueReference) ||
4575}
4576
4582
4583/// Returns kind of fixed enum promotion the \a SCS uses.
4584static FixedEnumPromotion
4586
4587 if (SCS.Second != ICK_Integral_Promotion)
4589
4590 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4591 if (!Enum)
4593
4594 if (!Enum->isFixed())
4596
4597 QualType UnderlyingType = Enum->getIntegerType();
4598 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4600
4602}
4603
4604/// CompareStandardConversionSequences - Compare two standard
4605/// conversion sequences to determine whether one is better than the
4606/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4609 const StandardConversionSequence& SCS1,
4610 const StandardConversionSequence& SCS2)
4611{
4612 // Standard conversion sequence S1 is a better conversion sequence
4613 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4614
4615 // -- S1 is a proper subsequence of S2 (comparing the conversion
4616 // sequences in the canonical form defined by 13.3.3.1.1,
4617 // excluding any Lvalue Transformation; the identity conversion
4618 // sequence is considered to be a subsequence of any
4619 // non-identity conversion sequence) or, if not that,
4622 return CK;
4623
4624 // -- the rank of S1 is better than the rank of S2 (by the rules
4625 // defined below), or, if not that,
4626 ImplicitConversionRank Rank1 = SCS1.getRank();
4627 ImplicitConversionRank Rank2 = SCS2.getRank();
4628 if (Rank1 < Rank2)
4630 else if (Rank2 < Rank1)
4632
4633 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4634 // are indistinguishable unless one of the following rules
4635 // applies:
4636
4637 // A conversion that is not a conversion of a pointer, or
4638 // pointer to member, to bool is better than another conversion
4639 // that is such a conversion.
4641 return SCS2.isPointerConversionToBool()
4644
4645 // C++14 [over.ics.rank]p4b2:
4646 // This is retroactively applied to C++11 by CWG 1601.
4647 //
4648 // A conversion that promotes an enumeration whose underlying type is fixed
4649 // to its underlying type is better than one that promotes to the promoted
4650 // underlying type, if the two are different.
4653 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4654 FEP1 != FEP2)
4658
4659 // C++ [over.ics.rank]p4b2:
4660 //
4661 // If class B is derived directly or indirectly from class A,
4662 // conversion of B* to A* is better than conversion of B* to
4663 // void*, and conversion of A* to void* is better than conversion
4664 // of B* to void*.
4665 bool SCS1ConvertsToVoid
4667 bool SCS2ConvertsToVoid
4669 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4670 // Exactly one of the conversion sequences is a conversion to
4671 // a void pointer; it's the worse conversion.
4672 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4674 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4675 // Neither conversion sequence converts to a void pointer; compare
4676 // their derived-to-base conversions.
4678 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4679 return DerivedCK;
4680 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4681 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4682 // Both conversion sequences are conversions to void
4683 // pointers. Compare the source types to determine if there's an
4684 // inheritance relationship in their sources.
4685 QualType FromType1 = SCS1.getFromType();
4686 QualType FromType2 = SCS2.getFromType();
4687
4688 // Adjust the types we're converting from via the array-to-pointer
4689 // conversion, if we need to.
4690 if (SCS1.First == ICK_Array_To_Pointer)
4691 FromType1 = S.Context.getArrayDecayedType(FromType1);
4692 if (SCS2.First == ICK_Array_To_Pointer)
4693 FromType2 = S.Context.getArrayDecayedType(FromType2);
4694
4695 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4696 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4697
4698 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4700 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4702
4703 // Objective-C++: If one interface is more specific than the
4704 // other, it is the better one.
4705 const ObjCObjectPointerType* FromObjCPtr1
4706 = FromType1->getAs<ObjCObjectPointerType>();
4707 const ObjCObjectPointerType* FromObjCPtr2
4708 = FromType2->getAs<ObjCObjectPointerType>();
4709 if (FromObjCPtr1 && FromObjCPtr2) {
4710 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4711 FromObjCPtr2);
4712 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4713 FromObjCPtr1);
4714 if (AssignLeft != AssignRight) {
4715 return AssignLeft? ImplicitConversionSequence::Better
4717 }
4718 }
4719 }
4720
4721 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4722 // Check for a better reference binding based on the kind of bindings.
4723 if (isBetterReferenceBindingKind(SCS1, SCS2))
4725 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4727 }
4728
4729 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4730 // bullet 3).
4732 = CompareQualificationConversions(S, SCS1, SCS2))
4733 return QualCK;
4734
4735 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4736 // C++ [over.ics.rank]p3b4:
4737 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4738 // which the references refer are the same type except for
4739 // top-level cv-qualifiers, and the type to which the reference
4740 // initialized by S2 refers is more cv-qualified than the type
4741 // to which the reference initialized by S1 refers.
4742 QualType T1 = SCS1.getToType(2);
4743 QualType T2 = SCS2.getToType(2);
4744 T1 = S.Context.getCanonicalType(T1);
4745 T2 = S.Context.getCanonicalType(T2);
4746 Qualifiers T1Quals, T2Quals;
4747 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4748 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4749 if (UnqualT1 == UnqualT2) {
4750 // Objective-C++ ARC: If the references refer to objects with different
4751 // lifetimes, prefer bindings that don't change lifetime.
4757 }
4758
4759 // If the type is an array type, promote the element qualifiers to the
4760 // type for comparison.
4761 if (isa<ArrayType>(T1) && T1Quals)
4762 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4763 if (isa<ArrayType>(T2) && T2Quals)
4764 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4765 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4767 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4769 }
4770 }
4771
4772 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4773 // floating-to-integral conversion if the integral conversion
4774 // is between types of the same size.
4775 // For example:
4776 // void f(float);
4777 // void f(int);
4778 // int main {
4779 // long a;
4780 // f(a);
4781 // }
4782 // Here, MSVC will call f(int) instead of generating a compile error
4783 // as clang will do in standard mode.
4784 if (S.getLangOpts().MSVCCompat &&
4787 SCS2.Second == ICK_Floating_Integral &&
4788 S.Context.getTypeSize(SCS1.getFromType()) ==
4789 S.Context.getTypeSize(SCS1.getToType(2)))
4791
4792 // Prefer a compatible vector conversion over a lax vector conversion
4793 // For example:
4794 //
4795 // typedef float __v4sf __attribute__((__vector_size__(16)));
4796 // void f(vector float);
4797 // void f(vector signed int);
4798 // int main() {
4799 // __v4sf a;
4800 // f(a);
4801 // }
4802 // Here, we'd like to choose f(vector float) and not
4803 // report an ambiguous call error
4804 if (SCS1.Second == ICK_Vector_Conversion &&
4805 SCS2.Second == ICK_Vector_Conversion) {
4806 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4807 SCS1.getFromType(), SCS1.getToType(2));
4808 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4809 SCS2.getFromType(), SCS2.getToType(2));
4810
4811 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4812 return SCS1IsCompatibleVectorConversion
4815 }
4816
4817 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4819 bool SCS1IsCompatibleSVEVectorConversion =
4820 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4821 bool SCS2IsCompatibleSVEVectorConversion =
4822 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4823
4824 if (SCS1IsCompatibleSVEVectorConversion !=
4825 SCS2IsCompatibleSVEVectorConversion)
4826 return SCS1IsCompatibleSVEVectorConversion
4829 }
4830
4831 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4833 bool SCS1IsCompatibleRVVVectorConversion =
4835 bool SCS2IsCompatibleRVVVectorConversion =
4837
4838 if (SCS1IsCompatibleRVVVectorConversion !=
4839 SCS2IsCompatibleRVVVectorConversion)
4840 return SCS1IsCompatibleRVVVectorConversion
4843 }
4845}
4846
4847/// CompareQualificationConversions - Compares two standard conversion
4848/// sequences to determine whether they can be ranked based on their
4849/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4852 const StandardConversionSequence& SCS1,
4853 const StandardConversionSequence& SCS2) {
4854 // C++ [over.ics.rank]p3:
4855 // -- S1 and S2 differ only in their qualification conversion and
4856 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4857 // [C++98]
4858 // [...] and the cv-qualification signature of type T1 is a proper subset
4859 // of the cv-qualification signature of type T2, and S1 is not the
4860 // deprecated string literal array-to-pointer conversion (4.2).
4861 // [C++2a]
4862 // [...] where T1 can be converted to T2 by a qualification conversion.
4863 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4864 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4866
4867 // FIXME: the example in the standard doesn't use a qualification
4868 // conversion (!)
4869 QualType T1 = SCS1.getToType(2);
4870 QualType T2 = SCS2.getToType(2);
4871 T1 = S.Context.getCanonicalType(T1);
4872 T2 = S.Context.getCanonicalType(T2);
4873 assert(!T1->isReferenceType() && !T2->isReferenceType());
4874 Qualifiers T1Quals, T2Quals;
4875 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4876 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4877
4878 // If the types are the same, we won't learn anything by unwrapping
4879 // them.
4880 if (UnqualT1 == UnqualT2)
4882
4883 // Don't ever prefer a standard conversion sequence that uses the deprecated
4884 // string literal array to pointer conversion.
4885 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4886 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4887
4888 // Objective-C++ ARC:
4889 // Prefer qualification conversions not involving a change in lifetime
4890 // to qualification conversions that do change lifetime.
4893 CanPick1 = false;
4896 CanPick2 = false;
4897
4898 bool ObjCLifetimeConversion;
4899 if (CanPick1 &&
4900 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4901 CanPick1 = false;
4902 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4903 // directions, so we can't short-cut this second check in general.
4904 if (CanPick2 &&
4905 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4906 CanPick2 = false;
4907
4908 if (CanPick1 != CanPick2)
4909 return CanPick1 ? ImplicitConversionSequence::Better
4912}
4913
4914/// CompareDerivedToBaseConversions - Compares two standard conversion
4915/// sequences to determine whether they can be ranked based on their
4916/// various kinds of derived-to-base conversions (C++
4917/// [over.ics.rank]p4b3). As part of these checks, we also look at
4918/// conversions between Objective-C interface types.
4921 const StandardConversionSequence& SCS1,
4922 const StandardConversionSequence& SCS2) {
4923 QualType FromType1 = SCS1.getFromType();
4924 QualType ToType1 = SCS1.getToType(1);
4925 QualType FromType2 = SCS2.getFromType();
4926 QualType ToType2 = SCS2.getToType(1);
4927
4928 // Adjust the types we're converting from via the array-to-pointer
4929 // conversion, if we need to.
4930 if (SCS1.First == ICK_Array_To_Pointer)
4931 FromType1 = S.Context.getArrayDecayedType(FromType1);
4932 if (SCS2.First == ICK_Array_To_Pointer)
4933 FromType2 = S.Context.getArrayDecayedType(FromType2);
4934
4935 // Canonicalize all of the types.
4936 FromType1 = S.Context.getCanonicalType(FromType1);
4937 ToType1 = S.Context.getCanonicalType(ToType1);
4938 FromType2 = S.Context.getCanonicalType(FromType2);
4939 ToType2 = S.Context.getCanonicalType(ToType2);
4940
4941 // C++ [over.ics.rank]p4b3:
4942 //
4943 // If class B is derived directly or indirectly from class A and
4944 // class C is derived directly or indirectly from B,
4945 //
4946 // Compare based on pointer conversions.
4947 if (SCS1.Second == ICK_Pointer_Conversion &&
4949 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4950 FromType1->isPointerType() && FromType2->isPointerType() &&
4951 ToType1->isPointerType() && ToType2->isPointerType()) {
4952 QualType FromPointee1 =
4954 QualType ToPointee1 =
4956 QualType FromPointee2 =
4958 QualType ToPointee2 =
4960
4961 // -- conversion of C* to B* is better than conversion of C* to A*,
4962 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4963 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4965 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4967 }
4968
4969 // -- conversion of B* to A* is better than conversion of C* to A*,
4970 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4971 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4973 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4975 }
4976 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4978 const ObjCObjectPointerType *FromPtr1
4979 = FromType1->getAs<ObjCObjectPointerType>();
4980 const ObjCObjectPointerType *FromPtr2
4981 = FromType2->getAs<ObjCObjectPointerType>();
4982 const ObjCObjectPointerType *ToPtr1
4983 = ToType1->getAs<ObjCObjectPointerType>();
4984 const ObjCObjectPointerType *ToPtr2
4985 = ToType2->getAs<ObjCObjectPointerType>();
4986
4987 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4988 // Apply the same conversion ranking rules for Objective-C pointer types
4989 // that we do for C++ pointers to class types. However, we employ the
4990 // Objective-C pseudo-subtyping relationship used for assignment of
4991 // Objective-C pointer types.
4992 bool FromAssignLeft
4993 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4994 bool FromAssignRight
4995 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4996 bool ToAssignLeft
4997 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4998 bool ToAssignRight
4999 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5000
5001 // A conversion to an a non-id object pointer type or qualified 'id'
5002 // type is better than a conversion to 'id'.
5003 if (ToPtr1->isObjCIdType() &&
5004 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5006 if (ToPtr2->isObjCIdType() &&
5007 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5009
5010 // A conversion to a non-id object pointer type is better than a
5011 // conversion to a qualified 'id' type
5012 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5014 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5016
5017 // A conversion to an a non-Class object pointer type or qualified 'Class'
5018 // type is better than a conversion to 'Class'.
5019 if (ToPtr1->isObjCClassType() &&
5020 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5022 if (ToPtr2->isObjCClassType() &&
5023 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5025
5026 // A conversion to a non-Class object pointer type is better than a
5027 // conversion to a qualified 'Class' type.
5028 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5030 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5032
5033 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5034 if (S.Context.hasSameType(FromType1, FromType2) &&
5035 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5036 (ToAssignLeft != ToAssignRight)) {
5037 if (FromPtr1->isSpecialized()) {
5038 // "conversion of B<A> * to B * is better than conversion of B * to
5039 // C *.
5040 bool IsFirstSame =
5041 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5042 bool IsSecondSame =
5043 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5044 if (IsFirstSame) {
5045 if (!IsSecondSame)
5047 } else if (IsSecondSame)
5049 }
5050 return ToAssignLeft? ImplicitConversionSequence::Worse
5052 }
5053
5054 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5055 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5056 (FromAssignLeft != FromAssignRight))
5057 return FromAssignLeft? ImplicitConversionSequence::Better
5059 }
5060 }
5061
5062 // Ranking of member-pointer types.
5063 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5064 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5065 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5066 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5067 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5068 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5069 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5070 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5071 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5072 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5073 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5074 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5075 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5076 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5078 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5080 }
5081 // conversion of B::* to C::* is better than conversion of A::* to C::*
5082 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5083 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5085 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5087 }
5088 }
5089
5090 if (SCS1.Second == ICK_Derived_To_Base) {
5091 // -- conversion of C to B is better than conversion of C to A,
5092 // -- binding of an expression of type C to a reference of type
5093 // B& is better than binding an expression of type C to a
5094 // reference of type A&,
5095 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5096 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5097 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5099 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5101 }
5102
5103 // -- conversion of B to A is better than conversion of C to A.
5104 // -- binding of an expression of type B to a reference of type
5105 // A& is better than binding an expression of type C to a
5106 // reference of type A&,
5107 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5108 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5109 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5111 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5113 }
5114 }
5115
5117}
5118
5120 if (!T.getQualifiers().hasUnaligned())
5121 return T;
5122
5123 Qualifiers Q;
5124 T = Ctx.getUnqualifiedArrayType(T, Q);
5125 Q.removeUnaligned();
5126 return Ctx.getQualifiedType(T, Q);
5127}
5128
5131 QualType OrigT1, QualType OrigT2,
5132 ReferenceConversions *ConvOut) {
5133 assert(!OrigT1->isReferenceType() &&
5134 "T1 must be the pointee type of the reference type");
5135 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5136
5137 QualType T1 = Context.getCanonicalType(OrigT1);
5138 QualType T2 = Context.getCanonicalType(OrigT2);
5139 Qualifiers T1Quals, T2Quals;
5140 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5141 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5142
5143 ReferenceConversions ConvTmp;
5144 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5145 Conv = ReferenceConversions();
5146
5147 // C++2a [dcl.init.ref]p4:
5148 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5149 // reference-related to "cv2 T2" if T1 is similar to T2, or
5150 // T1 is a base class of T2.
5151 // "cv1 T1" is reference-compatible with "cv2 T2" if
5152 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5153 // "pointer to cv1 T1" via a standard conversion sequence.
5154
5155 // Check for standard conversions we can apply to pointers: derived-to-base
5156 // conversions, ObjC pointer conversions, and function pointer conversions.
5157 // (Qualification conversions are checked last.)
5158 if (UnqualT1 == UnqualT2) {
5159 // Nothing to do.
5160 } else if (isCompleteType(Loc, OrigT2) &&
5161 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5162 Conv |= ReferenceConversions::DerivedToBase;
5163 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5164 UnqualT2->isObjCObjectOrInterfaceType() &&
5165 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5166 Conv |= ReferenceConversions::ObjC;
5167 else if (UnqualT2->isFunctionType() &&
5168 IsFunctionConversion(UnqualT2, UnqualT1)) {
5169 Conv |= ReferenceConversions::Function;
5170 // No need to check qualifiers; function types don't have them.
5171 return Ref_Compatible;
5172 }
5173 bool ConvertedReferent = Conv != 0;
5174
5175 // We can have a qualification conversion. Compute whether the types are
5176 // similar at the same time.
5177 bool PreviousToQualsIncludeConst = true;
5178 bool TopLevel = true;
5179 do {
5180 if (T1 == T2)
5181 break;
5182
5183 // We will need a qualification conversion.
5184 Conv |= ReferenceConversions::Qualification;
5185
5186 // Track whether we performed a qualification conversion anywhere other
5187 // than the top level. This matters for ranking reference bindings in
5188 // overload resolution.
5189 if (!TopLevel)
5190 Conv |= ReferenceConversions::NestedQualification;
5191
5192 // MS compiler ignores __unaligned qualifier for references; do the same.
5193 T1 = withoutUnaligned(Context, T1);
5194 T2 = withoutUnaligned(Context, T2);
5195
5196 // If we find a qualifier mismatch, the types are not reference-compatible,
5197 // but are still be reference-related if they're similar.
5198 bool ObjCLifetimeConversion = false;
5199 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5200 PreviousToQualsIncludeConst,
5201 ObjCLifetimeConversion, getASTContext()))
5202 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5203 ? Ref_Related
5205
5206 // FIXME: Should we track this for any level other than the first?
5207 if (ObjCLifetimeConversion)
5208 Conv |= ReferenceConversions::ObjCLifetime;
5209
5210 TopLevel = false;
5211 } while (Context.UnwrapSimilarTypes(T1, T2));
5212
5213 // At this point, if the types are reference-related, we must either have the
5214 // same inner type (ignoring qualifiers), or must have already worked out how
5215 // to convert the referent.
5216 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5219}
5220
5221/// Look for a user-defined conversion to a value reference-compatible
5222/// with DeclType. Return true if something definite is found.
5223static bool
5225 QualType DeclType, SourceLocation DeclLoc,
5226 Expr *Init, QualType T2, bool AllowRvalues,
5227 bool AllowExplicit) {
5228 assert(T2->isRecordType() && "Can only find conversions of record types.");
5229 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5230 OverloadCandidateSet CandidateSet(
5232 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5233 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5234 NamedDecl *D = *I;
5236 if (isa<UsingShadowDecl>(D))
5237 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5238
5239 FunctionTemplateDecl *ConvTemplate
5240 = dyn_cast<FunctionTemplateDecl>(D);
5241 CXXConversionDecl *Conv;
5242 if (ConvTemplate)
5243 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5244 else
5245 Conv = cast<CXXConversionDecl>(D);
5246
5247 if (AllowRvalues) {
5248 // If we are initializing an rvalue reference, don't permit conversion
5249 // functions that return lvalues.
5250 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5251 const ReferenceType *RefType
5253 if (RefType && !RefType->getPointeeType()->isFunctionType())
5254 continue;
5255 }
5256
5257 if (!ConvTemplate &&
5259 DeclLoc,
5260 Conv->getConversionType()
5265 continue;
5266 } else {
5267 // If the conversion function doesn't return a reference type,
5268 // it can't be considered for this conversion. An rvalue reference
5269 // is only acceptable if its referencee is a function type.
5270
5271 const ReferenceType *RefType =
5273 if (!RefType ||
5274 (!RefType->isLValueReferenceType() &&
5275 !RefType->getPointeeType()->isFunctionType()))
5276 continue;
5277 }
5278
5279 if (ConvTemplate)
5281 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5282 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5283 else
5285 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5286 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5287 }
5288
5289 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5290
5292 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5293 case OR_Success:
5294
5295 assert(Best->HasFinalConversion);
5296
5297 // C++ [over.ics.ref]p1:
5298 //
5299 // [...] If the parameter binds directly to the result of
5300 // applying a conversion function to the argument
5301 // expression, the implicit conversion sequence is a
5302 // user-defined conversion sequence (13.3.3.1.2), with the
5303 // second standard conversion sequence either an identity
5304 // conversion or, if the conversion function returns an
5305 // entity of a type that is a derived class of the parameter
5306 // type, a derived-to-base Conversion.
5307 if (!Best->FinalConversion.DirectBinding)
5308 return false;
5309
5310 ICS.setUserDefined();
5311 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5312 ICS.UserDefined.After = Best->FinalConversion;
5313 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5314 ICS.UserDefined.ConversionFunction = Best->Function;
5315 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5316 ICS.UserDefined.EllipsisConversion = false;
5317 assert(ICS.UserDefined.After.ReferenceBinding &&
5319 "Expected a direct reference binding!");
5320 return true;
5321
5322 case OR_Ambiguous:
5323 ICS.setAmbiguous();
5324 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5325 Cand != CandidateSet.end(); ++Cand)
5326 if (Cand->Best)
5327 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5328 return true;
5329
5331 case OR_Deleted:
5332 // There was no suitable conversion, or we found a deleted
5333 // conversion; continue with other checks.
5334 return false;
5335 }
5336
5337 llvm_unreachable("Invalid OverloadResult!");
5338}
5339
5340/// Compute an implicit conversion sequence for reference
5341/// initialization.
5342static ImplicitConversionSequence
5344 SourceLocation DeclLoc,
5345 bool SuppressUserConversions,
5346 bool AllowExplicit) {
5347 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5348
5349 // Most paths end in a failed conversion.
5352
5353 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5354 QualType T2 = Init->getType();
5355
5356 // If the initializer is the address of an overloaded function, try
5357 // to resolve the overloaded function. If all goes well, T2 is the
5358 // type of the resulting function.
5359 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5362 false, Found))
5363 T2 = Fn->getType();
5364 }
5365
5366 // Compute some basic properties of the types and the initializer.
5367 bool isRValRef = DeclType->isRValueReferenceType();
5368 Expr::Classification InitCategory = Init->Classify(S.Context);
5369
5371 Sema::ReferenceCompareResult RefRelationship =
5372 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5373
5374 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5375 ICS.setStandard();
5377 // FIXME: A reference binding can be a function conversion too. We should
5378 // consider that when ordering reference-to-function bindings.
5379 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5381 : (RefConv & Sema::ReferenceConversions::ObjC)
5383 : ICK_Identity;
5385 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5386 // a reference binding that performs a non-top-level qualification
5387 // conversion as a qualification conversion, not as an identity conversion.
5388 ICS.Standard.Third = (RefConv &
5389 Sema::ReferenceConversions::NestedQualification)
5391 : ICK_Identity;
5392 ICS.Standard.setFromType(T2);
5393 ICS.Standard.setToType(0, T2);
5394 ICS.Standard.setToType(1, T1);
5395 ICS.Standard.setToType(2, T1);
5396 ICS.Standard.ReferenceBinding = true;
5397 ICS.Standard.DirectBinding = BindsDirectly;
5398 ICS.Standard.IsLvalueReference = !isRValRef;
5400 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5403 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5404 ICS.Standard.FromBracedInitList = false;
5405 ICS.Standard.CopyConstructor = nullptr;
5407 };
5408
5409 // C++0x [dcl.init.ref]p5:
5410 // A reference to type "cv1 T1" is initialized by an expression
5411 // of type "cv2 T2" as follows:
5412
5413 // -- If reference is an lvalue reference and the initializer expression
5414 if (!isRValRef) {
5415 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5416 // reference-compatible with "cv2 T2," or
5417 //
5418 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5419 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5420 // C++ [over.ics.ref]p1:
5421 // When a parameter of reference type binds directly (8.5.3)
5422 // to an argument expression, the implicit conversion sequence
5423 // is the identity conversion, unless the argument expression
5424 // has a type that is a derived class of the parameter type,
5425 // in which case the implicit conversion sequence is a
5426 // derived-to-base Conversion (13.3.3.1).
5427 SetAsReferenceBinding(/*BindsDirectly=*/true);
5428
5429 // Nothing more to do: the inaccessibility/ambiguity check for
5430 // derived-to-base conversions is suppressed when we're
5431 // computing the implicit conversion sequence (C++
5432 // [over.best.ics]p2).
5433 return ICS;
5434 }
5435
5436 // -- has a class type (i.e., T2 is a class type), where T1 is
5437 // not reference-related to T2, and can be implicitly
5438 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5439 // is reference-compatible with "cv3 T3" 92) (this
5440 // conversion is selected by enumerating the applicable
5441 // conversion functions (13.3.1.6) and choosing the best
5442 // one through overload resolution (13.3)),
5443 if (!SuppressUserConversions && T2->isRecordType() &&
5444 S.isCompleteType(DeclLoc, T2) &&
5445 RefRelationship == Sema::Ref_Incompatible) {
5446 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5447 Init, T2, /*AllowRvalues=*/false,
5448 AllowExplicit))
5449 return ICS;
5450 }
5451 }
5452
5453 // -- Otherwise, the reference shall be an lvalue reference to a
5454 // non-volatile const type (i.e., cv1 shall be const), or the reference
5455 // shall be an rvalue reference.
5456 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5457 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5459 return ICS;
5460 }
5461
5462 // -- If the initializer expression
5463 //
5464 // -- is an xvalue, class prvalue, array prvalue or function
5465 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5466 if (RefRelationship == Sema::Ref_Compatible &&
5467 (InitCategory.isXValue() ||
5468 (InitCategory.isPRValue() &&
5469 (T2->isRecordType() || T2->isArrayType())) ||
5470 (InitCategory.isLValue() && T2->isFunctionType()))) {
5471 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5472 // binding unless we're binding to a class prvalue.
5473 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5474 // allow the use of rvalue references in C++98/03 for the benefit of
5475 // standard library implementors; therefore, we need the xvalue check here.
5476 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5477 !(InitCategory.isPRValue() || T2->isRecordType()));
5478 return ICS;
5479 }
5480
5481 // -- has a class type (i.e., T2 is a class type), where T1 is not
5482 // reference-related to T2, and can be implicitly converted to
5483 // an xvalue, class prvalue, or function lvalue of type
5484 // "cv3 T3", where "cv1 T1" is reference-compatible with
5485 // "cv3 T3",
5486 //
5487 // then the reference is bound to the value of the initializer
5488 // expression in the first case and to the result of the conversion
5489 // in the second case (or, in either case, to an appropriate base
5490 // class subobject).
5491 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5492 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5493 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5494 Init, T2, /*AllowRvalues=*/true,
5495 AllowExplicit)) {
5496 // In the second case, if the reference is an rvalue reference
5497 // and the second standard conversion sequence of the
5498 // user-defined conversion sequence includes an lvalue-to-rvalue
5499 // conversion, the program is ill-formed.
5500 if (ICS.isUserDefined() && isRValRef &&
5503
5504 return ICS;
5505 }
5506
5507 // A temporary of function type cannot be created; don't even try.
5508 if (T1->isFunctionType())
5509 return ICS;
5510
5511 // -- Otherwise, a temporary of type "cv1 T1" is created and
5512 // initialized from the initializer expression using the
5513 // rules for a non-reference copy initialization (8.5). The
5514 // reference is then bound to the temporary. If T1 is
5515 // reference-related to T2, cv1 must be the same
5516 // cv-qualification as, or greater cv-qualification than,
5517 // cv2; otherwise, the program is ill-formed.
5518 if (RefRelationship == Sema::Ref_Related) {
5519 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5520 // we would be reference-compatible or reference-compatible with
5521 // added qualification. But that wasn't the case, so the reference
5522 // initialization fails.
5523 //
5524 // Note that we only want to check address spaces and cvr-qualifiers here.
5525 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5526 Qualifiers T1Quals = T1.getQualifiers();
5527 Qualifiers T2Quals = T2.getQualifiers();
5528 T1Quals.removeObjCGCAttr();
5529 T1Quals.removeObjCLifetime();
5530 T2Quals.removeObjCGCAttr();
5531 T2Quals.removeObjCLifetime();
5532 // MS compiler ignores __unaligned qualifier for references; do the same.
5533 T1Quals.removeUnaligned();
5534 T2Quals.removeUnaligned();
5535 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5536 return ICS;
5537 }
5538
5539 // If at least one of the types is a class type, the types are not
5540 // related, and we aren't allowed any user conversions, the
5541 // reference binding fails. This case is important for breaking
5542 // recursion, since TryImplicitConversion below will attempt to
5543 // create a temporary through the use of a copy constructor.
5544 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5545 (T1->isRecordType() || T2->isRecordType()))
5546 return ICS;
5547
5548 // If T1 is reference-related to T2 and the reference is an rvalue
5549 // reference, the initializer expression shall not be an lvalue.
5550 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5551 Init->Classify(S.Context).isLValue()) {
5553 return ICS;
5554 }
5555
5556 // C++ [over.ics.ref]p2:
5557 // When a parameter of reference type is not bound directly to
5558 // an argument expression, the conversion sequence is the one
5559 // required to convert the argument expression to the
5560 // underlying type of the reference according to
5561 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5562 // to copy-initializing a temporary of the underlying type with
5563 // the argument expression. Any difference in top-level
5564 // cv-qualification is subsumed by the initialization itself
5565 // and does not constitute a conversion.
5566 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5567 AllowedExplicit::None,
5568 /*InOverloadResolution=*/false,
5569 /*CStyle=*/false,
5570 /*AllowObjCWritebackConversion=*/false,
5571 /*AllowObjCConversionOnExplicit=*/false);
5572
5573 // Of course, that's still a reference binding.
5574 if (ICS.isStandard()) {
5575 ICS.Standard.ReferenceBinding = true;
5576 ICS.Standard.IsLvalueReference = !isRValRef;
5577 ICS.Standard.BindsToFunctionLvalue = false;
5578 ICS.Standard.BindsToRvalue = true;
5581 } else if (ICS.isUserDefined()) {
5582 const ReferenceType *LValRefType =
5585
5586 // C++ [over.ics.ref]p3:
5587 // Except for an implicit object parameter, for which see 13.3.1, a
5588 // standard conversion sequence cannot be formed if it requires [...]
5589 // binding an rvalue reference to an lvalue other than a function
5590 // lvalue.
5591 // Note that the function case is not possible here.
5592 if (isRValRef && LValRefType) {
5594 return ICS;
5595 }
5596
5598 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5600 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5604 }
5605
5606 return ICS;
5607}
5608
5609static ImplicitConversionSequence
5610TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5611 bool SuppressUserConversions,
5612 bool InOverloadResolution,
5613 bool AllowObjCWritebackConversion,
5614 bool AllowExplicit = false);
5615
5616/// TryListConversion - Try to copy-initialize a value of type ToType from the
5617/// initializer list From.
5618static ImplicitConversionSequence
5620 bool SuppressUserConversions,
5621 bool InOverloadResolution,
5622 bool AllowObjCWritebackConversion) {
5623 // C++11 [over.ics.list]p1:
5624 // When an argument is an initializer list, it is not an expression and
5625 // special rules apply for converting it to a parameter type.
5626
5628 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5629
5630 // We need a complete type for what follows. With one C++20 exception,
5631 // incomplete types can never be initialized from init lists.
5632 QualType InitTy = ToType;
5633 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5634 if (AT && S.getLangOpts().CPlusPlus20)
5635 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5636 // C++20 allows list initialization of an incomplete array type.
5637 InitTy = IAT->getElementType();
5638 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5639 return Result;
5640
5641 // C++20 [over.ics.list]/2:
5642 // If the initializer list is a designated-initializer-list, a conversion
5643 // is only possible if the parameter has an aggregate type
5644 //
5645 // FIXME: The exception for reference initialization here is not part of the
5646 // language rules, but follow other compilers in adding it as a tentative DR
5647 // resolution.
5648 bool IsDesignatedInit = From->hasDesignatedInit();
5649 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5650 IsDesignatedInit)
5651 return Result;
5652
5653 // Per DR1467 and DR2137:
5654 // If the parameter type is an aggregate class X and the initializer list
5655 // has a single element of type cv U, where U is X or a class derived from
5656 // X, the implicit conversion sequence is the one required to convert the
5657 // element to the parameter type.
5658 //
5659 // Otherwise, if the parameter type is a character array [... ]
5660 // and the initializer list has a single element that is an
5661 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5662 // implicit conversion sequence is the identity conversion.
5663 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5664 if (ToType->isRecordType() && ToType->isAggregateType()) {
5665 QualType InitType = From->getInit(0)->getType();
5666 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5667 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5668 return TryCopyInitialization(S, From->getInit(0), ToType,
5669 SuppressUserConversions,
5670 InOverloadResolution,
5671 AllowObjCWritebackConversion);
5672 }
5673
5674 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5675 InitializedEntity Entity =
5677 /*Consumed=*/false);
5678 if (S.CanPerformCopyInitialization(Entity, From)) {
5679 Result.setStandard();
5680 Result.Standard.setAsIdentityConversion();
5681 Result.Standard.setFromType(ToType);
5682 Result.Standard.setAllToTypes(ToType);
5683 return Result;
5684 }
5685 }
5686 }
5687
5688 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5689 // C++11 [over.ics.list]p2:
5690 // If the parameter type is std::initializer_list<X> or "array of X" and
5691 // all the elements can be implicitly converted to X, the implicit
5692 // conversion sequence is the worst conversion necessary to convert an
5693 // element of the list to X.
5694 //
5695 // C++14 [over.ics.list]p3:
5696 // Otherwise, if the parameter type is "array of N X", if the initializer
5697 // list has exactly N elements or if it has fewer than N elements and X is
5698 // default-constructible, and if all the elements of the initializer list
5699 // can be implicitly converted to X, the implicit conversion sequence is
5700 // the worst conversion necessary to convert an element of the list to X.
5701 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5702 unsigned e = From->getNumInits();
5705 QualType());
5706 QualType ContTy = ToType;
5707 bool IsUnbounded = false;
5708 if (AT) {
5709 InitTy = AT->getElementType();
5710 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5711 if (CT->getSize().ult(e)) {
5712 // Too many inits, fatally bad
5714 ToType);
5715 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5716 return Result;
5717 }
5718 if (CT->getSize().ugt(e)) {
5719 // Need an init from empty {}, is there one?
5720 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5721 From->getEndLoc());
5722 EmptyList.setType(S.Context.VoidTy);
5723 DfltElt = TryListConversion(
5724 S, &EmptyList, InitTy, SuppressUserConversions,
5725 InOverloadResolution, AllowObjCWritebackConversion);
5726 if (DfltElt.isBad()) {
5727 // No {} init, fatally bad
5729 ToType);
5730 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5731 return Result;
5732 }
5733 }
5734 } else {
5735 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5736 IsUnbounded = true;
5737 if (!e) {
5738 // Cannot convert to zero-sized.
5740 ToType);
5741 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5742 return Result;
5743 }
5744 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5745 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5747 }
5748 }
5749
5750 Result.setStandard();
5751 Result.Standard.setAsIdentityConversion();
5752 Result.Standard.setFromType(InitTy);
5753 Result.Standard.setAllToTypes(InitTy);
5754 for (unsigned i = 0; i < e; ++i) {
5755 Expr *Init = From->getInit(i);
5757 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5758 AllowObjCWritebackConversion);
5759
5760 // Keep the worse conversion seen so far.
5761 // FIXME: Sequences are not totally ordered, so 'worse' can be
5762 // ambiguous. CWG has been informed.
5764 Result) ==
5766 Result = ICS;
5767 // Bail as soon as we find something unconvertible.
5768 if (Result.isBad()) {
5769 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5770 return Result;
5771 }
5772 }
5773 }
5774
5775 // If we needed any implicit {} initialization, compare that now.
5776 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5777 // has been informed that this might not be the best thing.
5778 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5779 S, From->getEndLoc(), DfltElt, Result) ==
5781 Result = DfltElt;
5782 // Record the type being initialized so that we may compare sequences
5783 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5784 return Result;
5785 }
5786
5787 // C++14 [over.ics.list]p4:
5788 // C++11 [over.ics.list]p3:
5789 // Otherwise, if the parameter is a non-aggregate class X and overload
5790 // resolution chooses a single best constructor [...] the implicit
5791 // conversion sequence is a user-defined conversion sequence. If multiple
5792 // constructors are viable but none is better than the others, the
5793 // implicit conversion sequence is a user-defined conversion sequence.
5794 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5795 // This function can deal with initializer lists.
5796 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5797 AllowedExplicit::None,
5798 InOverloadResolution, /*CStyle=*/false,
5799 AllowObjCWritebackConversion,
5800 /*AllowObjCConversionOnExplicit=*/false);
5801 }
5802
5803 // C++14 [over.ics.list]p5:
5804 // C++11 [over.ics.list]p4:
5805 // Otherwise, if the parameter has an aggregate type which can be
5806 // initialized from the initializer list [...] the implicit conversion
5807 // sequence is a user-defined conversion sequence.
5808 if (ToType->isAggregateType()) {
5809 // Type is an aggregate, argument is an init list. At this point it comes
5810 // down to checking whether the initialization works.
5811 // FIXME: Find out whether this parameter is consumed or not.
5812 InitializedEntity Entity =
5814 /*Consumed=*/false);
5816 From)) {
5817 Result.setUserDefined();
5818 Result.UserDefined.Before.setAsIdentityConversion();
5819 // Initializer lists don't have a type.
5820 Result.UserDefined.Before.setFromType(QualType());
5821 Result.UserDefined.Before.setAllToTypes(QualType());
5822
5823 Result.UserDefined.After.setAsIdentityConversion();
5824 Result.UserDefined.After.setFromType(ToType);
5825 Result.UserDefined.After.setAllToTypes(ToType);
5826 Result.UserDefined.ConversionFunction = nullptr;
5827 }
5828 return Result;
5829 }
5830
5831 // C++14 [over.ics.list]p6:
5832 // C++11 [over.ics.list]p5:
5833 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5834 if (ToType->isReferenceType()) {
5835 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5836 // mention initializer lists in any way. So we go by what list-
5837 // initialization would do and try to extrapolate from that.
5838
5839 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5840
5841 // If the initializer list has a single element that is reference-related
5842 // to the parameter type, we initialize the reference from that.
5843 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5844 Expr *Init = From->getInit(0);
5845
5846 QualType T2 = Init->getType();
5847
5848 // If the initializer is the address of an overloaded function, try
5849 // to resolve the overloaded function. If all goes well, T2 is the
5850 // type of the resulting function.
5851 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5854 Init, ToType, false, Found))
5855 T2 = Fn->getType();
5856 }
5857
5858 // Compute some basic properties of the types and the initializer.
5859 Sema::ReferenceCompareResult RefRelationship =
5860 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5861
5862 if (RefRelationship >= Sema::Ref_Related) {
5863 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5864 SuppressUserConversions,
5865 /*AllowExplicit=*/false);
5866 }
5867 }
5868
5869 // Otherwise, we bind the reference to a temporary created from the
5870 // initializer list.
5871 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5872 InOverloadResolution,
5873 AllowObjCWritebackConversion);
5874 if (Result.isFailure())
5875 return Result;
5876 assert(!Result.isEllipsis() &&
5877 "Sub-initialization cannot result in ellipsis conversion.");
5878
5879 // Can we even bind to a temporary?
5880 if (ToType->isRValueReferenceType() ||
5881 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5882 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5883 Result.UserDefined.After;
5884 SCS.ReferenceBinding = true;
5886 SCS.BindsToRvalue = true;
5887 SCS.BindsToFunctionLvalue = false;
5890 SCS.FromBracedInitList = false;
5891
5892 } else
5894 From, ToType);
5895 return Result;
5896 }
5897
5898 // C++14 [over.ics.list]p7:
5899 // C++11 [over.ics.list]p6:
5900 // Otherwise, if the parameter type is not a class:
5901 if (!ToType->isRecordType()) {
5902 // - if the initializer list has one element that is not itself an
5903 // initializer list, the implicit conversion sequence is the one
5904 // required to convert the element to the parameter type.
5905 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5906 // single integer.
5907 unsigned NumInits = From->getNumInits();
5908 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5909 !isa<EmbedExpr>(From->getInit(0))) {
5910 Result = TryCopyInitialization(
5911 S, From->getInit(0), ToType, SuppressUserConversions,
5912 InOverloadResolution, AllowObjCWritebackConversion);
5913 if (Result.isStandard())
5914 Result.Standard.FromBracedInitList = true;
5915 }
5916 // - if the initializer list has no elements, the implicit conversion
5917 // sequence is the identity conversion.
5918 else if (NumInits == 0) {
5919 Result.setStandard();
5920 Result.Standard.setAsIdentityConversion();
5921 Result.Standard.setFromType(ToType);
5922 Result.Standard.setAllToTypes(ToType);
5923 }
5924 return Result;
5925 }
5926
5927 // C++14 [over.ics.list]p8:
5928 // C++11 [over.ics.list]p7:
5929 // In all cases other than those enumerated above, no conversion is possible
5930 return Result;
5931}
5932
5933/// TryCopyInitialization - Try to copy-initialize a value of type
5934/// ToType from the expression From. Return the implicit conversion
5935/// sequence required to pass this argument, which may be a bad
5936/// conversion sequence (meaning that the argument cannot be passed to
5937/// a parameter of this type). If @p SuppressUserConversions, then we
5938/// do not permit any user-defined conversion sequences.
5939static ImplicitConversionSequence
5941 bool SuppressUserConversions,
5942 bool InOverloadResolution,
5943 bool AllowObjCWritebackConversion,
5944 bool AllowExplicit) {
5945 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5946 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5947 InOverloadResolution,AllowObjCWritebackConversion);
5948
5949 if (ToType->isReferenceType())
5950 return TryReferenceInit(S, From, ToType,
5951 /*FIXME:*/ From->getBeginLoc(),
5952 SuppressUserConversions, AllowExplicit);
5953
5954 return TryImplicitConversion(S, From, ToType,
5955 SuppressUserConversions,
5956 AllowedExplicit::None,
5957 InOverloadResolution,
5958 /*CStyle=*/false,
5959 AllowObjCWritebackConversion,
5960 /*AllowObjCConversionOnExplicit=*/false);
5961}
5962
5963static bool TryCopyInitialization(const CanQualType FromQTy,
5964 const CanQualType ToQTy,
5965 Sema &S,
5966 SourceLocation Loc,
5967 ExprValueKind FromVK) {
5968 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5970 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5971
5972 return !ICS.isBad();
5973}
5974
5975/// TryObjectArgumentInitialization - Try to initialize the object
5976/// parameter of the given member function (@c Method) from the
5977/// expression @p From.
5979 Sema &S, SourceLocation Loc, QualType FromType,
5980 Expr::Classification FromClassification, CXXMethodDecl *Method,
5981 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5982 QualType ExplicitParameterType = QualType(),
5983 bool SuppressUserConversion = false) {
5984
5985 // We need to have an object of class type.
5986 if (const auto *PT = FromType->getAs<PointerType>()) {
5987 FromType = PT->getPointeeType();
5988
5989 // When we had a pointer, it's implicitly dereferenced, so we
5990 // better have an lvalue.
5991 assert(FromClassification.isLValue());
5992 }
5993
5994 auto ValueKindFromClassification = [](Expr::Classification C) {
5995 if (C.isPRValue())
5996 return clang::VK_PRValue;
5997 if (C.isXValue())
5998 return VK_XValue;
5999 return clang::VK_LValue;
6000 };
6001
6002 if (Method->isExplicitObjectMemberFunction()) {
6003 if (ExplicitParameterType.isNull())
6004 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6005 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6006 ValueKindFromClassification(FromClassification));
6008 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6009 /*InOverloadResolution=*/true, false);
6010 if (ICS.isBad())
6011 ICS.Bad.FromExpr = nullptr;
6012 return ICS;
6013 }
6014
6015 assert(FromType->isRecordType());
6016
6017 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6018 // C++98 [class.dtor]p2:
6019 // A destructor can be invoked for a const, volatile or const volatile
6020 // object.
6021 // C++98 [over.match.funcs]p4:
6022 // For static member functions, the implicit object parameter is considered
6023 // to match any object (since if the function is selected, the object is
6024 // discarded).
6025 Qualifiers Quals = Method->getMethodQualifiers();
6026 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6027 Quals.addConst();
6028 Quals.addVolatile();
6029 }
6030
6031 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6032
6033 // Set up the conversion sequence as a "bad" conversion, to allow us
6034 // to exit early.
6036
6037 // C++0x [over.match.funcs]p4:
6038 // For non-static member functions, the type of the implicit object
6039 // parameter is
6040 //
6041 // - "lvalue reference to cv X" for functions declared without a
6042 // ref-qualifier or with the & ref-qualifier
6043 // - "rvalue reference to cv X" for functions declared with the &&
6044 // ref-qualifier
6045 //
6046 // where X is the class of which the function is a member and cv is the
6047 // cv-qualification on the member function declaration.
6048 //
6049 // However, when finding an implicit conversion sequence for the argument, we
6050 // are not allowed to perform user-defined conversions
6051 // (C++ [over.match.funcs]p5). We perform a simplified version of
6052 // reference binding here, that allows class rvalues to bind to
6053 // non-constant references.
6054
6055 // First check the qualifiers.
6056 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6057 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6058 if (ImplicitParamType.getCVRQualifiers() !=
6059 FromTypeCanon.getLocalCVRQualifiers() &&
6060 !ImplicitParamType.isAtLeastAsQualifiedAs(
6061 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6063 FromType, ImplicitParamType);
6064 return ICS;
6065 }
6066
6067 if (FromTypeCanon.hasAddressSpace()) {
6068 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6069 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6070 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6071 S.getASTContext())) {
6073 FromType, ImplicitParamType);
6074 return ICS;
6075 }
6076 }
6077
6078 // Check that we have either the same type or a derived type. It
6079 // affects the conversion rank.
6080 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6081 ImplicitConversionKind SecondKind;
6082 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6083 SecondKind = ICK_Identity;
6084 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6085 SecondKind = ICK_Derived_To_Base;
6086 } else if (!Method->isExplicitObjectMemberFunction()) {
6088 FromType, ImplicitParamType);
6089 return ICS;
6090 }
6091
6092 // Check the ref-qualifier.
6093 switch (Method->getRefQualifier()) {
6094 case RQ_None:
6095 // Do nothing; we don't care about lvalueness or rvalueness.
6096 break;
6097
6098 case RQ_LValue:
6099 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6100 // non-const lvalue reference cannot bind to an rvalue
6102 ImplicitParamType);
6103 return ICS;
6104 }
6105 break;
6106
6107 case RQ_RValue:
6108 if (!FromClassification.isRValue()) {
6109 // rvalue reference cannot bind to an lvalue
6111 ImplicitParamType);
6112 return ICS;
6113 }
6114 break;
6115 }
6116
6117 // Success. Mark this as a reference binding.
6118 ICS.setStandard();
6120 ICS.Standard.Second = SecondKind;
6121 ICS.Standard.setFromType(FromType);
6122 ICS.Standard.setAllToTypes(ImplicitParamType);
6123 ICS.Standard.ReferenceBinding = true;
6124 ICS.Standard.DirectBinding = true;
6125 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6126 ICS.Standard.BindsToFunctionLvalue = false;
6127 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6128 ICS.Standard.FromBracedInitList = false;
6130 = (Method->getRefQualifier() == RQ_None);
6131 return ICS;
6132}
6133
6134/// PerformObjectArgumentInitialization - Perform initialization of
6135/// the implicit object parameter for the given Method with the given
6136/// expression.
6138 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6140 QualType FromRecordType, DestType;
6141 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6142
6143 Expr::Classification FromClassification;
6144 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6145 FromRecordType = PT->getPointeeType();
6146 DestType = Method->getThisType();
6147 FromClassification = Expr::Classification::makeSimpleLValue();
6148 } else {
6149 FromRecordType = From->getType();
6150 DestType = ImplicitParamRecordType;
6151 FromClassification = From->Classify(Context);
6152
6153 // CWG2813 [expr.call]p6:
6154 // If the function is an implicit object member function, the object
6155 // expression of the class member access shall be a glvalue [...]
6156 if (From->isPRValue()) {
6157 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6158 Method->getRefQualifier() !=
6160 }
6161 }
6162
6163 // Note that we always use the true parent context when performing
6164 // the actual argument initialization.
6166 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6167 Method->getParent());
6168 if (ICS.isBad()) {
6169 switch (ICS.Bad.Kind) {
6171 Qualifiers FromQs = FromRecordType.getQualifiers();
6172 Qualifiers ToQs = DestType.getQualifiers();
6173 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6174 if (CVR) {
6175 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6176 << Method->getDeclName() << FromRecordType << (CVR - 1)
6177 << From->getSourceRange();
6178 Diag(Method->getLocation(), diag::note_previous_decl)
6179 << Method->getDeclName();
6180 return ExprError();
6181 }
6182 break;
6183 }
6184
6187 bool IsRValueQualified =
6188 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6189 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6190 << Method->getDeclName() << FromClassification.isRValue()
6191 << IsRValueQualified;
6192 Diag(Method->getLocation(), diag::note_previous_decl)
6193 << Method->getDeclName();
6194 return ExprError();
6195 }
6196
6199 break;
6200
6203 llvm_unreachable("Lists are not objects");
6204 }
6205
6206 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6207 << ImplicitParamRecordType << FromRecordType
6208 << From->getSourceRange();
6209 }
6210
6211 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6212 ExprResult FromRes =
6213 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6214 if (FromRes.isInvalid())
6215 return ExprError();
6216 From = FromRes.get();
6217 }
6218
6219 if (!Context.hasSameType(From->getType(), DestType)) {
6220 CastKind CK;
6221 QualType PteeTy = DestType->getPointeeType();
6222 LangAS DestAS =
6223 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6224 if (FromRecordType.getAddressSpace() != DestAS)
6225 CK = CK_AddressSpaceConversion;
6226 else
6227 CK = CK_NoOp;
6228 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6229 }
6230 return From;
6231}
6232
6233/// TryContextuallyConvertToBool - Attempt to contextually convert the
6234/// expression From to bool (C++0x [conv]p3).
6237 // C++ [dcl.init]/17.8:
6238 // - Otherwise, if the initialization is direct-initialization, the source
6239 // type is std::nullptr_t, and the destination type is bool, the initial
6240 // value of the object being initialized is false.
6241 if (From->getType()->isNullPtrType())
6243 S.Context.BoolTy,
6244 From->isGLValue());
6245
6246 // All other direct-initialization of bool is equivalent to an implicit
6247 // conversion to bool in which explicit conversions are permitted.
6248 return TryImplicitConversion(S, From, S.Context.BoolTy,
6249 /*SuppressUserConversions=*/false,
6250 AllowedExplicit::Conversions,
6251 /*InOverloadResolution=*/false,
6252 /*CStyle=*/false,
6253 /*AllowObjCWritebackConversion=*/false,
6254 /*AllowObjCConversionOnExplicit=*/false);
6255}
6256
6258 if (checkPlaceholderForOverload(*this, From))
6259 return ExprError();
6260
6262 if (!ICS.isBad())
6263 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6265
6267 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6268 << From->getType() << From->getSourceRange();
6269 return ExprError();
6270}
6271
6272/// Check that the specified conversion is permitted in a converted constant
6273/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6274/// is acceptable.
6277 // Since we know that the target type is an integral or unscoped enumeration
6278 // type, most conversion kinds are impossible. All possible First and Third
6279 // conversions are fine.
6280 switch (SCS.Second) {
6281 case ICK_Identity:
6283 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6285 return true;
6286
6288 // Conversion from an integral or unscoped enumeration type to bool is
6289 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6290 // conversion, so we allow it in a converted constant expression.
6291 //
6292 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6293 // a lot of popular code. We should at least add a warning for this
6294 // (non-conforming) extension.
6296 SCS.getToType(2)->isBooleanType();
6297
6299 case ICK_Pointer_Member:
6300 // C++1z: null pointer conversions and null member pointer conversions are
6301 // only permitted if the source type is std::nullptr_t.
6302 return SCS.getFromType()->isNullPtrType();
6303
6316 case ICK_Vector_Splat:
6317 case ICK_Complex_Real:
6327 return false;
6328
6333 llvm_unreachable("found a first conversion kind in Second");
6334
6336 case ICK_Qualification:
6337 llvm_unreachable("found a third conversion kind in Second");
6338
6340 break;
6341 }
6342
6343 llvm_unreachable("unknown conversion kind");
6344}
6345
6346/// BuildConvertedConstantExpression - Check that the expression From is a
6347/// converted constant expression of type T, perform the conversion but
6348/// does not evaluate the expression
6350 QualType T, CCEKind CCE,
6351 NamedDecl *Dest,
6352 APValue &PreNarrowingValue) {
6353 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6355 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6356 "converted constant expression outside C++11 or TTP matching");
6357
6358 if (checkPlaceholderForOverload(S, From))
6359 return ExprError();
6360
6361 // C++1z [expr.const]p3:
6362 // A converted constant expression of type T is an expression,
6363 // implicitly converted to type T, where the converted
6364 // expression is a constant expression and the implicit conversion
6365 // sequence contains only [... list of conversions ...].
6367 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6369 : TryCopyInitialization(S, From, T,
6370 /*SuppressUserConversions=*/false,
6371 /*InOverloadResolution=*/false,
6372 /*AllowObjCWritebackConversion=*/false,
6373 /*AllowExplicit=*/false);
6374 StandardConversionSequence *SCS = nullptr;
6375 switch (ICS.getKind()) {
6377 SCS = &ICS.Standard;
6378 break;
6380 if (T->isRecordType())
6381 SCS = &ICS.UserDefined.Before;
6382 else
6383 SCS = &ICS.UserDefined.After;
6384 break;
6388 return S.Diag(From->getBeginLoc(),
6389 diag::err_typecheck_converted_constant_expression)
6390 << From->getType() << From->getSourceRange() << T;
6391 return ExprError();
6392
6395 llvm_unreachable("bad conversion in converted constant expression");
6396 }
6397
6398 // Check that we would only use permitted conversions.
6399 if (!CheckConvertedConstantConversions(S, *SCS)) {
6400 return S.Diag(From->getBeginLoc(),
6401 diag::err_typecheck_converted_constant_expression_disallowed)
6402 << From->getType() << From->getSourceRange() << T;
6403 }
6404 // [...] and where the reference binding (if any) binds directly.
6405 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6406 return S.Diag(From->getBeginLoc(),
6407 diag::err_typecheck_converted_constant_expression_indirect)
6408 << From->getType() << From->getSourceRange() << T;
6409 }
6410 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6411 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6412 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6413 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6414 // case explicitly.
6415 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6416 return S.Diag(From->getBeginLoc(),
6417 diag::err_reference_bind_to_bitfield_in_cce)
6418 << From->getSourceRange();
6419 }
6420
6421 // Usually we can simply apply the ImplicitConversionSequence we formed
6422 // earlier, but that's not guaranteed to work when initializing an object of
6423 // class type.
6424 ExprResult Result;
6425 bool IsTemplateArgument =
6427 if (T->isRecordType()) {
6428 assert(IsTemplateArgument &&
6429 "unexpected class type converted constant expr");
6430 Result = S.PerformCopyInitialization(
6433 SourceLocation(), From);
6434 } else {
6435 Result =
6437 }
6438 if (Result.isInvalid())
6439 return Result;
6440
6441 // C++2a [intro.execution]p5:
6442 // A full-expression is [...] a constant-expression [...]
6443 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6444 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6445 IsTemplateArgument);
6446 if (Result.isInvalid())
6447 return Result;
6448
6449 // Check for a narrowing implicit conversion.
6450 bool ReturnPreNarrowingValue = false;
6451 QualType PreNarrowingType;
6452 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6453 PreNarrowingType)) {
6455 // Implicit conversion to a narrower type, and the value is not a constant
6456 // expression. We'll diagnose this in a moment.
6457 case NK_Not_Narrowing:
6458 break;
6459
6461 if (CCE == CCEKind::ArrayBound &&
6462 PreNarrowingType->isIntegralOrEnumerationType() &&
6463 PreNarrowingValue.isInt()) {
6464 // Don't diagnose array bound narrowing here; we produce more precise
6465 // errors by allowing the un-narrowed value through.
6466 ReturnPreNarrowingValue = true;
6467 break;
6468 }
6469 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6470 << CCE << /*Constant*/ 1
6471 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6472 break;
6473
6475 // Implicit conversion to a narrower type, but the expression is
6476 // value-dependent so we can't tell whether it's actually narrowing.
6477 // For matching the parameters of a TTP, the conversion is ill-formed
6478 // if it may narrow.
6479 if (CCE != CCEKind::TempArgStrict)
6480 break;
6481 [[fallthrough]];
6482 case NK_Type_Narrowing:
6483 // FIXME: It would be better to diagnose that the expression is not a
6484 // constant expression.
6485 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6486 << CCE << /*Constant*/ 0 << From->getType() << T;
6487 break;
6488 }
6489 if (!ReturnPreNarrowingValue)
6490 PreNarrowingValue = {};
6491
6492 return Result;
6493}
6494
6495/// CheckConvertedConstantExpression - Check that the expression From is a
6496/// converted constant expression of type T, perform the conversion and produce
6497/// the converted expression, per C++11 [expr.const]p3.
6500 CCEKind CCE, bool RequireInt,
6501 NamedDecl *Dest) {
6502
6503 APValue PreNarrowingValue;
6504 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6505 PreNarrowingValue);
6506 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6507 Value = APValue();
6508 return Result;
6509 }
6510 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6511 RequireInt, PreNarrowingValue);
6512}
6513
6515 CCEKind CCE,
6516 NamedDecl *Dest) {
6517 APValue PreNarrowingValue;
6518 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6519 PreNarrowingValue);
6520}
6521
6523 APValue &Value, CCEKind CCE,
6524 NamedDecl *Dest) {
6525 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6526 Dest);
6527}
6528
6530 llvm::APSInt &Value,
6531 CCEKind CCE) {
6532 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6533
6534 APValue V;
6535 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6536 /*Dest=*/nullptr);
6537 if (!R.isInvalid() && !R.get()->isValueDependent())
6538 Value = V.getInt();
6539 return R;
6540}
6541
6544 CCEKind CCE, bool RequireInt,
6545 const APValue &PreNarrowingValue) {
6546
6547 ExprResult Result = E;
6548 // Check the expression is a constant expression.
6550 Expr::EvalResult Eval;
6551 Eval.Diag = &Notes;
6552
6553 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6554
6555 ConstantExprKind Kind;
6556 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6557 Kind = ConstantExprKind::ClassTemplateArgument;
6558 else if (CCE == CCEKind::TemplateArg)
6559 Kind = ConstantExprKind::NonClassTemplateArgument;
6560 else
6561 Kind = ConstantExprKind::Normal;
6562
6563 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6564 (RequireInt && !Eval.Val.isInt())) {
6565 // The expression can't be folded, so we can't keep it at this position in
6566 // the AST.
6567 Result = ExprError();
6568 } else {
6569 Value = Eval.Val;
6570
6571 if (Notes.empty()) {
6572 // It's a constant expression.
6573 Expr *E = Result.get();
6574 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6575 // We expect a ConstantExpr to have a value associated with it
6576 // by this point.
6577 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6578 "ConstantExpr has no value associated with it");
6579 (void)CE;
6580 } else {
6582 }
6583 if (!PreNarrowingValue.isAbsent())
6584 Value = std::move(PreNarrowingValue);
6585 return E;
6586 }
6587 }
6588
6589 // It's not a constant expression. Produce an appropriate diagnostic.
6590 if (Notes.size() == 1 &&
6591 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6592 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6593 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6594 diag::note_constexpr_invalid_template_arg) {
6595 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6596 for (unsigned I = 0; I < Notes.size(); ++I)
6597 Diag(Notes[I].first, Notes[I].second);
6598 } else {
6599 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6600 << CCE << E->getSourceRange();
6601 for (unsigned I = 0; I < Notes.size(); ++I)
6602 Diag(Notes[I].first, Notes[I].second);
6603 }
6604 return ExprError();
6605}
6606
6607/// dropPointerConversions - If the given standard conversion sequence
6608/// involves any pointer conversions, remove them. This may change
6609/// the result type of the conversion sequence.
6611 if (SCS.Second == ICK_Pointer_Conversion) {
6612 SCS.Second = ICK_Identity;
6613 SCS.Dimension = ICK_Identity;
6614 SCS.Third = ICK_Identity;
6615 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6616 }
6617}
6618
6619/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6620/// convert the expression From to an Objective-C pointer type.
6621static ImplicitConversionSequence
6623 // Do an implicit conversion to 'id'.
6626 = TryImplicitConversion(S, From, Ty,
6627 // FIXME: Are these flags correct?
6628 /*SuppressUserConversions=*/false,
6629 AllowedExplicit::Conversions,
6630 /*InOverloadResolution=*/false,
6631 /*CStyle=*/false,
6632 /*AllowObjCWritebackConversion=*/false,
6633 /*AllowObjCConversionOnExplicit=*/true);
6634
6635 // Strip off any final conversions to 'id'.
6636 switch (ICS.getKind()) {
6641 break;
6642
6645 break;
6646
6649 break;
6650 }
6651
6652 return ICS;
6653}
6654
6656 if (checkPlaceholderForOverload(*this, From))
6657 return ExprError();
6658
6659 QualType Ty = Context.getObjCIdType();
6662 if (!ICS.isBad())
6663 return PerformImplicitConversion(From, Ty, ICS,
6665 return ExprResult();
6666}
6667
6668static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6669 const Expr *Base = nullptr;
6670 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6671 "expected a member expression");
6672
6673 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6674 M && !M->isImplicitAccess())
6675 Base = M->getBase();
6676 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6677 M && !M->isImplicitAccess())
6678 Base = M->getBase();
6679
6680 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6681
6682 if (T->isPointerType())
6683 T = T->getPointeeType();
6684
6685 return T;
6686}
6687
6689 const FunctionDecl *Fun) {
6690 QualType ObjType = Obj->getType();
6691 if (ObjType->isPointerType()) {
6692 ObjType = ObjType->getPointeeType();
6693 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6695 /*CanOverflow=*/false, FPOptionsOverride());
6696 }
6697 return Obj;
6698}
6699
6707
6709 Expr *Object, MultiExprArg &Args,
6710 SmallVectorImpl<Expr *> &NewArgs) {
6711 assert(Method->isExplicitObjectMemberFunction() &&
6712 "Method is not an explicit member function");
6713 assert(NewArgs.empty() && "NewArgs should be empty");
6714
6715 NewArgs.reserve(Args.size() + 1);
6716 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6717 NewArgs.push_back(This);
6718 NewArgs.append(Args.begin(), Args.end());
6719 Args = NewArgs;
6721 Method, Object->getBeginLoc());
6722}
6723
6724/// Determine whether the provided type is an integral type, or an enumeration
6725/// type of a permitted flavor.
6727 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6728 : T->isIntegralOrUnscopedEnumerationType();
6729}
6730
6731static ExprResult
6734 QualType T, UnresolvedSetImpl &ViableConversions) {
6735
6736 if (Converter.Suppress)
6737 return ExprError();
6738
6739 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6740 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6741 CXXConversionDecl *Conv =
6742 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6744 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6745 }
6746 return From;
6747}
6748
6749static bool
6752 QualType T, bool HadMultipleCandidates,
6753 UnresolvedSetImpl &ExplicitConversions) {
6754 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6755 DeclAccessPair Found = ExplicitConversions[0];
6756 CXXConversionDecl *Conversion =
6757 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6758
6759 // The user probably meant to invoke the given explicit
6760 // conversion; use it.
6761 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6762 std::string TypeStr;
6763 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6764
6765 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6767 "static_cast<" + TypeStr + ">(")
6769 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6770 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6771
6772 // If we aren't in a SFINAE context, build a call to the
6773 // explicit conversion function.
6774 if (SemaRef.isSFINAEContext())
6775 return true;
6776
6777 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6778 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6779 HadMultipleCandidates);
6780 if (Result.isInvalid())
6781 return true;
6782
6783 // Replace the conversion with a RecoveryExpr, so we don't try to
6784 // instantiate it later, but can further diagnose here.
6785 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6786 From, Result.get()->getType());
6787 if (Result.isInvalid())
6788 return true;
6789 From = Result.get();
6790 }
6791 return false;
6792}
6793
6794static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6796 QualType T, bool HadMultipleCandidates,
6798 CXXConversionDecl *Conversion =
6799 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6800 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6801
6802 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6803 if (!Converter.SuppressConversion) {
6804 if (SemaRef.isSFINAEContext())
6805 return true;
6806
6807 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6808 << From->getSourceRange();
6809 }
6810
6811 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6812 HadMultipleCandidates);
6813 if (Result.isInvalid())
6814 return true;
6815 // Record usage of conversion in an implicit cast.
6816 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6817 CK_UserDefinedConversion, Result.get(),
6818 nullptr, Result.get()->getValueKind(),
6819 SemaRef.CurFPFeatureOverrides());
6820 return false;
6821}
6822
6824 Sema &SemaRef, SourceLocation Loc, Expr *From,
6826 if (!Converter.match(From->getType()) && !Converter.Suppress)
6827 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6828 << From->getSourceRange();
6829
6830 return SemaRef.DefaultLvalueConversion(From);
6831}
6832
6833static void
6835 UnresolvedSetImpl &ViableConversions,
6836 OverloadCandidateSet &CandidateSet) {
6837 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6838 NamedDecl *D = FoundDecl.getDecl();
6839 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6840 if (isa<UsingShadowDecl>(D))
6841 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6842
6843 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6845 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6846 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6847 continue;
6848 }
6850 SemaRef.AddConversionCandidate(
6851 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6852 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6853 }
6854}
6855
6856/// Attempt to convert the given expression to a type which is accepted
6857/// by the given converter.
6858///
6859/// This routine will attempt to convert an expression of class type to a
6860/// type accepted by the specified converter. In C++11 and before, the class
6861/// must have a single non-explicit conversion function converting to a matching
6862/// type. In C++1y, there can be multiple such conversion functions, but only
6863/// one target type.
6864///
6865/// \param Loc The source location of the construct that requires the
6866/// conversion.
6867///
6868/// \param From The expression we're converting from.
6869///
6870/// \param Converter Used to control and diagnose the conversion process.
6871///
6872/// \returns The expression, converted to an integral or enumeration type if
6873/// successful.
6875 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6876 // We can't perform any more checking for type-dependent expressions.
6877 if (From->isTypeDependent())
6878 return From;
6879
6880 // Process placeholders immediately.
6881 if (From->hasPlaceholderType()) {
6882 ExprResult result = CheckPlaceholderExpr(From);
6883 if (result.isInvalid())
6884 return result;
6885 From = result.get();
6886 }
6887
6888 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6889 ExprResult Converted = DefaultLvalueConversion(From);
6890 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6891 // If the expression already has a matching type, we're golden.
6892 if (Converter.match(T))
6893 return Converted;
6894
6895 // FIXME: Check for missing '()' if T is a function type?
6896
6897 // We can only perform contextual implicit conversions on objects of class
6898 // type.
6899 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6900 if (!RecordTy || !getLangOpts().CPlusPlus) {
6901 if (!Converter.Suppress)
6902 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6903 return From;
6904 }
6905
6906 // We must have a complete class type.
6907 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6908 ContextualImplicitConverter &Converter;
6909 Expr *From;
6910
6911 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6912 : Converter(Converter), From(From) {}
6913
6914 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6915 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6916 }
6917 } IncompleteDiagnoser(Converter, From);
6918
6919 if (Converter.Suppress ? !isCompleteType(Loc, T)
6920 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6921 return From;
6922
6923 // Look for a conversion to an integral or enumeration type.
6925 ViableConversions; // These are *potentially* viable in C++1y.
6926 UnresolvedSet<4> ExplicitConversions;
6927 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
6928 ->getDefinitionOrSelf()
6929 ->getVisibleConversionFunctions();
6930
6931 bool HadMultipleCandidates =
6932 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6933
6934 // To check that there is only one target type, in C++1y:
6935 QualType ToType;
6936 bool HasUniqueTargetType = true;
6937
6938 // Collect explicit or viable (potentially in C++1y) conversions.
6939 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6940 NamedDecl *D = (*I)->getUnderlyingDecl();
6941 CXXConversionDecl *Conversion;
6942 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6943 if (ConvTemplate) {
6945 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6946 else
6947 continue; // C++11 does not consider conversion operator templates(?).
6948 } else
6949 Conversion = cast<CXXConversionDecl>(D);
6950
6951 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6952 "Conversion operator templates are considered potentially "
6953 "viable in C++1y");
6954
6955 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6956 if (Converter.match(CurToType) || ConvTemplate) {
6957
6958 if (Conversion->isExplicit()) {
6959 // FIXME: For C++1y, do we need this restriction?
6960 // cf. diagnoseNoViableConversion()
6961 if (!ConvTemplate)
6962 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6963 } else {
6964 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6965 if (ToType.isNull())
6966 ToType = CurToType.getUnqualifiedType();
6967 else if (HasUniqueTargetType &&
6968 (CurToType.getUnqualifiedType() != ToType))
6969 HasUniqueTargetType = false;
6970 }
6971 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6972 }
6973 }
6974 }
6975
6976 if (getLangOpts().CPlusPlus14) {
6977 // C++1y [conv]p6:
6978 // ... An expression e of class type E appearing in such a context
6979 // is said to be contextually implicitly converted to a specified
6980 // type T and is well-formed if and only if e can be implicitly
6981 // converted to a type T that is determined as follows: E is searched
6982 // for conversion functions whose return type is cv T or reference to
6983 // cv T such that T is allowed by the context. There shall be
6984 // exactly one such T.
6985
6986 // If no unique T is found:
6987 if (ToType.isNull()) {
6988 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6989 HadMultipleCandidates,
6990 ExplicitConversions))
6991 return ExprError();
6992 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6993 }
6994
6995 // If more than one unique Ts are found:
6996 if (!HasUniqueTargetType)
6997 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6998 ViableConversions);
6999
7000 // If one unique T is found:
7001 // First, build a candidate set from the previously recorded
7002 // potentially viable conversions.
7004 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7005 CandidateSet);
7006
7007 // Then, perform overload resolution over the candidate set.
7009 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7010 case OR_Success: {
7011 // Apply this conversion.
7013 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7014 if (recordConversion(*this, Loc, From, Converter, T,
7015 HadMultipleCandidates, Found))
7016 return ExprError();
7017 break;
7018 }
7019 case OR_Ambiguous:
7020 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7021 ViableConversions);
7023 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7024 HadMultipleCandidates,
7025 ExplicitConversions))
7026 return ExprError();
7027 [[fallthrough]];
7028 case OR_Deleted:
7029 // We'll complain below about a non-integral condition type.
7030 break;
7031 }
7032 } else {
7033 switch (ViableConversions.size()) {
7034 case 0: {
7035 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7036 HadMultipleCandidates,
7037 ExplicitConversions))
7038 return ExprError();
7039
7040 // We'll complain below about a non-integral condition type.
7041 break;
7042 }
7043 case 1: {
7044 // Apply this conversion.
7045 DeclAccessPair Found = ViableConversions[0];
7046 if (recordConversion(*this, Loc, From, Converter, T,
7047 HadMultipleCandidates, Found))
7048 return ExprError();
7049 break;
7050 }
7051 default:
7052 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7053 ViableConversions);
7054 }
7055 }
7056
7057 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7058}
7059
7060/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7061/// an acceptable non-member overloaded operator for a call whose
7062/// arguments have types T1 (and, if non-empty, T2). This routine
7063/// implements the check in C++ [over.match.oper]p3b2 concerning
7064/// enumeration types.
7066 FunctionDecl *Fn,
7067 ArrayRef<Expr *> Args) {
7068 QualType T1 = Args[0]->getType();
7069 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7070
7071 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7072 return true;
7073
7074 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7075 return true;
7076
7077 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7078 if (Proto->getNumParams() < 1)
7079 return false;
7080
7081 if (T1->isEnumeralType()) {
7082 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7083 if (Context.hasSameUnqualifiedType(T1, ArgType))
7084 return true;
7085 }
7086
7087 if (Proto->getNumParams() < 2)
7088 return false;
7089
7090 if (!T2.isNull() && T2->isEnumeralType()) {
7091 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7092 if (Context.hasSameUnqualifiedType(T2, ArgType))
7093 return true;
7094 }
7095
7096 return false;
7097}
7098
7101 return false;
7102
7103 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7104 return FD->isTargetMultiVersion();
7105
7106 if (!FD->isMultiVersion())
7107 return false;
7108
7109 // Among multiple target versions consider either the default,
7110 // or the first non-default in the absence of default version.
7111 unsigned SeenAt = 0;
7112 unsigned I = 0;
7113 bool HasDefault = false;
7115 FD, [&](const FunctionDecl *CurFD) {
7116 if (FD == CurFD)
7117 SeenAt = I;
7118 else if (CurFD->isTargetMultiVersionDefault())
7119 HasDefault = true;
7120 ++I;
7121 });
7122 return HasDefault || SeenAt != 0;
7123}
7124
7127 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7128 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7129 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7130 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7131 bool StrictPackMatch) {
7132 const FunctionProtoType *Proto
7133 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7134 assert(Proto && "Functions without a prototype cannot be overloaded");
7135 assert(!Function->getDescribedFunctionTemplate() &&
7136 "Use AddTemplateOverloadCandidate for function templates");
7137
7138 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7140 // If we get here, it's because we're calling a member function
7141 // that is named without a member access expression (e.g.,
7142 // "this->f") that was either written explicitly or created
7143 // implicitly. This can happen with a qualified call to a member
7144 // function, e.g., X::f(). We use an empty type for the implied
7145 // object argument (C++ [over.call.func]p3), and the acting context
7146 // is irrelevant.
7147 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7149 CandidateSet, SuppressUserConversions,
7150 PartialOverloading, EarlyConversions, PO,
7151 StrictPackMatch);
7152 return;
7153 }
7154 // We treat a constructor like a non-member function, since its object
7155 // argument doesn't participate in overload resolution.
7156 }
7157
7158 if (!CandidateSet.isNewCandidate(Function, PO))
7159 return;
7160
7161 // C++11 [class.copy]p11: [DR1402]
7162 // A defaulted move constructor that is defined as deleted is ignored by
7163 // overload resolution.
7164 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7165 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7166 Constructor->isMoveConstructor())
7167 return;
7168
7169 // Overload resolution is always an unevaluated context.
7172
7173 // C++ [over.match.oper]p3:
7174 // if no operand has a class type, only those non-member functions in the
7175 // lookup set that have a first parameter of type T1 or "reference to
7176 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7177 // is a right operand) a second parameter of type T2 or "reference to
7178 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7179 // candidate functions.
7180 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7182 return;
7183
7184 // Add this candidate
7185 OverloadCandidate &Candidate =
7186 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7187 Candidate.FoundDecl = FoundDecl;
7188 Candidate.Function = Function;
7189 Candidate.Viable = true;
7190 Candidate.RewriteKind =
7191 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7192 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7193 Candidate.ExplicitCallArguments = Args.size();
7194 Candidate.StrictPackMatch = StrictPackMatch;
7195
7196 // Explicit functions are not actually candidates at all if we're not
7197 // allowing them in this context, but keep them around so we can point
7198 // to them in diagnostics.
7199 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7200 Candidate.Viable = false;
7201 Candidate.FailureKind = ovl_fail_explicit;
7202 return;
7203 }
7204
7205 // Functions with internal linkage are only viable in the same module unit.
7206 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7207 /// FIXME: Currently, the semantics of linkage in clang is slightly
7208 /// different from the semantics in C++ spec. In C++ spec, only names
7209 /// have linkage. So that all entities of the same should share one
7210 /// linkage. But in clang, different entities of the same could have
7211 /// different linkage.
7212 const NamedDecl *ND = Function;
7213 bool IsImplicitlyInstantiated = false;
7214 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7215 ND = SpecInfo->getTemplate();
7216 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7218 }
7219
7220 /// Don't remove inline functions with internal linkage from the overload
7221 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7222 /// However:
7223 /// - Inline functions with internal linkage are a common pattern in
7224 /// headers to avoid ODR issues.
7225 /// - The global module is meant to be a transition mechanism for C and C++
7226 /// headers, and the current rules as written work against that goal.
7227 const bool IsInlineFunctionInGMF =
7228 Function->isFromGlobalModule() &&
7229 (IsImplicitlyInstantiated || Function->isInlined());
7230
7231 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7232 Candidate.Viable = false;
7234 return;
7235 }
7236 }
7237
7239 Candidate.Viable = false;
7241 return;
7242 }
7243
7244 if (Constructor) {
7245 // C++ [class.copy]p3:
7246 // A member function template is never instantiated to perform the copy
7247 // of a class object to an object of its class type.
7248 CanQualType ClassType =
7249 Context.getCanonicalTagType(Constructor->getParent());
7250 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7251 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7252 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7253 ClassType))) {
7254 Candidate.Viable = false;
7256 return;
7257 }
7258
7259 // C++ [over.match.funcs]p8: (proposed DR resolution)
7260 // A constructor inherited from class type C that has a first parameter
7261 // of type "reference to P" (including such a constructor instantiated
7262 // from a template) is excluded from the set of candidate functions when
7263 // constructing an object of type cv D if the argument list has exactly
7264 // one argument and D is reference-related to P and P is reference-related
7265 // to C.
7266 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7267 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7268 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7269 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7270 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7271 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7272 SourceLocation Loc = Args.front()->getExprLoc();
7273 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7274 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7275 Candidate.Viable = false;
7277 return;
7278 }
7279 }
7280
7281 // Check that the constructor is capable of constructing an object in the
7282 // destination address space.
7284 Constructor->getMethodQualifiers().getAddressSpace(),
7285 CandidateSet.getDestAS(), getASTContext())) {
7286 Candidate.Viable = false;
7288 }
7289 }
7290
7291 unsigned NumParams = Proto->getNumParams();
7292
7293 // (C++ 13.3.2p2): A candidate function having fewer than m
7294 // parameters is viable only if it has an ellipsis in its parameter
7295 // list (8.3.5).
7296 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7297 !Proto->isVariadic() &&
7298 shouldEnforceArgLimit(PartialOverloading, Function)) {
7299 Candidate.Viable = false;
7301 return;
7302 }
7303
7304 // (C++ 13.3.2p2): A candidate function having more than m parameters
7305 // is viable only if the (m+1)st parameter has a default argument
7306 // (8.3.6). For the purposes of overload resolution, the
7307 // parameter list is truncated on the right, so that there are
7308 // exactly m parameters.
7309 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7310 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7311 !PartialOverloading) {
7312 // Not enough arguments.
7313 Candidate.Viable = false;
7315 return;
7316 }
7317
7318 // (CUDA B.1): Check for invalid calls between targets.
7319 if (getLangOpts().CUDA) {
7320 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7321 // Skip the check for callers that are implicit members, because in this
7322 // case we may not yet know what the member's target is; the target is
7323 // inferred for the member automatically, based on the bases and fields of
7324 // the class.
7325 if (!(Caller && Caller->isImplicit()) &&
7326 !CUDA().IsAllowedCall(Caller, Function)) {
7327 Candidate.Viable = false;
7328 Candidate.FailureKind = ovl_fail_bad_target;
7329 return;
7330 }
7331 }
7332
7333 if (Function->getTrailingRequiresClause()) {
7334 ConstraintSatisfaction Satisfaction;
7335 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7336 /*ForOverloadResolution*/ true) ||
7337 !Satisfaction.IsSatisfied) {
7338 Candidate.Viable = false;
7340 return;
7341 }
7342 }
7343
7344 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7345 // Determine the implicit conversion sequences for each of the
7346 // arguments.
7347 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7348 unsigned ConvIdx =
7349 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7350 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7351 // We already formed a conversion sequence for this parameter during
7352 // template argument deduction.
7353 } else if (ArgIdx < NumParams) {
7354 // (C++ 13.3.2p3): for F to be a viable function, there shall
7355 // exist for each argument an implicit conversion sequence
7356 // (13.3.3.1) that converts that argument to the corresponding
7357 // parameter of F.
7358 QualType ParamType = Proto->getParamType(ArgIdx);
7359 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7360 if (ParamABI == ParameterABI::HLSLOut ||
7361 ParamABI == ParameterABI::HLSLInOut)
7362 ParamType = ParamType.getNonReferenceType();
7363 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7364 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7365 /*InOverloadResolution=*/true,
7366 /*AllowObjCWritebackConversion=*/
7367 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7368 if (Candidate.Conversions[ConvIdx].isBad()) {
7369 Candidate.Viable = false;
7371 return;
7372 }
7373 } else {
7374 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7375 // argument for which there is no corresponding parameter is
7376 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7377 Candidate.Conversions[ConvIdx].setEllipsis();
7378 }
7379 }
7380
7381 if (EnableIfAttr *FailedAttr =
7382 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7383 Candidate.Viable = false;
7384 Candidate.FailureKind = ovl_fail_enable_if;
7385 Candidate.DeductionFailure.Data = FailedAttr;
7386 return;
7387 }
7388}
7389
7393 if (Methods.size() <= 1)
7394 return nullptr;
7395
7396 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7397 bool Match = true;
7398 ObjCMethodDecl *Method = Methods[b];
7399 unsigned NumNamedArgs = Sel.getNumArgs();
7400 // Method might have more arguments than selector indicates. This is due
7401 // to addition of c-style arguments in method.
7402 if (Method->param_size() > NumNamedArgs)
7403 NumNamedArgs = Method->param_size();
7404 if (Args.size() < NumNamedArgs)
7405 continue;
7406
7407 for (unsigned i = 0; i < NumNamedArgs; i++) {
7408 // We can't do any type-checking on a type-dependent argument.
7409 if (Args[i]->isTypeDependent()) {
7410 Match = false;
7411 break;
7412 }
7413
7414 ParmVarDecl *param = Method->parameters()[i];
7415 Expr *argExpr = Args[i];
7416 assert(argExpr && "SelectBestMethod(): missing expression");
7417
7418 // Strip the unbridged-cast placeholder expression off unless it's
7419 // a consumed argument.
7420 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7421 !param->hasAttr<CFConsumedAttr>())
7422 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7423
7424 // If the parameter is __unknown_anytype, move on to the next method.
7425 if (param->getType() == Context.UnknownAnyTy) {
7426 Match = false;
7427 break;
7428 }
7429
7430 ImplicitConversionSequence ConversionState
7431 = TryCopyInitialization(*this, argExpr, param->getType(),
7432 /*SuppressUserConversions*/false,
7433 /*InOverloadResolution=*/true,
7434 /*AllowObjCWritebackConversion=*/
7435 getLangOpts().ObjCAutoRefCount,
7436 /*AllowExplicit*/false);
7437 // This function looks for a reasonably-exact match, so we consider
7438 // incompatible pointer conversions to be a failure here.
7439 if (ConversionState.isBad() ||
7440 (ConversionState.isStandard() &&
7441 ConversionState.Standard.Second ==
7443 Match = false;
7444 break;
7445 }
7446 }
7447 // Promote additional arguments to variadic methods.
7448 if (Match && Method->isVariadic()) {
7449 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7450 if (Args[i]->isTypeDependent()) {
7451 Match = false;
7452 break;
7453 }
7455 Args[i], VariadicCallType::Method, nullptr);
7456 if (Arg.isInvalid()) {
7457 Match = false;
7458 break;
7459 }
7460 }
7461 } else {
7462 // Check for extra arguments to non-variadic methods.
7463 if (Args.size() != NumNamedArgs)
7464 Match = false;
7465 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7466 // Special case when selectors have no argument. In this case, select
7467 // one with the most general result type of 'id'.
7468 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7469 QualType ReturnT = Methods[b]->getReturnType();
7470 if (ReturnT->isObjCIdType())
7471 return Methods[b];
7472 }
7473 }
7474 }
7475
7476 if (Match)
7477 return Method;
7478 }
7479 return nullptr;
7480}
7481
7483 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7484 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7485 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7486 if (ThisArg) {
7487 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7488 assert(!isa<CXXConstructorDecl>(Method) &&
7489 "Shouldn't have `this` for ctors!");
7490 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7492 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7493 if (R.isInvalid())
7494 return false;
7495 ConvertedThis = R.get();
7496 } else {
7497 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7498 (void)MD;
7499 assert((MissingImplicitThis || MD->isStatic() ||
7501 "Expected `this` for non-ctor instance methods");
7502 }
7503 ConvertedThis = nullptr;
7504 }
7505
7506 // Ignore any variadic arguments. Converting them is pointless, since the
7507 // user can't refer to them in the function condition.
7508 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7509
7510 // Convert the arguments.
7511 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7512 ExprResult R;
7514 S.Context, Function->getParamDecl(I)),
7515 SourceLocation(), Args[I]);
7516
7517 if (R.isInvalid())
7518 return false;
7519
7520 ConvertedArgs.push_back(R.get());
7521 }
7522
7523 if (Trap.hasErrorOccurred())
7524 return false;
7525
7526 // Push default arguments if needed.
7527 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7528 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7529 ParmVarDecl *P = Function->getParamDecl(i);
7530 if (!P->hasDefaultArg())
7531 return false;
7532 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7533 if (R.isInvalid())
7534 return false;
7535 ConvertedArgs.push_back(R.get());
7536 }
7537
7538 if (Trap.hasErrorOccurred())
7539 return false;
7540 }
7541 return true;
7542}
7543
7545 SourceLocation CallLoc,
7546 ArrayRef<Expr *> Args,
7547 bool MissingImplicitThis) {
7548 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7549 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7550 return nullptr;
7551
7552 SFINAETrap Trap(*this);
7553 SmallVector<Expr *, 16> ConvertedArgs;
7554 // FIXME: We should look into making enable_if late-parsed.
7555 Expr *DiscardedThis;
7557 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7558 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7559 return *EnableIfAttrs.begin();
7560
7561 for (auto *EIA : EnableIfAttrs) {
7563 // FIXME: This doesn't consider value-dependent cases, because doing so is
7564 // very difficult. Ideally, we should handle them more gracefully.
7565 if (EIA->getCond()->isValueDependent() ||
7566 !EIA->getCond()->EvaluateWithSubstitution(
7567 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7568 return EIA;
7569
7570 if (!Result.isInt() || !Result.getInt().getBoolValue())
7571 return EIA;
7572 }
7573 return nullptr;
7574}
7575
7576template <typename CheckFn>
7578 bool ArgDependent, SourceLocation Loc,
7579 CheckFn &&IsSuccessful) {
7581 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7582 if (ArgDependent == DIA->getArgDependent())
7583 Attrs.push_back(DIA);
7584 }
7585
7586 // Common case: No diagnose_if attributes, so we can quit early.
7587 if (Attrs.empty())
7588 return false;
7589
7590 auto WarningBegin = std::stable_partition(
7591 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7592 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7593 DIA->getWarningGroup().empty();
7594 });
7595
7596 // Note that diagnose_if attributes are late-parsed, so they appear in the
7597 // correct order (unlike enable_if attributes).
7598 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7599 IsSuccessful);
7600 if (ErrAttr != WarningBegin) {
7601 const DiagnoseIfAttr *DIA = *ErrAttr;
7602 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7603 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7604 << DIA->getParent() << DIA->getCond()->getSourceRange();
7605 return true;
7606 }
7607
7608 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7609 switch (Sev) {
7610 case DiagnoseIfAttr::DS_warning:
7612 case DiagnoseIfAttr::DS_error:
7613 return diag::Severity::Error;
7614 }
7615 llvm_unreachable("Fully covered switch above!");
7616 };
7617
7618 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7619 if (IsSuccessful(DIA)) {
7620 if (DIA->getWarningGroup().empty() &&
7621 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7622 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7623 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7624 << DIA->getParent() << DIA->getCond()->getSourceRange();
7625 } else {
7626 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7627 DIA->getWarningGroup());
7628 assert(DiagGroup);
7629 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7630 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7631 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7632 S.Diag(Loc, DiagID) << DIA->getMessage();
7633 }
7634 }
7635
7636 return false;
7637}
7638
7640 const Expr *ThisArg,
7642 SourceLocation Loc) {
7644 *this, Function, /*ArgDependent=*/true, Loc,
7645 [&](const DiagnoseIfAttr *DIA) {
7647 // It's sane to use the same Args for any redecl of this function, since
7648 // EvaluateWithSubstitution only cares about the position of each
7649 // argument in the arg list, not the ParmVarDecl* it maps to.
7650 if (!DIA->getCond()->EvaluateWithSubstitution(
7651 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7652 return false;
7653 return Result.isInt() && Result.getInt().getBoolValue();
7654 });
7655}
7656
7658 SourceLocation Loc) {
7660 *this, ND, /*ArgDependent=*/false, Loc,
7661 [&](const DiagnoseIfAttr *DIA) {
7662 bool Result;
7663 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7664 Result;
7665 });
7666}
7667
7669 ArrayRef<Expr *> Args,
7670 OverloadCandidateSet &CandidateSet,
7671 TemplateArgumentListInfo *ExplicitTemplateArgs,
7672 bool SuppressUserConversions,
7673 bool PartialOverloading,
7674 bool FirstArgumentIsBase) {
7675 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7676 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7677 ArrayRef<Expr *> FunctionArgs = Args;
7678
7679 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7680 FunctionDecl *FD =
7681 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7682
7683 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7684 QualType ObjectType;
7685 Expr::Classification ObjectClassification;
7686 if (Args.size() > 0) {
7687 if (Expr *E = Args[0]) {
7688 // Use the explicit base to restrict the lookup:
7689 ObjectType = E->getType();
7690 // Pointers in the object arguments are implicitly dereferenced, so we
7691 // always classify them as l-values.
7692 if (!ObjectType.isNull() && ObjectType->isPointerType())
7693 ObjectClassification = Expr::Classification::makeSimpleLValue();
7694 else
7695 ObjectClassification = E->Classify(Context);
7696 } // .. else there is an implicit base.
7697 FunctionArgs = Args.slice(1);
7698 }
7699 if (FunTmpl) {
7701 FunTmpl, F.getPair(),
7703 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7704 FunctionArgs, CandidateSet, SuppressUserConversions,
7705 PartialOverloading);
7706 } else {
7707 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7708 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7709 ObjectClassification, FunctionArgs, CandidateSet,
7710 SuppressUserConversions, PartialOverloading);
7711 }
7712 } else {
7713 // This branch handles both standalone functions and static methods.
7714
7715 // Slice the first argument (which is the base) when we access
7716 // static method as non-static.
7717 if (Args.size() > 0 &&
7718 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7719 !isa<CXXConstructorDecl>(FD)))) {
7720 assert(cast<CXXMethodDecl>(FD)->isStatic());
7721 FunctionArgs = Args.slice(1);
7722 }
7723 if (FunTmpl) {
7724 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7725 ExplicitTemplateArgs, FunctionArgs,
7726 CandidateSet, SuppressUserConversions,
7727 PartialOverloading);
7728 } else {
7729 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7730 SuppressUserConversions, PartialOverloading);
7731 }
7732 }
7733 }
7734}
7735
7737 Expr::Classification ObjectClassification,
7738 ArrayRef<Expr *> Args,
7739 OverloadCandidateSet &CandidateSet,
7740 bool SuppressUserConversions,
7742 NamedDecl *Decl = FoundDecl.getDecl();
7744
7746 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7747
7748 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7749 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7750 "Expected a member function template");
7751 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7752 /*ExplicitArgs*/ nullptr, ObjectType,
7753 ObjectClassification, Args, CandidateSet,
7754 SuppressUserConversions, false, PO);
7755 } else {
7756 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7757 ObjectType, ObjectClassification, Args, CandidateSet,
7758 SuppressUserConversions, false, {}, PO);
7759 }
7760}
7761
7764 CXXRecordDecl *ActingContext, QualType ObjectType,
7765 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7766 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7767 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7768 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7769 const FunctionProtoType *Proto
7770 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7771 assert(Proto && "Methods without a prototype cannot be overloaded");
7773 "Use AddOverloadCandidate for constructors");
7774
7775 if (!CandidateSet.isNewCandidate(Method, PO))
7776 return;
7777
7778 // C++11 [class.copy]p23: [DR1402]
7779 // A defaulted move assignment operator that is defined as deleted is
7780 // ignored by overload resolution.
7781 if (Method->isDefaulted() && Method->isDeleted() &&
7782 Method->isMoveAssignmentOperator())
7783 return;
7784
7785 // Overload resolution is always an unevaluated context.
7788
7789 bool IgnoreExplicitObject =
7790 (Method->isExplicitObjectMemberFunction() &&
7791 CandidateSet.getKind() ==
7793 bool ImplicitObjectMethodTreatedAsStatic =
7794 CandidateSet.getKind() ==
7796 Method->isImplicitObjectMemberFunction();
7797
7798 unsigned ExplicitOffset =
7799 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7800
7801 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7802 int(ImplicitObjectMethodTreatedAsStatic);
7803
7804 unsigned ExtraArgs =
7806 ? 0
7807 : 1;
7808
7809 // Add this candidate
7810 OverloadCandidate &Candidate =
7811 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7812 Candidate.FoundDecl = FoundDecl;
7813 Candidate.Function = Method;
7814 Candidate.RewriteKind =
7815 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7816 Candidate.TookAddressOfOverload =
7818 Candidate.ExplicitCallArguments = Args.size();
7819 Candidate.StrictPackMatch = StrictPackMatch;
7820
7821 // (C++ 13.3.2p2): A candidate function having fewer than m
7822 // parameters is viable only if it has an ellipsis in its parameter
7823 // list (8.3.5).
7824 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7825 !Proto->isVariadic() &&
7826 shouldEnforceArgLimit(PartialOverloading, Method)) {
7827 Candidate.Viable = false;
7829 return;
7830 }
7831
7832 // (C++ 13.3.2p2): A candidate function having more than m parameters
7833 // is viable only if the (m+1)st parameter has a default argument
7834 // (8.3.6). For the purposes of overload resolution, the
7835 // parameter list is truncated on the right, so that there are
7836 // exactly m parameters.
7837 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7838 ExplicitOffset +
7839 int(ImplicitObjectMethodTreatedAsStatic);
7840
7841 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7842 // Not enough arguments.
7843 Candidate.Viable = false;
7845 return;
7846 }
7847
7848 Candidate.Viable = true;
7849
7850 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7851 if (!IgnoreExplicitObject) {
7852 if (ObjectType.isNull())
7853 Candidate.IgnoreObjectArgument = true;
7854 else if (Method->isStatic()) {
7855 // [over.best.ics.general]p8
7856 // When the parameter is the implicit object parameter of a static member
7857 // function, the implicit conversion sequence is a standard conversion
7858 // sequence that is neither better nor worse than any other standard
7859 // conversion sequence.
7860 //
7861 // This is a rule that was introduced in C++23 to support static lambdas.
7862 // We apply it retroactively because we want to support static lambdas as
7863 // an extension and it doesn't hurt previous code.
7864 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7865 } else {
7866 // Determine the implicit conversion sequence for the object
7867 // parameter.
7868 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7869 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7870 Method, ActingContext, /*InOverloadResolution=*/true);
7871 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7872 Candidate.Viable = false;
7874 return;
7875 }
7876 }
7877 }
7878
7879 // (CUDA B.1): Check for invalid calls between targets.
7880 if (getLangOpts().CUDA)
7881 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7882 Method)) {
7883 Candidate.Viable = false;
7884 Candidate.FailureKind = ovl_fail_bad_target;
7885 return;
7886 }
7887
7888 if (Method->getTrailingRequiresClause()) {
7889 ConstraintSatisfaction Satisfaction;
7890 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7891 /*ForOverloadResolution*/ true) ||
7892 !Satisfaction.IsSatisfied) {
7893 Candidate.Viable = false;
7895 return;
7896 }
7897 }
7898
7899 // Determine the implicit conversion sequences for each of the
7900 // arguments.
7901 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7902 unsigned ConvIdx =
7903 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7904 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7905 // We already formed a conversion sequence for this parameter during
7906 // template argument deduction.
7907 } else if (ArgIdx < NumParams) {
7908 // (C++ 13.3.2p3): for F to be a viable function, there shall
7909 // exist for each argument an implicit conversion sequence
7910 // (13.3.3.1) that converts that argument to the corresponding
7911 // parameter of F.
7912 QualType ParamType;
7913 if (ImplicitObjectMethodTreatedAsStatic) {
7914 ParamType = ArgIdx == 0
7915 ? Method->getFunctionObjectParameterReferenceType()
7916 : Proto->getParamType(ArgIdx - 1);
7917 } else {
7918 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7919 }
7920 Candidate.Conversions[ConvIdx]
7921 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7922 SuppressUserConversions,
7923 /*InOverloadResolution=*/true,
7924 /*AllowObjCWritebackConversion=*/
7925 getLangOpts().ObjCAutoRefCount);
7926 if (Candidate.Conversions[ConvIdx].isBad()) {
7927 Candidate.Viable = false;
7929 return;
7930 }
7931 } else {
7932 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7933 // argument for which there is no corresponding parameter is
7934 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7935 Candidate.Conversions[ConvIdx].setEllipsis();
7936 }
7937 }
7938
7939 if (EnableIfAttr *FailedAttr =
7940 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7941 Candidate.Viable = false;
7942 Candidate.FailureKind = ovl_fail_enable_if;
7943 Candidate.DeductionFailure.Data = FailedAttr;
7944 return;
7945 }
7946
7948 Candidate.Viable = false;
7950 }
7951}
7952
7954 Sema &S, OverloadCandidateSet &CandidateSet,
7955 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7956 CXXRecordDecl *ActingContext,
7957 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7958 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7959 bool SuppressUserConversions, bool PartialOverloading,
7961
7962 // C++ [over.match.funcs]p7:
7963 // In each case where a candidate is a function template, candidate
7964 // function template specializations are generated using template argument
7965 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7966 // candidate functions in the usual way.113) A given name can refer to one
7967 // or more function templates and also to a set of overloaded non-template
7968 // functions. In such a case, the candidate functions generated from each
7969 // function template are combined with the set of non-template candidate
7970 // functions.
7971 TemplateDeductionInfo Info(CandidateSet.getLocation());
7972 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7973 FunctionDecl *Specialization = nullptr;
7974 ConversionSequenceList Conversions;
7976 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7977 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7978 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7979 CandidateSet.getKind() ==
7981 [&](ArrayRef<QualType> ParamTypes,
7982 bool OnlyInitializeNonUserDefinedConversions) {
7983 return S.CheckNonDependentConversions(
7984 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7985 Sema::CheckNonDependentConversionsFlag(
7986 SuppressUserConversions,
7987 OnlyInitializeNonUserDefinedConversions),
7988 ActingContext, ObjectType, ObjectClassification, PO);
7989 });
7991 OverloadCandidate &Candidate =
7992 CandidateSet.addCandidate(Conversions.size(), Conversions);
7993 Candidate.FoundDecl = FoundDecl;
7994 Candidate.Function = Method;
7995 Candidate.Viable = false;
7996 Candidate.RewriteKind =
7997 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7998 Candidate.IsSurrogate = false;
7999 Candidate.TookAddressOfOverload =
8000 CandidateSet.getKind() ==
8002
8003 Candidate.IgnoreObjectArgument =
8004 Method->isStatic() ||
8005 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8006 Candidate.ExplicitCallArguments = Args.size();
8009 else {
8011 Candidate.DeductionFailure =
8012 MakeDeductionFailureInfo(S.Context, Result, Info);
8013 }
8014 return;
8015 }
8016
8017 // Add the function template specialization produced by template argument
8018 // deduction as a candidate.
8019 assert(Specialization && "Missing member function template specialization?");
8021 "Specialization is not a member function?");
8023 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8024 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8025 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8026}
8027
8029 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8030 CXXRecordDecl *ActingContext,
8031 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8032 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8033 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8034 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8035 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8036 return;
8037
8038 if (ExplicitTemplateArgs ||
8041 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8042 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8043 SuppressUserConversions, PartialOverloading, PO);
8044 return;
8045 }
8046
8048 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8049 Args, SuppressUserConversions, PartialOverloading, PO);
8050}
8051
8052/// Determine whether a given function template has a simple explicit specifier
8053/// or a non-value-dependent explicit-specification that evaluates to true.
8057
8062
8064 Sema &S, OverloadCandidateSet &CandidateSet,
8066 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8067 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8069 bool AggregateCandidateDeduction) {
8070
8071 // If the function template has a non-dependent explicit specification,
8072 // exclude it now if appropriate; we are not permitted to perform deduction
8073 // and substitution in this case.
8074 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8075 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8076 Candidate.FoundDecl = FoundDecl;
8077 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8078 Candidate.Viable = false;
8079 Candidate.FailureKind = ovl_fail_explicit;
8080 return;
8081 }
8082
8083 // C++ [over.match.funcs]p7:
8084 // In each case where a candidate is a function template, candidate
8085 // function template specializations are generated using template argument
8086 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8087 // candidate functions in the usual way.113) A given name can refer to one
8088 // or more function templates and also to a set of overloaded non-template
8089 // functions. In such a case, the candidate functions generated from each
8090 // function template are combined with the set of non-template candidate
8091 // functions.
8092 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8093 FunctionTemplate->getTemplateDepth());
8094 FunctionDecl *Specialization = nullptr;
8095 ConversionSequenceList Conversions;
8097 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8098 PartialOverloading, AggregateCandidateDeduction,
8099 /*PartialOrdering=*/false,
8100 /*ObjectType=*/QualType(),
8101 /*ObjectClassification=*/Expr::Classification(),
8102 CandidateSet.getKind() ==
8104 [&](ArrayRef<QualType> ParamTypes,
8105 bool OnlyInitializeNonUserDefinedConversions) {
8106 return S.CheckNonDependentConversions(
8107 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8108 Sema::CheckNonDependentConversionsFlag(
8109 SuppressUserConversions,
8110 OnlyInitializeNonUserDefinedConversions),
8111 nullptr, QualType(), {}, PO);
8112 });
8114 OverloadCandidate &Candidate =
8115 CandidateSet.addCandidate(Conversions.size(), Conversions);
8116 Candidate.FoundDecl = FoundDecl;
8117 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8118 Candidate.Viable = false;
8119 Candidate.RewriteKind =
8120 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8121 Candidate.IsSurrogate = false;
8122 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8123 // Ignore the object argument if there is one, since we don't have an object
8124 // type.
8125 Candidate.TookAddressOfOverload =
8126 CandidateSet.getKind() ==
8128
8129 Candidate.IgnoreObjectArgument =
8130 isa<CXXMethodDecl>(Candidate.Function) &&
8131 !cast<CXXMethodDecl>(Candidate.Function)
8132 ->isExplicitObjectMemberFunction() &&
8134
8135 Candidate.ExplicitCallArguments = Args.size();
8138 else {
8140 Candidate.DeductionFailure =
8142 }
8143 return;
8144 }
8145
8146 // Add the function template specialization produced by template argument
8147 // deduction as a candidate.
8148 assert(Specialization && "Missing function template specialization?");
8150 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8151 PartialOverloading, AllowExplicit,
8152 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8153 Info.AggregateDeductionCandidateHasMismatchedArity,
8154 Info.hasStrictPackMatch());
8155}
8156
8159 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8160 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8161 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8162 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8163 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8164 return;
8165
8166 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8167
8168 if (ExplicitTemplateArgs ||
8170 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8171 DependentExplicitSpecifier)) {
8172
8174 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8175 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8176 IsADLCandidate, PO, AggregateCandidateDeduction);
8177
8178 if (DependentExplicitSpecifier)
8180 return;
8181 }
8182
8183 CandidateSet.AddDeferredTemplateCandidate(
8184 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8185 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8186 AggregateCandidateDeduction);
8187}
8188
8191 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8193 CheckNonDependentConversionsFlag UserConversionFlag,
8194 CXXRecordDecl *ActingContext, QualType ObjectType,
8195 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8196 // FIXME: The cases in which we allow explicit conversions for constructor
8197 // arguments never consider calling a constructor template. It's not clear
8198 // that is correct.
8199 const bool AllowExplicit = false;
8200
8201 bool ForOverloadSetAddressResolution =
8203 auto *FD = FunctionTemplate->getTemplatedDecl();
8204 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8205 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8207 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8208
8209 if (Conversions.empty())
8210 Conversions =
8211 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8212
8213 // Overload resolution is always an unevaluated context.
8216
8217 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8218 // require that, but this check should never result in a hard error, and
8219 // overload resolution is permitted to sidestep instantiations.
8220 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8221 !ObjectType.isNull()) {
8222 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8223 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8224 !ParamTypes[0]->isDependentType()) {
8226 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8227 Method, ActingContext, /*InOverloadResolution=*/true,
8228 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8229 : QualType());
8230 if (Conversions[ConvIdx].isBad())
8231 return true;
8232 }
8233 }
8234
8235 // A speculative workaround for self-dependent constraint bugs that manifest
8236 // after CWG2369.
8237 // FIXME: Add references to the standard once P3606 is adopted.
8238 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8239 QualType ArgType) {
8240 ParamType = ParamType.getNonReferenceType();
8241 ArgType = ArgType.getNonReferenceType();
8242 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8243 if (PointerConv) {
8244 ParamType = ParamType->getPointeeType();
8245 ArgType = ArgType->getPointeeType();
8246 }
8247
8248 if (auto *RD = ParamType->getAsCXXRecordDecl();
8249 RD && RD->hasDefinition() &&
8250 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8251 auto Info = getConstructorInfo(ND);
8252 if (!Info)
8253 return false;
8254 CXXConstructorDecl *Ctor = Info.Constructor;
8255 /// isConvertingConstructor takes copy/move constructors into
8256 /// account!
8257 return !Ctor->isCopyOrMoveConstructor() &&
8259 /*AllowExplicit=*/true);
8260 }))
8261 return true;
8262 if (auto *RD = ArgType->getAsCXXRecordDecl();
8263 RD && RD->hasDefinition() &&
8264 !RD->getVisibleConversionFunctions().empty())
8265 return true;
8266
8267 return false;
8268 };
8269
8270 unsigned Offset =
8271 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8272 : 0;
8273
8274 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8275 I != N; ++I) {
8276 QualType ParamType = ParamTypes[I + Offset];
8277 if (!ParamType->isDependentType()) {
8278 unsigned ConvIdx;
8280 ConvIdx = Args.size() - 1 - I;
8281 assert(Args.size() + ThisConversions == 2 &&
8282 "number of args (including 'this') must be exactly 2 for "
8283 "reversed order");
8284 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8285 // would also be 0. 'this' got ConvIdx = 1 previously.
8286 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8287 } else {
8288 // For members, 'this' got ConvIdx = 0 previously.
8289 ConvIdx = ThisConversions + I;
8290 }
8291 if (Conversions[ConvIdx].isInitialized())
8292 continue;
8293 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8294 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8295 continue;
8297 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8298 /*InOverloadResolution=*/true,
8299 /*AllowObjCWritebackConversion=*/
8300 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8301 if (Conversions[ConvIdx].isBad())
8302 return true;
8303 }
8304 }
8305
8306 return false;
8307}
8308
8309/// Determine whether this is an allowable conversion from the result
8310/// of an explicit conversion operator to the expected type, per C++
8311/// [over.match.conv]p1 and [over.match.ref]p1.
8312///
8313/// \param ConvType The return type of the conversion function.
8314///
8315/// \param ToType The type we are converting to.
8316///
8317/// \param AllowObjCPointerConversion Allow a conversion from one
8318/// Objective-C pointer to another.
8319///
8320/// \returns true if the conversion is allowable, false otherwise.
8322 QualType ConvType, QualType ToType,
8323 bool AllowObjCPointerConversion) {
8324 QualType ToNonRefType = ToType.getNonReferenceType();
8325
8326 // Easy case: the types are the same.
8327 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8328 return true;
8329
8330 // Allow qualification conversions.
8331 bool ObjCLifetimeConversion;
8332 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8333 ObjCLifetimeConversion))
8334 return true;
8335
8336 // If we're not allowed to consider Objective-C pointer conversions,
8337 // we're done.
8338 if (!AllowObjCPointerConversion)
8339 return false;
8340
8341 // Is this an Objective-C pointer conversion?
8342 bool IncompatibleObjC = false;
8343 QualType ConvertedType;
8344 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8345 IncompatibleObjC);
8346}
8347
8349 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8350 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8351 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8352 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8353 assert(!Conversion->getDescribedFunctionTemplate() &&
8354 "Conversion function templates use AddTemplateConversionCandidate");
8355 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8356 if (!CandidateSet.isNewCandidate(Conversion))
8357 return;
8358
8359 // If the conversion function has an undeduced return type, trigger its
8360 // deduction now.
8361 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8362 if (DeduceReturnType(Conversion, From->getExprLoc()))
8363 return;
8364 ConvType = Conversion->getConversionType().getNonReferenceType();
8365 }
8366
8367 // If we don't allow any conversion of the result type, ignore conversion
8368 // functions that don't convert to exactly (possibly cv-qualified) T.
8369 if (!AllowResultConversion &&
8370 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8371 return;
8372
8373 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8374 // operator is only a candidate if its return type is the target type or
8375 // can be converted to the target type with a qualification conversion.
8376 //
8377 // FIXME: Include such functions in the candidate list and explain why we
8378 // can't select them.
8379 if (Conversion->isExplicit() &&
8380 !isAllowableExplicitConversion(*this, ConvType, ToType,
8381 AllowObjCConversionOnExplicit))
8382 return;
8383
8384 // Overload resolution is always an unevaluated context.
8387
8388 // Add this candidate
8389 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8390 Candidate.FoundDecl = FoundDecl;
8391 Candidate.Function = Conversion;
8393 Candidate.FinalConversion.setFromType(ConvType);
8394 Candidate.FinalConversion.setAllToTypes(ToType);
8395 Candidate.HasFinalConversion = true;
8396 Candidate.Viable = true;
8397 Candidate.ExplicitCallArguments = 1;
8398 Candidate.StrictPackMatch = StrictPackMatch;
8399
8400 // Explicit functions are not actually candidates at all if we're not
8401 // allowing them in this context, but keep them around so we can point
8402 // to them in diagnostics.
8403 if (!AllowExplicit && Conversion->isExplicit()) {
8404 Candidate.Viable = false;
8405 Candidate.FailureKind = ovl_fail_explicit;
8406 return;
8407 }
8408
8409 // C++ [over.match.funcs]p4:
8410 // For conversion functions, the function is considered to be a member of
8411 // the class of the implicit implied object argument for the purpose of
8412 // defining the type of the implicit object parameter.
8413 //
8414 // Determine the implicit conversion sequence for the implicit
8415 // object parameter.
8416 QualType ObjectType = From->getType();
8417 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8418 ObjectType = FromPtrType->getPointeeType();
8419 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8420 // C++23 [over.best.ics.general]
8421 // However, if the target is [...]
8422 // - the object parameter of a user-defined conversion function
8423 // [...] user-defined conversion sequences are not considered.
8425 *this, CandidateSet.getLocation(), From->getType(),
8426 From->Classify(Context), Conversion, ConversionContext,
8427 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8428 /*SuppressUserConversion*/ true);
8429
8430 if (Candidate.Conversions[0].isBad()) {
8431 Candidate.Viable = false;
8433 return;
8434 }
8435
8436 if (Conversion->getTrailingRequiresClause()) {
8437 ConstraintSatisfaction Satisfaction;
8438 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8439 !Satisfaction.IsSatisfied) {
8440 Candidate.Viable = false;
8442 return;
8443 }
8444 }
8445
8446 // We won't go through a user-defined type conversion function to convert a
8447 // derived to base as such conversions are given Conversion Rank. They only
8448 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8449 QualType FromCanon
8450 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8451 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8452 if (FromCanon == ToCanon ||
8453 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8454 Candidate.Viable = false;
8456 return;
8457 }
8458
8459 // To determine what the conversion from the result of calling the
8460 // conversion function to the type we're eventually trying to
8461 // convert to (ToType), we need to synthesize a call to the
8462 // conversion function and attempt copy initialization from it. This
8463 // makes sure that we get the right semantics with respect to
8464 // lvalues/rvalues and the type. Fortunately, we can allocate this
8465 // call on the stack and we don't need its arguments to be
8466 // well-formed.
8467 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8468 VK_LValue, From->getBeginLoc());
8470 Context.getPointerType(Conversion->getType()),
8471 CK_FunctionToPointerDecay, &ConversionRef,
8473
8474 QualType ConversionType = Conversion->getConversionType();
8475 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8476 Candidate.Viable = false;
8478 return;
8479 }
8480
8481 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8482
8483 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8484
8485 // Introduce a temporary expression with the right type and value category
8486 // that we can use for deduction purposes.
8487 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8488
8490 TryCopyInitialization(*this, &FakeCall, ToType,
8491 /*SuppressUserConversions=*/true,
8492 /*InOverloadResolution=*/false,
8493 /*AllowObjCWritebackConversion=*/false);
8494
8495 switch (ICS.getKind()) {
8497 Candidate.FinalConversion = ICS.Standard;
8498 Candidate.HasFinalConversion = true;
8499
8500 // C++ [over.ics.user]p3:
8501 // If the user-defined conversion is specified by a specialization of a
8502 // conversion function template, the second standard conversion sequence
8503 // shall have exact match rank.
8504 if (Conversion->getPrimaryTemplate() &&
8506 Candidate.Viable = false;
8508 return;
8509 }
8510
8511 // C++0x [dcl.init.ref]p5:
8512 // In the second case, if the reference is an rvalue reference and
8513 // the second standard conversion sequence of the user-defined
8514 // conversion sequence includes an lvalue-to-rvalue conversion, the
8515 // program is ill-formed.
8516 if (ToType->isRValueReferenceType() &&
8518 Candidate.Viable = false;
8520 return;
8521 }
8522 break;
8523
8525 Candidate.Viable = false;
8527 return;
8528
8529 default:
8530 llvm_unreachable(
8531 "Can only end up with a standard conversion sequence or failure");
8532 }
8533
8534 if (EnableIfAttr *FailedAttr =
8535 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8536 Candidate.Viable = false;
8537 Candidate.FailureKind = ovl_fail_enable_if;
8538 Candidate.DeductionFailure.Data = FailedAttr;
8539 return;
8540 }
8541
8542 if (isNonViableMultiVersionOverload(Conversion)) {
8543 Candidate.Viable = false;
8545 }
8546}
8547
8549 Sema &S, OverloadCandidateSet &CandidateSet,
8551 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8552 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8553 bool AllowResultConversion) {
8554
8555 // If the function template has a non-dependent explicit specification,
8556 // exclude it now if appropriate; we are not permitted to perform deduction
8557 // and substitution in this case.
8558 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8559 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8560 Candidate.FoundDecl = FoundDecl;
8561 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8562 Candidate.Viable = false;
8563 Candidate.FailureKind = ovl_fail_explicit;
8564 return;
8565 }
8566
8567 QualType ObjectType = From->getType();
8568 Expr::Classification ObjectClassification = From->Classify(S.Context);
8569
8570 TemplateDeductionInfo Info(CandidateSet.getLocation());
8573 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8574 Specialization, Info);
8576 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8577 Candidate.FoundDecl = FoundDecl;
8578 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8579 Candidate.Viable = false;
8581 Candidate.ExplicitCallArguments = 1;
8582 Candidate.DeductionFailure =
8583 MakeDeductionFailureInfo(S.Context, Result, Info);
8584 return;
8585 }
8586
8587 // Add the conversion function template specialization produced by
8588 // template argument deduction as a candidate.
8589 assert(Specialization && "Missing function template specialization?");
8590 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8591 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8592 AllowExplicit, AllowResultConversion,
8593 Info.hasStrictPackMatch());
8594}
8595
8598 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8599 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8600 bool AllowExplicit, bool AllowResultConversion) {
8601 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8602 "Only conversion function templates permitted here");
8603
8604 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8605 return;
8606
8608 CandidateSet.getKind() ==
8612 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8613 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8614 AllowResultConversion);
8615
8617 return;
8618 }
8619
8621 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8622 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8623}
8624
8626 DeclAccessPair FoundDecl,
8627 CXXRecordDecl *ActingContext,
8628 const FunctionProtoType *Proto,
8629 Expr *Object,
8630 ArrayRef<Expr *> Args,
8631 OverloadCandidateSet& CandidateSet) {
8632 if (!CandidateSet.isNewCandidate(Conversion))
8633 return;
8634
8635 // Overload resolution is always an unevaluated context.
8638
8639 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8640 Candidate.FoundDecl = FoundDecl;
8641 Candidate.Function = nullptr;
8642 Candidate.Surrogate = Conversion;
8643 Candidate.IsSurrogate = true;
8644 Candidate.Viable = true;
8645 Candidate.ExplicitCallArguments = Args.size();
8646
8647 // Determine the implicit conversion sequence for the implicit
8648 // object parameter.
8649 ImplicitConversionSequence ObjectInit;
8650 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8651 ObjectInit = TryCopyInitialization(*this, Object,
8652 Conversion->getParamDecl(0)->getType(),
8653 /*SuppressUserConversions=*/false,
8654 /*InOverloadResolution=*/true, false);
8655 } else {
8657 *this, CandidateSet.getLocation(), Object->getType(),
8658 Object->Classify(Context), Conversion, ActingContext);
8659 }
8660
8661 if (ObjectInit.isBad()) {
8662 Candidate.Viable = false;
8664 Candidate.Conversions[0] = ObjectInit;
8665 return;
8666 }
8667
8668 // The first conversion is actually a user-defined conversion whose
8669 // first conversion is ObjectInit's standard conversion (which is
8670 // effectively a reference binding). Record it as such.
8671 Candidate.Conversions[0].setUserDefined();
8672 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8673 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8674 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8675 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8676 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8677 Candidate.Conversions[0].UserDefined.After
8678 = Candidate.Conversions[0].UserDefined.Before;
8679 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8680
8681 // Find the
8682 unsigned NumParams = Proto->getNumParams();
8683
8684 // (C++ 13.3.2p2): A candidate function having fewer than m
8685 // parameters is viable only if it has an ellipsis in its parameter
8686 // list (8.3.5).
8687 if (Args.size() > NumParams && !Proto->isVariadic()) {
8688 Candidate.Viable = false;
8690 return;
8691 }
8692
8693 // Function types don't have any default arguments, so just check if
8694 // we have enough arguments.
8695 if (Args.size() < NumParams) {
8696 // Not enough arguments.
8697 Candidate.Viable = false;
8699 return;
8700 }
8701
8702 // Determine the implicit conversion sequences for each of the
8703 // arguments.
8704 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8705 if (ArgIdx < NumParams) {
8706 // (C++ 13.3.2p3): for F to be a viable function, there shall
8707 // exist for each argument an implicit conversion sequence
8708 // (13.3.3.1) that converts that argument to the corresponding
8709 // parameter of F.
8710 QualType ParamType = Proto->getParamType(ArgIdx);
8711 Candidate.Conversions[ArgIdx + 1]
8712 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8713 /*SuppressUserConversions=*/false,
8714 /*InOverloadResolution=*/false,
8715 /*AllowObjCWritebackConversion=*/
8716 getLangOpts().ObjCAutoRefCount);
8717 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8718 Candidate.Viable = false;
8720 return;
8721 }
8722 } else {
8723 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8724 // argument for which there is no corresponding parameter is
8725 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8726 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8727 }
8728 }
8729
8730 if (Conversion->getTrailingRequiresClause()) {
8731 ConstraintSatisfaction Satisfaction;
8732 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8733 /*ForOverloadResolution*/ true) ||
8734 !Satisfaction.IsSatisfied) {
8735 Candidate.Viable = false;
8737 return;
8738 }
8739 }
8740
8741 if (EnableIfAttr *FailedAttr =
8742 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8743 Candidate.Viable = false;
8744 Candidate.FailureKind = ovl_fail_enable_if;
8745 Candidate.DeductionFailure.Data = FailedAttr;
8746 return;
8747 }
8748}
8749
8751 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8752 OverloadCandidateSet &CandidateSet,
8753 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8754 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8755 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8756 ArrayRef<Expr *> FunctionArgs = Args;
8757
8758 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8759 FunctionDecl *FD =
8760 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8761
8762 // Don't consider rewritten functions if we're not rewriting.
8763 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8764 continue;
8765
8766 assert(!isa<CXXMethodDecl>(FD) &&
8767 "unqualified operator lookup found a member function");
8768
8769 if (FunTmpl) {
8770 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8771 FunctionArgs, CandidateSet);
8772 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8773
8774 // As template candidates are not deduced immediately,
8775 // persist the array in the overload set.
8777 FunctionArgs[1], FunctionArgs[0]);
8778 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8779 Reversed, CandidateSet, false, false, true,
8780 ADLCallKind::NotADL,
8782 }
8783 } else {
8784 if (ExplicitTemplateArgs)
8785 continue;
8786 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8787 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8788 AddOverloadCandidate(FD, F.getPair(),
8789 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8790 false, false, true, false, ADLCallKind::NotADL, {},
8792 }
8793 }
8794}
8795
8797 SourceLocation OpLoc,
8798 ArrayRef<Expr *> Args,
8799 OverloadCandidateSet &CandidateSet,
8801 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8802
8803 // C++ [over.match.oper]p3:
8804 // For a unary operator @ with an operand of a type whose
8805 // cv-unqualified version is T1, and for a binary operator @ with
8806 // a left operand of a type whose cv-unqualified version is T1 and
8807 // a right operand of a type whose cv-unqualified version is T2,
8808 // three sets of candidate functions, designated member
8809 // candidates, non-member candidates and built-in candidates, are
8810 // constructed as follows:
8811 QualType T1 = Args[0]->getType();
8812
8813 // -- If T1 is a complete class type or a class currently being
8814 // defined, the set of member candidates is the result of the
8815 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8816 // the set of member candidates is empty.
8817 if (T1->isRecordType()) {
8818 bool IsComplete = isCompleteType(OpLoc, T1);
8819 auto *T1RD = T1->getAsCXXRecordDecl();
8820 // Complete the type if it can be completed.
8821 // If the type is neither complete nor being defined, bail out now.
8822 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8823 return;
8824
8825 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8826 LookupQualifiedName(Operators, T1RD);
8827 Operators.suppressAccessDiagnostics();
8828
8829 for (LookupResult::iterator Oper = Operators.begin(),
8830 OperEnd = Operators.end();
8831 Oper != OperEnd; ++Oper) {
8832 if (Oper->getAsFunction() &&
8834 !CandidateSet.getRewriteInfo().shouldAddReversed(
8835 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8836 continue;
8837 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8838 Args[0]->Classify(Context), Args.slice(1),
8839 CandidateSet, /*SuppressUserConversion=*/false, PO);
8840 }
8841 }
8842}
8843
8845 OverloadCandidateSet& CandidateSet,
8846 bool IsAssignmentOperator,
8847 unsigned NumContextualBoolArguments) {
8848 // Overload resolution is always an unevaluated context.
8851
8852 // Add this candidate
8853 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8854 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8855 Candidate.Function = nullptr;
8856 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8857
8858 // Determine the implicit conversion sequences for each of the
8859 // arguments.
8860 Candidate.Viable = true;
8861 Candidate.ExplicitCallArguments = Args.size();
8862 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8863 // C++ [over.match.oper]p4:
8864 // For the built-in assignment operators, conversions of the
8865 // left operand are restricted as follows:
8866 // -- no temporaries are introduced to hold the left operand, and
8867 // -- no user-defined conversions are applied to the left
8868 // operand to achieve a type match with the left-most
8869 // parameter of a built-in candidate.
8870 //
8871 // We block these conversions by turning off user-defined
8872 // conversions, since that is the only way that initialization of
8873 // a reference to a non-class type can occur from something that
8874 // is not of the same type.
8875 if (ArgIdx < NumContextualBoolArguments) {
8876 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8877 "Contextual conversion to bool requires bool type");
8878 Candidate.Conversions[ArgIdx]
8879 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8880 } else {
8881 Candidate.Conversions[ArgIdx]
8882 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8883 ArgIdx == 0 && IsAssignmentOperator,
8884 /*InOverloadResolution=*/false,
8885 /*AllowObjCWritebackConversion=*/
8886 getLangOpts().ObjCAutoRefCount);
8887 }
8888 if (Candidate.Conversions[ArgIdx].isBad()) {
8889 Candidate.Viable = false;
8891 break;
8892 }
8893 }
8894}
8895
8896namespace {
8897
8898/// BuiltinCandidateTypeSet - A set of types that will be used for the
8899/// candidate operator functions for built-in operators (C++
8900/// [over.built]). The types are separated into pointer types and
8901/// enumeration types.
8902class BuiltinCandidateTypeSet {
8903 /// TypeSet - A set of types.
8904 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8905
8906 /// PointerTypes - The set of pointer types that will be used in the
8907 /// built-in candidates.
8908 TypeSet PointerTypes;
8909
8910 /// MemberPointerTypes - The set of member pointer types that will be
8911 /// used in the built-in candidates.
8912 TypeSet MemberPointerTypes;
8913
8914 /// EnumerationTypes - The set of enumeration types that will be
8915 /// used in the built-in candidates.
8916 TypeSet EnumerationTypes;
8917
8918 /// The set of vector types that will be used in the built-in
8919 /// candidates.
8920 TypeSet VectorTypes;
8921
8922 /// The set of matrix types that will be used in the built-in
8923 /// candidates.
8924 TypeSet MatrixTypes;
8925
8926 /// The set of _BitInt types that will be used in the built-in candidates.
8927 TypeSet BitIntTypes;
8928
8929 /// A flag indicating non-record types are viable candidates
8930 bool HasNonRecordTypes;
8931
8932 /// A flag indicating whether either arithmetic or enumeration types
8933 /// were present in the candidate set.
8934 bool HasArithmeticOrEnumeralTypes;
8935
8936 /// A flag indicating whether the nullptr type was present in the
8937 /// candidate set.
8938 bool HasNullPtrType;
8939
8940 /// Sema - The semantic analysis instance where we are building the
8941 /// candidate type set.
8942 Sema &SemaRef;
8943
8944 /// Context - The AST context in which we will build the type sets.
8945 ASTContext &Context;
8946
8947 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8948 const Qualifiers &VisibleQuals);
8949 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8950
8951public:
8952 /// iterator - Iterates through the types that are part of the set.
8953 typedef TypeSet::iterator iterator;
8954
8955 BuiltinCandidateTypeSet(Sema &SemaRef)
8956 : HasNonRecordTypes(false),
8957 HasArithmeticOrEnumeralTypes(false),
8958 HasNullPtrType(false),
8959 SemaRef(SemaRef),
8960 Context(SemaRef.Context) { }
8961
8962 void AddTypesConvertedFrom(QualType Ty,
8963 SourceLocation Loc,
8964 bool AllowUserConversions,
8965 bool AllowExplicitConversions,
8966 const Qualifiers &VisibleTypeConversionsQuals);
8967
8968 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8969 llvm::iterator_range<iterator> member_pointer_types() {
8970 return MemberPointerTypes;
8971 }
8972 llvm::iterator_range<iterator> enumeration_types() {
8973 return EnumerationTypes;
8974 }
8975 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8976 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8977 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8978
8979 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8980 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8981 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8982 bool hasNullPtrType() const { return HasNullPtrType; }
8983};
8984
8985} // end anonymous namespace
8986
8987/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8988/// the set of pointer types along with any more-qualified variants of
8989/// that type. For example, if @p Ty is "int const *", this routine
8990/// will add "int const *", "int const volatile *", "int const
8991/// restrict *", and "int const volatile restrict *" to the set of
8992/// pointer types. Returns true if the add of @p Ty itself succeeded,
8993/// false otherwise.
8994///
8995/// FIXME: what to do about extended qualifiers?
8996bool
8997BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8998 const Qualifiers &VisibleQuals) {
8999
9000 // Insert this type.
9001 if (!PointerTypes.insert(Ty))
9002 return false;
9003
9004 QualType PointeeTy;
9005 const PointerType *PointerTy = Ty->getAs<PointerType>();
9006 bool buildObjCPtr = false;
9007 if (!PointerTy) {
9008 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9009 PointeeTy = PTy->getPointeeType();
9010 buildObjCPtr = true;
9011 } else {
9012 PointeeTy = PointerTy->getPointeeType();
9013 }
9014
9015 // Don't add qualified variants of arrays. For one, they're not allowed
9016 // (the qualifier would sink to the element type), and for another, the
9017 // only overload situation where it matters is subscript or pointer +- int,
9018 // and those shouldn't have qualifier variants anyway.
9019 if (PointeeTy->isArrayType())
9020 return true;
9021
9022 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9023 bool hasVolatile = VisibleQuals.hasVolatile();
9024 bool hasRestrict = VisibleQuals.hasRestrict();
9025
9026 // Iterate through all strict supersets of BaseCVR.
9027 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9028 if ((CVR | BaseCVR) != CVR) continue;
9029 // Skip over volatile if no volatile found anywhere in the types.
9030 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9031
9032 // Skip over restrict if no restrict found anywhere in the types, or if
9033 // the type cannot be restrict-qualified.
9034 if ((CVR & Qualifiers::Restrict) &&
9035 (!hasRestrict ||
9036 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9037 continue;
9038
9039 // Build qualified pointee type.
9040 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9041
9042 // Build qualified pointer type.
9043 QualType QPointerTy;
9044 if (!buildObjCPtr)
9045 QPointerTy = Context.getPointerType(QPointeeTy);
9046 else
9047 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9048
9049 // Insert qualified pointer type.
9050 PointerTypes.insert(QPointerTy);
9051 }
9052
9053 return true;
9054}
9055
9056/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9057/// to the set of pointer types along with any more-qualified variants of
9058/// that type. For example, if @p Ty is "int const *", this routine
9059/// will add "int const *", "int const volatile *", "int const
9060/// restrict *", and "int const volatile restrict *" to the set of
9061/// pointer types. Returns true if the add of @p Ty itself succeeded,
9062/// false otherwise.
9063///
9064/// FIXME: what to do about extended qualifiers?
9065bool
9066BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9067 QualType Ty) {
9068 // Insert this type.
9069 if (!MemberPointerTypes.insert(Ty))
9070 return false;
9071
9072 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9073 assert(PointerTy && "type was not a member pointer type!");
9074
9075 QualType PointeeTy = PointerTy->getPointeeType();
9076 // Don't add qualified variants of arrays. For one, they're not allowed
9077 // (the qualifier would sink to the element type), and for another, the
9078 // only overload situation where it matters is subscript or pointer +- int,
9079 // and those shouldn't have qualifier variants anyway.
9080 if (PointeeTy->isArrayType())
9081 return true;
9082 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9083
9084 // Iterate through all strict supersets of the pointee type's CVR
9085 // qualifiers.
9086 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9087 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9088 if ((CVR | BaseCVR) != CVR) continue;
9089
9090 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9091 MemberPointerTypes.insert(Context.getMemberPointerType(
9092 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9093 }
9094
9095 return true;
9096}
9097
9098/// AddTypesConvertedFrom - Add each of the types to which the type @p
9099/// Ty can be implicit converted to the given set of @p Types. We're
9100/// primarily interested in pointer types and enumeration types. We also
9101/// take member pointer types, for the conditional operator.
9102/// AllowUserConversions is true if we should look at the conversion
9103/// functions of a class type, and AllowExplicitConversions if we
9104/// should also include the explicit conversion functions of a class
9105/// type.
9106void
9107BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9108 SourceLocation Loc,
9109 bool AllowUserConversions,
9110 bool AllowExplicitConversions,
9111 const Qualifiers &VisibleQuals) {
9112 // Only deal with canonical types.
9113 Ty = Context.getCanonicalType(Ty);
9114
9115 // Look through reference types; they aren't part of the type of an
9116 // expression for the purposes of conversions.
9117 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9118 Ty = RefTy->getPointeeType();
9119
9120 // If we're dealing with an array type, decay to the pointer.
9121 if (Ty->isArrayType())
9122 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9123
9124 // Otherwise, we don't care about qualifiers on the type.
9125 Ty = Ty.getLocalUnqualifiedType();
9126
9127 // Flag if we ever add a non-record type.
9128 bool TyIsRec = Ty->isRecordType();
9129 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9130
9131 // Flag if we encounter an arithmetic type.
9132 HasArithmeticOrEnumeralTypes =
9133 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9134
9135 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9136 PointerTypes.insert(Ty);
9137 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9138 // Insert our type, and its more-qualified variants, into the set
9139 // of types.
9140 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9141 return;
9142 } else if (Ty->isMemberPointerType()) {
9143 // Member pointers are far easier, since the pointee can't be converted.
9144 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9145 return;
9146 } else if (Ty->isEnumeralType()) {
9147 HasArithmeticOrEnumeralTypes = true;
9148 EnumerationTypes.insert(Ty);
9149 } else if (Ty->isBitIntType()) {
9150 HasArithmeticOrEnumeralTypes = true;
9151 BitIntTypes.insert(Ty);
9152 } else if (Ty->isVectorType()) {
9153 // We treat vector types as arithmetic types in many contexts as an
9154 // extension.
9155 HasArithmeticOrEnumeralTypes = true;
9156 VectorTypes.insert(Ty);
9157 } else if (Ty->isMatrixType()) {
9158 // Similar to vector types, we treat vector types as arithmetic types in
9159 // many contexts as an extension.
9160 HasArithmeticOrEnumeralTypes = true;
9161 MatrixTypes.insert(Ty);
9162 } else if (Ty->isNullPtrType()) {
9163 HasNullPtrType = true;
9164 } else if (AllowUserConversions && TyIsRec) {
9165 // No conversion functions in incomplete types.
9166 if (!SemaRef.isCompleteType(Loc, Ty))
9167 return;
9168
9169 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9170 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9171 if (isa<UsingShadowDecl>(D))
9172 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9173
9174 // Skip conversion function templates; they don't tell us anything
9175 // about which builtin types we can convert to.
9177 continue;
9178
9179 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9180 if (AllowExplicitConversions || !Conv->isExplicit()) {
9181 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9182 VisibleQuals);
9183 }
9184 }
9185 }
9186}
9187/// Helper function for adjusting address spaces for the pointer or reference
9188/// operands of builtin operators depending on the argument.
9193
9194/// Helper function for AddBuiltinOperatorCandidates() that adds
9195/// the volatile- and non-volatile-qualified assignment operators for the
9196/// given type to the candidate set.
9198 QualType T,
9199 ArrayRef<Expr *> Args,
9200 OverloadCandidateSet &CandidateSet) {
9201 QualType ParamTypes[2];
9202
9203 // T& operator=(T&, T)
9204 ParamTypes[0] = S.Context.getLValueReferenceType(
9206 ParamTypes[1] = T;
9207 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9208 /*IsAssignmentOperator=*/true);
9209
9211 // volatile T& operator=(volatile T&, T)
9212 ParamTypes[0] = S.Context.getLValueReferenceType(
9214 Args[0]));
9215 ParamTypes[1] = T;
9216 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9217 /*IsAssignmentOperator=*/true);
9218 }
9219}
9220
9221/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9222/// if any, found in visible type conversion functions found in ArgExpr's type.
9223static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9224 Qualifiers VRQuals;
9225 CXXRecordDecl *ClassDecl;
9226 if (const MemberPointerType *RHSMPType =
9227 ArgExpr->getType()->getAs<MemberPointerType>())
9228 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9229 else
9230 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9231 if (!ClassDecl) {
9232 // Just to be safe, assume the worst case.
9233 VRQuals.addVolatile();
9234 VRQuals.addRestrict();
9235 return VRQuals;
9236 }
9237 if (!ClassDecl->hasDefinition())
9238 return VRQuals;
9239
9240 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9241 if (isa<UsingShadowDecl>(D))
9242 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9243 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9244 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9245 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9246 CanTy = ResTypeRef->getPointeeType();
9247 // Need to go down the pointer/mempointer chain and add qualifiers
9248 // as see them.
9249 bool done = false;
9250 while (!done) {
9251 if (CanTy.isRestrictQualified())
9252 VRQuals.addRestrict();
9253 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9254 CanTy = ResTypePtr->getPointeeType();
9255 else if (const MemberPointerType *ResTypeMPtr =
9256 CanTy->getAs<MemberPointerType>())
9257 CanTy = ResTypeMPtr->getPointeeType();
9258 else
9259 done = true;
9260 if (CanTy.isVolatileQualified())
9261 VRQuals.addVolatile();
9262 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9263 return VRQuals;
9264 }
9265 }
9266 }
9267 return VRQuals;
9268}
9269
9270// Note: We're currently only handling qualifiers that are meaningful for the
9271// LHS of compound assignment overloading.
9273 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9274 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9275 // _Atomic
9276 if (Available.hasAtomic()) {
9277 Available.removeAtomic();
9278 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9279 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9280 return;
9281 }
9282
9283 // volatile
9284 if (Available.hasVolatile()) {
9285 Available.removeVolatile();
9286 assert(!Applied.hasVolatile());
9287 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9288 Callback);
9289 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9290 return;
9291 }
9292
9293 Callback(Applied);
9294}
9295
9297 QualifiersAndAtomic Quals,
9298 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9300 Callback);
9301}
9302
9304 QualifiersAndAtomic Quals,
9305 Sema &S) {
9306 if (Quals.hasAtomic())
9308 if (Quals.hasVolatile())
9311}
9312
9313namespace {
9314
9315/// Helper class to manage the addition of builtin operator overload
9316/// candidates. It provides shared state and utility methods used throughout
9317/// the process, as well as a helper method to add each group of builtin
9318/// operator overloads from the standard to a candidate set.
9319class BuiltinOperatorOverloadBuilder {
9320 // Common instance state available to all overload candidate addition methods.
9321 Sema &S;
9322 ArrayRef<Expr *> Args;
9323 QualifiersAndAtomic VisibleTypeConversionsQuals;
9324 bool HasArithmeticOrEnumeralCandidateType;
9325 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9326 OverloadCandidateSet &CandidateSet;
9327
9328 static constexpr int ArithmeticTypesCap = 26;
9329 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9330
9331 // Define some indices used to iterate over the arithmetic types in
9332 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9333 // types are that preserved by promotion (C++ [over.built]p2).
9334 unsigned FirstIntegralType,
9335 LastIntegralType;
9336 unsigned FirstPromotedIntegralType,
9337 LastPromotedIntegralType;
9338 unsigned FirstPromotedArithmeticType,
9339 LastPromotedArithmeticType;
9340 unsigned NumArithmeticTypes;
9341
9342 void InitArithmeticTypes() {
9343 // Start of promoted types.
9344 FirstPromotedArithmeticType = 0;
9345 ArithmeticTypes.push_back(S.Context.FloatTy);
9346 ArithmeticTypes.push_back(S.Context.DoubleTy);
9347 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9349 ArithmeticTypes.push_back(S.Context.Float128Ty);
9351 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9352
9353 // Start of integral types.
9354 FirstIntegralType = ArithmeticTypes.size();
9355 FirstPromotedIntegralType = ArithmeticTypes.size();
9356 ArithmeticTypes.push_back(S.Context.IntTy);
9357 ArithmeticTypes.push_back(S.Context.LongTy);
9358 ArithmeticTypes.push_back(S.Context.LongLongTy);
9362 ArithmeticTypes.push_back(S.Context.Int128Ty);
9363 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9364 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9365 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9369 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9370
9371 /// We add candidates for the unique, unqualified _BitInt types present in
9372 /// the candidate type set. The candidate set already handled ensuring the
9373 /// type is unqualified and canonical, but because we're adding from N
9374 /// different sets, we need to do some extra work to unique things. Insert
9375 /// the candidates into a unique set, then move from that set into the list
9376 /// of arithmetic types.
9377 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9378 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9379 for (QualType BitTy : Candidate.bitint_types())
9380 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9381 }
9382 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9383 LastPromotedIntegralType = ArithmeticTypes.size();
9384 LastPromotedArithmeticType = ArithmeticTypes.size();
9385 // End of promoted types.
9386
9387 ArithmeticTypes.push_back(S.Context.BoolTy);
9388 ArithmeticTypes.push_back(S.Context.CharTy);
9389 ArithmeticTypes.push_back(S.Context.WCharTy);
9390 if (S.Context.getLangOpts().Char8)
9391 ArithmeticTypes.push_back(S.Context.Char8Ty);
9392 ArithmeticTypes.push_back(S.Context.Char16Ty);
9393 ArithmeticTypes.push_back(S.Context.Char32Ty);
9394 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9395 ArithmeticTypes.push_back(S.Context.ShortTy);
9396 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9397 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9398 LastIntegralType = ArithmeticTypes.size();
9399 NumArithmeticTypes = ArithmeticTypes.size();
9400 // End of integral types.
9401 // FIXME: What about complex? What about half?
9402
9403 // We don't know for sure how many bit-precise candidates were involved, so
9404 // we subtract those from the total when testing whether we're under the
9405 // cap or not.
9406 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9407 ArithmeticTypesCap &&
9408 "Enough inline storage for all arithmetic types.");
9409 }
9410
9411 /// Helper method to factor out the common pattern of adding overloads
9412 /// for '++' and '--' builtin operators.
9413 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9414 bool HasVolatile,
9415 bool HasRestrict) {
9416 QualType ParamTypes[2] = {
9417 S.Context.getLValueReferenceType(CandidateTy),
9418 S.Context.IntTy
9419 };
9420
9421 // Non-volatile version.
9422 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9423
9424 // Use a heuristic to reduce number of builtin candidates in the set:
9425 // add volatile version only if there are conversions to a volatile type.
9426 if (HasVolatile) {
9427 ParamTypes[0] =
9429 S.Context.getVolatileType(CandidateTy));
9430 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9431 }
9432
9433 // Add restrict version only if there are conversions to a restrict type
9434 // and our candidate type is a non-restrict-qualified pointer.
9435 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9436 !CandidateTy.isRestrictQualified()) {
9437 ParamTypes[0]
9440 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9441
9442 if (HasVolatile) {
9443 ParamTypes[0]
9445 S.Context.getCVRQualifiedType(CandidateTy,
9448 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9449 }
9450 }
9451
9452 }
9453
9454 /// Helper to add an overload candidate for a binary builtin with types \p L
9455 /// and \p R.
9456 void AddCandidate(QualType L, QualType R) {
9457 QualType LandR[2] = {L, R};
9458 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9459 }
9460
9461public:
9462 BuiltinOperatorOverloadBuilder(
9463 Sema &S, ArrayRef<Expr *> Args,
9464 QualifiersAndAtomic VisibleTypeConversionsQuals,
9465 bool HasArithmeticOrEnumeralCandidateType,
9466 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9467 OverloadCandidateSet &CandidateSet)
9468 : S(S), Args(Args),
9469 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9470 HasArithmeticOrEnumeralCandidateType(
9471 HasArithmeticOrEnumeralCandidateType),
9472 CandidateTypes(CandidateTypes),
9473 CandidateSet(CandidateSet) {
9474
9475 InitArithmeticTypes();
9476 }
9477
9478 // Increment is deprecated for bool since C++17.
9479 //
9480 // C++ [over.built]p3:
9481 //
9482 // For every pair (T, VQ), where T is an arithmetic type other
9483 // than bool, and VQ is either volatile or empty, there exist
9484 // candidate operator functions of the form
9485 //
9486 // VQ T& operator++(VQ T&);
9487 // T operator++(VQ T&, int);
9488 //
9489 // C++ [over.built]p4:
9490 //
9491 // For every pair (T, VQ), where T is an arithmetic type other
9492 // than bool, and VQ is either volatile or empty, there exist
9493 // candidate operator functions of the form
9494 //
9495 // VQ T& operator--(VQ T&);
9496 // T operator--(VQ T&, int);
9497 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9498 if (!HasArithmeticOrEnumeralCandidateType)
9499 return;
9500
9501 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9502 const auto TypeOfT = ArithmeticTypes[Arith];
9503 if (TypeOfT == S.Context.BoolTy) {
9504 if (Op == OO_MinusMinus)
9505 continue;
9506 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9507 continue;
9508 }
9509 addPlusPlusMinusMinusStyleOverloads(
9510 TypeOfT,
9511 VisibleTypeConversionsQuals.hasVolatile(),
9512 VisibleTypeConversionsQuals.hasRestrict());
9513 }
9514 }
9515
9516 // C++ [over.built]p5:
9517 //
9518 // For every pair (T, VQ), where T is a cv-qualified or
9519 // cv-unqualified object type, and VQ is either volatile or
9520 // empty, there exist candidate operator functions of the form
9521 //
9522 // T*VQ& operator++(T*VQ&);
9523 // T*VQ& operator--(T*VQ&);
9524 // T* operator++(T*VQ&, int);
9525 // T* operator--(T*VQ&, int);
9526 void addPlusPlusMinusMinusPointerOverloads() {
9527 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9528 // Skip pointer types that aren't pointers to object types.
9529 if (!PtrTy->getPointeeType()->isObjectType())
9530 continue;
9531
9532 addPlusPlusMinusMinusStyleOverloads(
9533 PtrTy,
9534 (!PtrTy.isVolatileQualified() &&
9535 VisibleTypeConversionsQuals.hasVolatile()),
9536 (!PtrTy.isRestrictQualified() &&
9537 VisibleTypeConversionsQuals.hasRestrict()));
9538 }
9539 }
9540
9541 // C++ [over.built]p6:
9542 // For every cv-qualified or cv-unqualified object type T, there
9543 // exist candidate operator functions of the form
9544 //
9545 // T& operator*(T*);
9546 //
9547 // C++ [over.built]p7:
9548 // For every function type T that does not have cv-qualifiers or a
9549 // ref-qualifier, there exist candidate operator functions of the form
9550 // T& operator*(T*);
9551 void addUnaryStarPointerOverloads() {
9552 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9553 QualType PointeeTy = ParamTy->getPointeeType();
9554 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9555 continue;
9556
9557 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9558 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9559 continue;
9560
9561 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9562 }
9563 }
9564
9565 // C++ [over.built]p9:
9566 // For every promoted arithmetic type T, there exist candidate
9567 // operator functions of the form
9568 //
9569 // T operator+(T);
9570 // T operator-(T);
9571 void addUnaryPlusOrMinusArithmeticOverloads() {
9572 if (!HasArithmeticOrEnumeralCandidateType)
9573 return;
9574
9575 for (unsigned Arith = FirstPromotedArithmeticType;
9576 Arith < LastPromotedArithmeticType; ++Arith) {
9577 QualType ArithTy = ArithmeticTypes[Arith];
9578 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9579 }
9580
9581 // Extension: We also add these operators for vector types.
9582 for (QualType VecTy : CandidateTypes[0].vector_types())
9583 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9584 }
9585
9586 // C++ [over.built]p8:
9587 // For every type T, there exist candidate operator functions of
9588 // the form
9589 //
9590 // T* operator+(T*);
9591 void addUnaryPlusPointerOverloads() {
9592 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9593 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9594 }
9595
9596 // C++ [over.built]p10:
9597 // For every promoted integral type T, there exist candidate
9598 // operator functions of the form
9599 //
9600 // T operator~(T);
9601 void addUnaryTildePromotedIntegralOverloads() {
9602 if (!HasArithmeticOrEnumeralCandidateType)
9603 return;
9604
9605 for (unsigned Int = FirstPromotedIntegralType;
9606 Int < LastPromotedIntegralType; ++Int) {
9607 QualType IntTy = ArithmeticTypes[Int];
9608 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9609 }
9610
9611 // Extension: We also add this operator for vector types.
9612 for (QualType VecTy : CandidateTypes[0].vector_types())
9613 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9614 }
9615
9616 // C++ [over.match.oper]p16:
9617 // For every pointer to member type T or type std::nullptr_t, there
9618 // exist candidate operator functions of the form
9619 //
9620 // bool operator==(T,T);
9621 // bool operator!=(T,T);
9622 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9623 /// Set of (canonical) types that we've already handled.
9624 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9625
9626 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9627 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9628 // Don't add the same builtin candidate twice.
9629 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9630 continue;
9631
9632 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9633 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9634 }
9635
9636 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9638 if (AddedTypes.insert(NullPtrTy).second) {
9639 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9641 }
9642 }
9643 }
9644 }
9645
9646 // C++ [over.built]p15:
9647 //
9648 // For every T, where T is an enumeration type or a pointer type,
9649 // there exist candidate operator functions of the form
9650 //
9651 // bool operator<(T, T);
9652 // bool operator>(T, T);
9653 // bool operator<=(T, T);
9654 // bool operator>=(T, T);
9655 // bool operator==(T, T);
9656 // bool operator!=(T, T);
9657 // R operator<=>(T, T)
9658 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9659 // C++ [over.match.oper]p3:
9660 // [...]the built-in candidates include all of the candidate operator
9661 // functions defined in 13.6 that, compared to the given operator, [...]
9662 // do not have the same parameter-type-list as any non-template non-member
9663 // candidate.
9664 //
9665 // Note that in practice, this only affects enumeration types because there
9666 // aren't any built-in candidates of record type, and a user-defined operator
9667 // must have an operand of record or enumeration type. Also, the only other
9668 // overloaded operator with enumeration arguments, operator=,
9669 // cannot be overloaded for enumeration types, so this is the only place
9670 // where we must suppress candidates like this.
9671 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9672 UserDefinedBinaryOperators;
9673
9674 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9675 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9676 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9677 CEnd = CandidateSet.end();
9678 C != CEnd; ++C) {
9679 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9680 continue;
9681
9682 if (C->Function->isFunctionTemplateSpecialization())
9683 continue;
9684
9685 // We interpret "same parameter-type-list" as applying to the
9686 // "synthesized candidate, with the order of the two parameters
9687 // reversed", not to the original function.
9688 bool Reversed = C->isReversed();
9689 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9690 ->getType()
9691 .getUnqualifiedType();
9692 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9693 ->getType()
9694 .getUnqualifiedType();
9695
9696 // Skip if either parameter isn't of enumeral type.
9697 if (!FirstParamType->isEnumeralType() ||
9698 !SecondParamType->isEnumeralType())
9699 continue;
9700
9701 // Add this operator to the set of known user-defined operators.
9702 UserDefinedBinaryOperators.insert(
9703 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9704 S.Context.getCanonicalType(SecondParamType)));
9705 }
9706 }
9707 }
9708
9709 /// Set of (canonical) types that we've already handled.
9710 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9711
9712 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9713 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9714 // Don't add the same builtin candidate twice.
9715 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9716 continue;
9717 if (IsSpaceship && PtrTy->isFunctionPointerType())
9718 continue;
9719
9720 QualType ParamTypes[2] = {PtrTy, PtrTy};
9721 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9722 }
9723 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9724 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9725
9726 // Don't add the same builtin candidate twice, or if a user defined
9727 // candidate exists.
9728 if (!AddedTypes.insert(CanonType).second ||
9729 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9730 CanonType)))
9731 continue;
9732 QualType ParamTypes[2] = {EnumTy, EnumTy};
9733 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9734 }
9735 }
9736 }
9737
9738 // C++ [over.built]p13:
9739 //
9740 // For every cv-qualified or cv-unqualified object type T
9741 // there exist candidate operator functions of the form
9742 //
9743 // T* operator+(T*, ptrdiff_t);
9744 // T& operator[](T*, ptrdiff_t); [BELOW]
9745 // T* operator-(T*, ptrdiff_t);
9746 // T* operator+(ptrdiff_t, T*);
9747 // T& operator[](ptrdiff_t, T*); [BELOW]
9748 //
9749 // C++ [over.built]p14:
9750 //
9751 // For every T, where T is a pointer to object type, there
9752 // exist candidate operator functions of the form
9753 //
9754 // ptrdiff_t operator-(T, T);
9755 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9756 /// Set of (canonical) types that we've already handled.
9757 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9758
9759 for (int Arg = 0; Arg < 2; ++Arg) {
9760 QualType AsymmetricParamTypes[2] = {
9763 };
9764 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9765 QualType PointeeTy = PtrTy->getPointeeType();
9766 if (!PointeeTy->isObjectType())
9767 continue;
9768
9769 AsymmetricParamTypes[Arg] = PtrTy;
9770 if (Arg == 0 || Op == OO_Plus) {
9771 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9772 // T* operator+(ptrdiff_t, T*);
9773 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9774 }
9775 if (Op == OO_Minus) {
9776 // ptrdiff_t operator-(T, T);
9777 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9778 continue;
9779
9780 QualType ParamTypes[2] = {PtrTy, PtrTy};
9781 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9782 }
9783 }
9784 }
9785 }
9786
9787 // C++ [over.built]p12:
9788 //
9789 // For every pair of promoted arithmetic types L and R, there
9790 // exist candidate operator functions of the form
9791 //
9792 // LR operator*(L, R);
9793 // LR operator/(L, R);
9794 // LR operator+(L, R);
9795 // LR operator-(L, R);
9796 // bool operator<(L, R);
9797 // bool operator>(L, R);
9798 // bool operator<=(L, R);
9799 // bool operator>=(L, R);
9800 // bool operator==(L, R);
9801 // bool operator!=(L, R);
9802 //
9803 // where LR is the result of the usual arithmetic conversions
9804 // between types L and R.
9805 //
9806 // C++ [over.built]p24:
9807 //
9808 // For every pair of promoted arithmetic types L and R, there exist
9809 // candidate operator functions of the form
9810 //
9811 // LR operator?(bool, L, R);
9812 //
9813 // where LR is the result of the usual arithmetic conversions
9814 // between types L and R.
9815 // Our candidates ignore the first parameter.
9816 void addGenericBinaryArithmeticOverloads() {
9817 if (!HasArithmeticOrEnumeralCandidateType)
9818 return;
9819
9820 for (unsigned Left = FirstPromotedArithmeticType;
9821 Left < LastPromotedArithmeticType; ++Left) {
9822 for (unsigned Right = FirstPromotedArithmeticType;
9823 Right < LastPromotedArithmeticType; ++Right) {
9824 QualType LandR[2] = { ArithmeticTypes[Left],
9825 ArithmeticTypes[Right] };
9826 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9827 }
9828 }
9829
9830 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9831 // conditional operator for vector types.
9832 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9833 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9834 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9835 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9836 }
9837 }
9838
9839 /// Add binary operator overloads for each candidate matrix type M1, M2:
9840 /// * (M1, M1) -> M1
9841 /// * (M1, M1.getElementType()) -> M1
9842 /// * (M2.getElementType(), M2) -> M2
9843 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9844 void addMatrixBinaryArithmeticOverloads() {
9845 if (!HasArithmeticOrEnumeralCandidateType)
9846 return;
9847
9848 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9849 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9850 AddCandidate(M1, M1);
9851 }
9852
9853 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9854 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9855 if (!CandidateTypes[0].containsMatrixType(M2))
9856 AddCandidate(M2, M2);
9857 }
9858 }
9859
9860 // C++2a [over.built]p14:
9861 //
9862 // For every integral type T there exists a candidate operator function
9863 // of the form
9864 //
9865 // std::strong_ordering operator<=>(T, T)
9866 //
9867 // C++2a [over.built]p15:
9868 //
9869 // For every pair of floating-point types L and R, there exists a candidate
9870 // operator function of the form
9871 //
9872 // std::partial_ordering operator<=>(L, R);
9873 //
9874 // FIXME: The current specification for integral types doesn't play nice with
9875 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9876 // comparisons. Under the current spec this can lead to ambiguity during
9877 // overload resolution. For example:
9878 //
9879 // enum A : int {a};
9880 // auto x = (a <=> (long)42);
9881 //
9882 // error: call is ambiguous for arguments 'A' and 'long'.
9883 // note: candidate operator<=>(int, int)
9884 // note: candidate operator<=>(long, long)
9885 //
9886 // To avoid this error, this function deviates from the specification and adds
9887 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9888 // arithmetic types (the same as the generic relational overloads).
9889 //
9890 // For now this function acts as a placeholder.
9891 void addThreeWayArithmeticOverloads() {
9892 addGenericBinaryArithmeticOverloads();
9893 }
9894
9895 // C++ [over.built]p17:
9896 //
9897 // For every pair of promoted integral types L and R, there
9898 // exist candidate operator functions of the form
9899 //
9900 // LR operator%(L, R);
9901 // LR operator&(L, R);
9902 // LR operator^(L, R);
9903 // LR operator|(L, R);
9904 // L operator<<(L, R);
9905 // L operator>>(L, R);
9906 //
9907 // where LR is the result of the usual arithmetic conversions
9908 // between types L and R.
9909 void addBinaryBitwiseArithmeticOverloads() {
9910 if (!HasArithmeticOrEnumeralCandidateType)
9911 return;
9912
9913 for (unsigned Left = FirstPromotedIntegralType;
9914 Left < LastPromotedIntegralType; ++Left) {
9915 for (unsigned Right = FirstPromotedIntegralType;
9916 Right < LastPromotedIntegralType; ++Right) {
9917 QualType LandR[2] = { ArithmeticTypes[Left],
9918 ArithmeticTypes[Right] };
9919 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9920 }
9921 }
9922 }
9923
9924 // C++ [over.built]p20:
9925 //
9926 // For every pair (T, VQ), where T is an enumeration or
9927 // pointer to member type and VQ is either volatile or
9928 // empty, there exist candidate operator functions of the form
9929 //
9930 // VQ T& operator=(VQ T&, T);
9931 void addAssignmentMemberPointerOrEnumeralOverloads() {
9932 /// Set of (canonical) types that we've already handled.
9933 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9934
9935 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9936 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9937 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9938 continue;
9939
9940 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9941 }
9942
9943 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9944 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9945 continue;
9946
9947 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9948 }
9949 }
9950 }
9951
9952 // C++ [over.built]p19:
9953 //
9954 // For every pair (T, VQ), where T is any type and VQ is either
9955 // volatile or empty, there exist candidate operator functions
9956 // of the form
9957 //
9958 // T*VQ& operator=(T*VQ&, T*);
9959 //
9960 // C++ [over.built]p21:
9961 //
9962 // For every pair (T, VQ), where T is a cv-qualified or
9963 // cv-unqualified object type and VQ is either volatile or
9964 // empty, there exist candidate operator functions of the form
9965 //
9966 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9967 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9968 void addAssignmentPointerOverloads(bool isEqualOp) {
9969 /// Set of (canonical) types that we've already handled.
9970 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9971
9972 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9973 // If this is operator=, keep track of the builtin candidates we added.
9974 if (isEqualOp)
9975 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9976 else if (!PtrTy->getPointeeType()->isObjectType())
9977 continue;
9978
9979 // non-volatile version
9980 QualType ParamTypes[2] = {
9982 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9983 };
9984 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9985 /*IsAssignmentOperator=*/ isEqualOp);
9986
9987 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9988 VisibleTypeConversionsQuals.hasVolatile();
9989 if (NeedVolatile) {
9990 // volatile version
9991 ParamTypes[0] =
9993 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9994 /*IsAssignmentOperator=*/isEqualOp);
9995 }
9996
9997 if (!PtrTy.isRestrictQualified() &&
9998 VisibleTypeConversionsQuals.hasRestrict()) {
9999 // restrict version
10000 ParamTypes[0] =
10002 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10003 /*IsAssignmentOperator=*/isEqualOp);
10004
10005 if (NeedVolatile) {
10006 // volatile restrict version
10007 ParamTypes[0] =
10010 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10011 /*IsAssignmentOperator=*/isEqualOp);
10012 }
10013 }
10014 }
10015
10016 if (isEqualOp) {
10017 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10018 // Make sure we don't add the same candidate twice.
10019 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10020 continue;
10021
10022 QualType ParamTypes[2] = {
10024 PtrTy,
10025 };
10026
10027 // non-volatile version
10028 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10029 /*IsAssignmentOperator=*/true);
10030
10031 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10032 VisibleTypeConversionsQuals.hasVolatile();
10033 if (NeedVolatile) {
10034 // volatile version
10035 ParamTypes[0] = S.Context.getLValueReferenceType(
10036 S.Context.getVolatileType(PtrTy));
10037 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10038 /*IsAssignmentOperator=*/true);
10039 }
10040
10041 if (!PtrTy.isRestrictQualified() &&
10042 VisibleTypeConversionsQuals.hasRestrict()) {
10043 // restrict version
10044 ParamTypes[0] = S.Context.getLValueReferenceType(
10045 S.Context.getRestrictType(PtrTy));
10046 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10047 /*IsAssignmentOperator=*/true);
10048
10049 if (NeedVolatile) {
10050 // volatile restrict version
10051 ParamTypes[0] =
10054 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10055 /*IsAssignmentOperator=*/true);
10056 }
10057 }
10058 }
10059 }
10060 }
10061
10062 // C++ [over.built]p18:
10063 //
10064 // For every triple (L, VQ, R), where L is an arithmetic type,
10065 // VQ is either volatile or empty, and R is a promoted
10066 // arithmetic type, there exist candidate operator functions of
10067 // the form
10068 //
10069 // VQ L& operator=(VQ L&, R);
10070 // VQ L& operator*=(VQ L&, R);
10071 // VQ L& operator/=(VQ L&, R);
10072 // VQ L& operator+=(VQ L&, R);
10073 // VQ L& operator-=(VQ L&, R);
10074 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10075 if (!HasArithmeticOrEnumeralCandidateType)
10076 return;
10077
10078 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10079 for (unsigned Right = FirstPromotedArithmeticType;
10080 Right < LastPromotedArithmeticType; ++Right) {
10081 QualType ParamTypes[2];
10082 ParamTypes[1] = ArithmeticTypes[Right];
10084 S, ArithmeticTypes[Left], Args[0]);
10085
10087 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10088 ParamTypes[0] =
10089 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10090 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10091 /*IsAssignmentOperator=*/isEqualOp);
10092 });
10093 }
10094 }
10095
10096 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10097 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10098 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10099 QualType ParamTypes[2];
10100 ParamTypes[1] = Vec2Ty;
10101 // Add this built-in operator as a candidate (VQ is empty).
10102 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10103 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10104 /*IsAssignmentOperator=*/isEqualOp);
10105
10106 // Add this built-in operator as a candidate (VQ is 'volatile').
10107 if (VisibleTypeConversionsQuals.hasVolatile()) {
10108 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10109 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10110 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10111 /*IsAssignmentOperator=*/isEqualOp);
10112 }
10113 }
10114 }
10115
10116 // C++ [over.built]p22:
10117 //
10118 // For every triple (L, VQ, R), where L is an integral type, VQ
10119 // is either volatile or empty, and R is a promoted integral
10120 // type, there exist candidate operator functions of the form
10121 //
10122 // VQ L& operator%=(VQ L&, R);
10123 // VQ L& operator<<=(VQ L&, R);
10124 // VQ L& operator>>=(VQ L&, R);
10125 // VQ L& operator&=(VQ L&, R);
10126 // VQ L& operator^=(VQ L&, R);
10127 // VQ L& operator|=(VQ L&, R);
10128 void addAssignmentIntegralOverloads() {
10129 if (!HasArithmeticOrEnumeralCandidateType)
10130 return;
10131
10132 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10133 for (unsigned Right = FirstPromotedIntegralType;
10134 Right < LastPromotedIntegralType; ++Right) {
10135 QualType ParamTypes[2];
10136 ParamTypes[1] = ArithmeticTypes[Right];
10138 S, ArithmeticTypes[Left], Args[0]);
10139
10141 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10142 ParamTypes[0] =
10143 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10144 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10145 });
10146 }
10147 }
10148 }
10149
10150 // C++ [over.operator]p23:
10151 //
10152 // There also exist candidate operator functions of the form
10153 //
10154 // bool operator!(bool);
10155 // bool operator&&(bool, bool);
10156 // bool operator||(bool, bool);
10157 void addExclaimOverload() {
10158 QualType ParamTy = S.Context.BoolTy;
10159 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10160 /*IsAssignmentOperator=*/false,
10161 /*NumContextualBoolArguments=*/1);
10162 }
10163 void addAmpAmpOrPipePipeOverload() {
10164 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10165 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10166 /*IsAssignmentOperator=*/false,
10167 /*NumContextualBoolArguments=*/2);
10168 }
10169
10170 // C++ [over.built]p13:
10171 //
10172 // For every cv-qualified or cv-unqualified object type T there
10173 // exist candidate operator functions of the form
10174 //
10175 // T* operator+(T*, ptrdiff_t); [ABOVE]
10176 // T& operator[](T*, ptrdiff_t);
10177 // T* operator-(T*, ptrdiff_t); [ABOVE]
10178 // T* operator+(ptrdiff_t, T*); [ABOVE]
10179 // T& operator[](ptrdiff_t, T*);
10180 void addSubscriptOverloads() {
10181 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10182 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10183 QualType PointeeType = PtrTy->getPointeeType();
10184 if (!PointeeType->isObjectType())
10185 continue;
10186
10187 // T& operator[](T*, ptrdiff_t)
10188 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10189 }
10190
10191 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10192 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10193 QualType PointeeType = PtrTy->getPointeeType();
10194 if (!PointeeType->isObjectType())
10195 continue;
10196
10197 // T& operator[](ptrdiff_t, T*)
10198 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10199 }
10200 }
10201
10202 // C++ [over.built]p11:
10203 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10204 // C1 is the same type as C2 or is a derived class of C2, T is an object
10205 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10206 // there exist candidate operator functions of the form
10207 //
10208 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10209 //
10210 // where CV12 is the union of CV1 and CV2.
10211 void addArrowStarOverloads() {
10212 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10213 QualType C1Ty = PtrTy;
10214 QualType C1;
10215 QualifierCollector Q1;
10216 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10217 if (!isa<RecordType>(C1))
10218 continue;
10219 // heuristic to reduce number of builtin candidates in the set.
10220 // Add volatile/restrict version only if there are conversions to a
10221 // volatile/restrict type.
10222 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10223 continue;
10224 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10225 continue;
10226 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10227 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10228 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10229 *D2 = mptr->getMostRecentCXXRecordDecl();
10230 if (!declaresSameEntity(D1, D2) &&
10231 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10232 break;
10233 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10234 // build CV12 T&
10235 QualType T = mptr->getPointeeType();
10236 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10237 T.isVolatileQualified())
10238 continue;
10239 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10240 T.isRestrictQualified())
10241 continue;
10242 T = Q1.apply(S.Context, T);
10243 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10244 }
10245 }
10246 }
10247
10248 // Note that we don't consider the first argument, since it has been
10249 // contextually converted to bool long ago. The candidates below are
10250 // therefore added as binary.
10251 //
10252 // C++ [over.built]p25:
10253 // For every type T, where T is a pointer, pointer-to-member, or scoped
10254 // enumeration type, there exist candidate operator functions of the form
10255 //
10256 // T operator?(bool, T, T);
10257 //
10258 void addConditionalOperatorOverloads() {
10259 /// Set of (canonical) types that we've already handled.
10260 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10261
10262 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10263 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10264 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10265 continue;
10266
10267 QualType ParamTypes[2] = {PtrTy, PtrTy};
10268 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10269 }
10270
10271 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10272 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10273 continue;
10274
10275 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10276 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10277 }
10278
10279 if (S.getLangOpts().CPlusPlus11) {
10280 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10281 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10282 continue;
10283
10284 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10285 continue;
10286
10287 QualType ParamTypes[2] = {EnumTy, EnumTy};
10288 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10289 }
10290 }
10291 }
10292 }
10293};
10294
10295} // end anonymous namespace
10296
10298 SourceLocation OpLoc,
10299 ArrayRef<Expr *> Args,
10300 OverloadCandidateSet &CandidateSet) {
10301 // Find all of the types that the arguments can convert to, but only
10302 // if the operator we're looking at has built-in operator candidates
10303 // that make use of these types. Also record whether we encounter non-record
10304 // candidate types or either arithmetic or enumeral candidate types.
10305 QualifiersAndAtomic VisibleTypeConversionsQuals;
10306 VisibleTypeConversionsQuals.addConst();
10307 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10308 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10309 if (Args[ArgIdx]->getType()->isAtomicType())
10310 VisibleTypeConversionsQuals.addAtomic();
10311 }
10312
10313 bool HasNonRecordCandidateType = false;
10314 bool HasArithmeticOrEnumeralCandidateType = false;
10316 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10317 CandidateTypes.emplace_back(*this);
10318 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10319 OpLoc,
10320 true,
10321 (Op == OO_Exclaim ||
10322 Op == OO_AmpAmp ||
10323 Op == OO_PipePipe),
10324 VisibleTypeConversionsQuals);
10325 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10326 CandidateTypes[ArgIdx].hasNonRecordTypes();
10327 HasArithmeticOrEnumeralCandidateType =
10328 HasArithmeticOrEnumeralCandidateType ||
10329 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10330 }
10331
10332 // Exit early when no non-record types have been added to the candidate set
10333 // for any of the arguments to the operator.
10334 //
10335 // We can't exit early for !, ||, or &&, since there we have always have
10336 // 'bool' overloads.
10337 if (!HasNonRecordCandidateType &&
10338 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10339 return;
10340
10341 // Setup an object to manage the common state for building overloads.
10342 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10343 VisibleTypeConversionsQuals,
10344 HasArithmeticOrEnumeralCandidateType,
10345 CandidateTypes, CandidateSet);
10346
10347 // Dispatch over the operation to add in only those overloads which apply.
10348 switch (Op) {
10349 case OO_None:
10351 llvm_unreachable("Expected an overloaded operator");
10352
10353 case OO_New:
10354 case OO_Delete:
10355 case OO_Array_New:
10356 case OO_Array_Delete:
10357 case OO_Call:
10358 llvm_unreachable(
10359 "Special operators don't use AddBuiltinOperatorCandidates");
10360
10361 case OO_Comma:
10362 case OO_Arrow:
10363 case OO_Coawait:
10364 // C++ [over.match.oper]p3:
10365 // -- For the operator ',', the unary operator '&', the
10366 // operator '->', or the operator 'co_await', the
10367 // built-in candidates set is empty.
10368 break;
10369
10370 case OO_Plus: // '+' is either unary or binary
10371 if (Args.size() == 1)
10372 OpBuilder.addUnaryPlusPointerOverloads();
10373 [[fallthrough]];
10374
10375 case OO_Minus: // '-' is either unary or binary
10376 if (Args.size() == 1) {
10377 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10378 } else {
10379 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10380 OpBuilder.addGenericBinaryArithmeticOverloads();
10381 OpBuilder.addMatrixBinaryArithmeticOverloads();
10382 }
10383 break;
10384
10385 case OO_Star: // '*' is either unary or binary
10386 if (Args.size() == 1)
10387 OpBuilder.addUnaryStarPointerOverloads();
10388 else {
10389 OpBuilder.addGenericBinaryArithmeticOverloads();
10390 OpBuilder.addMatrixBinaryArithmeticOverloads();
10391 }
10392 break;
10393
10394 case OO_Slash:
10395 OpBuilder.addGenericBinaryArithmeticOverloads();
10396 break;
10397
10398 case OO_PlusPlus:
10399 case OO_MinusMinus:
10400 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10401 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10402 break;
10403
10404 case OO_EqualEqual:
10405 case OO_ExclaimEqual:
10406 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10407 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10408 OpBuilder.addGenericBinaryArithmeticOverloads();
10409 break;
10410
10411 case OO_Less:
10412 case OO_Greater:
10413 case OO_LessEqual:
10414 case OO_GreaterEqual:
10415 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10416 OpBuilder.addGenericBinaryArithmeticOverloads();
10417 break;
10418
10419 case OO_Spaceship:
10420 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10421 OpBuilder.addThreeWayArithmeticOverloads();
10422 break;
10423
10424 case OO_Percent:
10425 case OO_Caret:
10426 case OO_Pipe:
10427 case OO_LessLess:
10428 case OO_GreaterGreater:
10429 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10430 break;
10431
10432 case OO_Amp: // '&' is either unary or binary
10433 if (Args.size() == 1)
10434 // C++ [over.match.oper]p3:
10435 // -- For the operator ',', the unary operator '&', or the
10436 // operator '->', the built-in candidates set is empty.
10437 break;
10438
10439 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10440 break;
10441
10442 case OO_Tilde:
10443 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10444 break;
10445
10446 case OO_Equal:
10447 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10448 [[fallthrough]];
10449
10450 case OO_PlusEqual:
10451 case OO_MinusEqual:
10452 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10453 [[fallthrough]];
10454
10455 case OO_StarEqual:
10456 case OO_SlashEqual:
10457 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10458 break;
10459
10460 case OO_PercentEqual:
10461 case OO_LessLessEqual:
10462 case OO_GreaterGreaterEqual:
10463 case OO_AmpEqual:
10464 case OO_CaretEqual:
10465 case OO_PipeEqual:
10466 OpBuilder.addAssignmentIntegralOverloads();
10467 break;
10468
10469 case OO_Exclaim:
10470 OpBuilder.addExclaimOverload();
10471 break;
10472
10473 case OO_AmpAmp:
10474 case OO_PipePipe:
10475 OpBuilder.addAmpAmpOrPipePipeOverload();
10476 break;
10477
10478 case OO_Subscript:
10479 if (Args.size() == 2)
10480 OpBuilder.addSubscriptOverloads();
10481 break;
10482
10483 case OO_ArrowStar:
10484 OpBuilder.addArrowStarOverloads();
10485 break;
10486
10487 case OO_Conditional:
10488 OpBuilder.addConditionalOperatorOverloads();
10489 OpBuilder.addGenericBinaryArithmeticOverloads();
10490 break;
10491 }
10492}
10493
10494void
10496 SourceLocation Loc,
10497 ArrayRef<Expr *> Args,
10498 TemplateArgumentListInfo *ExplicitTemplateArgs,
10499 OverloadCandidateSet& CandidateSet,
10500 bool PartialOverloading) {
10501 ADLResult Fns;
10502
10503 // FIXME: This approach for uniquing ADL results (and removing
10504 // redundant candidates from the set) relies on pointer-equality,
10505 // which means we need to key off the canonical decl. However,
10506 // always going back to the canonical decl might not get us the
10507 // right set of default arguments. What default arguments are
10508 // we supposed to consider on ADL candidates, anyway?
10509
10510 // FIXME: Pass in the explicit template arguments?
10511 ArgumentDependentLookup(Name, Loc, Args, Fns);
10512
10513 ArrayRef<Expr *> ReversedArgs;
10514
10515 // Erase all of the candidates we already knew about.
10516 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10517 CandEnd = CandidateSet.end();
10518 Cand != CandEnd; ++Cand)
10519 if (Cand->Function) {
10520 FunctionDecl *Fn = Cand->Function;
10521 Fns.erase(Fn);
10522 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10523 Fns.erase(FunTmpl);
10524 }
10525
10526 // For each of the ADL candidates we found, add it to the overload
10527 // set.
10528 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10530
10531 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10532 if (ExplicitTemplateArgs)
10533 continue;
10534
10536 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10537 PartialOverloading, /*AllowExplicit=*/true,
10538 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10539 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10541 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10542 /*SuppressUserConversions=*/false, PartialOverloading,
10543 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10544 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10545 }
10546 } else {
10547 auto *FTD = cast<FunctionTemplateDecl>(*I);
10549 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10550 /*SuppressUserConversions=*/false, PartialOverloading,
10551 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10552 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10553 *this, Args, FTD->getTemplatedDecl())) {
10554
10555 // As template candidates are not deduced immediately,
10556 // persist the array in the overload set.
10557 if (ReversedArgs.empty())
10558 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10559
10561 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10562 /*SuppressUserConversions=*/false, PartialOverloading,
10563 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10565 }
10566 }
10567 }
10568}
10569
10570namespace {
10571enum class Comparison { Equal, Better, Worse };
10572}
10573
10574/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10575/// overload resolution.
10576///
10577/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10578/// Cand1's first N enable_if attributes have precisely the same conditions as
10579/// Cand2's first N enable_if attributes (where N = the number of enable_if
10580/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10581///
10582/// Note that you can have a pair of candidates such that Cand1's enable_if
10583/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10584/// worse than Cand1's.
10585static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10586 const FunctionDecl *Cand2) {
10587 // Common case: One (or both) decls don't have enable_if attrs.
10588 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10589 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10590 if (!Cand1Attr || !Cand2Attr) {
10591 if (Cand1Attr == Cand2Attr)
10592 return Comparison::Equal;
10593 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10594 }
10595
10596 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10597 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10598
10599 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10600 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10601 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10602 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10603
10604 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10605 // has fewer enable_if attributes than Cand2, and vice versa.
10606 if (!Cand1A)
10607 return Comparison::Worse;
10608 if (!Cand2A)
10609 return Comparison::Better;
10610
10611 Cand1ID.clear();
10612 Cand2ID.clear();
10613
10614 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10615 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10616 if (Cand1ID != Cand2ID)
10617 return Comparison::Worse;
10618 }
10619
10620 return Comparison::Equal;
10621}
10622
10623static Comparison
10625 const OverloadCandidate &Cand2) {
10626 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10627 !Cand2.Function->isMultiVersion())
10628 return Comparison::Equal;
10629
10630 // If both are invalid, they are equal. If one of them is invalid, the other
10631 // is better.
10632 if (Cand1.Function->isInvalidDecl()) {
10633 if (Cand2.Function->isInvalidDecl())
10634 return Comparison::Equal;
10635 return Comparison::Worse;
10636 }
10637 if (Cand2.Function->isInvalidDecl())
10638 return Comparison::Better;
10639
10640 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10641 // cpu_dispatch, else arbitrarily based on the identifiers.
10642 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10643 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10644 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10645 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10646
10647 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10648 return Comparison::Equal;
10649
10650 if (Cand1CPUDisp && !Cand2CPUDisp)
10651 return Comparison::Better;
10652 if (Cand2CPUDisp && !Cand1CPUDisp)
10653 return Comparison::Worse;
10654
10655 if (Cand1CPUSpec && Cand2CPUSpec) {
10656 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10657 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10658 ? Comparison::Better
10659 : Comparison::Worse;
10660
10661 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10662 FirstDiff = std::mismatch(
10663 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10664 Cand2CPUSpec->cpus_begin(),
10665 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10666 return LHS->getName() == RHS->getName();
10667 });
10668
10669 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10670 "Two different cpu-specific versions should not have the same "
10671 "identifier list, otherwise they'd be the same decl!");
10672 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10673 ? Comparison::Better
10674 : Comparison::Worse;
10675 }
10676 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10677}
10678
10679/// Compute the type of the implicit object parameter for the given function,
10680/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10681/// null QualType if there is a 'matches anything' implicit object parameter.
10682static std::optional<QualType>
10685 return std::nullopt;
10686
10687 auto *M = cast<CXXMethodDecl>(F);
10688 // Static member functions' object parameters match all types.
10689 if (M->isStatic())
10690 return QualType();
10691 return M->getFunctionObjectParameterReferenceType();
10692}
10693
10694// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10695// represent the same entity.
10696static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10697 const FunctionDecl *F2) {
10698 if (declaresSameEntity(F1, F2))
10699 return true;
10700 auto PT1 = F1->getPrimaryTemplate();
10701 auto PT2 = F2->getPrimaryTemplate();
10702 if (PT1 && PT2) {
10703 if (declaresSameEntity(PT1, PT2) ||
10704 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10705 PT2->getInstantiatedFromMemberTemplate()))
10706 return true;
10707 }
10708 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10709 // different functions with same params). Consider removing this (as no test
10710 // fail w/o it).
10711 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10712 if (First) {
10713 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10714 return *T;
10715 }
10716 assert(I < F->getNumParams());
10717 return F->getParamDecl(I++)->getType();
10718 };
10719
10720 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10721 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10722
10723 if (F1NumParams != F2NumParams)
10724 return false;
10725
10726 unsigned I1 = 0, I2 = 0;
10727 for (unsigned I = 0; I != F1NumParams; ++I) {
10728 QualType T1 = NextParam(F1, I1, I == 0);
10729 QualType T2 = NextParam(F2, I2, I == 0);
10730 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10731 if (!Context.hasSameUnqualifiedType(T1, T2))
10732 return false;
10733 }
10734 return true;
10735}
10736
10737/// We're allowed to use constraints partial ordering only if the candidates
10738/// have the same parameter types:
10739/// [over.match.best.general]p2.6
10740/// F1 and F2 are non-template functions with the same
10741/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10743 FunctionDecl *Fn2,
10744 bool IsFn1Reversed,
10745 bool IsFn2Reversed) {
10746 assert(Fn1 && Fn2);
10747 if (Fn1->isVariadic() != Fn2->isVariadic())
10748 return false;
10749
10750 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10751 IsFn1Reversed ^ IsFn2Reversed))
10752 return false;
10753
10754 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10755 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10756 if (Mem1 && Mem2) {
10757 // if they are member functions, both are direct members of the same class,
10758 // and
10759 if (Mem1->getParent() != Mem2->getParent())
10760 return false;
10761 // if both are non-static member functions, they have the same types for
10762 // their object parameters
10763 if (Mem1->isInstance() && Mem2->isInstance() &&
10765 Mem1->getFunctionObjectParameterReferenceType(),
10766 Mem1->getFunctionObjectParameterReferenceType()))
10767 return false;
10768 }
10769 return true;
10770}
10771
10772static FunctionDecl *
10774 bool IsFn1Reversed, bool IsFn2Reversed) {
10775 if (!Fn1 || !Fn2)
10776 return nullptr;
10777
10778 // C++ [temp.constr.order]:
10779 // A non-template function F1 is more partial-ordering-constrained than a
10780 // non-template function F2 if:
10781 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10782 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10783
10784 if (Cand1IsSpecialization || Cand2IsSpecialization)
10785 return nullptr;
10786
10787 // - they have the same non-object-parameter-type-lists, and [...]
10788 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10789 IsFn2Reversed))
10790 return nullptr;
10791
10792 // - the declaration of F1 is more constrained than the declaration of F2.
10793 return S.getMoreConstrainedFunction(Fn1, Fn2);
10794}
10795
10796/// isBetterOverloadCandidate - Determines whether the first overload
10797/// candidate is a better candidate than the second (C++ 13.3.3p1).
10799 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10801 bool PartialOverloading) {
10802 // Define viable functions to be better candidates than non-viable
10803 // functions.
10804 if (!Cand2.Viable)
10805 return Cand1.Viable;
10806 else if (!Cand1.Viable)
10807 return false;
10808
10809 // [CUDA] A function with 'never' preference is marked not viable, therefore
10810 // is never shown up here. The worst preference shown up here is 'wrong side',
10811 // e.g. an H function called by a HD function in device compilation. This is
10812 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10813 // function which is called only by an H function. A deferred diagnostic will
10814 // be triggered if it is emitted. However a wrong-sided function is still
10815 // a viable candidate here.
10816 //
10817 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10818 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10819 // can be emitted, Cand1 is not better than Cand2. This rule should have
10820 // precedence over other rules.
10821 //
10822 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10823 // other rules should be used to determine which is better. This is because
10824 // host/device based overloading resolution is mostly for determining
10825 // viability of a function. If two functions are both viable, other factors
10826 // should take precedence in preference, e.g. the standard-defined preferences
10827 // like argument conversion ranks or enable_if partial-ordering. The
10828 // preference for pass-object-size parameters is probably most similar to a
10829 // type-based-overloading decision and so should take priority.
10830 //
10831 // If other rules cannot determine which is better, CUDA preference will be
10832 // used again to determine which is better.
10833 //
10834 // TODO: Currently IdentifyPreference does not return correct values
10835 // for functions called in global variable initializers due to missing
10836 // correct context about device/host. Therefore we can only enforce this
10837 // rule when there is a caller. We should enforce this rule for functions
10838 // in global variable initializers once proper context is added.
10839 //
10840 // TODO: We can only enable the hostness based overloading resolution when
10841 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10842 // overloading resolution diagnostics.
10843 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10844 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10845 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10846 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10847 bool IsCand1ImplicitHD =
10849 bool IsCand2ImplicitHD =
10851 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10852 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10853 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10854 // The implicit HD function may be a function in a system header which
10855 // is forced by pragma. In device compilation, if we prefer HD candidates
10856 // over wrong-sided candidates, overloading resolution may change, which
10857 // may result in non-deferrable diagnostics. As a workaround, we let
10858 // implicit HD candidates take equal preference as wrong-sided candidates.
10859 // This will preserve the overloading resolution.
10860 // TODO: We still need special handling of implicit HD functions since
10861 // they may incur other diagnostics to be deferred. We should make all
10862 // host/device related diagnostics deferrable and remove special handling
10863 // of implicit HD functions.
10864 auto EmitThreshold =
10865 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10866 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10869 auto Cand1Emittable = P1 > EmitThreshold;
10870 auto Cand2Emittable = P2 > EmitThreshold;
10871 if (Cand1Emittable && !Cand2Emittable)
10872 return true;
10873 if (!Cand1Emittable && Cand2Emittable)
10874 return false;
10875 }
10876 }
10877
10878 // C++ [over.match.best]p1: (Changed in C++23)
10879 //
10880 // -- if F is a static member function, ICS1(F) is defined such
10881 // that ICS1(F) is neither better nor worse than ICS1(G) for
10882 // any function G, and, symmetrically, ICS1(G) is neither
10883 // better nor worse than ICS1(F).
10884 unsigned StartArg = 0;
10885 if (!Cand1.TookAddressOfOverload &&
10887 StartArg = 1;
10888
10889 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10890 // We don't allow incompatible pointer conversions in C++.
10891 if (!S.getLangOpts().CPlusPlus)
10892 return ICS.isStandard() &&
10893 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10894
10895 // The only ill-formed conversion we allow in C++ is the string literal to
10896 // char* conversion, which is only considered ill-formed after C++11.
10897 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10899 };
10900
10901 // Define functions that don't require ill-formed conversions for a given
10902 // argument to be better candidates than functions that do.
10903 unsigned NumArgs = Cand1.Conversions.size();
10904 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10905 bool HasBetterConversion = false;
10906 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10907 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10908 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10909 if (Cand1Bad != Cand2Bad) {
10910 if (Cand1Bad)
10911 return false;
10912 HasBetterConversion = true;
10913 }
10914 }
10915
10916 if (HasBetterConversion)
10917 return true;
10918
10919 // C++ [over.match.best]p1:
10920 // A viable function F1 is defined to be a better function than another
10921 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10922 // conversion sequence than ICSi(F2), and then...
10923 bool HasWorseConversion = false;
10924 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10926 Cand1.Conversions[ArgIdx],
10927 Cand2.Conversions[ArgIdx])) {
10929 // Cand1 has a better conversion sequence.
10930 HasBetterConversion = true;
10931 break;
10932
10934 if (Cand1.Function && Cand2.Function &&
10935 Cand1.isReversed() != Cand2.isReversed() &&
10936 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10937 // Work around large-scale breakage caused by considering reversed
10938 // forms of operator== in C++20:
10939 //
10940 // When comparing a function against a reversed function, if we have a
10941 // better conversion for one argument and a worse conversion for the
10942 // other, the implicit conversion sequences are treated as being equally
10943 // good.
10944 //
10945 // This prevents a comparison function from being considered ambiguous
10946 // with a reversed form that is written in the same way.
10947 //
10948 // We diagnose this as an extension from CreateOverloadedBinOp.
10949 HasWorseConversion = true;
10950 break;
10951 }
10952
10953 // Cand1 can't be better than Cand2.
10954 return false;
10955
10957 // Do nothing.
10958 break;
10959 }
10960 }
10961
10962 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10963 // ICSj(F2), or, if not that,
10964 if (HasBetterConversion && !HasWorseConversion)
10965 return true;
10966
10967 // -- the context is an initialization by user-defined conversion
10968 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10969 // from the return type of F1 to the destination type (i.e.,
10970 // the type of the entity being initialized) is a better
10971 // conversion sequence than the standard conversion sequence
10972 // from the return type of F2 to the destination type.
10974 Cand1.Function && Cand2.Function &&
10977
10978 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10979 // First check whether we prefer one of the conversion functions over the
10980 // other. This only distinguishes the results in non-standard, extension
10981 // cases such as the conversion from a lambda closure type to a function
10982 // pointer or block.
10987 Cand1.FinalConversion,
10988 Cand2.FinalConversion);
10989
10992
10993 // FIXME: Compare kind of reference binding if conversion functions
10994 // convert to a reference type used in direct reference binding, per
10995 // C++14 [over.match.best]p1 section 2 bullet 3.
10996 }
10997
10998 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10999 // as combined with the resolution to CWG issue 243.
11000 //
11001 // When the context is initialization by constructor ([over.match.ctor] or
11002 // either phase of [over.match.list]), a constructor is preferred over
11003 // a conversion function.
11004 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11005 Cand1.Function && Cand2.Function &&
11008 return isa<CXXConstructorDecl>(Cand1.Function);
11009
11010 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11011 return Cand2.StrictPackMatch;
11012
11013 // -- F1 is a non-template function and F2 is a function template
11014 // specialization, or, if not that,
11015 bool Cand1IsSpecialization = Cand1.Function &&
11017 bool Cand2IsSpecialization = Cand2.Function &&
11019 if (Cand1IsSpecialization != Cand2IsSpecialization)
11020 return Cand2IsSpecialization;
11021
11022 // -- F1 and F2 are function template specializations, and the function
11023 // template for F1 is more specialized than the template for F2
11024 // according to the partial ordering rules described in 14.5.5.2, or,
11025 // if not that,
11026 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11027 const auto *Obj1Context =
11028 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11029 const auto *Obj2Context =
11030 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11031 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11033 Cand2.Function->getPrimaryTemplate(), Loc,
11035 : TPOC_Call,
11037 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11038 : QualType{},
11039 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11040 : QualType{},
11041 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11042 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11043 }
11044 }
11045
11046 // -— F1 and F2 are non-template functions and F1 is more
11047 // partial-ordering-constrained than F2 [...],
11049 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11050 Cand2.isReversed());
11051 F && F == Cand1.Function)
11052 return true;
11053
11054 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11055 // class B of D, and for all arguments the corresponding parameters of
11056 // F1 and F2 have the same type.
11057 // FIXME: Implement the "all parameters have the same type" check.
11058 bool Cand1IsInherited =
11059 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11060 bool Cand2IsInherited =
11061 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11062 if (Cand1IsInherited != Cand2IsInherited)
11063 return Cand2IsInherited;
11064 else if (Cand1IsInherited) {
11065 assert(Cand2IsInherited);
11066 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11067 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11068 if (Cand1Class->isDerivedFrom(Cand2Class))
11069 return true;
11070 if (Cand2Class->isDerivedFrom(Cand1Class))
11071 return false;
11072 // Inherited from sibling base classes: still ambiguous.
11073 }
11074
11075 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11076 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11077 // with reversed order of parameters and F1 is not
11078 //
11079 // We rank reversed + different operator as worse than just reversed, but
11080 // that comparison can never happen, because we only consider reversing for
11081 // the maximally-rewritten operator (== or <=>).
11082 if (Cand1.RewriteKind != Cand2.RewriteKind)
11083 return Cand1.RewriteKind < Cand2.RewriteKind;
11084
11085 // Check C++17 tie-breakers for deduction guides.
11086 {
11087 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11088 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11089 if (Guide1 && Guide2) {
11090 // -- F1 is generated from a deduction-guide and F2 is not
11091 if (Guide1->isImplicit() != Guide2->isImplicit())
11092 return Guide2->isImplicit();
11093
11094 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11095 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11096 return true;
11097 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11098 return false;
11099
11100 // --F1 is generated from a non-template constructor and F2 is generated
11101 // from a constructor template
11102 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11103 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11104 if (Constructor1 && Constructor2) {
11105 bool isC1Templated = Constructor1->getTemplatedKind() !=
11107 bool isC2Templated = Constructor2->getTemplatedKind() !=
11109 if (isC1Templated != isC2Templated)
11110 return isC2Templated;
11111 }
11112 }
11113 }
11114
11115 // Check for enable_if value-based overload resolution.
11116 if (Cand1.Function && Cand2.Function) {
11117 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11118 if (Cmp != Comparison::Equal)
11119 return Cmp == Comparison::Better;
11120 }
11121
11122 bool HasPS1 = Cand1.Function != nullptr &&
11124 bool HasPS2 = Cand2.Function != nullptr &&
11126 if (HasPS1 != HasPS2 && HasPS1)
11127 return true;
11128
11129 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11130 if (MV == Comparison::Better)
11131 return true;
11132 if (MV == Comparison::Worse)
11133 return false;
11134
11135 // If other rules cannot determine which is better, CUDA preference is used
11136 // to determine which is better.
11137 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11138 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11139 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11140 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11141 }
11142
11143 // General member function overloading is handled above, so this only handles
11144 // constructors with address spaces.
11145 // This only handles address spaces since C++ has no other
11146 // qualifier that can be used with constructors.
11147 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11148 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11149 if (CD1 && CD2) {
11150 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11151 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11152 if (AS1 != AS2) {
11154 return true;
11156 return false;
11157 }
11158 }
11159
11160 return false;
11161}
11162
11163/// Determine whether two declarations are "equivalent" for the purposes of
11164/// name lookup and overload resolution. This applies when the same internal/no
11165/// linkage entity is defined by two modules (probably by textually including
11166/// the same header). In such a case, we don't consider the declarations to
11167/// declare the same entity, but we also don't want lookups with both
11168/// declarations visible to be ambiguous in some cases (this happens when using
11169/// a modularized libstdc++).
11171 const NamedDecl *B) {
11172 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11173 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11174 if (!VA || !VB)
11175 return false;
11176
11177 // The declarations must be declaring the same name as an internal linkage
11178 // entity in different modules.
11179 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11180 VB->getDeclContext()->getRedeclContext()) ||
11181 getOwningModule(VA) == getOwningModule(VB) ||
11182 VA->isExternallyVisible() || VB->isExternallyVisible())
11183 return false;
11184
11185 // Check that the declarations appear to be equivalent.
11186 //
11187 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11188 // For constants and functions, we should check the initializer or body is
11189 // the same. For non-constant variables, we shouldn't allow it at all.
11190 if (Context.hasSameType(VA->getType(), VB->getType()))
11191 return true;
11192
11193 // Enum constants within unnamed enumerations will have different types, but
11194 // may still be similar enough to be interchangeable for our purposes.
11195 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11196 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11197 // Only handle anonymous enums. If the enumerations were named and
11198 // equivalent, they would have been merged to the same type.
11199 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11200 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11201 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11202 !Context.hasSameType(EnumA->getIntegerType(),
11203 EnumB->getIntegerType()))
11204 return false;
11205 // Allow this only if the value is the same for both enumerators.
11206 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11207 }
11208 }
11209
11210 // Nothing else is sufficiently similar.
11211 return false;
11212}
11213
11216 assert(D && "Unknown declaration");
11217 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11218
11219 Module *M = getOwningModule(D);
11220 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11221 << !M << (M ? M->getFullModuleName() : "");
11222
11223 for (auto *E : Equiv) {
11224 Module *M = getOwningModule(E);
11225 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11226 << !M << (M ? M->getFullModuleName() : "");
11227 }
11228}
11229
11232 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11234 static_cast<CNSInfo *>(DeductionFailure.Data)
11235 ->Satisfaction.ContainsErrors;
11236}
11237
11240 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11241 bool PartialOverloading, bool AllowExplicit,
11243 bool AggregateCandidateDeduction) {
11244
11245 auto *C =
11246 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11247
11250 /*AllowObjCConversionOnExplicit=*/false,
11251 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11252 PartialOverloading, AggregateCandidateDeduction},
11254 FoundDecl,
11255 Args,
11256 IsADLCandidate,
11257 PO};
11258
11259 HasDeferredTemplateConstructors |=
11260 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11261}
11262
11264 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11265 CXXRecordDecl *ActingContext, QualType ObjectType,
11266 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11267 bool SuppressUserConversions, bool PartialOverloading,
11269
11270 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11271
11272 auto *C =
11273 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11274
11277 /*AllowObjCConversionOnExplicit=*/false,
11278 /*AllowResultConversion=*/false,
11279 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11280 /*AggregateCandidateDeduction=*/false},
11281 MethodTmpl,
11282 FoundDecl,
11283 Args,
11284 ActingContext,
11285 ObjectClassification,
11286 ObjectType,
11287 PO};
11288}
11289
11292 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11293 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11294 bool AllowResultConversion) {
11295
11296 auto *C =
11297 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11298
11301 AllowObjCConversionOnExplicit, AllowResultConversion,
11302 /*AllowExplicit=*/false,
11303 /*SuppressUserConversions=*/false,
11304 /*PartialOverloading*/ false,
11305 /*AggregateCandidateDeduction=*/false},
11307 FoundDecl,
11308 ActingContext,
11309 From,
11310 ToType};
11311}
11312
11313static void
11316
11318 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11319 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11320 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11321}
11322
11323static void
11327 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11328 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11329 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11330 C.AggregateCandidateDeduction);
11331}
11332
11333static void
11337 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11338 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11339 C.AllowResultConversion);
11340}
11341
11343 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11344 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11345 while (Cand) {
11346 switch (Cand->Kind) {
11349 S, *this,
11350 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11351 break;
11354 S, *this,
11355 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11356 break;
11359 S, *this,
11360 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11361 break;
11362 }
11363 Cand = Cand->Next;
11364 }
11365 FirstDeferredCandidate = nullptr;
11366 DeferredCandidatesCount = 0;
11367}
11368
11370OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11371 Best->Best = true;
11372 if (Best->Function && Best->Function->isDeleted())
11373 return OR_Deleted;
11374 return OR_Success;
11375}
11376
11377void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11379 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11380 // are accepted by both clang and NVCC. However, during a particular
11381 // compilation mode only one call variant is viable. We need to
11382 // exclude non-viable overload candidates from consideration based
11383 // only on their host/device attributes. Specifically, if one
11384 // candidate call is WrongSide and the other is SameSide, we ignore
11385 // the WrongSide candidate.
11386 // We only need to remove wrong-sided candidates here if
11387 // -fgpu-exclude-wrong-side-overloads is off. When
11388 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11389 // uniformly in isBetterOverloadCandidate.
11390 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11391 return;
11392 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11393
11394 bool ContainsSameSideCandidate =
11395 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11396 // Check viable function only.
11397 return Cand->Viable && Cand->Function &&
11398 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11400 });
11401
11402 if (!ContainsSameSideCandidate)
11403 return;
11404
11405 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11406 // Check viable function only to avoid unnecessary data copying/moving.
11407 return Cand->Viable && Cand->Function &&
11408 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11410 };
11411 llvm::erase_if(Candidates, IsWrongSideCandidate);
11412}
11413
11414/// Computes the best viable function (C++ 13.3.3)
11415/// within an overload candidate set.
11416///
11417/// \param Loc The location of the function name (or operator symbol) for
11418/// which overload resolution occurs.
11419///
11420/// \param Best If overload resolution was successful or found a deleted
11421/// function, \p Best points to the candidate function found.
11422///
11423/// \returns The result of overload resolution.
11425 SourceLocation Loc,
11426 iterator &Best) {
11427
11429 DeferredCandidatesCount == 0) &&
11430 "Unexpected deferred template candidates");
11431
11432 bool TwoPhaseResolution =
11433 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11434
11435 if (TwoPhaseResolution) {
11436 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11437 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11438 if (!(HasDeferredTemplateConstructors &&
11439 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11440 return Res;
11441 }
11442 }
11443
11445 return BestViableFunctionImpl(S, Loc, Best);
11446}
11447
11448OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11450
11452 Candidates.reserve(this->Candidates.size());
11453 std::transform(this->Candidates.begin(), this->Candidates.end(),
11454 std::back_inserter(Candidates),
11455 [](OverloadCandidate &Cand) { return &Cand; });
11456
11457 if (S.getLangOpts().CUDA)
11458 CudaExcludeWrongSideCandidates(S, Candidates);
11459
11460 Best = end();
11461 for (auto *Cand : Candidates) {
11462 Cand->Best = false;
11463 if (Cand->Viable) {
11464 if (Best == end() ||
11465 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11466 Best = Cand;
11467 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11468 // This candidate has constraint that we were unable to evaluate because
11469 // it referenced an expression that contained an error. Rather than fall
11470 // back onto a potentially unintended candidate (made worse by
11471 // subsuming constraints), treat this as 'no viable candidate'.
11472 Best = end();
11473 return OR_No_Viable_Function;
11474 }
11475 }
11476
11477 // If we didn't find any viable functions, abort.
11478 if (Best == end())
11479 return OR_No_Viable_Function;
11480
11481 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11482 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11483 PendingBest.push_back(&*Best);
11484 Best->Best = true;
11485
11486 // Make sure that this function is better than every other viable
11487 // function. If not, we have an ambiguity.
11488 while (!PendingBest.empty()) {
11489 auto *Curr = PendingBest.pop_back_val();
11490 for (auto *Cand : Candidates) {
11491 if (Cand->Viable && !Cand->Best &&
11492 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11493 PendingBest.push_back(Cand);
11494 Cand->Best = true;
11495
11497 Curr->Function))
11498 EquivalentCands.push_back(Cand->Function);
11499 else
11500 Best = end();
11501 }
11502 }
11503 }
11504
11505 if (Best == end())
11506 return OR_Ambiguous;
11507
11508 OverloadingResult R = ResultForBestCandidate(Best);
11509
11510 if (!EquivalentCands.empty())
11512 EquivalentCands);
11513 return R;
11514}
11515
11516namespace {
11517
11518enum OverloadCandidateKind {
11519 oc_function,
11520 oc_method,
11521 oc_reversed_binary_operator,
11522 oc_constructor,
11523 oc_implicit_default_constructor,
11524 oc_implicit_copy_constructor,
11525 oc_implicit_move_constructor,
11526 oc_implicit_copy_assignment,
11527 oc_implicit_move_assignment,
11528 oc_implicit_equality_comparison,
11529 oc_inherited_constructor
11530};
11531
11532enum OverloadCandidateSelect {
11533 ocs_non_template,
11534 ocs_template,
11535 ocs_described_template,
11536};
11537
11538static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11539ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11540 const FunctionDecl *Fn,
11542 std::string &Description) {
11543
11544 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11545 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11546 isTemplate = true;
11547 Description = S.getTemplateArgumentBindingsText(
11548 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11549 }
11550
11551 OverloadCandidateSelect Select = [&]() {
11552 if (!Description.empty())
11553 return ocs_described_template;
11554 return isTemplate ? ocs_template : ocs_non_template;
11555 }();
11556
11557 OverloadCandidateKind Kind = [&]() {
11558 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11559 return oc_implicit_equality_comparison;
11560
11561 if (CRK & CRK_Reversed)
11562 return oc_reversed_binary_operator;
11563
11564 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11565 if (!Ctor->isImplicit()) {
11567 return oc_inherited_constructor;
11568 else
11569 return oc_constructor;
11570 }
11571
11572 if (Ctor->isDefaultConstructor())
11573 return oc_implicit_default_constructor;
11574
11575 if (Ctor->isMoveConstructor())
11576 return oc_implicit_move_constructor;
11577
11578 assert(Ctor->isCopyConstructor() &&
11579 "unexpected sort of implicit constructor");
11580 return oc_implicit_copy_constructor;
11581 }
11582
11583 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11584 // This actually gets spelled 'candidate function' for now, but
11585 // it doesn't hurt to split it out.
11586 if (!Meth->isImplicit())
11587 return oc_method;
11588
11589 if (Meth->isMoveAssignmentOperator())
11590 return oc_implicit_move_assignment;
11591
11592 if (Meth->isCopyAssignmentOperator())
11593 return oc_implicit_copy_assignment;
11594
11595 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11596 return oc_method;
11597 }
11598
11599 return oc_function;
11600 }();
11601
11602 return std::make_pair(Kind, Select);
11603}
11604
11605void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11606 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11607 // set.
11608 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11609 S.Diag(FoundDecl->getLocation(),
11610 diag::note_ovl_candidate_inherited_constructor)
11611 << Shadow->getNominatedBaseClass();
11612}
11613
11614} // end anonymous namespace
11615
11617 const FunctionDecl *FD) {
11618 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11619 bool AlwaysTrue;
11620 if (EnableIf->getCond()->isValueDependent() ||
11621 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11622 return false;
11623 if (!AlwaysTrue)
11624 return false;
11625 }
11626 return true;
11627}
11628
11629/// Returns true if we can take the address of the function.
11630///
11631/// \param Complain - If true, we'll emit a diagnostic
11632/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11633/// we in overload resolution?
11634/// \param Loc - The location of the statement we're complaining about. Ignored
11635/// if we're not complaining, or if we're in overload resolution.
11637 bool Complain,
11638 bool InOverloadResolution,
11639 SourceLocation Loc) {
11640 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11641 if (Complain) {
11642 if (InOverloadResolution)
11643 S.Diag(FD->getBeginLoc(),
11644 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11645 else
11646 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11647 }
11648 return false;
11649 }
11650
11651 if (FD->getTrailingRequiresClause()) {
11652 ConstraintSatisfaction Satisfaction;
11653 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11654 return false;
11655 if (!Satisfaction.IsSatisfied) {
11656 if (Complain) {
11657 if (InOverloadResolution) {
11658 SmallString<128> TemplateArgString;
11659 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11660 TemplateArgString += " ";
11661 TemplateArgString += S.getTemplateArgumentBindingsText(
11662 FunTmpl->getTemplateParameters(),
11664 }
11665
11666 S.Diag(FD->getBeginLoc(),
11667 diag::note_ovl_candidate_unsatisfied_constraints)
11668 << TemplateArgString;
11669 } else
11670 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11671 << FD;
11672 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11673 }
11674 return false;
11675 }
11676 }
11677
11678 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11679 return P->hasAttr<PassObjectSizeAttr>();
11680 });
11681 if (I == FD->param_end())
11682 return true;
11683
11684 if (Complain) {
11685 // Add one to ParamNo because it's user-facing
11686 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11687 if (InOverloadResolution)
11688 S.Diag(FD->getLocation(),
11689 diag::note_ovl_candidate_has_pass_object_size_params)
11690 << ParamNo;
11691 else
11692 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11693 << FD << ParamNo;
11694 }
11695 return false;
11696}
11697
11699 const FunctionDecl *FD) {
11700 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11701 /*InOverloadResolution=*/true,
11702 /*Loc=*/SourceLocation());
11703}
11704
11706 bool Complain,
11707 SourceLocation Loc) {
11708 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11709 /*InOverloadResolution=*/false,
11710 Loc);
11711}
11712
11713// Don't print candidates other than the one that matches the calling
11714// convention of the call operator, since that is guaranteed to exist.
11716 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11717
11718 if (!ConvD)
11719 return false;
11720 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11721 if (!RD->isLambda())
11722 return false;
11723
11724 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11725 CallingConv CallOpCC =
11726 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11727 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11728 CallingConv ConvToCC =
11729 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11730
11731 return ConvToCC != CallOpCC;
11732}
11733
11734// Notes the location of an overload candidate.
11736 OverloadCandidateRewriteKind RewriteKind,
11737 QualType DestType, bool TakingAddress) {
11738 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11739 return;
11740 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11741 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11742 return;
11743 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11744 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11745 return;
11747 return;
11748
11749 std::string FnDesc;
11750 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11751 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11752 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11753 << (unsigned)KSPair.first << (unsigned)KSPair.second
11754 << Fn << FnDesc;
11755
11756 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11757 Diag(Fn->getLocation(), PD);
11758 MaybeEmitInheritedConstructorNote(*this, Found);
11759}
11760
11761static void
11763 // Perhaps the ambiguity was caused by two atomic constraints that are
11764 // 'identical' but not equivalent:
11765 //
11766 // void foo() requires (sizeof(T) > 4) { } // #1
11767 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11768 //
11769 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11770 // #2 to subsume #1, but these constraint are not considered equivalent
11771 // according to the subsumption rules because they are not the same
11772 // source-level construct. This behavior is quite confusing and we should try
11773 // to help the user figure out what happened.
11774
11775 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11776 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11777 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11778 if (!I->Function)
11779 continue;
11781 if (auto *Template = I->Function->getPrimaryTemplate())
11782 Template->getAssociatedConstraints(AC);
11783 else
11784 I->Function->getAssociatedConstraints(AC);
11785 if (AC.empty())
11786 continue;
11787 if (FirstCand == nullptr) {
11788 FirstCand = I->Function;
11789 FirstAC = AC;
11790 } else if (SecondCand == nullptr) {
11791 SecondCand = I->Function;
11792 SecondAC = AC;
11793 } else {
11794 // We have more than one pair of constrained functions - this check is
11795 // expensive and we'd rather not try to diagnose it.
11796 return;
11797 }
11798 }
11799 if (!SecondCand)
11800 return;
11801 // The diagnostic can only happen if there are associated constraints on
11802 // both sides (there needs to be some identical atomic constraint).
11803 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11804 SecondCand, SecondAC))
11805 // Just show the user one diagnostic, they'll probably figure it out
11806 // from here.
11807 return;
11808}
11809
11810// Notes the location of all overload candidates designated through
11811// OverloadedExpr
11812void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11813 bool TakingAddress) {
11814 assert(OverloadedExpr->getType() == Context.OverloadTy);
11815
11816 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11817 OverloadExpr *OvlExpr = Ovl.Expression;
11818
11819 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11820 IEnd = OvlExpr->decls_end();
11821 I != IEnd; ++I) {
11822 if (FunctionTemplateDecl *FunTmpl =
11823 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11824 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11825 TakingAddress);
11826 } else if (FunctionDecl *Fun
11827 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11828 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11829 }
11830 }
11831}
11832
11833/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11834/// "lead" diagnostic; it will be given two arguments, the source and
11835/// target types of the conversion.
11837 Sema &S,
11838 SourceLocation CaretLoc,
11839 const PartialDiagnostic &PDiag) const {
11840 S.Diag(CaretLoc, PDiag)
11841 << Ambiguous.getFromType() << Ambiguous.getToType();
11842 unsigned CandsShown = 0;
11844 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11845 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11846 break;
11847 ++CandsShown;
11848 S.NoteOverloadCandidate(I->first, I->second);
11849 }
11850 S.Diags.overloadCandidatesShown(CandsShown);
11851 if (I != E)
11852 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11853}
11854
11856 unsigned I, bool TakingCandidateAddress) {
11857 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11858 assert(Conv.isBad());
11859 assert(Cand->Function && "for now, candidate must be a function");
11860 FunctionDecl *Fn = Cand->Function;
11861
11862 // There's a conversion slot for the object argument if this is a
11863 // non-constructor method. Note that 'I' corresponds the
11864 // conversion-slot index.
11865 bool isObjectArgument = false;
11866 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11868 if (I == 0)
11869 isObjectArgument = true;
11870 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11871 I--;
11872 }
11873
11874 std::string FnDesc;
11875 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11876 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11877 FnDesc);
11878
11879 Expr *FromExpr = Conv.Bad.FromExpr;
11880 QualType FromTy = Conv.Bad.getFromType();
11881 QualType ToTy = Conv.Bad.getToType();
11882 SourceRange ToParamRange;
11883
11884 // FIXME: In presence of parameter packs we can't determine parameter range
11885 // reliably, as we don't have access to instantiation.
11886 bool HasParamPack =
11887 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11888 return Parm->isParameterPack();
11889 });
11890 if (!isObjectArgument && !HasParamPack)
11891 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11892
11893 if (FromTy == S.Context.OverloadTy) {
11894 assert(FromExpr && "overload set argument came from implicit argument?");
11895 Expr *E = FromExpr->IgnoreParens();
11896 if (isa<UnaryOperator>(E))
11897 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11898 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11899
11900 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11901 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11902 << ToParamRange << ToTy << Name << I + 1;
11903 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11904 return;
11905 }
11906
11907 // Do some hand-waving analysis to see if the non-viability is due
11908 // to a qualifier mismatch.
11909 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11910 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11911 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11912 CToTy = RT->getPointeeType();
11913 else {
11914 // TODO: detect and diagnose the full richness of const mismatches.
11915 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11916 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11917 CFromTy = FromPT->getPointeeType();
11918 CToTy = ToPT->getPointeeType();
11919 }
11920 }
11921
11922 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11923 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11924 Qualifiers FromQs = CFromTy.getQualifiers();
11925 Qualifiers ToQs = CToTy.getQualifiers();
11926
11927 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11928 if (isObjectArgument)
11929 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11930 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11931 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11932 else
11933 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11934 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11935 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11936 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11937 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11938 return;
11939 }
11940
11941 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11942 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11943 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11944 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11945 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11946 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11947 return;
11948 }
11949
11950 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11951 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11952 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11953 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11954 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11955 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11956 return;
11957 }
11958
11959 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11960 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11961 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11962 << FromTy << !!FromQs.getPointerAuth()
11963 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11964 << ToQs.getPointerAuth().getAsString() << I + 1
11965 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11966 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11967 return;
11968 }
11969
11970 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11971 assert(CVR && "expected qualifiers mismatch");
11972
11973 if (isObjectArgument) {
11974 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11975 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11976 << FromTy << (CVR - 1);
11977 } else {
11978 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11979 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11980 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11981 }
11982 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11983 return;
11984 }
11985
11988 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11989 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11990 << (unsigned)isObjectArgument << I + 1
11992 << ToParamRange;
11993 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11994 return;
11995 }
11996
11997 // Special diagnostic for failure to convert an initializer list, since
11998 // telling the user that it has type void is not useful.
11999 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12000 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12001 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12002 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12005 ? 2
12006 : 0);
12007 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12008 return;
12009 }
12010
12011 // Diagnose references or pointers to incomplete types differently,
12012 // since it's far from impossible that the incompleteness triggered
12013 // the failure.
12014 QualType TempFromTy = FromTy.getNonReferenceType();
12015 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12016 TempFromTy = PTy->getPointeeType();
12017 if (TempFromTy->isIncompleteType()) {
12018 // Emit the generic diagnostic and, optionally, add the hints to it.
12019 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12020 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12021 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12022 << (unsigned)(Cand->Fix.Kind);
12023
12024 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12025 return;
12026 }
12027
12028 // Diagnose base -> derived pointer conversions.
12029 unsigned BaseToDerivedConversion = 0;
12030 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12031 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12032 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12033 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12034 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12035 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12036 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12037 FromPtrTy->getPointeeType()))
12038 BaseToDerivedConversion = 1;
12039 }
12040 } else if (const ObjCObjectPointerType *FromPtrTy
12041 = FromTy->getAs<ObjCObjectPointerType>()) {
12042 if (const ObjCObjectPointerType *ToPtrTy
12043 = ToTy->getAs<ObjCObjectPointerType>())
12044 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12045 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12046 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12047 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12048 FromIface->isSuperClassOf(ToIface))
12049 BaseToDerivedConversion = 2;
12050 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12051 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12052 S.getASTContext()) &&
12053 !FromTy->isIncompleteType() &&
12054 !ToRefTy->getPointeeType()->isIncompleteType() &&
12055 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12056 BaseToDerivedConversion = 3;
12057 }
12058 }
12059
12060 if (BaseToDerivedConversion) {
12061 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12062 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12063 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12064 << I + 1;
12065 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12066 return;
12067 }
12068
12069 if (isa<ObjCObjectPointerType>(CFromTy) &&
12070 isa<PointerType>(CToTy)) {
12071 Qualifiers FromQs = CFromTy.getQualifiers();
12072 Qualifiers ToQs = CToTy.getQualifiers();
12073 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12074 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12075 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12076 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12077 << I + 1;
12078 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12079 return;
12080 }
12081 }
12082
12083 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12084 return;
12085
12086 // Emit the generic diagnostic and, optionally, add the hints to it.
12087 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12088 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12089 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12090 << (unsigned)(Cand->Fix.Kind);
12091
12092 // Check that location of Fn is not in system header.
12093 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12094 // If we can fix the conversion, suggest the FixIts.
12095 for (const FixItHint &HI : Cand->Fix.Hints)
12096 FDiag << HI;
12097 }
12098
12099 S.Diag(Fn->getLocation(), FDiag);
12100
12101 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12102}
12103
12104/// Additional arity mismatch diagnosis specific to a function overload
12105/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12106/// over a candidate in any candidate set.
12108 unsigned NumArgs, bool IsAddressOf = false) {
12109 assert(Cand->Function && "Candidate is required to be a function.");
12110 FunctionDecl *Fn = Cand->Function;
12111 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12112 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12113
12114 // With invalid overloaded operators, it's possible that we think we
12115 // have an arity mismatch when in fact it looks like we have the
12116 // right number of arguments, because only overloaded operators have
12117 // the weird behavior of overloading member and non-member functions.
12118 // Just don't report anything.
12119 if (Fn->isInvalidDecl() &&
12120 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12121 return true;
12122
12123 if (NumArgs < MinParams) {
12124 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12126 Cand->DeductionFailure.getResult() ==
12128 } else {
12129 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12131 Cand->DeductionFailure.getResult() ==
12133 }
12134
12135 return false;
12136}
12137
12138/// General arity mismatch diagnosis over a candidate in a candidate set.
12140 unsigned NumFormalArgs,
12141 bool IsAddressOf = false) {
12142 assert(isa<FunctionDecl>(D) &&
12143 "The templated declaration should at least be a function"
12144 " when diagnosing bad template argument deduction due to too many"
12145 " or too few arguments");
12146
12148
12149 // TODO: treat calls to a missing default constructor as a special case
12150 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12151 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12152 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12153
12154 // at least / at most / exactly
12155 bool HasExplicitObjectParam =
12156 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12157
12158 unsigned ParamCount =
12159 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12160 unsigned mode, modeCount;
12161
12162 if (NumFormalArgs < MinParams) {
12163 if (MinParams != ParamCount || FnTy->isVariadic() ||
12164 FnTy->isTemplateVariadic())
12165 mode = 0; // "at least"
12166 else
12167 mode = 2; // "exactly"
12168 modeCount = MinParams;
12169 } else {
12170 if (MinParams != ParamCount)
12171 mode = 1; // "at most"
12172 else
12173 mode = 2; // "exactly"
12174 modeCount = ParamCount;
12175 }
12176
12177 std::string Description;
12178 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12179 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12180
12181 if (modeCount == 1 && !IsAddressOf &&
12182 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12184 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12185 << Description << mode
12186 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12187 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12188 else
12189 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12190 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12191 << Description << mode << modeCount << NumFormalArgs
12192 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12193
12194 MaybeEmitInheritedConstructorNote(S, Found);
12195}
12196
12197/// Arity mismatch diagnosis specific to a function overload candidate.
12199 unsigned NumFormalArgs) {
12200 assert(Cand->Function && "Candidate must be a function");
12201 FunctionDecl *Fn = Cand->Function;
12202 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12203 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12204 Cand->TookAddressOfOverload);
12205}
12206
12208 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12209 return TD;
12210 llvm_unreachable("Unsupported: Getting the described template declaration"
12211 " for bad deduction diagnosis");
12212}
12213
12214/// Diagnose a failed template-argument deduction.
12215static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12216 DeductionFailureInfo &DeductionFailure,
12217 unsigned NumArgs,
12218 bool TakingCandidateAddress) {
12219 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12220 NamedDecl *ParamD;
12221 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12222 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12223 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12224 switch (DeductionFailure.getResult()) {
12226 llvm_unreachable(
12227 "TemplateDeductionResult::Success while diagnosing bad deduction");
12229 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12230 "while diagnosing bad deduction");
12233 return;
12234
12236 assert(ParamD && "no parameter found for incomplete deduction result");
12237 S.Diag(Templated->getLocation(),
12238 diag::note_ovl_candidate_incomplete_deduction)
12239 << ParamD->getDeclName();
12240 MaybeEmitInheritedConstructorNote(S, Found);
12241 return;
12242 }
12243
12245 assert(ParamD && "no parameter found for incomplete deduction result");
12246 S.Diag(Templated->getLocation(),
12247 diag::note_ovl_candidate_incomplete_deduction_pack)
12248 << ParamD->getDeclName()
12249 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12250 << *DeductionFailure.getFirstArg();
12251 MaybeEmitInheritedConstructorNote(S, Found);
12252 return;
12253 }
12254
12256 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12258
12259 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12260
12261 // Param will have been canonicalized, but it should just be a
12262 // qualified version of ParamD, so move the qualifiers to that.
12264 Qs.strip(Param);
12265 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12266 assert(S.Context.hasSameType(Param, NonCanonParam));
12267
12268 // Arg has also been canonicalized, but there's nothing we can do
12269 // about that. It also doesn't matter as much, because it won't
12270 // have any template parameters in it (because deduction isn't
12271 // done on dependent types).
12272 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12273
12274 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12275 << ParamD->getDeclName() << Arg << NonCanonParam;
12276 MaybeEmitInheritedConstructorNote(S, Found);
12277 return;
12278 }
12279
12281 assert(ParamD && "no parameter found for inconsistent deduction result");
12282 int which = 0;
12283 if (isa<TemplateTypeParmDecl>(ParamD))
12284 which = 0;
12285 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12286 // Deduction might have failed because we deduced arguments of two
12287 // different types for a non-type template parameter.
12288 // FIXME: Use a different TDK value for this.
12289 QualType T1 =
12290 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12291 QualType T2 =
12292 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12293 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12294 S.Diag(Templated->getLocation(),
12295 diag::note_ovl_candidate_inconsistent_deduction_types)
12296 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12297 << *DeductionFailure.getSecondArg() << T2;
12298 MaybeEmitInheritedConstructorNote(S, Found);
12299 return;
12300 }
12301
12302 which = 1;
12303 } else {
12304 which = 2;
12305 }
12306
12307 // Tweak the diagnostic if the problem is that we deduced packs of
12308 // different arities. We'll print the actual packs anyway in case that
12309 // includes additional useful information.
12310 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12311 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12312 DeductionFailure.getFirstArg()->pack_size() !=
12313 DeductionFailure.getSecondArg()->pack_size()) {
12314 which = 3;
12315 }
12316
12317 S.Diag(Templated->getLocation(),
12318 diag::note_ovl_candidate_inconsistent_deduction)
12319 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12320 << *DeductionFailure.getSecondArg();
12321 MaybeEmitInheritedConstructorNote(S, Found);
12322 return;
12323 }
12324
12326 assert(ParamD && "no parameter found for invalid explicit arguments");
12327 if (ParamD->getDeclName())
12328 S.Diag(Templated->getLocation(),
12329 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12330 << ParamD->getDeclName();
12331 else {
12332 int index = 0;
12333 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12334 index = TTP->getIndex();
12335 else if (NonTypeTemplateParmDecl *NTTP
12336 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12337 index = NTTP->getIndex();
12338 else
12339 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12340 S.Diag(Templated->getLocation(),
12341 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12342 << (index + 1);
12343 }
12344 MaybeEmitInheritedConstructorNote(S, Found);
12345 return;
12346
12348 // Format the template argument list into the argument string.
12349 SmallString<128> TemplateArgString;
12350 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12351 TemplateArgString = " ";
12352 TemplateArgString += S.getTemplateArgumentBindingsText(
12353 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12354 if (TemplateArgString.size() == 1)
12355 TemplateArgString.clear();
12356 S.Diag(Templated->getLocation(),
12357 diag::note_ovl_candidate_unsatisfied_constraints)
12358 << TemplateArgString;
12359
12361 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12362 return;
12363 }
12366 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12367 return;
12368
12370 S.Diag(Templated->getLocation(),
12371 diag::note_ovl_candidate_instantiation_depth);
12372 MaybeEmitInheritedConstructorNote(S, Found);
12373 return;
12374
12376 // Format the template argument list into the argument string.
12377 SmallString<128> TemplateArgString;
12378 if (TemplateArgumentList *Args =
12379 DeductionFailure.getTemplateArgumentList()) {
12380 TemplateArgString = " ";
12381 TemplateArgString += S.getTemplateArgumentBindingsText(
12382 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12383 if (TemplateArgString.size() == 1)
12384 TemplateArgString.clear();
12385 }
12386
12387 // If this candidate was disabled by enable_if, say so.
12388 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12389 if (PDiag && PDiag->second.getDiagID() ==
12390 diag::err_typename_nested_not_found_enable_if) {
12391 // FIXME: Use the source range of the condition, and the fully-qualified
12392 // name of the enable_if template. These are both present in PDiag.
12393 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12394 << "'enable_if'" << TemplateArgString;
12395 return;
12396 }
12397
12398 // We found a specific requirement that disabled the enable_if.
12399 if (PDiag && PDiag->second.getDiagID() ==
12400 diag::err_typename_nested_not_found_requirement) {
12401 S.Diag(Templated->getLocation(),
12402 diag::note_ovl_candidate_disabled_by_requirement)
12403 << PDiag->second.getStringArg(0) << TemplateArgString;
12404 return;
12405 }
12406
12407 // Format the SFINAE diagnostic into the argument string.
12408 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12409 // formatted message in another diagnostic.
12410 SmallString<128> SFINAEArgString;
12411 SourceRange R;
12412 if (PDiag) {
12413 SFINAEArgString = ": ";
12414 R = SourceRange(PDiag->first, PDiag->first);
12415 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12416 }
12417
12418 S.Diag(Templated->getLocation(),
12419 diag::note_ovl_candidate_substitution_failure)
12420 << TemplateArgString << SFINAEArgString << R;
12421 MaybeEmitInheritedConstructorNote(S, Found);
12422 return;
12423 }
12424
12427 // Format the template argument list into the argument string.
12428 SmallString<128> TemplateArgString;
12429 if (TemplateArgumentList *Args =
12430 DeductionFailure.getTemplateArgumentList()) {
12431 TemplateArgString = " ";
12432 TemplateArgString += S.getTemplateArgumentBindingsText(
12433 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12434 if (TemplateArgString.size() == 1)
12435 TemplateArgString.clear();
12436 }
12437
12438 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12439 << (*DeductionFailure.getCallArgIndex() + 1)
12440 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12441 << TemplateArgString
12442 << (DeductionFailure.getResult() ==
12444 break;
12445 }
12446
12448 // FIXME: Provide a source location to indicate what we couldn't match.
12449 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12450 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12451 if (FirstTA.getKind() == TemplateArgument::Template &&
12452 SecondTA.getKind() == TemplateArgument::Template) {
12453 TemplateName FirstTN = FirstTA.getAsTemplate();
12454 TemplateName SecondTN = SecondTA.getAsTemplate();
12455 if (FirstTN.getKind() == TemplateName::Template &&
12456 SecondTN.getKind() == TemplateName::Template) {
12457 if (FirstTN.getAsTemplateDecl()->getName() ==
12458 SecondTN.getAsTemplateDecl()->getName()) {
12459 // FIXME: This fixes a bad diagnostic where both templates are named
12460 // the same. This particular case is a bit difficult since:
12461 // 1) It is passed as a string to the diagnostic printer.
12462 // 2) The diagnostic printer only attempts to find a better
12463 // name for types, not decls.
12464 // Ideally, this should folded into the diagnostic printer.
12465 S.Diag(Templated->getLocation(),
12466 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12467 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12468 return;
12469 }
12470 }
12471 }
12472
12473 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12475 return;
12476
12477 // FIXME: For generic lambda parameters, check if the function is a lambda
12478 // call operator, and if so, emit a prettier and more informative
12479 // diagnostic that mentions 'auto' and lambda in addition to
12480 // (or instead of?) the canonical template type parameters.
12481 S.Diag(Templated->getLocation(),
12482 diag::note_ovl_candidate_non_deduced_mismatch)
12483 << FirstTA << SecondTA;
12484 return;
12485 }
12486 // TODO: diagnose these individually, then kill off
12487 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12489 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12490 MaybeEmitInheritedConstructorNote(S, Found);
12491 return;
12493 S.Diag(Templated->getLocation(),
12494 diag::note_cuda_ovl_candidate_target_mismatch);
12495 return;
12496 }
12497}
12498
12499/// Diagnose a failed template-argument deduction, for function calls.
12501 unsigned NumArgs,
12502 bool TakingCandidateAddress) {
12503 assert(Cand->Function && "Candidate must be a function");
12504 FunctionDecl *Fn = Cand->Function;
12508 if (CheckArityMismatch(S, Cand, NumArgs))
12509 return;
12510 }
12511 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12512 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12513}
12514
12515/// CUDA: diagnose an invalid call across targets.
12517 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12518 assert(Cand->Function && "Candidate must be a Function.");
12519 FunctionDecl *Callee = Cand->Function;
12520
12521 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12522 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12523
12524 std::string FnDesc;
12525 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12526 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12527 Cand->getRewriteKind(), FnDesc);
12528
12529 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12530 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12531 << FnDesc /* Ignored */
12532 << CalleeTarget << CallerTarget;
12533
12534 // This could be an implicit constructor for which we could not infer the
12535 // target due to a collsion. Diagnose that case.
12536 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12537 if (Meth != nullptr && Meth->isImplicit()) {
12538 CXXRecordDecl *ParentClass = Meth->getParent();
12540
12541 switch (FnKindPair.first) {
12542 default:
12543 return;
12544 case oc_implicit_default_constructor:
12546 break;
12547 case oc_implicit_copy_constructor:
12549 break;
12550 case oc_implicit_move_constructor:
12552 break;
12553 case oc_implicit_copy_assignment:
12555 break;
12556 case oc_implicit_move_assignment:
12558 break;
12559 };
12560
12561 bool ConstRHS = false;
12562 if (Meth->getNumParams()) {
12563 if (const ReferenceType *RT =
12564 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12565 ConstRHS = RT->getPointeeType().isConstQualified();
12566 }
12567 }
12568
12569 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12570 /* ConstRHS */ ConstRHS,
12571 /* Diagnose */ true);
12572 }
12573}
12574
12576 assert(Cand->Function && "Candidate must be a function");
12577 FunctionDecl *Callee = Cand->Function;
12578 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12579
12580 S.Diag(Callee->getLocation(),
12581 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12582 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12583}
12584
12586 assert(Cand->Function && "Candidate must be a function");
12587 FunctionDecl *Fn = Cand->Function;
12589 assert(ES.isExplicit() && "not an explicit candidate");
12590
12591 unsigned Kind;
12592 switch (Fn->getDeclKind()) {
12593 case Decl::Kind::CXXConstructor:
12594 Kind = 0;
12595 break;
12596 case Decl::Kind::CXXConversion:
12597 Kind = 1;
12598 break;
12599 case Decl::Kind::CXXDeductionGuide:
12600 Kind = Fn->isImplicit() ? 0 : 2;
12601 break;
12602 default:
12603 llvm_unreachable("invalid Decl");
12604 }
12605
12606 // Note the location of the first (in-class) declaration; a redeclaration
12607 // (particularly an out-of-class definition) will typically lack the
12608 // 'explicit' specifier.
12609 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12610 FunctionDecl *First = Fn->getFirstDecl();
12611 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12612 First = Pattern->getFirstDecl();
12613
12614 S.Diag(First->getLocation(),
12615 diag::note_ovl_candidate_explicit)
12616 << Kind << (ES.getExpr() ? 1 : 0)
12617 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12618}
12619
12621 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12622 if (!DG)
12623 return;
12624 TemplateDecl *OriginTemplate =
12626 // We want to always print synthesized deduction guides for type aliases.
12627 // They would retain the explicit bit of the corresponding constructor.
12628 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12629 return;
12630 std::string FunctionProto;
12631 llvm::raw_string_ostream OS(FunctionProto);
12632 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12633 if (!Template) {
12634 // This also could be an instantiation. Find out the primary template.
12635 FunctionDecl *Pattern =
12636 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12637 if (!Pattern) {
12638 // The implicit deduction guide is built on an explicit non-template
12639 // deduction guide. Currently, this might be the case only for type
12640 // aliases.
12641 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12642 // gets merged.
12643 assert(OriginTemplate->isTypeAlias() &&
12644 "Non-template implicit deduction guides are only possible for "
12645 "type aliases");
12646 DG->print(OS);
12647 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12648 << FunctionProto;
12649 return;
12650 }
12652 assert(Template && "Cannot find the associated function template of "
12653 "CXXDeductionGuideDecl?");
12654 }
12655 Template->print(OS);
12656 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12657 << FunctionProto;
12658}
12659
12660/// Generates a 'note' diagnostic for an overload candidate. We've
12661/// already generated a primary error at the call site.
12662///
12663/// It really does need to be a single diagnostic with its caret
12664/// pointed at the candidate declaration. Yes, this creates some
12665/// major challenges of technical writing. Yes, this makes pointing
12666/// out problems with specific arguments quite awkward. It's still
12667/// better than generating twenty screens of text for every failed
12668/// overload.
12669///
12670/// It would be great to be able to express per-candidate problems
12671/// more richly for those diagnostic clients that cared, but we'd
12672/// still have to be just as careful with the default diagnostics.
12673/// \param CtorDestAS Addr space of object being constructed (for ctor
12674/// candidates only).
12676 unsigned NumArgs,
12677 bool TakingCandidateAddress,
12678 LangAS CtorDestAS = LangAS::Default) {
12679 assert(Cand->Function && "Candidate must be a function");
12680 FunctionDecl *Fn = Cand->Function;
12682 return;
12683
12684 // There is no physical candidate declaration to point to for OpenCL builtins.
12685 // Except for failed conversions, the notes are identical for each candidate,
12686 // so do not generate such notes.
12687 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12689 return;
12690
12691 // Skip implicit member functions when trying to resolve
12692 // the address of a an overload set for a function pointer.
12693 if (Cand->TookAddressOfOverload &&
12694 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12695 return;
12696
12697 // Note deleted candidates, but only if they're viable.
12698 if (Cand->Viable) {
12699 if (Fn->isDeleted()) {
12700 std::string FnDesc;
12701 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12702 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12703 Cand->getRewriteKind(), FnDesc);
12704
12705 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12706 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12707 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12708 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12709 return;
12710 }
12711
12712 // We don't really have anything else to say about viable candidates.
12713 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12714 return;
12715 }
12716
12717 // If this is a synthesized deduction guide we're deducing against, add a note
12718 // for it. These deduction guides are not explicitly spelled in the source
12719 // code, so simply printing a deduction failure note mentioning synthesized
12720 // template parameters or pointing to the header of the surrounding RecordDecl
12721 // would be confusing.
12722 //
12723 // We prefer adding such notes at the end of the deduction failure because
12724 // duplicate code snippets appearing in the diagnostic would likely become
12725 // noisy.
12726 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12727
12728 switch (Cand->FailureKind) {
12731 return DiagnoseArityMismatch(S, Cand, NumArgs);
12732
12734 return DiagnoseBadDeduction(S, Cand, NumArgs,
12735 TakingCandidateAddress);
12736
12738 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12739 << (Fn->getPrimaryTemplate() ? 1 : 0);
12740 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12741 return;
12742 }
12743
12745 Qualifiers QualsForPrinting;
12746 QualsForPrinting.setAddressSpace(CtorDestAS);
12747 S.Diag(Fn->getLocation(),
12748 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12749 << QualsForPrinting;
12750 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12751 return;
12752 }
12753
12757 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12758
12760 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12761 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12762 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12763 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12764
12765 // FIXME: this currently happens when we're called from SemaInit
12766 // when user-conversion overload fails. Figure out how to handle
12767 // those conditions and diagnose them well.
12768 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12769 }
12770
12772 return DiagnoseBadTarget(S, Cand);
12773
12774 case ovl_fail_enable_if:
12775 return DiagnoseFailedEnableIfAttr(S, Cand);
12776
12777 case ovl_fail_explicit:
12778 return DiagnoseFailedExplicitSpec(S, Cand);
12779
12781 // It's generally not interesting to note copy/move constructors here.
12782 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12783 return;
12784 S.Diag(Fn->getLocation(),
12785 diag::note_ovl_candidate_inherited_constructor_slice)
12786 << (Fn->getPrimaryTemplate() ? 1 : 0)
12787 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12788 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12789 return;
12790
12792 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12793 (void)Available;
12794 assert(!Available);
12795 break;
12796 }
12798 // Do nothing, these should simply be ignored.
12799 break;
12800
12802 std::string FnDesc;
12803 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12804 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12805 Cand->getRewriteKind(), FnDesc);
12806
12807 S.Diag(Fn->getLocation(),
12808 diag::note_ovl_candidate_constraints_not_satisfied)
12809 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12810 << FnDesc /* Ignored */;
12811 ConstraintSatisfaction Satisfaction;
12812 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12813 /*ForOverloadResolution=*/true))
12814 break;
12815 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12816 }
12817 }
12818}
12819
12822 return;
12823
12824 // Desugar the type of the surrogate down to a function type,
12825 // retaining as many typedefs as possible while still showing
12826 // the function type (and, therefore, its parameter types).
12827 QualType FnType = Cand->Surrogate->getConversionType();
12828 bool isLValueReference = false;
12829 bool isRValueReference = false;
12830 bool isPointer = false;
12831 if (const LValueReferenceType *FnTypeRef =
12832 FnType->getAs<LValueReferenceType>()) {
12833 FnType = FnTypeRef->getPointeeType();
12834 isLValueReference = true;
12835 } else if (const RValueReferenceType *FnTypeRef =
12836 FnType->getAs<RValueReferenceType>()) {
12837 FnType = FnTypeRef->getPointeeType();
12838 isRValueReference = true;
12839 }
12840 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12841 FnType = FnTypePtr->getPointeeType();
12842 isPointer = true;
12843 }
12844 // Desugar down to a function type.
12845 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12846 // Reconstruct the pointer/reference as appropriate.
12847 if (isPointer) FnType = S.Context.getPointerType(FnType);
12848 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12849 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12850
12851 if (!Cand->Viable &&
12853 S.Diag(Cand->Surrogate->getLocation(),
12854 diag::note_ovl_surrogate_constraints_not_satisfied)
12855 << Cand->Surrogate;
12856 ConstraintSatisfaction Satisfaction;
12857 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12858 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12859 } else {
12860 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12861 << FnType;
12862 }
12863}
12864
12865static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12866 SourceLocation OpLoc,
12867 OverloadCandidate *Cand) {
12868 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12869 std::string TypeStr("operator");
12870 TypeStr += Opc;
12871 TypeStr += "(";
12872 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12873 if (Cand->Conversions.size() == 1) {
12874 TypeStr += ")";
12875 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12876 } else {
12877 TypeStr += ", ";
12878 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12879 TypeStr += ")";
12880 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12881 }
12882}
12883
12885 OverloadCandidate *Cand) {
12886 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12887 if (ICS.isBad()) break; // all meaningless after first invalid
12888 if (!ICS.isAmbiguous()) continue;
12889
12891 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12892 }
12893}
12894
12896 if (Cand->Function)
12897 return Cand->Function->getLocation();
12898 if (Cand->IsSurrogate)
12899 return Cand->Surrogate->getLocation();
12900 return SourceLocation();
12901}
12902
12903static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12904 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12908 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12909
12913 return 1;
12914
12917 return 2;
12918
12926 return 3;
12927
12929 return 4;
12930
12932 return 5;
12933
12936 return 6;
12937 }
12938 llvm_unreachable("Unhandled deduction result");
12939}
12940
12941namespace {
12942
12943struct CompareOverloadCandidatesForDisplay {
12944 Sema &S;
12945 SourceLocation Loc;
12946 size_t NumArgs;
12948
12949 CompareOverloadCandidatesForDisplay(
12950 Sema &S, SourceLocation Loc, size_t NArgs,
12952 : S(S), NumArgs(NArgs), CSK(CSK) {}
12953
12954 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12955 // If there are too many or too few arguments, that's the high-order bit we
12956 // want to sort by, even if the immediate failure kind was something else.
12957 if (C->FailureKind == ovl_fail_too_many_arguments ||
12958 C->FailureKind == ovl_fail_too_few_arguments)
12959 return static_cast<OverloadFailureKind>(C->FailureKind);
12960
12961 if (C->Function) {
12962 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12964 if (NumArgs < C->Function->getMinRequiredArguments())
12966 }
12967
12968 return static_cast<OverloadFailureKind>(C->FailureKind);
12969 }
12970
12971 bool operator()(const OverloadCandidate *L,
12972 const OverloadCandidate *R) {
12973 // Fast-path this check.
12974 if (L == R) return false;
12975
12976 // Order first by viability.
12977 if (L->Viable) {
12978 if (!R->Viable) return true;
12979
12980 if (int Ord = CompareConversions(*L, *R))
12981 return Ord < 0;
12982 // Use other tie breakers.
12983 } else if (R->Viable)
12984 return false;
12985
12986 assert(L->Viable == R->Viable);
12987
12988 // Criteria by which we can sort non-viable candidates:
12989 if (!L->Viable) {
12990 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12991 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12992
12993 // 1. Arity mismatches come after other candidates.
12994 if (LFailureKind == ovl_fail_too_many_arguments ||
12995 LFailureKind == ovl_fail_too_few_arguments) {
12996 if (RFailureKind == ovl_fail_too_many_arguments ||
12997 RFailureKind == ovl_fail_too_few_arguments) {
12998 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12999 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13000 if (LDist == RDist) {
13001 if (LFailureKind == RFailureKind)
13002 // Sort non-surrogates before surrogates.
13003 return !L->IsSurrogate && R->IsSurrogate;
13004 // Sort candidates requiring fewer parameters than there were
13005 // arguments given after candidates requiring more parameters
13006 // than there were arguments given.
13007 return LFailureKind == ovl_fail_too_many_arguments;
13008 }
13009 return LDist < RDist;
13010 }
13011 return false;
13012 }
13013 if (RFailureKind == ovl_fail_too_many_arguments ||
13014 RFailureKind == ovl_fail_too_few_arguments)
13015 return true;
13016
13017 // 2. Bad conversions come first and are ordered by the number
13018 // of bad conversions and quality of good conversions.
13019 if (LFailureKind == ovl_fail_bad_conversion) {
13020 if (RFailureKind != ovl_fail_bad_conversion)
13021 return true;
13022
13023 // The conversion that can be fixed with a smaller number of changes,
13024 // comes first.
13025 unsigned numLFixes = L->Fix.NumConversionsFixed;
13026 unsigned numRFixes = R->Fix.NumConversionsFixed;
13027 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13028 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13029 if (numLFixes != numRFixes) {
13030 return numLFixes < numRFixes;
13031 }
13032
13033 // If there's any ordering between the defined conversions...
13034 if (int Ord = CompareConversions(*L, *R))
13035 return Ord < 0;
13036 } else if (RFailureKind == ovl_fail_bad_conversion)
13037 return false;
13038
13039 if (LFailureKind == ovl_fail_bad_deduction) {
13040 if (RFailureKind != ovl_fail_bad_deduction)
13041 return true;
13042
13044 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13045 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13046 if (LRank != RRank)
13047 return LRank < RRank;
13048 }
13049 } else if (RFailureKind == ovl_fail_bad_deduction)
13050 return false;
13051
13052 // TODO: others?
13053 }
13054
13055 // Sort everything else by location.
13056 SourceLocation LLoc = GetLocationForCandidate(L);
13057 SourceLocation RLoc = GetLocationForCandidate(R);
13058
13059 // Put candidates without locations (e.g. builtins) at the end.
13060 if (LLoc.isValid() && RLoc.isValid())
13061 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13062 if (LLoc.isValid() && !RLoc.isValid())
13063 return true;
13064 if (RLoc.isValid() && !LLoc.isValid())
13065 return false;
13066 assert(!LLoc.isValid() && !RLoc.isValid());
13067 // For builtins and other functions without locations, fallback to the order
13068 // in which they were added into the candidate set.
13069 return L < R;
13070 }
13071
13072private:
13073 struct ConversionSignals {
13074 unsigned KindRank = 0;
13076
13077 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13078 ConversionSignals Sig;
13079 Sig.KindRank = Seq.getKindRank();
13080 if (Seq.isStandard())
13081 Sig.Rank = Seq.Standard.getRank();
13082 else if (Seq.isUserDefined())
13083 Sig.Rank = Seq.UserDefined.After.getRank();
13084 // We intend StaticObjectArgumentConversion to compare the same as
13085 // StandardConversion with ICR_ExactMatch rank.
13086 return Sig;
13087 }
13088
13089 static ConversionSignals ForObjectArgument() {
13090 // We intend StaticObjectArgumentConversion to compare the same as
13091 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13092 return {};
13093 }
13094 };
13095
13096 // Returns -1 if conversions in L are considered better.
13097 // 0 if they are considered indistinguishable.
13098 // 1 if conversions in R are better.
13099 int CompareConversions(const OverloadCandidate &L,
13100 const OverloadCandidate &R) {
13101 // We cannot use `isBetterOverloadCandidate` because it is defined
13102 // according to the C++ standard and provides a partial order, but we need
13103 // a total order as this function is used in sort.
13104 assert(L.Conversions.size() == R.Conversions.size());
13105 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13106 auto LS = L.IgnoreObjectArgument && I == 0
13107 ? ConversionSignals::ForObjectArgument()
13108 : ConversionSignals::ForSequence(L.Conversions[I]);
13109 auto RS = R.IgnoreObjectArgument
13110 ? ConversionSignals::ForObjectArgument()
13111 : ConversionSignals::ForSequence(R.Conversions[I]);
13112 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13113 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13114 ? -1
13115 : 1;
13116 }
13117 // FIXME: find a way to compare templates for being more or less
13118 // specialized that provides a strict weak ordering.
13119 return 0;
13120 }
13121};
13122}
13123
13124/// CompleteNonViableCandidate - Normally, overload resolution only
13125/// computes up to the first bad conversion. Produces the FixIt set if
13126/// possible.
13127static void
13129 ArrayRef<Expr *> Args,
13131 assert(!Cand->Viable);
13132
13133 // Don't do anything on failures other than bad conversion.
13135 return;
13136
13137 // We only want the FixIts if all the arguments can be corrected.
13138 bool Unfixable = false;
13139 // Use a implicit copy initialization to check conversion fixes.
13141
13142 // Attempt to fix the bad conversion.
13143 unsigned ConvCount = Cand->Conversions.size();
13144 for (unsigned ConvIdx =
13145 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13146 : 0);
13147 /**/; ++ConvIdx) {
13148 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13149 if (Cand->Conversions[ConvIdx].isInitialized() &&
13150 Cand->Conversions[ConvIdx].isBad()) {
13151 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13152 break;
13153 }
13154 }
13155
13156 // FIXME: this should probably be preserved from the overload
13157 // operation somehow.
13158 bool SuppressUserConversions = false;
13159
13160 unsigned ConvIdx = 0;
13161 unsigned ArgIdx = 0;
13162 ArrayRef<QualType> ParamTypes;
13163 bool Reversed = Cand->isReversed();
13164
13165 if (Cand->IsSurrogate) {
13166 QualType ConvType
13168 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13169 ConvType = ConvPtrType->getPointeeType();
13170 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13171 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13172 ConvIdx = 1;
13173 } else if (Cand->Function) {
13174 ParamTypes =
13175 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13176 if (isa<CXXMethodDecl>(Cand->Function) &&
13179 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13180 ConvIdx = 1;
13182 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13184 OO_Subscript)
13185 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13186 ArgIdx = 1;
13187 }
13188 } else {
13189 // Builtin operator.
13190 assert(ConvCount <= 3);
13191 ParamTypes = Cand->BuiltinParamTypes;
13192 }
13193
13194 // Fill in the rest of the conversions.
13195 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13196 ConvIdx != ConvCount && ArgIdx < Args.size();
13197 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13198 if (Cand->Conversions[ConvIdx].isInitialized()) {
13199 // We've already checked this conversion.
13200 } else if (ParamIdx < ParamTypes.size()) {
13201 if (ParamTypes[ParamIdx]->isDependentType())
13202 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13203 Args[ArgIdx]->getType());
13204 else {
13205 Cand->Conversions[ConvIdx] =
13206 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13207 SuppressUserConversions,
13208 /*InOverloadResolution=*/true,
13209 /*AllowObjCWritebackConversion=*/
13210 S.getLangOpts().ObjCAutoRefCount);
13211 // Store the FixIt in the candidate if it exists.
13212 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13213 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13214 }
13215 } else
13216 Cand->Conversions[ConvIdx].setEllipsis();
13217 }
13218}
13219
13222 SourceLocation OpLoc,
13223 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13224
13226
13227 // Sort the candidates by viability and position. Sorting directly would
13228 // be prohibitive, so we make a set of pointers and sort those.
13230 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13231 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13232 Cand != LastCand; ++Cand) {
13233 if (!Filter(*Cand))
13234 continue;
13235 switch (OCD) {
13236 case OCD_AllCandidates:
13237 if (!Cand->Viable) {
13238 if (!Cand->Function && !Cand->IsSurrogate) {
13239 // This a non-viable builtin candidate. We do not, in general,
13240 // want to list every possible builtin candidate.
13241 continue;
13242 }
13243 CompleteNonViableCandidate(S, Cand, Args, Kind);
13244 }
13245 break;
13246
13248 if (!Cand->Viable)
13249 continue;
13250 break;
13251
13253 if (!Cand->Best)
13254 continue;
13255 break;
13256 }
13257
13258 Cands.push_back(Cand);
13259 }
13260
13261 llvm::stable_sort(
13262 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13263
13264 return Cands;
13265}
13266
13268 SourceLocation OpLoc) {
13269 bool DeferHint = false;
13270 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13271 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13272 // host device candidates.
13273 auto WrongSidedCands =
13274 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13275 return (Cand.Viable == false &&
13277 (Cand.Function &&
13278 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13279 Cand.Function->template hasAttr<CUDADeviceAttr>());
13280 });
13281 DeferHint = !WrongSidedCands.empty();
13282 }
13283 return DeferHint;
13284}
13285
13286/// When overload resolution fails, prints diagnostic messages containing the
13287/// candidates in the candidate set.
13290 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13291 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13292
13293 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13294
13295 {
13296 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13297 S.Diag(PD.first, PD.second);
13298 }
13299
13300 // In WebAssembly we don't want to emit further diagnostics if a table is
13301 // passed as an argument to a function.
13302 bool NoteCands = true;
13303 for (const Expr *Arg : Args) {
13304 if (Arg->getType()->isWebAssemblyTableType())
13305 NoteCands = false;
13306 }
13307
13308 if (NoteCands)
13309 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13310
13311 if (OCD == OCD_AmbiguousCandidates)
13313 {Candidates.begin(), Candidates.end()});
13314}
13315
13318 StringRef Opc, SourceLocation OpLoc) {
13319 bool ReportedAmbiguousConversions = false;
13320
13321 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13322 unsigned CandsShown = 0;
13323 auto I = Cands.begin(), E = Cands.end();
13324 for (; I != E; ++I) {
13325 OverloadCandidate *Cand = *I;
13326
13327 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13328 ShowOverloads == Ovl_Best) {
13329 break;
13330 }
13331 ++CandsShown;
13332
13333 if (Cand->Function)
13334 NoteFunctionCandidate(S, Cand, Args.size(),
13335 Kind == CSK_AddressOfOverloadSet, DestAS);
13336 else if (Cand->IsSurrogate)
13337 NoteSurrogateCandidate(S, Cand);
13338 else {
13339 assert(Cand->Viable &&
13340 "Non-viable built-in candidates are not added to Cands.");
13341 // Generally we only see ambiguities including viable builtin
13342 // operators if overload resolution got screwed up by an
13343 // ambiguous user-defined conversion.
13344 //
13345 // FIXME: It's quite possible for different conversions to see
13346 // different ambiguities, though.
13347 if (!ReportedAmbiguousConversions) {
13348 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13349 ReportedAmbiguousConversions = true;
13350 }
13351
13352 // If this is a viable builtin, print it.
13353 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13354 }
13355 }
13356
13357 // Inform S.Diags that we've shown an overload set with N elements. This may
13358 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13359 S.Diags.overloadCandidatesShown(CandsShown);
13360
13361 if (I != E) {
13362 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13363 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13364 }
13365}
13366
13367static SourceLocation
13369 return Cand->Specialization ? Cand->Specialization->getLocation()
13370 : SourceLocation();
13371}
13372
13373namespace {
13374struct CompareTemplateSpecCandidatesForDisplay {
13375 Sema &S;
13376 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13377
13378 bool operator()(const TemplateSpecCandidate *L,
13379 const TemplateSpecCandidate *R) {
13380 // Fast-path this check.
13381 if (L == R)
13382 return false;
13383
13384 // Assuming that both candidates are not matches...
13385
13386 // Sort by the ranking of deduction failures.
13390
13391 // Sort everything else by location.
13392 SourceLocation LLoc = GetLocationForCandidate(L);
13393 SourceLocation RLoc = GetLocationForCandidate(R);
13394
13395 // Put candidates without locations (e.g. builtins) at the end.
13396 if (LLoc.isInvalid())
13397 return false;
13398 if (RLoc.isInvalid())
13399 return true;
13400
13401 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13402 }
13403};
13404}
13405
13406/// Diagnose a template argument deduction failure.
13407/// We are treating these failures as overload failures due to bad
13408/// deductions.
13410 bool ForTakingAddress) {
13412 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13413}
13414
13415void TemplateSpecCandidateSet::destroyCandidates() {
13416 for (iterator i = begin(), e = end(); i != e; ++i) {
13417 i->DeductionFailure.Destroy();
13418 }
13419}
13420
13422 destroyCandidates();
13423 Candidates.clear();
13424}
13425
13426/// NoteCandidates - When no template specialization match is found, prints
13427/// diagnostic messages containing the non-matching specializations that form
13428/// the candidate set.
13429/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13430/// OCD == OCD_AllCandidates and Cand->Viable == false.
13432 // Sort the candidates by position (assuming no candidate is a match).
13433 // Sorting directly would be prohibitive, so we make a set of pointers
13434 // and sort those.
13436 Cands.reserve(size());
13437 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13438 if (Cand->Specialization)
13439 Cands.push_back(Cand);
13440 // Otherwise, this is a non-matching builtin candidate. We do not,
13441 // in general, want to list every possible builtin candidate.
13442 }
13443
13444 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13445
13446 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13447 // for generalization purposes (?).
13448 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13449
13451 unsigned CandsShown = 0;
13452 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13453 TemplateSpecCandidate *Cand = *I;
13454
13455 // Set an arbitrary limit on the number of candidates we'll spam
13456 // the user with. FIXME: This limit should depend on details of the
13457 // candidate list.
13458 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13459 break;
13460 ++CandsShown;
13461
13462 assert(Cand->Specialization &&
13463 "Non-matching built-in candidates are not added to Cands.");
13464 Cand->NoteDeductionFailure(S, ForTakingAddress);
13465 }
13466
13467 if (I != E)
13468 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13469}
13470
13471// [PossiblyAFunctionType] --> [Return]
13472// NonFunctionType --> NonFunctionType
13473// R (A) --> R(A)
13474// R (*)(A) --> R (A)
13475// R (&)(A) --> R (A)
13476// R (S::*)(A) --> R (A)
13478 QualType Ret = PossiblyAFunctionType;
13479 if (const PointerType *ToTypePtr =
13480 PossiblyAFunctionType->getAs<PointerType>())
13481 Ret = ToTypePtr->getPointeeType();
13482 else if (const ReferenceType *ToTypeRef =
13483 PossiblyAFunctionType->getAs<ReferenceType>())
13484 Ret = ToTypeRef->getPointeeType();
13485 else if (const MemberPointerType *MemTypePtr =
13486 PossiblyAFunctionType->getAs<MemberPointerType>())
13487 Ret = MemTypePtr->getPointeeType();
13488 Ret =
13489 Context.getCanonicalType(Ret).getUnqualifiedType();
13490 return Ret;
13491}
13492
13494 bool Complain = true) {
13495 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13496 S.DeduceReturnType(FD, Loc, Complain))
13497 return true;
13498
13499 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13500 if (S.getLangOpts().CPlusPlus17 &&
13501 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13502 !S.ResolveExceptionSpec(Loc, FPT))
13503 return true;
13504
13505 return false;
13506}
13507
13508namespace {
13509// A helper class to help with address of function resolution
13510// - allows us to avoid passing around all those ugly parameters
13511class AddressOfFunctionResolver {
13512 Sema& S;
13513 Expr* SourceExpr;
13514 const QualType& TargetType;
13515 QualType TargetFunctionType; // Extracted function type from target type
13516
13517 bool Complain;
13518 //DeclAccessPair& ResultFunctionAccessPair;
13519 ASTContext& Context;
13520
13521 bool TargetTypeIsNonStaticMemberFunction;
13522 bool FoundNonTemplateFunction;
13523 bool StaticMemberFunctionFromBoundPointer;
13524 bool HasComplained;
13525
13526 OverloadExpr::FindResult OvlExprInfo;
13527 OverloadExpr *OvlExpr;
13528 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13529 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13530 TemplateSpecCandidateSet FailedCandidates;
13531
13532public:
13533 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13534 const QualType &TargetType, bool Complain)
13535 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13536 Complain(Complain), Context(S.getASTContext()),
13537 TargetTypeIsNonStaticMemberFunction(
13538 !!TargetType->getAs<MemberPointerType>()),
13539 FoundNonTemplateFunction(false),
13540 StaticMemberFunctionFromBoundPointer(false),
13541 HasComplained(false),
13542 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13543 OvlExpr(OvlExprInfo.Expression),
13544 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13545 ExtractUnqualifiedFunctionTypeFromTargetType();
13546
13547 if (TargetFunctionType->isFunctionType()) {
13548 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13549 if (!UME->isImplicitAccess() &&
13551 StaticMemberFunctionFromBoundPointer = true;
13552 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13553 DeclAccessPair dap;
13554 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13555 OvlExpr, false, &dap)) {
13556 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13557 if (!Method->isStatic()) {
13558 // If the target type is a non-function type and the function found
13559 // is a non-static member function, pretend as if that was the
13560 // target, it's the only possible type to end up with.
13561 TargetTypeIsNonStaticMemberFunction = true;
13562
13563 // And skip adding the function if its not in the proper form.
13564 // We'll diagnose this due to an empty set of functions.
13565 if (!OvlExprInfo.HasFormOfMemberPointer)
13566 return;
13567 }
13568
13569 Matches.push_back(std::make_pair(dap, Fn));
13570 }
13571 return;
13572 }
13573
13574 if (OvlExpr->hasExplicitTemplateArgs())
13575 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13576
13577 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13578 // C++ [over.over]p4:
13579 // If more than one function is selected, [...]
13580 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13581 if (FoundNonTemplateFunction) {
13582 EliminateAllTemplateMatches();
13583 EliminateLessPartialOrderingConstrainedMatches();
13584 } else
13585 EliminateAllExceptMostSpecializedTemplate();
13586 }
13587 }
13588
13589 if (S.getLangOpts().CUDA && Matches.size() > 1)
13590 EliminateSuboptimalCudaMatches();
13591 }
13592
13593 bool hasComplained() const { return HasComplained; }
13594
13595private:
13596 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13597 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13598 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13599 }
13600
13601 /// \return true if A is considered a better overload candidate for the
13602 /// desired type than B.
13603 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13604 // If A doesn't have exactly the correct type, we don't want to classify it
13605 // as "better" than anything else. This way, the user is required to
13606 // disambiguate for us if there are multiple candidates and no exact match.
13607 return candidateHasExactlyCorrectType(A) &&
13608 (!candidateHasExactlyCorrectType(B) ||
13609 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13610 }
13611
13612 /// \return true if we were able to eliminate all but one overload candidate,
13613 /// false otherwise.
13614 bool eliminiateSuboptimalOverloadCandidates() {
13615 // Same algorithm as overload resolution -- one pass to pick the "best",
13616 // another pass to be sure that nothing is better than the best.
13617 auto Best = Matches.begin();
13618 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13619 if (isBetterCandidate(I->second, Best->second))
13620 Best = I;
13621
13622 const FunctionDecl *BestFn = Best->second;
13623 auto IsBestOrInferiorToBest = [this, BestFn](
13624 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13625 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13626 };
13627
13628 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13629 // option, so we can potentially give the user a better error
13630 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13631 return false;
13632 Matches[0] = *Best;
13633 Matches.resize(1);
13634 return true;
13635 }
13636
13637 bool isTargetTypeAFunction() const {
13638 return TargetFunctionType->isFunctionType();
13639 }
13640
13641 // [ToType] [Return]
13642
13643 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13644 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13645 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13646 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13647 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13648 }
13649
13650 // return true if any matching specializations were found
13651 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13652 const DeclAccessPair& CurAccessFunPair) {
13653 if (CXXMethodDecl *Method
13654 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13655 // Skip non-static function templates when converting to pointer, and
13656 // static when converting to member pointer.
13657 bool CanConvertToFunctionPointer =
13658 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13659 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13660 return false;
13661 }
13662 else if (TargetTypeIsNonStaticMemberFunction)
13663 return false;
13664
13665 // C++ [over.over]p2:
13666 // If the name is a function template, template argument deduction is
13667 // done (14.8.2.2), and if the argument deduction succeeds, the
13668 // resulting template argument list is used to generate a single
13669 // function template specialization, which is added to the set of
13670 // overloaded functions considered.
13671 FunctionDecl *Specialization = nullptr;
13672 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13674 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13675 Specialization, Info, /*IsAddressOfFunction*/ true);
13676 Result != TemplateDeductionResult::Success) {
13677 // Make a note of the failed deduction for diagnostics.
13678 FailedCandidates.addCandidate()
13679 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13680 MakeDeductionFailureInfo(Context, Result, Info));
13681 return false;
13682 }
13683
13684 // Template argument deduction ensures that we have an exact match or
13685 // compatible pointer-to-function arguments that would be adjusted by ICS.
13686 // This function template specicalization works.
13688 Context.getCanonicalType(Specialization->getType()),
13689 Context.getCanonicalType(TargetFunctionType)));
13690
13692 return false;
13693
13694 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13695 return true;
13696 }
13697
13698 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13699 const DeclAccessPair& CurAccessFunPair) {
13700 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13701 // Skip non-static functions when converting to pointer, and static
13702 // when converting to member pointer.
13703 bool CanConvertToFunctionPointer =
13704 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13705 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13706 return false;
13707 }
13708 else if (TargetTypeIsNonStaticMemberFunction)
13709 return false;
13710
13711 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13712 if (S.getLangOpts().CUDA) {
13713 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13714 if (!(Caller && Caller->isImplicit()) &&
13715 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13716 return false;
13717 }
13718 if (FunDecl->isMultiVersion()) {
13719 const auto *TA = FunDecl->getAttr<TargetAttr>();
13720 if (TA && !TA->isDefaultVersion())
13721 return false;
13722 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13723 if (TVA && !TVA->isDefaultVersion())
13724 return false;
13725 }
13726
13727 // If any candidate has a placeholder return type, trigger its deduction
13728 // now.
13729 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13730 Complain)) {
13731 HasComplained |= Complain;
13732 return false;
13733 }
13734
13735 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13736 return false;
13737
13738 // If we're in C, we need to support types that aren't exactly identical.
13739 if (!S.getLangOpts().CPlusPlus ||
13740 candidateHasExactlyCorrectType(FunDecl)) {
13741 Matches.push_back(std::make_pair(
13742 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13743 FoundNonTemplateFunction = true;
13744 return true;
13745 }
13746 }
13747
13748 return false;
13749 }
13750
13751 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13752 bool Ret = false;
13753
13754 // If the overload expression doesn't have the form of a pointer to
13755 // member, don't try to convert it to a pointer-to-member type.
13756 if (IsInvalidFormOfPointerToMemberFunction())
13757 return false;
13758
13759 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13760 E = OvlExpr->decls_end();
13761 I != E; ++I) {
13762 // Look through any using declarations to find the underlying function.
13763 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13764
13765 // C++ [over.over]p3:
13766 // Non-member functions and static member functions match
13767 // targets of type "pointer-to-function" or "reference-to-function."
13768 // Nonstatic member functions match targets of
13769 // type "pointer-to-member-function."
13770 // Note that according to DR 247, the containing class does not matter.
13771 if (FunctionTemplateDecl *FunctionTemplate
13772 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13773 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13774 Ret = true;
13775 }
13776 // If we have explicit template arguments supplied, skip non-templates.
13777 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13778 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13779 Ret = true;
13780 }
13781 assert(Ret || Matches.empty());
13782 return Ret;
13783 }
13784
13785 void EliminateAllExceptMostSpecializedTemplate() {
13786 // [...] and any given function template specialization F1 is
13787 // eliminated if the set contains a second function template
13788 // specialization whose function template is more specialized
13789 // than the function template of F1 according to the partial
13790 // ordering rules of 14.5.5.2.
13791
13792 // The algorithm specified above is quadratic. We instead use a
13793 // two-pass algorithm (similar to the one used to identify the
13794 // best viable function in an overload set) that identifies the
13795 // best function template (if it exists).
13796
13797 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13798 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13799 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13800
13801 // TODO: It looks like FailedCandidates does not serve much purpose
13802 // here, since the no_viable diagnostic has index 0.
13803 UnresolvedSetIterator Result = S.getMostSpecialized(
13804 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13805 SourceExpr->getBeginLoc(), S.PDiag(),
13806 S.PDiag(diag::err_addr_ovl_ambiguous)
13807 << Matches[0].second->getDeclName(),
13808 S.PDiag(diag::note_ovl_candidate)
13809 << (unsigned)oc_function << (unsigned)ocs_described_template,
13810 Complain, TargetFunctionType);
13811
13812 if (Result != MatchesCopy.end()) {
13813 // Make it the first and only element
13814 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13815 Matches[0].second = cast<FunctionDecl>(*Result);
13816 Matches.resize(1);
13817 } else
13818 HasComplained |= Complain;
13819 }
13820
13821 void EliminateAllTemplateMatches() {
13822 // [...] any function template specializations in the set are
13823 // eliminated if the set also contains a non-template function, [...]
13824 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13825 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13826 ++I;
13827 else {
13828 Matches[I] = Matches[--N];
13829 Matches.resize(N);
13830 }
13831 }
13832 }
13833
13834 void EliminateLessPartialOrderingConstrainedMatches() {
13835 // C++ [over.over]p5:
13836 // [...] Any given non-template function F0 is eliminated if the set
13837 // contains a second non-template function that is more
13838 // partial-ordering-constrained than F0. [...]
13839 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13840 "Call EliminateAllTemplateMatches() first");
13841 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13842 Results.push_back(Matches[0]);
13843 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13844 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13845 FunctionDecl *F = getMorePartialOrderingConstrained(
13846 S, Matches[I].second, Results[0].second,
13847 /*IsFn1Reversed=*/false,
13848 /*IsFn2Reversed=*/false);
13849 if (!F) {
13850 Results.push_back(Matches[I]);
13851 continue;
13852 }
13853 if (F == Matches[I].second) {
13854 Results.clear();
13855 Results.push_back(Matches[I]);
13856 }
13857 }
13858 std::swap(Matches, Results);
13859 }
13860
13861 void EliminateSuboptimalCudaMatches() {
13862 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13863 Matches);
13864 }
13865
13866public:
13867 void ComplainNoMatchesFound() const {
13868 assert(Matches.empty());
13869 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13870 << OvlExpr->getName() << TargetFunctionType
13871 << OvlExpr->getSourceRange();
13872 if (FailedCandidates.empty())
13873 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13874 /*TakingAddress=*/true);
13875 else {
13876 // We have some deduction failure messages. Use them to diagnose
13877 // the function templates, and diagnose the non-template candidates
13878 // normally.
13879 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13880 IEnd = OvlExpr->decls_end();
13881 I != IEnd; ++I)
13882 if (FunctionDecl *Fun =
13883 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13885 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13886 /*TakingAddress=*/true);
13887 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13888 }
13889 }
13890
13891 bool IsInvalidFormOfPointerToMemberFunction() const {
13892 return TargetTypeIsNonStaticMemberFunction &&
13893 !OvlExprInfo.HasFormOfMemberPointer;
13894 }
13895
13896 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13897 // TODO: Should we condition this on whether any functions might
13898 // have matched, or is it more appropriate to do that in callers?
13899 // TODO: a fixit wouldn't hurt.
13900 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13901 << TargetType << OvlExpr->getSourceRange();
13902 }
13903
13904 bool IsStaticMemberFunctionFromBoundPointer() const {
13905 return StaticMemberFunctionFromBoundPointer;
13906 }
13907
13908 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13909 S.Diag(OvlExpr->getBeginLoc(),
13910 diag::err_invalid_form_pointer_member_function)
13911 << OvlExpr->getSourceRange();
13912 }
13913
13914 void ComplainOfInvalidConversion() const {
13915 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13916 << OvlExpr->getName() << TargetType;
13917 }
13918
13919 void ComplainMultipleMatchesFound() const {
13920 assert(Matches.size() > 1);
13921 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13922 << OvlExpr->getName() << OvlExpr->getSourceRange();
13923 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13924 /*TakingAddress=*/true);
13925 }
13926
13927 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13928
13929 int getNumMatches() const { return Matches.size(); }
13930
13931 FunctionDecl* getMatchingFunctionDecl() const {
13932 if (Matches.size() != 1) return nullptr;
13933 return Matches[0].second;
13934 }
13935
13936 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13937 if (Matches.size() != 1) return nullptr;
13938 return &Matches[0].first;
13939 }
13940};
13941}
13942
13943FunctionDecl *
13945 QualType TargetType,
13946 bool Complain,
13947 DeclAccessPair &FoundResult,
13948 bool *pHadMultipleCandidates) {
13949 assert(AddressOfExpr->getType() == Context.OverloadTy);
13950
13951 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13952 Complain);
13953 int NumMatches = Resolver.getNumMatches();
13954 FunctionDecl *Fn = nullptr;
13955 bool ShouldComplain = Complain && !Resolver.hasComplained();
13956 if (NumMatches == 0 && ShouldComplain) {
13957 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13958 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13959 else
13960 Resolver.ComplainNoMatchesFound();
13961 }
13962 else if (NumMatches > 1 && ShouldComplain)
13963 Resolver.ComplainMultipleMatchesFound();
13964 else if (NumMatches == 1) {
13965 Fn = Resolver.getMatchingFunctionDecl();
13966 assert(Fn);
13967 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13968 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13969 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13970 if (Complain) {
13971 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13972 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13973 else
13974 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13975 }
13976 }
13977
13978 if (pHadMultipleCandidates)
13979 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13980 return Fn;
13981}
13982
13986 OverloadExpr *Ovl = R.Expression;
13987 bool IsResultAmbiguous = false;
13988 FunctionDecl *Result = nullptr;
13989 DeclAccessPair DAP;
13990 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13991
13992 // Return positive for better, negative for worse, 0 for equal preference.
13993 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13994 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13995 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13996 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13997 };
13998
13999 // Don't use the AddressOfResolver because we're specifically looking for
14000 // cases where we have one overload candidate that lacks
14001 // enable_if/pass_object_size/...
14002 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14003 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14004 if (!FD)
14005 return nullptr;
14006
14008 continue;
14009
14010 // If we found a better result, update Result.
14011 auto FoundBetter = [&]() {
14012 IsResultAmbiguous = false;
14013 DAP = I.getPair();
14014 Result = FD;
14015 };
14016
14017 // We have more than one result - see if it is more
14018 // partial-ordering-constrained than the previous one.
14019 if (Result) {
14020 // Check CUDA preference first. If the candidates have differennt CUDA
14021 // preference, choose the one with higher CUDA preference. Otherwise,
14022 // choose the one with more constraints.
14023 if (getLangOpts().CUDA) {
14024 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14025 // FD has different preference than Result.
14026 if (PreferenceByCUDA != 0) {
14027 // FD is more preferable than Result.
14028 if (PreferenceByCUDA > 0)
14029 FoundBetter();
14030 continue;
14031 }
14032 }
14033 // FD has the same CUDA preference than Result. Continue to check
14034 // constraints.
14035
14036 // C++ [over.over]p5:
14037 // [...] Any given non-template function F0 is eliminated if the set
14038 // contains a second non-template function that is more
14039 // partial-ordering-constrained than F0 [...]
14040 FunctionDecl *MoreConstrained =
14042 /*IsFn1Reversed=*/false,
14043 /*IsFn2Reversed=*/false);
14044 if (MoreConstrained != FD) {
14045 if (!MoreConstrained) {
14046 IsResultAmbiguous = true;
14047 AmbiguousDecls.push_back(FD);
14048 }
14049 continue;
14050 }
14051 // FD is more constrained - replace Result with it.
14052 }
14053 FoundBetter();
14054 }
14055
14056 if (IsResultAmbiguous)
14057 return nullptr;
14058
14059 if (Result) {
14060 // We skipped over some ambiguous declarations which might be ambiguous with
14061 // the selected result.
14062 for (FunctionDecl *Skipped : AmbiguousDecls) {
14063 // If skipped candidate has different CUDA preference than the result,
14064 // there is no ambiguity. Otherwise check whether they have different
14065 // constraints.
14066 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14067 continue;
14068 if (!getMoreConstrainedFunction(Skipped, Result))
14069 return nullptr;
14070 }
14071 Pair = DAP;
14072 }
14073 return Result;
14074}
14075
14077 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14078 Expr *E = SrcExpr.get();
14079 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14080
14081 DeclAccessPair DAP;
14083 if (!Found || Found->isCPUDispatchMultiVersion() ||
14084 Found->isCPUSpecificMultiVersion())
14085 return false;
14086
14087 // Emitting multiple diagnostics for a function that is both inaccessible and
14088 // unavailable is consistent with our behavior elsewhere. So, always check
14089 // for both.
14093 if (Res.isInvalid())
14094 return false;
14095 Expr *Fixed = Res.get();
14096 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14097 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14098 else
14099 SrcExpr = Fixed;
14100 return true;
14101}
14102
14104 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14105 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14106 // C++ [over.over]p1:
14107 // [...] [Note: any redundant set of parentheses surrounding the
14108 // overloaded function name is ignored (5.1). ]
14109 // C++ [over.over]p1:
14110 // [...] The overloaded function name can be preceded by the &
14111 // operator.
14112
14113 // If we didn't actually find any template-ids, we're done.
14114 if (!ovl->hasExplicitTemplateArgs())
14115 return nullptr;
14116
14117 TemplateArgumentListInfo ExplicitTemplateArgs;
14118 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14119
14120 // Look through all of the overloaded functions, searching for one
14121 // whose type matches exactly.
14122 FunctionDecl *Matched = nullptr;
14123 for (UnresolvedSetIterator I = ovl->decls_begin(),
14124 E = ovl->decls_end(); I != E; ++I) {
14125 // C++0x [temp.arg.explicit]p3:
14126 // [...] In contexts where deduction is done and fails, or in contexts
14127 // where deduction is not done, if a template argument list is
14128 // specified and it, along with any default template arguments,
14129 // identifies a single function template specialization, then the
14130 // template-id is an lvalue for the function template specialization.
14132 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14133 if (!FunctionTemplate)
14134 continue;
14135
14136 // C++ [over.over]p2:
14137 // If the name is a function template, template argument deduction is
14138 // done (14.8.2.2), and if the argument deduction succeeds, the
14139 // resulting template argument list is used to generate a single
14140 // function template specialization, which is added to the set of
14141 // overloaded functions considered.
14142 FunctionDecl *Specialization = nullptr;
14143 TemplateDeductionInfo Info(ovl->getNameLoc());
14145 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14146 /*IsAddressOfFunction*/ true);
14148 // Make a note of the failed deduction for diagnostics.
14149 if (FailedTSC)
14150 FailedTSC->addCandidate().set(
14151 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14153 continue;
14154 }
14155
14156 assert(Specialization && "no specialization and no error?");
14157
14158 // C++ [temp.deduct.call]p6:
14159 // [...] If all successful deductions yield the same deduced A, that
14160 // deduced A is the result of deduction; otherwise, the parameter is
14161 // treated as a non-deduced context.
14162 if (Matched) {
14163 if (ForTypeDeduction &&
14165 Specialization->getType()))
14166 continue;
14167 // Multiple matches; we can't resolve to a single declaration.
14168 if (Complain) {
14169 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14170 << ovl->getName();
14172 }
14173 return nullptr;
14174 }
14175
14176 Matched = Specialization;
14177 if (FoundResult) *FoundResult = I.getPair();
14178 }
14179
14180 if (Matched &&
14181 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14182 return nullptr;
14183
14184 return Matched;
14185}
14186
14188 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14189 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14190 unsigned DiagIDForComplaining) {
14191 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14192
14194
14195 DeclAccessPair found;
14196 ExprResult SingleFunctionExpression;
14198 ovl.Expression, /*complain*/ false, &found)) {
14199 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14200 SrcExpr = ExprError();
14201 return true;
14202 }
14203
14204 // It is only correct to resolve to an instance method if we're
14205 // resolving a form that's permitted to be a pointer to member.
14206 // Otherwise we'll end up making a bound member expression, which
14207 // is illegal in all the contexts we resolve like this.
14208 if (!ovl.HasFormOfMemberPointer &&
14209 isa<CXXMethodDecl>(fn) &&
14210 cast<CXXMethodDecl>(fn)->isInstance()) {
14211 if (!complain) return false;
14212
14213 Diag(ovl.Expression->getExprLoc(),
14214 diag::err_bound_member_function)
14215 << 0 << ovl.Expression->getSourceRange();
14216
14217 // TODO: I believe we only end up here if there's a mix of
14218 // static and non-static candidates (otherwise the expression
14219 // would have 'bound member' type, not 'overload' type).
14220 // Ideally we would note which candidate was chosen and why
14221 // the static candidates were rejected.
14222 SrcExpr = ExprError();
14223 return true;
14224 }
14225
14226 // Fix the expression to refer to 'fn'.
14227 SingleFunctionExpression =
14228 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14229
14230 // If desired, do function-to-pointer decay.
14231 if (doFunctionPointerConversion) {
14232 SingleFunctionExpression =
14233 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14234 if (SingleFunctionExpression.isInvalid()) {
14235 SrcExpr = ExprError();
14236 return true;
14237 }
14238 }
14239 }
14240
14241 if (!SingleFunctionExpression.isUsable()) {
14242 if (complain) {
14243 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14244 << ovl.Expression->getName()
14245 << DestTypeForComplaining
14246 << OpRangeForComplaining
14248 NoteAllOverloadCandidates(SrcExpr.get());
14249
14250 SrcExpr = ExprError();
14251 return true;
14252 }
14253
14254 return false;
14255 }
14256
14257 SrcExpr = SingleFunctionExpression;
14258 return true;
14259}
14260
14261/// Add a single candidate to the overload set.
14263 DeclAccessPair FoundDecl,
14264 TemplateArgumentListInfo *ExplicitTemplateArgs,
14265 ArrayRef<Expr *> Args,
14266 OverloadCandidateSet &CandidateSet,
14267 bool PartialOverloading,
14268 bool KnownValid) {
14269 NamedDecl *Callee = FoundDecl.getDecl();
14270 if (isa<UsingShadowDecl>(Callee))
14271 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14272
14273 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14274 if (ExplicitTemplateArgs) {
14275 assert(!KnownValid && "Explicit template arguments?");
14276 return;
14277 }
14278 // Prevent ill-formed function decls to be added as overload candidates.
14279 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14280 return;
14281
14282 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14283 /*SuppressUserConversions=*/false,
14284 PartialOverloading);
14285 return;
14286 }
14287
14288 if (FunctionTemplateDecl *FuncTemplate
14289 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14290 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14291 ExplicitTemplateArgs, Args, CandidateSet,
14292 /*SuppressUserConversions=*/false,
14293 PartialOverloading);
14294 return;
14295 }
14296
14297 assert(!KnownValid && "unhandled case in overloaded call candidate");
14298}
14299
14301 ArrayRef<Expr *> Args,
14302 OverloadCandidateSet &CandidateSet,
14303 bool PartialOverloading) {
14304
14305#ifndef NDEBUG
14306 // Verify that ArgumentDependentLookup is consistent with the rules
14307 // in C++0x [basic.lookup.argdep]p3:
14308 //
14309 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14310 // and let Y be the lookup set produced by argument dependent
14311 // lookup (defined as follows). If X contains
14312 //
14313 // -- a declaration of a class member, or
14314 //
14315 // -- a block-scope function declaration that is not a
14316 // using-declaration, or
14317 //
14318 // -- a declaration that is neither a function or a function
14319 // template
14320 //
14321 // then Y is empty.
14322
14323 if (ULE->requiresADL()) {
14325 E = ULE->decls_end(); I != E; ++I) {
14326 assert(!(*I)->getDeclContext()->isRecord());
14327 assert(isa<UsingShadowDecl>(*I) ||
14328 !(*I)->getDeclContext()->isFunctionOrMethod());
14329 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14330 }
14331 }
14332#endif
14333
14334 // It would be nice to avoid this copy.
14335 TemplateArgumentListInfo TABuffer;
14336 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14337 if (ULE->hasExplicitTemplateArgs()) {
14338 ULE->copyTemplateArgumentsInto(TABuffer);
14339 ExplicitTemplateArgs = &TABuffer;
14340 }
14341
14343 E = ULE->decls_end(); I != E; ++I)
14344 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14345 CandidateSet, PartialOverloading,
14346 /*KnownValid*/ true);
14347
14348 if (ULE->requiresADL())
14350 Args, ExplicitTemplateArgs,
14351 CandidateSet, PartialOverloading);
14352}
14353
14355 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14356 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14357 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14358 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14359 CandidateSet, false, /*KnownValid*/ false);
14360}
14361
14362/// Determine whether a declaration with the specified name could be moved into
14363/// a different namespace.
14365 switch (Name.getCXXOverloadedOperator()) {
14366 case OO_New: case OO_Array_New:
14367 case OO_Delete: case OO_Array_Delete:
14368 return false;
14369
14370 default:
14371 return true;
14372 }
14373}
14374
14375/// Attempt to recover from an ill-formed use of a non-dependent name in a
14376/// template, where the non-dependent name was declared after the template
14377/// was defined. This is common in code written for a compilers which do not
14378/// correctly implement two-stage name lookup.
14379///
14380/// Returns true if a viable candidate was found and a diagnostic was issued.
14382 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14384 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14385 CXXRecordDecl **FoundInClass = nullptr) {
14386 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14387 return false;
14388
14389 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14390 if (DC->isTransparentContext())
14391 continue;
14392
14393 SemaRef.LookupQualifiedName(R, DC);
14394
14395 if (!R.empty()) {
14397
14398 OverloadCandidateSet Candidates(FnLoc, CSK);
14399 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14400 Candidates);
14401
14404 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14405
14406 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14407 // We either found non-function declarations or a best viable function
14408 // at class scope. A class-scope lookup result disables ADL. Don't
14409 // look past this, but let the caller know that we found something that
14410 // either is, or might be, usable in this class.
14411 if (FoundInClass) {
14412 *FoundInClass = RD;
14413 if (OR == OR_Success) {
14414 R.clear();
14415 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14416 R.resolveKind();
14417 }
14418 }
14419 return false;
14420 }
14421
14422 if (OR != OR_Success) {
14423 // There wasn't a unique best function or function template.
14424 return false;
14425 }
14426
14427 // Find the namespaces where ADL would have looked, and suggest
14428 // declaring the function there instead.
14429 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14430 Sema::AssociatedClassSet AssociatedClasses;
14431 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14432 AssociatedNamespaces,
14433 AssociatedClasses);
14434 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14436 DeclContext *Std = SemaRef.getStdNamespace();
14437 for (Sema::AssociatedNamespaceSet::iterator
14438 it = AssociatedNamespaces.begin(),
14439 end = AssociatedNamespaces.end(); it != end; ++it) {
14440 // Never suggest declaring a function within namespace 'std'.
14441 if (Std && Std->Encloses(*it))
14442 continue;
14443
14444 // Never suggest declaring a function within a namespace with a
14445 // reserved name, like __gnu_cxx.
14446 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14447 if (NS &&
14448 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14449 continue;
14450
14451 SuggestedNamespaces.insert(*it);
14452 }
14453 }
14454
14455 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14456 << R.getLookupName();
14457 if (SuggestedNamespaces.empty()) {
14458 SemaRef.Diag(Best->Function->getLocation(),
14459 diag::note_not_found_by_two_phase_lookup)
14460 << R.getLookupName() << 0;
14461 } else if (SuggestedNamespaces.size() == 1) {
14462 SemaRef.Diag(Best->Function->getLocation(),
14463 diag::note_not_found_by_two_phase_lookup)
14464 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14465 } else {
14466 // FIXME: It would be useful to list the associated namespaces here,
14467 // but the diagnostics infrastructure doesn't provide a way to produce
14468 // a localized representation of a list of items.
14469 SemaRef.Diag(Best->Function->getLocation(),
14470 diag::note_not_found_by_two_phase_lookup)
14471 << R.getLookupName() << 2;
14472 }
14473
14474 // Try to recover by calling this function.
14475 return true;
14476 }
14477
14478 R.clear();
14479 }
14480
14481 return false;
14482}
14483
14484/// Attempt to recover from ill-formed use of a non-dependent operator in a
14485/// template, where the non-dependent operator was declared after the template
14486/// was defined.
14487///
14488/// Returns true if a viable candidate was found and a diagnostic was issued.
14489static bool
14491 SourceLocation OpLoc,
14492 ArrayRef<Expr *> Args) {
14493 DeclarationName OpName =
14495 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14496 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14498 /*ExplicitTemplateArgs=*/nullptr, Args);
14499}
14500
14501namespace {
14502class BuildRecoveryCallExprRAII {
14503 Sema &SemaRef;
14504 Sema::SatisfactionStackResetRAII SatStack;
14505
14506public:
14507 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14508 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14509 SemaRef.IsBuildingRecoveryCallExpr = true;
14510 }
14511
14512 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14513};
14514}
14515
14516/// Attempts to recover from a call where no functions were found.
14517///
14518/// This function will do one of three things:
14519/// * Diagnose, recover, and return a recovery expression.
14520/// * Diagnose, fail to recover, and return ExprError().
14521/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14522/// expected to diagnose as appropriate.
14523static ExprResult
14526 SourceLocation LParenLoc,
14528 SourceLocation RParenLoc,
14529 bool EmptyLookup, bool AllowTypoCorrection) {
14530 // Do not try to recover if it is already building a recovery call.
14531 // This stops infinite loops for template instantiations like
14532 //
14533 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14534 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14535 if (SemaRef.IsBuildingRecoveryCallExpr)
14536 return ExprResult();
14537 BuildRecoveryCallExprRAII RCE(SemaRef);
14538
14539 CXXScopeSpec SS;
14540 SS.Adopt(ULE->getQualifierLoc());
14541 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14542
14543 TemplateArgumentListInfo TABuffer;
14544 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14545 if (ULE->hasExplicitTemplateArgs()) {
14546 ULE->copyTemplateArgumentsInto(TABuffer);
14547 ExplicitTemplateArgs = &TABuffer;
14548 }
14549
14550 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14552 CXXRecordDecl *FoundInClass = nullptr;
14553 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14555 ExplicitTemplateArgs, Args, &FoundInClass)) {
14556 // OK, diagnosed a two-phase lookup issue.
14557 } else if (EmptyLookup) {
14558 // Try to recover from an empty lookup with typo correction.
14559 R.clear();
14560 NoTypoCorrectionCCC NoTypoValidator{};
14561 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14562 ExplicitTemplateArgs != nullptr,
14563 dyn_cast<MemberExpr>(Fn));
14564 CorrectionCandidateCallback &Validator =
14565 AllowTypoCorrection
14566 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14567 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14568 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14569 Args))
14570 return ExprError();
14571 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14572 // We found a usable declaration of the name in a dependent base of some
14573 // enclosing class.
14574 // FIXME: We should also explain why the candidates found by name lookup
14575 // were not viable.
14576 if (SemaRef.DiagnoseDependentMemberLookup(R))
14577 return ExprError();
14578 } else {
14579 // We had viable candidates and couldn't recover; let the caller diagnose
14580 // this.
14581 return ExprResult();
14582 }
14583
14584 // If we get here, we should have issued a diagnostic and formed a recovery
14585 // lookup result.
14586 assert(!R.empty() && "lookup results empty despite recovery");
14587
14588 // If recovery created an ambiguity, just bail out.
14589 if (R.isAmbiguous()) {
14591 return ExprError();
14592 }
14593
14594 // Build an implicit member call if appropriate. Just drop the
14595 // casts and such from the call, we don't really care.
14596 ExprResult NewFn = ExprError();
14597 if ((*R.begin())->isCXXClassMember())
14598 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14599 ExplicitTemplateArgs, S);
14600 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14601 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14602 ExplicitTemplateArgs);
14603 else
14604 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14605
14606 if (NewFn.isInvalid())
14607 return ExprError();
14608
14609 // This shouldn't cause an infinite loop because we're giving it
14610 // an expression with viable lookup results, which should never
14611 // end up here.
14612 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14613 MultiExprArg(Args.data(), Args.size()),
14614 RParenLoc);
14615}
14616
14619 MultiExprArg Args,
14620 SourceLocation RParenLoc,
14621 OverloadCandidateSet *CandidateSet,
14622 ExprResult *Result) {
14623#ifndef NDEBUG
14624 if (ULE->requiresADL()) {
14625 // To do ADL, we must have found an unqualified name.
14626 assert(!ULE->getQualifier() && "qualified name with ADL");
14627
14628 // We don't perform ADL for implicit declarations of builtins.
14629 // Verify that this was correctly set up.
14630 FunctionDecl *F;
14631 if (ULE->decls_begin() != ULE->decls_end() &&
14632 ULE->decls_begin() + 1 == ULE->decls_end() &&
14633 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14634 F->getBuiltinID() && F->isImplicit())
14635 llvm_unreachable("performing ADL for builtin");
14636
14637 // We don't perform ADL in C.
14638 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14639 }
14640#endif
14641
14642 UnbridgedCastsSet UnbridgedCasts;
14643 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14644 *Result = ExprError();
14645 return true;
14646 }
14647
14648 // Add the functions denoted by the callee to the set of candidate
14649 // functions, including those from argument-dependent lookup.
14650 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14651
14652 if (getLangOpts().MSVCCompat &&
14653 CurContext->isDependentContext() && !isSFINAEContext() &&
14655
14657 if (CandidateSet->empty() ||
14658 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14660 // In Microsoft mode, if we are inside a template class member function
14661 // then create a type dependent CallExpr. The goal is to postpone name
14662 // lookup to instantiation time to be able to search into type dependent
14663 // base classes.
14664 CallExpr *CE =
14665 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14666 RParenLoc, CurFPFeatureOverrides());
14668 *Result = CE;
14669 return true;
14670 }
14671 }
14672
14673 if (CandidateSet->empty())
14674 return false;
14675
14676 UnbridgedCasts.restore();
14677 return false;
14678}
14679
14680// Guess at what the return type for an unresolvable overload should be.
14683 std::optional<QualType> Result;
14684 // Adjust Type after seeing a candidate.
14685 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14686 if (!Candidate.Function)
14687 return;
14688 if (Candidate.Function->isInvalidDecl())
14689 return;
14690 QualType T = Candidate.Function->getReturnType();
14691 if (T.isNull())
14692 return;
14693 if (!Result)
14694 Result = T;
14695 else if (Result != T)
14696 Result = QualType();
14697 };
14698
14699 // Look for an unambiguous type from a progressively larger subset.
14700 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14701 //
14702 // First, consider only the best candidate.
14703 if (Best && *Best != CS.end())
14704 ConsiderCandidate(**Best);
14705 // Next, consider only viable candidates.
14706 if (!Result)
14707 for (const auto &C : CS)
14708 if (C.Viable)
14709 ConsiderCandidate(C);
14710 // Finally, consider all candidates.
14711 if (!Result)
14712 for (const auto &C : CS)
14713 ConsiderCandidate(C);
14714
14715 if (!Result)
14716 return QualType();
14717 auto Value = *Result;
14718 if (Value.isNull() || Value->isUndeducedType())
14719 return QualType();
14720 return Value;
14721}
14722
14723/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14724/// the completed call expression. If overload resolution fails, emits
14725/// diagnostics and returns ExprError()
14728 SourceLocation LParenLoc,
14729 MultiExprArg Args,
14730 SourceLocation RParenLoc,
14731 Expr *ExecConfig,
14732 OverloadCandidateSet *CandidateSet,
14734 OverloadingResult OverloadResult,
14735 bool AllowTypoCorrection) {
14736 switch (OverloadResult) {
14737 case OR_Success: {
14738 FunctionDecl *FDecl = (*Best)->Function;
14739 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14740 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14741 return ExprError();
14742 ExprResult Res =
14743 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14744 if (Res.isInvalid())
14745 return ExprError();
14746 return SemaRef.BuildResolvedCallExpr(
14747 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14748 /*IsExecConfig=*/false,
14749 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14750 }
14751
14752 case OR_No_Viable_Function: {
14753 if (*Best != CandidateSet->end() &&
14754 CandidateSet->getKind() ==
14756 if (CXXMethodDecl *M =
14757 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14759 CandidateSet->NoteCandidates(
14761 Fn->getBeginLoc(),
14762 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14763 SemaRef, OCD_AmbiguousCandidates, Args);
14764 return ExprError();
14765 }
14766 }
14767
14768 // Try to recover by looking for viable functions which the user might
14769 // have meant to call.
14770 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14771 Args, RParenLoc,
14772 CandidateSet->empty(),
14773 AllowTypoCorrection);
14774 if (Recovery.isInvalid() || Recovery.isUsable())
14775 return Recovery;
14776
14777 // If the user passes in a function that we can't take the address of, we
14778 // generally end up emitting really bad error messages. Here, we attempt to
14779 // emit better ones.
14780 for (const Expr *Arg : Args) {
14781 if (!Arg->getType()->isFunctionType())
14782 continue;
14783 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14784 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14785 if (FD &&
14786 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14787 Arg->getExprLoc()))
14788 return ExprError();
14789 }
14790 }
14791
14792 CandidateSet->NoteCandidates(
14794 Fn->getBeginLoc(),
14795 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14796 << ULE->getName() << Fn->getSourceRange()),
14797 SemaRef, OCD_AllCandidates, Args);
14798 break;
14799 }
14800
14801 case OR_Ambiguous:
14802 CandidateSet->NoteCandidates(
14803 PartialDiagnosticAt(Fn->getBeginLoc(),
14804 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14805 << ULE->getName() << Fn->getSourceRange()),
14806 SemaRef, OCD_AmbiguousCandidates, Args);
14807 break;
14808
14809 case OR_Deleted: {
14810 FunctionDecl *FDecl = (*Best)->Function;
14811 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14812 Fn->getSourceRange(), ULE->getName(),
14813 *CandidateSet, FDecl, Args);
14814
14815 // We emitted an error for the unavailable/deleted function call but keep
14816 // the call in the AST.
14817 ExprResult Res =
14818 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14819 if (Res.isInvalid())
14820 return ExprError();
14821 return SemaRef.BuildResolvedCallExpr(
14822 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14823 /*IsExecConfig=*/false,
14824 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14825 }
14826 }
14827
14828 // Overload resolution failed, try to recover.
14829 SmallVector<Expr *, 8> SubExprs = {Fn};
14830 SubExprs.append(Args.begin(), Args.end());
14831 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14832 chooseRecoveryType(*CandidateSet, Best));
14833}
14834
14837 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14838 if (I->Viable &&
14839 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14840 I->Viable = false;
14841 I->FailureKind = ovl_fail_addr_not_available;
14842 }
14843 }
14844}
14845
14848 SourceLocation LParenLoc,
14849 MultiExprArg Args,
14850 SourceLocation RParenLoc,
14851 Expr *ExecConfig,
14852 bool AllowTypoCorrection,
14853 bool CalleesAddressIsTaken) {
14854
14858
14859 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14860 ExprResult result;
14861
14862 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14863 &result))
14864 return result;
14865
14866 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14867 // functions that aren't addressible are considered unviable.
14868 if (CalleesAddressIsTaken)
14869 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14870
14872 OverloadingResult OverloadResult =
14873 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14874
14875 // [C++23][over.call.func]
14876 // if overload resolution selects a non-static member function,
14877 // the call is ill-formed;
14879 Best != CandidateSet.end()) {
14880 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14881 M && M->isImplicitObjectMemberFunction()) {
14882 OverloadResult = OR_No_Viable_Function;
14883 }
14884 }
14885
14886 // Model the case with a call to a templated function whose definition
14887 // encloses the call and whose return type contains a placeholder type as if
14888 // the UnresolvedLookupExpr was type-dependent.
14889 if (OverloadResult == OR_Success) {
14890 const FunctionDecl *FDecl = Best->Function;
14891 if (LangOpts.CUDA)
14892 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14893 if (FDecl && FDecl->isTemplateInstantiation() &&
14894 FDecl->getReturnType()->isUndeducedType()) {
14895
14896 // Creating dependent CallExpr is not okay if the enclosing context itself
14897 // is not dependent. This situation notably arises if a non-dependent
14898 // member function calls the later-defined overloaded static function.
14899 //
14900 // For example, in
14901 // class A {
14902 // void c() { callee(1); }
14903 // static auto callee(auto x) { }
14904 // };
14905 //
14906 // Here callee(1) is unresolved at the call site, but is not inside a
14907 // dependent context. There will be no further attempt to resolve this
14908 // call if it is made dependent.
14909
14910 if (const auto *TP =
14911 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14912 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14913 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14914 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14915 }
14916 }
14917 }
14918
14919 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14920 ExecConfig, &CandidateSet, &Best,
14921 OverloadResult, AllowTypoCorrection);
14922}
14923
14927 const UnresolvedSetImpl &Fns,
14928 bool PerformADL) {
14930 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14931 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14932}
14933
14936 bool HadMultipleCandidates) {
14937 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14938 // the FoundDecl as it impedes TransformMemberExpr.
14939 // We go a bit further here: if there's no difference in UnderlyingDecl,
14940 // then using FoundDecl vs Method shouldn't make a difference either.
14941 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14942 FoundDecl = Method;
14943 // Convert the expression to match the conversion function's implicit object
14944 // parameter.
14945 ExprResult Exp;
14946 if (Method->isExplicitObjectMemberFunction())
14948 else
14950 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14951 if (Exp.isInvalid())
14952 return true;
14953
14954 if (Method->getParent()->isLambda() &&
14955 Method->getConversionType()->isBlockPointerType()) {
14956 // This is a lambda conversion to block pointer; check if the argument
14957 // was a LambdaExpr.
14958 Expr *SubE = E;
14959 auto *CE = dyn_cast<CastExpr>(SubE);
14960 if (CE && CE->getCastKind() == CK_NoOp)
14961 SubE = CE->getSubExpr();
14962 SubE = SubE->IgnoreParens();
14963 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14964 SubE = BE->getSubExpr();
14965 if (isa<LambdaExpr>(SubE)) {
14966 // For the conversion to block pointer on a lambda expression, we
14967 // construct a special BlockLiteral instead; this doesn't really make
14968 // a difference in ARC, but outside of ARC the resulting block literal
14969 // follows the normal lifetime rules for block literals instead of being
14970 // autoreleased.
14974 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14976
14977 // FIXME: This note should be produced by a CodeSynthesisContext.
14978 if (BlockExp.isInvalid())
14979 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14980 return BlockExp;
14981 }
14982 }
14983 CallExpr *CE;
14984 QualType ResultType = Method->getReturnType();
14986 ResultType = ResultType.getNonLValueExprType(Context);
14987 if (Method->isExplicitObjectMemberFunction()) {
14988 ExprResult FnExpr =
14989 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14990 HadMultipleCandidates, E->getBeginLoc());
14991 if (FnExpr.isInvalid())
14992 return ExprError();
14993 Expr *ObjectParam = Exp.get();
14994 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14995 ResultType, VK, Exp.get()->getEndLoc(),
14997 CE->setUsesMemberSyntax(true);
14998 } else {
14999 MemberExpr *ME =
15000 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15002 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15003 HadMultipleCandidates, DeclarationNameInfo(),
15004 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15005
15006 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15007 Exp.get()->getEndLoc(),
15009 }
15010
15011 if (CheckFunctionCall(Method, CE,
15012 Method->getType()->castAs<FunctionProtoType>()))
15013 return ExprError();
15014
15016}
15017
15020 const UnresolvedSetImpl &Fns,
15021 Expr *Input, bool PerformADL) {
15023 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15024 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15025 // TODO: provide better source location info.
15026 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15027
15028 if (checkPlaceholderForOverload(*this, Input))
15029 return ExprError();
15030
15031 Expr *Args[2] = { Input, nullptr };
15032 unsigned NumArgs = 1;
15033
15034 // For post-increment and post-decrement, add the implicit '0' as
15035 // the second argument, so that we know this is a post-increment or
15036 // post-decrement.
15037 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15038 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15039 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15040 SourceLocation());
15041 NumArgs = 2;
15042 }
15043
15044 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15045
15046 if (Input->isTypeDependent()) {
15048 // [C++26][expr.unary.op][expr.pre.incr]
15049 // The * operator yields an lvalue of type
15050 // The pre/post increment operators yied an lvalue.
15051 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15052 VK = VK_LValue;
15053
15054 if (Fns.empty())
15055 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15056 OK_Ordinary, OpLoc, false,
15058
15059 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15061 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15062 if (Fn.isInvalid())
15063 return ExprError();
15064 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15065 Context.DependentTy, VK_PRValue, OpLoc,
15067 }
15068
15069 // Build an empty overload set.
15071
15072 // Add the candidates from the given function set.
15073 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15074
15075 // Add operator candidates that are member functions.
15076 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15077
15078 // Add candidates from ADL.
15079 if (PerformADL) {
15080 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15081 /*ExplicitTemplateArgs*/nullptr,
15082 CandidateSet);
15083 }
15084
15085 // Add builtin operator candidates.
15086 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15087
15088 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15089
15090 // Perform overload resolution.
15092 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15093 case OR_Success: {
15094 // We found a built-in operator or an overloaded operator.
15095 FunctionDecl *FnDecl = Best->Function;
15096
15097 if (FnDecl) {
15098 Expr *Base = nullptr;
15099 // We matched an overloaded operator. Build a call to that
15100 // operator.
15101
15102 // Convert the arguments.
15103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15104 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15105
15106 ExprResult InputInit;
15107 if (Method->isExplicitObjectMemberFunction())
15108 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15109 else
15111 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15112 if (InputInit.isInvalid())
15113 return ExprError();
15114 Base = Input = InputInit.get();
15115 } else {
15116 // Convert the arguments.
15117 ExprResult InputInit
15119 Context,
15120 FnDecl->getParamDecl(0)),
15122 Input);
15123 if (InputInit.isInvalid())
15124 return ExprError();
15125 Input = InputInit.get();
15126 }
15127
15128 // Build the actual expression node.
15129 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15130 Base, HadMultipleCandidates,
15131 OpLoc);
15132 if (FnExpr.isInvalid())
15133 return ExprError();
15134
15135 // Determine the result type.
15136 QualType ResultTy = FnDecl->getReturnType();
15138 ResultTy = ResultTy.getNonLValueExprType(Context);
15139
15140 Args[0] = Input;
15142 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15144 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15145
15146 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15147 return ExprError();
15148
15149 if (CheckFunctionCall(FnDecl, TheCall,
15150 FnDecl->getType()->castAs<FunctionProtoType>()))
15151 return ExprError();
15152 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15153 } else {
15154 // We matched a built-in operator. Convert the arguments, then
15155 // break out so that we will build the appropriate built-in
15156 // operator node.
15158 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15161 if (InputRes.isInvalid())
15162 return ExprError();
15163 Input = InputRes.get();
15164 break;
15165 }
15166 }
15167
15169 // This is an erroneous use of an operator which can be overloaded by
15170 // a non-member function. Check for non-member operators which were
15171 // defined too late to be candidates.
15172 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15173 // FIXME: Recover by calling the found function.
15174 return ExprError();
15175
15176 // No viable function; fall through to handling this as a
15177 // built-in operator, which will produce an error message for us.
15178 break;
15179
15180 case OR_Ambiguous:
15181 CandidateSet.NoteCandidates(
15182 PartialDiagnosticAt(OpLoc,
15183 PDiag(diag::err_ovl_ambiguous_oper_unary)
15185 << Input->getType() << Input->getSourceRange()),
15186 *this, OCD_AmbiguousCandidates, ArgsArray,
15187 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15188 return ExprError();
15189
15190 case OR_Deleted: {
15191 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15192 // object whose method was called. Later in NoteCandidates size of ArgsArray
15193 // is passed further and it eventually ends up compared to number of
15194 // function candidate parameters which never includes the object parameter,
15195 // so slice ArgsArray to make sure apples are compared to apples.
15196 StringLiteral *Msg = Best->Function->getDeletedMessage();
15197 CandidateSet.NoteCandidates(
15198 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15200 << (Msg != nullptr)
15201 << (Msg ? Msg->getString() : StringRef())
15202 << Input->getSourceRange()),
15203 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15204 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15205 return ExprError();
15206 }
15207 }
15208
15209 // Either we found no viable overloaded operator or we matched a
15210 // built-in operator. In either case, fall through to trying to
15211 // build a built-in operation.
15212 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15213}
15214
15217 const UnresolvedSetImpl &Fns,
15218 ArrayRef<Expr *> Args, bool PerformADL) {
15219 SourceLocation OpLoc = CandidateSet.getLocation();
15220
15221 OverloadedOperatorKind ExtraOp =
15224 : OO_None;
15225
15226 // Add the candidates from the given function set. This also adds the
15227 // rewritten candidates using these functions if necessary.
15228 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15229
15230 // As template candidates are not deduced immediately,
15231 // persist the array in the overload set.
15232 ArrayRef<Expr *> ReversedArgs;
15233 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15234 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15235 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15236
15237 // Add operator candidates that are member functions.
15238 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15239 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15240 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15242
15243 // In C++20, also add any rewritten member candidates.
15244 if (ExtraOp) {
15245 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15246 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15247 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15249 }
15250
15251 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15252 // performed for an assignment operator (nor for operator[] nor operator->,
15253 // which don't get here).
15254 if (Op != OO_Equal && PerformADL) {
15255 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15256 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15257 /*ExplicitTemplateArgs*/ nullptr,
15258 CandidateSet);
15259 if (ExtraOp) {
15260 DeclarationName ExtraOpName =
15261 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15262 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15263 /*ExplicitTemplateArgs*/ nullptr,
15264 CandidateSet);
15265 }
15266 }
15267
15268 // Add builtin operator candidates.
15269 //
15270 // FIXME: We don't add any rewritten candidates here. This is strictly
15271 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15272 // resulting in our selecting a rewritten builtin candidate. For example:
15273 //
15274 // enum class E { e };
15275 // bool operator!=(E, E) requires false;
15276 // bool k = E::e != E::e;
15277 //
15278 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15279 // it seems unreasonable to consider rewritten builtin candidates. A core
15280 // issue has been filed proposing to removed this requirement.
15281 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15282}
15283
15286 const UnresolvedSetImpl &Fns, Expr *LHS,
15287 Expr *RHS, bool PerformADL,
15288 bool AllowRewrittenCandidates,
15289 FunctionDecl *DefaultedFn) {
15290 Expr *Args[2] = { LHS, RHS };
15291 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15292
15293 if (!getLangOpts().CPlusPlus20)
15294 AllowRewrittenCandidates = false;
15295
15297
15298 // If either side is type-dependent, create an appropriate dependent
15299 // expression.
15300 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15301 if (Fns.empty()) {
15302 // If there are no functions to store, just build a dependent
15303 // BinaryOperator or CompoundAssignment.
15306 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15307 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15308 Context.DependentTy);
15310 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15312 }
15313
15314 // FIXME: save results of ADL from here?
15315 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15316 // TODO: provide better source location info in DNLoc component.
15317 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15318 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15320 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15321 if (Fn.isInvalid())
15322 return ExprError();
15323 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15324 Context.DependentTy, VK_PRValue, OpLoc,
15326 }
15327
15328 // If this is the .* operator, which is not overloadable, just
15329 // create a built-in binary operator.
15330 if (Opc == BO_PtrMemD) {
15331 auto CheckPlaceholder = [&](Expr *&Arg) {
15333 if (Res.isUsable())
15334 Arg = Res.get();
15335 return !Res.isUsable();
15336 };
15337
15338 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15339 // expression that contains placeholders (in either the LHS or RHS).
15340 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15341 return ExprError();
15342 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15343 }
15344
15345 // Always do placeholder-like conversions on the RHS.
15346 if (checkPlaceholderForOverload(*this, Args[1]))
15347 return ExprError();
15348
15349 // Do placeholder-like conversion on the LHS; note that we should
15350 // not get here with a PseudoObject LHS.
15351 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15352 if (checkPlaceholderForOverload(*this, Args[0]))
15353 return ExprError();
15354
15355 // If this is the assignment operator, we only perform overload resolution
15356 // if the left-hand side is a class or enumeration type. This is actually
15357 // a hack. The standard requires that we do overload resolution between the
15358 // various built-in candidates, but as DR507 points out, this can lead to
15359 // problems. So we do it this way, which pretty much follows what GCC does.
15360 // Note that we go the traditional code path for compound assignment forms.
15361 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15362 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15363
15364 // Build the overload set.
15367 Op, OpLoc, AllowRewrittenCandidates));
15368 if (DefaultedFn)
15369 CandidateSet.exclude(DefaultedFn);
15370 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15371
15372 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15373
15374 // Perform overload resolution.
15376 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15377 case OR_Success: {
15378 // We found a built-in operator or an overloaded operator.
15379 FunctionDecl *FnDecl = Best->Function;
15380
15381 bool IsReversed = Best->isReversed();
15382 if (IsReversed)
15383 std::swap(Args[0], Args[1]);
15384
15385 if (FnDecl) {
15386
15387 if (FnDecl->isInvalidDecl())
15388 return ExprError();
15389
15390 Expr *Base = nullptr;
15391 // We matched an overloaded operator. Build a call to that
15392 // operator.
15393
15394 OverloadedOperatorKind ChosenOp =
15396
15397 // C++2a [over.match.oper]p9:
15398 // If a rewritten operator== candidate is selected by overload
15399 // resolution for an operator@, its return type shall be cv bool
15400 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15401 !FnDecl->getReturnType()->isBooleanType()) {
15402 bool IsExtension =
15404 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15405 : diag::err_ovl_rewrite_equalequal_not_bool)
15406 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15407 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15408 Diag(FnDecl->getLocation(), diag::note_declared_at);
15409 if (!IsExtension)
15410 return ExprError();
15411 }
15412
15413 if (AllowRewrittenCandidates && !IsReversed &&
15414 CandidateSet.getRewriteInfo().isReversible()) {
15415 // We could have reversed this operator, but didn't. Check if some
15416 // reversed form was a viable candidate, and if so, if it had a
15417 // better conversion for either parameter. If so, this call is
15418 // formally ambiguous, and allowing it is an extension.
15420 for (OverloadCandidate &Cand : CandidateSet) {
15421 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15422 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15423 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15425 *this, OpLoc, Cand.Conversions[ArgIdx],
15426 Best->Conversions[ArgIdx]) ==
15428 AmbiguousWith.push_back(Cand.Function);
15429 break;
15430 }
15431 }
15432 }
15433 }
15434
15435 if (!AmbiguousWith.empty()) {
15436 bool AmbiguousWithSelf =
15437 AmbiguousWith.size() == 1 &&
15438 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15439 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15441 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15442 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15443 if (AmbiguousWithSelf) {
15444 Diag(FnDecl->getLocation(),
15445 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15446 // Mark member== const or provide matching != to disallow reversed
15447 // args. Eg.
15448 // struct S { bool operator==(const S&); };
15449 // S()==S();
15450 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15451 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15452 !MD->isConst() &&
15453 !MD->hasCXXExplicitFunctionObjectParameter() &&
15454 Context.hasSameUnqualifiedType(
15455 MD->getFunctionObjectParameterType(),
15456 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15457 Context.hasSameUnqualifiedType(
15458 MD->getFunctionObjectParameterType(),
15459 Args[0]->getType()) &&
15460 Context.hasSameUnqualifiedType(
15461 MD->getFunctionObjectParameterType(),
15462 Args[1]->getType()))
15463 Diag(FnDecl->getLocation(),
15464 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15465 } else {
15466 Diag(FnDecl->getLocation(),
15467 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15468 for (auto *F : AmbiguousWith)
15469 Diag(F->getLocation(),
15470 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15471 }
15472 }
15473 }
15474
15475 // Check for nonnull = nullable.
15476 // This won't be caught in the arg's initialization: the parameter to
15477 // the assignment operator is not marked nonnull.
15478 if (Op == OO_Equal)
15480 Args[1]->getType(), OpLoc);
15481
15482 // Convert the arguments.
15483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15484 // Best->Access is only meaningful for class members.
15485 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15486
15487 ExprResult Arg0, Arg1;
15488 unsigned ParamIdx = 0;
15489 if (Method->isExplicitObjectMemberFunction()) {
15490 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15491 ParamIdx = 1;
15492 } else {
15494 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15495 }
15498 Context, FnDecl->getParamDecl(ParamIdx)),
15499 SourceLocation(), Args[1]);
15500 if (Arg0.isInvalid() || Arg1.isInvalid())
15501 return ExprError();
15502
15503 Base = Args[0] = Arg0.getAs<Expr>();
15504 Args[1] = RHS = Arg1.getAs<Expr>();
15505 } else {
15506 // Convert the arguments.
15509 FnDecl->getParamDecl(0)),
15510 SourceLocation(), Args[0]);
15511 if (Arg0.isInvalid())
15512 return ExprError();
15513
15514 ExprResult Arg1 =
15517 FnDecl->getParamDecl(1)),
15518 SourceLocation(), Args[1]);
15519 if (Arg1.isInvalid())
15520 return ExprError();
15521 Args[0] = LHS = Arg0.getAs<Expr>();
15522 Args[1] = RHS = Arg1.getAs<Expr>();
15523 }
15524
15525 // Build the actual expression node.
15526 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15527 Best->FoundDecl, Base,
15528 HadMultipleCandidates, OpLoc);
15529 if (FnExpr.isInvalid())
15530 return ExprError();
15531
15532 // Determine the result type.
15533 QualType ResultTy = FnDecl->getReturnType();
15535 ResultTy = ResultTy.getNonLValueExprType(Context);
15536
15537 CallExpr *TheCall;
15538 ArrayRef<const Expr *> ArgsArray(Args, 2);
15539 const Expr *ImplicitThis = nullptr;
15540
15541 // We always create a CXXOperatorCallExpr, even for explicit object
15542 // members; CodeGen should take care not to emit the this pointer.
15544 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15546 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15547
15548 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15549 Method && Method->isImplicitObjectMemberFunction()) {
15550 // Cut off the implicit 'this'.
15551 ImplicitThis = ArgsArray[0];
15552 ArgsArray = ArgsArray.slice(1);
15553 }
15554
15555 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15556 FnDecl))
15557 return ExprError();
15558
15559 if (Op == OO_Equal) {
15560 // Check for a self move.
15561 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15562 // lifetime check.
15564 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15565 Args[1]);
15566 }
15567 if (ImplicitThis) {
15568 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15569 QualType ThisTypeFromDecl = Context.getPointerType(
15570 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15571
15572 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15573 ThisTypeFromDecl);
15574 }
15575
15576 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15577 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15579
15580 ExprResult R = MaybeBindToTemporary(TheCall);
15581 if (R.isInvalid())
15582 return ExprError();
15583
15584 R = CheckForImmediateInvocation(R, FnDecl);
15585 if (R.isInvalid())
15586 return ExprError();
15587
15588 // For a rewritten candidate, we've already reversed the arguments
15589 // if needed. Perform the rest of the rewrite now.
15590 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15591 (Op == OO_Spaceship && IsReversed)) {
15592 if (Op == OO_ExclaimEqual) {
15593 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15594 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15595 } else {
15596 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15597 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15598 Expr *ZeroLiteral =
15600
15603 Ctx.Entity = FnDecl;
15605
15607 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15608 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15609 /*AllowRewrittenCandidates=*/false);
15610
15612 }
15613 if (R.isInvalid())
15614 return ExprError();
15615 } else {
15616 assert(ChosenOp == Op && "unexpected operator name");
15617 }
15618
15619 // Make a note in the AST if we did any rewriting.
15620 if (Best->RewriteKind != CRK_None)
15621 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15622
15623 return R;
15624 } else {
15625 // We matched a built-in operator. Convert the arguments, then
15626 // break out so that we will build the appropriate built-in
15627 // operator node.
15629 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15632 if (ArgsRes0.isInvalid())
15633 return ExprError();
15634 Args[0] = ArgsRes0.get();
15635
15637 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15640 if (ArgsRes1.isInvalid())
15641 return ExprError();
15642 Args[1] = ArgsRes1.get();
15643 break;
15644 }
15645 }
15646
15647 case OR_No_Viable_Function: {
15648 // C++ [over.match.oper]p9:
15649 // If the operator is the operator , [...] and there are no
15650 // viable functions, then the operator is assumed to be the
15651 // built-in operator and interpreted according to clause 5.
15652 if (Opc == BO_Comma)
15653 break;
15654
15655 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15656 // compare result using '==' and '<'.
15657 if (DefaultedFn && Opc == BO_Cmp) {
15658 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15659 Args[1], DefaultedFn);
15660 if (E.isInvalid() || E.isUsable())
15661 return E;
15662 }
15663
15664 // For class as left operand for assignment or compound assignment
15665 // operator do not fall through to handling in built-in, but report that
15666 // no overloaded assignment operator found
15668 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15669 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15670 Args, OpLoc);
15671 DeferDiagsRAII DDR(*this,
15672 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15673 if (Args[0]->getType()->isRecordType() &&
15674 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15675 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15677 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15678 if (Args[0]->getType()->isIncompleteType()) {
15679 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15680 << Args[0]->getType()
15681 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15682 }
15683 } else {
15684 // This is an erroneous use of an operator which can be overloaded by
15685 // a non-member function. Check for non-member operators which were
15686 // defined too late to be candidates.
15687 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15688 // FIXME: Recover by calling the found function.
15689 return ExprError();
15690
15691 // No viable function; try to create a built-in operation, which will
15692 // produce an error. Then, show the non-viable candidates.
15693 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15694 }
15695 assert(Result.isInvalid() &&
15696 "C++ binary operator overloading is missing candidates!");
15697 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15698 return Result;
15699 }
15700
15701 case OR_Ambiguous:
15702 CandidateSet.NoteCandidates(
15703 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15705 << Args[0]->getType()
15706 << Args[1]->getType()
15707 << Args[0]->getSourceRange()
15708 << Args[1]->getSourceRange()),
15710 OpLoc);
15711 return ExprError();
15712
15713 case OR_Deleted: {
15714 if (isImplicitlyDeleted(Best->Function)) {
15715 FunctionDecl *DeletedFD = Best->Function;
15717 if (DFK.isSpecialMember()) {
15718 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15719 << Args[0]->getType() << DFK.asSpecialMember();
15720 } else {
15721 assert(DFK.isComparison());
15722 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15723 << Args[0]->getType() << DeletedFD;
15724 }
15725
15726 // The user probably meant to call this special member. Just
15727 // explain why it's deleted.
15728 NoteDeletedFunction(DeletedFD);
15729 return ExprError();
15730 }
15731
15732 StringLiteral *Msg = Best->Function->getDeletedMessage();
15733 CandidateSet.NoteCandidates(
15735 OpLoc,
15736 PDiag(diag::err_ovl_deleted_oper)
15737 << getOperatorSpelling(Best->Function->getDeclName()
15738 .getCXXOverloadedOperator())
15739 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15740 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15742 OpLoc);
15743 return ExprError();
15744 }
15745 }
15746
15747 // We matched a built-in operator; build it.
15748 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15749}
15750
15752 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15753 FunctionDecl *DefaultedFn) {
15754 const ComparisonCategoryInfo *Info =
15755 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15756 // If we're not producing a known comparison category type, we can't
15757 // synthesize a three-way comparison. Let the caller diagnose this.
15758 if (!Info)
15759 return ExprResult((Expr*)nullptr);
15760
15761 // If we ever want to perform this synthesis more generally, we will need to
15762 // apply the temporary materialization conversion to the operands.
15763 assert(LHS->isGLValue() && RHS->isGLValue() &&
15764 "cannot use prvalue expressions more than once");
15765 Expr *OrigLHS = LHS;
15766 Expr *OrigRHS = RHS;
15767
15768 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15769 // each of them multiple times below.
15770 LHS = new (Context)
15771 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15772 LHS->getObjectKind(), LHS);
15773 RHS = new (Context)
15774 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15775 RHS->getObjectKind(), RHS);
15776
15777 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15778 DefaultedFn);
15779 if (Eq.isInvalid())
15780 return ExprError();
15781
15782 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15783 true, DefaultedFn);
15784 if (Less.isInvalid())
15785 return ExprError();
15786
15788 if (Info->isPartial()) {
15789 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15790 DefaultedFn);
15791 if (Greater.isInvalid())
15792 return ExprError();
15793 }
15794
15795 // Form the list of comparisons we're going to perform.
15796 struct Comparison {
15797 ExprResult Cmp;
15799 } Comparisons[4] =
15805 };
15806
15807 int I = Info->isPartial() ? 3 : 2;
15808
15809 // Combine the comparisons with suitable conditional expressions.
15811 for (; I >= 0; --I) {
15812 // Build a reference to the comparison category constant.
15813 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15814 // FIXME: Missing a constant for a comparison category. Diagnose this?
15815 if (!VI)
15816 return ExprResult((Expr*)nullptr);
15817 ExprResult ThisResult =
15819 if (ThisResult.isInvalid())
15820 return ExprError();
15821
15822 // Build a conditional unless this is the final case.
15823 if (Result.get()) {
15824 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15825 ThisResult.get(), Result.get());
15826 if (Result.isInvalid())
15827 return ExprError();
15828 } else {
15829 Result = ThisResult;
15830 }
15831 }
15832
15833 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15834 // bind the OpaqueValueExprs before they're (repeatedly) used.
15835 Expr *SyntacticForm = BinaryOperator::Create(
15836 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15837 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15839 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15840 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15841}
15842
15844 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15845 MultiExprArg Args, SourceLocation LParenLoc) {
15846
15847 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15848 unsigned NumParams = Proto->getNumParams();
15849 unsigned NumArgsSlots =
15850 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15851 // Build the full argument list for the method call (the implicit object
15852 // parameter is placed at the beginning of the list).
15853 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15854 bool IsError = false;
15855 // Initialize the implicit object parameter.
15856 // Check the argument types.
15857 for (unsigned i = 0; i != NumParams; i++) {
15858 Expr *Arg;
15859 if (i < Args.size()) {
15860 Arg = Args[i];
15861 ExprResult InputInit =
15863 S.Context, Method->getParamDecl(i)),
15864 SourceLocation(), Arg);
15865 IsError |= InputInit.isInvalid();
15866 Arg = InputInit.getAs<Expr>();
15867 } else {
15868 ExprResult DefArg =
15869 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15870 if (DefArg.isInvalid()) {
15871 IsError = true;
15872 break;
15873 }
15874 Arg = DefArg.getAs<Expr>();
15875 }
15876
15877 MethodArgs.push_back(Arg);
15878 }
15879 return IsError;
15880}
15881
15883 SourceLocation RLoc,
15884 Expr *Base,
15885 MultiExprArg ArgExpr) {
15887 Args.push_back(Base);
15888 for (auto *e : ArgExpr) {
15889 Args.push_back(e);
15890 }
15891 DeclarationName OpName =
15892 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15893
15894 SourceRange Range = ArgExpr.empty()
15895 ? SourceRange{}
15896 : SourceRange(ArgExpr.front()->getBeginLoc(),
15897 ArgExpr.back()->getEndLoc());
15898
15899 // If either side is type-dependent, create an appropriate dependent
15900 // expression.
15902
15903 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15904 // CHECKME: no 'operator' keyword?
15905 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15906 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15908 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15909 if (Fn.isInvalid())
15910 return ExprError();
15911 // Can't add any actual overloads yet
15912
15913 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15914 Context.DependentTy, VK_PRValue, RLoc,
15916 }
15917
15918 // Handle placeholders
15919 UnbridgedCastsSet UnbridgedCasts;
15920 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15921 return ExprError();
15922 }
15923 // Build an empty overload set.
15925
15926 // Subscript can only be overloaded as a member function.
15927
15928 // Add operator candidates that are member functions.
15929 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15930
15931 // Add builtin operator candidates.
15932 if (Args.size() == 2)
15933 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15934
15935 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15936
15937 // Perform overload resolution.
15939 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15940 case OR_Success: {
15941 // We found a built-in operator or an overloaded operator.
15942 FunctionDecl *FnDecl = Best->Function;
15943
15944 if (FnDecl) {
15945 // We matched an overloaded operator. Build a call to that
15946 // operator.
15947
15948 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15949
15950 // Convert the arguments.
15952 SmallVector<Expr *, 2> MethodArgs;
15953
15954 // Initialize the object parameter.
15955 if (Method->isExplicitObjectMemberFunction()) {
15956 ExprResult Res =
15958 if (Res.isInvalid())
15959 return ExprError();
15960 Args[0] = Res.get();
15961 ArgExpr = Args;
15962 } else {
15964 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15965 if (Arg0.isInvalid())
15966 return ExprError();
15967
15968 MethodArgs.push_back(Arg0.get());
15969 }
15970
15972 *this, MethodArgs, Method, ArgExpr, LLoc);
15973 if (IsError)
15974 return ExprError();
15975
15976 // Build the actual expression node.
15977 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15978 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15980 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15981 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15982 if (FnExpr.isInvalid())
15983 return ExprError();
15984
15985 // Determine the result type
15986 QualType ResultTy = FnDecl->getReturnType();
15988 ResultTy = ResultTy.getNonLValueExprType(Context);
15989
15991 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15993
15994 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15995 return ExprError();
15996
15997 if (CheckFunctionCall(Method, TheCall,
15998 Method->getType()->castAs<FunctionProtoType>()))
15999 return ExprError();
16000
16002 FnDecl);
16003 } else {
16004 // We matched a built-in operator. Convert the arguments, then
16005 // break out so that we will build the appropriate built-in
16006 // operator node.
16008 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16011 if (ArgsRes0.isInvalid())
16012 return ExprError();
16013 Args[0] = ArgsRes0.get();
16014
16016 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16019 if (ArgsRes1.isInvalid())
16020 return ExprError();
16021 Args[1] = ArgsRes1.get();
16022
16023 break;
16024 }
16025 }
16026
16027 case OR_No_Viable_Function: {
16029 CandidateSet.empty()
16030 ? (PDiag(diag::err_ovl_no_oper)
16031 << Args[0]->getType() << /*subscript*/ 0
16032 << Args[0]->getSourceRange() << Range)
16033 : (PDiag(diag::err_ovl_no_viable_subscript)
16034 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16035 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16036 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16037 return ExprError();
16038 }
16039
16040 case OR_Ambiguous:
16041 if (Args.size() == 2) {
16042 CandidateSet.NoteCandidates(
16044 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16045 << "[]" << Args[0]->getType() << Args[1]->getType()
16046 << Args[0]->getSourceRange() << Range),
16047 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16048 } else {
16049 CandidateSet.NoteCandidates(
16051 PDiag(diag::err_ovl_ambiguous_subscript_call)
16052 << Args[0]->getType()
16053 << Args[0]->getSourceRange() << Range),
16054 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16055 }
16056 return ExprError();
16057
16058 case OR_Deleted: {
16059 StringLiteral *Msg = Best->Function->getDeletedMessage();
16060 CandidateSet.NoteCandidates(
16062 PDiag(diag::err_ovl_deleted_oper)
16063 << "[]" << (Msg != nullptr)
16064 << (Msg ? Msg->getString() : StringRef())
16065 << Args[0]->getSourceRange() << Range),
16066 *this, OCD_AllCandidates, Args, "[]", LLoc);
16067 return ExprError();
16068 }
16069 }
16070
16071 // We matched a built-in operator; build it.
16072 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16073}
16074
16076 SourceLocation LParenLoc,
16077 MultiExprArg Args,
16078 SourceLocation RParenLoc,
16079 Expr *ExecConfig, bool IsExecConfig,
16080 bool AllowRecovery) {
16081 assert(MemExprE->getType() == Context.BoundMemberTy ||
16082 MemExprE->getType() == Context.OverloadTy);
16083
16084 // Dig out the member expression. This holds both the object
16085 // argument and the member function we're referring to.
16086 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16087
16088 // Determine whether this is a call to a pointer-to-member function.
16089 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16090 assert(op->getType() == Context.BoundMemberTy);
16091 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16092
16093 QualType fnType =
16094 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16095
16096 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16097 QualType resultType = proto->getCallResultType(Context);
16099
16100 // Check that the object type isn't more qualified than the
16101 // member function we're calling.
16102 Qualifiers funcQuals = proto->getMethodQuals();
16103
16104 QualType objectType = op->getLHS()->getType();
16105 if (op->getOpcode() == BO_PtrMemI)
16106 objectType = objectType->castAs<PointerType>()->getPointeeType();
16107 Qualifiers objectQuals = objectType.getQualifiers();
16108
16109 Qualifiers difference = objectQuals - funcQuals;
16110 difference.removeObjCGCAttr();
16111 difference.removeAddressSpace();
16112 if (difference) {
16113 std::string qualsString = difference.getAsString();
16114 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16115 << fnType.getUnqualifiedType()
16116 << qualsString
16117 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16118 }
16119
16121 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16123
16124 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16125 call, nullptr))
16126 return ExprError();
16127
16128 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16129 return ExprError();
16130
16131 if (CheckOtherCall(call, proto))
16132 return ExprError();
16133
16134 return MaybeBindToTemporary(call);
16135 }
16136
16137 // We only try to build a recovery expr at this level if we can preserve
16138 // the return type, otherwise we return ExprError() and let the caller
16139 // recover.
16140 auto BuildRecoveryExpr = [&](QualType Type) {
16141 if (!AllowRecovery)
16142 return ExprError();
16143 std::vector<Expr *> SubExprs = {MemExprE};
16144 llvm::append_range(SubExprs, Args);
16145 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16146 Type);
16147 };
16148 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16149 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16150 RParenLoc, CurFPFeatureOverrides());
16151
16152 UnbridgedCastsSet UnbridgedCasts;
16153 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16154 return ExprError();
16155
16156 MemberExpr *MemExpr;
16157 CXXMethodDecl *Method = nullptr;
16158 bool HadMultipleCandidates = false;
16159 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16160 NestedNameSpecifier Qualifier = std::nullopt;
16161 if (isa<MemberExpr>(NakedMemExpr)) {
16162 MemExpr = cast<MemberExpr>(NakedMemExpr);
16164 FoundDecl = MemExpr->getFoundDecl();
16165 Qualifier = MemExpr->getQualifier();
16166 UnbridgedCasts.restore();
16167 } else {
16168 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16169 Qualifier = UnresExpr->getQualifier();
16170
16171 QualType ObjectType = UnresExpr->getBaseType();
16172 Expr::Classification ObjectClassification
16174 : UnresExpr->getBase()->Classify(Context);
16175
16176 // Add overload candidates
16177 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16179
16180 // FIXME: avoid copy.
16181 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16182 if (UnresExpr->hasExplicitTemplateArgs()) {
16183 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16184 TemplateArgs = &TemplateArgsBuffer;
16185 }
16186
16188 E = UnresExpr->decls_end(); I != E; ++I) {
16189
16190 QualType ExplicitObjectType = ObjectType;
16191
16192 NamedDecl *Func = *I;
16193 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16195 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16196
16197 bool HasExplicitParameter = false;
16198 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16199 M && M->hasCXXExplicitFunctionObjectParameter())
16200 HasExplicitParameter = true;
16201 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16202 M &&
16203 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16204 HasExplicitParameter = true;
16205
16206 if (HasExplicitParameter)
16207 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16208
16209 // Microsoft supports direct constructor calls.
16210 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16212 CandidateSet,
16213 /*SuppressUserConversions*/ false);
16214 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16215 // If explicit template arguments were provided, we can't call a
16216 // non-template member function.
16217 if (TemplateArgs)
16218 continue;
16219
16220 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16221 ObjectClassification, Args, CandidateSet,
16222 /*SuppressUserConversions=*/false);
16223 } else {
16225 I.getPair(), ActingDC, TemplateArgs,
16226 ExplicitObjectType, ObjectClassification,
16227 Args, CandidateSet,
16228 /*SuppressUserConversions=*/false);
16229 }
16230 }
16231
16232 HadMultipleCandidates = (CandidateSet.size() > 1);
16233
16234 DeclarationName DeclName = UnresExpr->getMemberName();
16235
16236 UnbridgedCasts.restore();
16237
16239 bool Succeeded = false;
16240 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16241 Best)) {
16242 case OR_Success:
16243 Method = cast<CXXMethodDecl>(Best->Function);
16244 FoundDecl = Best->FoundDecl;
16245 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16246 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16247 break;
16248 // If FoundDecl is different from Method (such as if one is a template
16249 // and the other a specialization), make sure DiagnoseUseOfDecl is
16250 // called on both.
16251 // FIXME: This would be more comprehensively addressed by modifying
16252 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16253 // being used.
16254 if (Method != FoundDecl.getDecl() &&
16256 break;
16257 Succeeded = true;
16258 break;
16259
16261 CandidateSet.NoteCandidates(
16263 UnresExpr->getMemberLoc(),
16264 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16265 << DeclName << MemExprE->getSourceRange()),
16266 *this, OCD_AllCandidates, Args);
16267 break;
16268 case OR_Ambiguous:
16269 CandidateSet.NoteCandidates(
16270 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16271 PDiag(diag::err_ovl_ambiguous_member_call)
16272 << DeclName << MemExprE->getSourceRange()),
16273 *this, OCD_AmbiguousCandidates, Args);
16274 break;
16275 case OR_Deleted:
16277 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16278 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16279 break;
16280 }
16281 // Overload resolution fails, try to recover.
16282 if (!Succeeded)
16283 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16284
16285 ExprResult Res =
16286 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16287 if (Res.isInvalid())
16288 return ExprError();
16289 MemExprE = Res.get();
16290
16291 // If overload resolution picked a static member
16292 // build a non-member call based on that function.
16293 if (Method->isStatic()) {
16294 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16295 ExecConfig, IsExecConfig);
16296 }
16297
16298 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16299 }
16300
16301 QualType ResultType = Method->getReturnType();
16303 ResultType = ResultType.getNonLValueExprType(Context);
16304
16305 assert(Method && "Member call to something that isn't a method?");
16306 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16307
16308 CallExpr *TheCall = nullptr;
16310 if (Method->isExplicitObjectMemberFunction()) {
16311 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16312 NewArgs))
16313 return ExprError();
16314
16315 // Build the actual expression node.
16316 ExprResult FnExpr =
16317 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16318 HadMultipleCandidates, MemExpr->getExprLoc());
16319 if (FnExpr.isInvalid())
16320 return ExprError();
16321
16322 TheCall =
16323 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16324 CurFPFeatureOverrides(), Proto->getNumParams());
16325 TheCall->setUsesMemberSyntax(true);
16326 } else {
16327 // Convert the object argument (for a non-static member function call).
16329 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16330 if (ObjectArg.isInvalid())
16331 return ExprError();
16332 MemExpr->setBase(ObjectArg.get());
16333 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16334 RParenLoc, CurFPFeatureOverrides(),
16335 Proto->getNumParams());
16336 }
16337
16338 // Check for a valid return type.
16339 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16340 TheCall, Method))
16341 return BuildRecoveryExpr(ResultType);
16342
16343 // Convert the rest of the arguments
16344 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16345 RParenLoc))
16346 return BuildRecoveryExpr(ResultType);
16347
16348 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16349
16350 if (CheckFunctionCall(Method, TheCall, Proto))
16351 return ExprError();
16352
16353 // In the case the method to call was not selected by the overloading
16354 // resolution process, we still need to handle the enable_if attribute. Do
16355 // that here, so it will not hide previous -- and more relevant -- errors.
16356 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16357 if (const EnableIfAttr *Attr =
16358 CheckEnableIf(Method, LParenLoc, Args, true)) {
16359 Diag(MemE->getMemberLoc(),
16360 diag::err_ovl_no_viable_member_function_in_call)
16361 << Method << Method->getSourceRange();
16362 Diag(Method->getLocation(),
16363 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16364 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16365 return ExprError();
16366 }
16367 }
16368
16370 TheCall->getDirectCallee()->isPureVirtual()) {
16371 const FunctionDecl *MD = TheCall->getDirectCallee();
16372
16373 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16375 Diag(MemExpr->getBeginLoc(),
16376 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16378 << MD->getParent();
16379
16380 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16381 if (getLangOpts().AppleKext)
16382 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16383 << MD->getParent() << MD->getDeclName();
16384 }
16385 }
16386
16387 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16388 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16389 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16390 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16391 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16392 MemExpr->getMemberLoc());
16393 }
16394
16396 TheCall->getDirectCallee());
16397}
16398
16401 SourceLocation LParenLoc,
16402 MultiExprArg Args,
16403 SourceLocation RParenLoc) {
16404 if (checkPlaceholderForOverload(*this, Obj))
16405 return ExprError();
16406 ExprResult Object = Obj;
16407
16408 UnbridgedCastsSet UnbridgedCasts;
16409 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16410 return ExprError();
16411
16412 assert(Object.get()->getType()->isRecordType() &&
16413 "Requires object type argument");
16414
16415 // C++ [over.call.object]p1:
16416 // If the primary-expression E in the function call syntax
16417 // evaluates to a class object of type "cv T", then the set of
16418 // candidate functions includes at least the function call
16419 // operators of T. The function call operators of T are obtained by
16420 // ordinary lookup of the name operator() in the context of
16421 // (E).operator().
16422 OverloadCandidateSet CandidateSet(LParenLoc,
16424 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16425
16426 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16427 diag::err_incomplete_object_call, Object.get()))
16428 return true;
16429
16430 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16431 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16434
16435 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16436 Oper != OperEnd; ++Oper) {
16437 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16438 Object.get()->Classify(Context), Args, CandidateSet,
16439 /*SuppressUserConversion=*/false);
16440 }
16441
16442 // When calling a lambda, both the call operator, and
16443 // the conversion operator to function pointer
16444 // are considered. But when constraint checking
16445 // on the call operator fails, it will also fail on the
16446 // conversion operator as the constraints are always the same.
16447 // As the user probably does not intend to perform a surrogate call,
16448 // we filter them out to produce better error diagnostics, ie to avoid
16449 // showing 2 failed overloads instead of one.
16450 bool IgnoreSurrogateFunctions = false;
16451 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16452 const OverloadCandidate &Candidate = *CandidateSet.begin();
16453 if (!Candidate.Viable &&
16455 IgnoreSurrogateFunctions = true;
16456 }
16457
16458 // C++ [over.call.object]p2:
16459 // In addition, for each (non-explicit in C++0x) conversion function
16460 // declared in T of the form
16461 //
16462 // operator conversion-type-id () cv-qualifier;
16463 //
16464 // where cv-qualifier is the same cv-qualification as, or a
16465 // greater cv-qualification than, cv, and where conversion-type-id
16466 // denotes the type "pointer to function of (P1,...,Pn) returning
16467 // R", or the type "reference to pointer to function of
16468 // (P1,...,Pn) returning R", or the type "reference to function
16469 // of (P1,...,Pn) returning R", a surrogate call function [...]
16470 // is also considered as a candidate function. Similarly,
16471 // surrogate call functions are added to the set of candidate
16472 // functions for each conversion function declared in an
16473 // accessible base class provided the function is not hidden
16474 // within T by another intervening declaration.
16475 const auto &Conversions = Record->getVisibleConversionFunctions();
16476 for (auto I = Conversions.begin(), E = Conversions.end();
16477 !IgnoreSurrogateFunctions && I != E; ++I) {
16478 NamedDecl *D = *I;
16479 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16480 if (isa<UsingShadowDecl>(D))
16481 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16482
16483 // Skip over templated conversion functions; they aren't
16484 // surrogates.
16486 continue;
16487
16489 if (!Conv->isExplicit()) {
16490 // Strip the reference type (if any) and then the pointer type (if
16491 // any) to get down to what might be a function type.
16492 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16493 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16494 ConvType = ConvPtrType->getPointeeType();
16495
16496 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16497 {
16498 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16499 Object.get(), Args, CandidateSet);
16500 }
16501 }
16502 }
16503
16504 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16505
16506 // Perform overload resolution.
16508 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16509 Best)) {
16510 case OR_Success:
16511 // Overload resolution succeeded; we'll build the appropriate call
16512 // below.
16513 break;
16514
16515 case OR_No_Viable_Function: {
16517 CandidateSet.empty()
16518 ? (PDiag(diag::err_ovl_no_oper)
16519 << Object.get()->getType() << /*call*/ 1
16520 << Object.get()->getSourceRange())
16521 : (PDiag(diag::err_ovl_no_viable_object_call)
16522 << Object.get()->getType() << Object.get()->getSourceRange());
16523 CandidateSet.NoteCandidates(
16524 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16525 OCD_AllCandidates, Args);
16526 break;
16527 }
16528 case OR_Ambiguous:
16529 if (!R.isAmbiguous())
16530 CandidateSet.NoteCandidates(
16531 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16532 PDiag(diag::err_ovl_ambiguous_object_call)
16533 << Object.get()->getType()
16534 << Object.get()->getSourceRange()),
16535 *this, OCD_AmbiguousCandidates, Args);
16536 break;
16537
16538 case OR_Deleted: {
16539 // FIXME: Is this diagnostic here really necessary? It seems that
16540 // 1. we don't have any tests for this diagnostic, and
16541 // 2. we already issue err_deleted_function_use for this later on anyway.
16542 StringLiteral *Msg = Best->Function->getDeletedMessage();
16543 CandidateSet.NoteCandidates(
16544 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16545 PDiag(diag::err_ovl_deleted_object_call)
16546 << Object.get()->getType() << (Msg != nullptr)
16547 << (Msg ? Msg->getString() : StringRef())
16548 << Object.get()->getSourceRange()),
16549 *this, OCD_AllCandidates, Args);
16550 break;
16551 }
16552 }
16553
16554 if (Best == CandidateSet.end())
16555 return true;
16556
16557 UnbridgedCasts.restore();
16558
16559 if (Best->Function == nullptr) {
16560 // Since there is no function declaration, this is one of the
16561 // surrogate candidates. Dig out the conversion function.
16562 CXXConversionDecl *Conv
16564 Best->Conversions[0].UserDefined.ConversionFunction);
16565
16566 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16567 Best->FoundDecl);
16568 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16569 return ExprError();
16570 assert(Conv == Best->FoundDecl.getDecl() &&
16571 "Found Decl & conversion-to-functionptr should be same, right?!");
16572 // We selected one of the surrogate functions that converts the
16573 // object parameter to a function pointer. Perform the conversion
16574 // on the object argument, then let BuildCallExpr finish the job.
16575
16576 // Create an implicit member expr to refer to the conversion operator.
16577 // and then call it.
16578 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16579 Conv, HadMultipleCandidates);
16580 if (Call.isInvalid())
16581 return ExprError();
16582 // Record usage of conversion in an implicit cast.
16584 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16585 nullptr, VK_PRValue, CurFPFeatureOverrides());
16586
16587 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16588 }
16589
16590 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16591
16592 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16593 // that calls this method, using Object for the implicit object
16594 // parameter and passing along the remaining arguments.
16595 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16596
16597 // An error diagnostic has already been printed when parsing the declaration.
16598 if (Method->isInvalidDecl())
16599 return ExprError();
16600
16601 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16602 unsigned NumParams = Proto->getNumParams();
16603
16604 DeclarationNameInfo OpLocInfo(
16605 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16606 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16607 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16608 Obj, HadMultipleCandidates,
16609 OpLocInfo.getLoc(),
16610 OpLocInfo.getInfo());
16611 if (NewFn.isInvalid())
16612 return true;
16613
16614 SmallVector<Expr *, 8> MethodArgs;
16615 MethodArgs.reserve(NumParams + 1);
16616
16617 bool IsError = false;
16618
16619 // Initialize the object parameter.
16621 if (Method->isExplicitObjectMemberFunction()) {
16622 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16623 } else {
16625 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16626 if (ObjRes.isInvalid())
16627 IsError = true;
16628 else
16629 Object = ObjRes;
16630 MethodArgs.push_back(Object.get());
16631 }
16632
16634 *this, MethodArgs, Method, Args, LParenLoc);
16635
16636 // If this is a variadic call, handle args passed through "...".
16637 if (Proto->isVariadic()) {
16638 // Promote the arguments (C99 6.5.2.2p7).
16639 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16641 Args[i], VariadicCallType::Method, nullptr);
16642 IsError |= Arg.isInvalid();
16643 MethodArgs.push_back(Arg.get());
16644 }
16645 }
16646
16647 if (IsError)
16648 return true;
16649
16650 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16651
16652 // Once we've built TheCall, all of the expressions are properly owned.
16653 QualType ResultTy = Method->getReturnType();
16655 ResultTy = ResultTy.getNonLValueExprType(Context);
16656
16658 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16660
16661 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16662 return true;
16663
16664 if (CheckFunctionCall(Method, TheCall, Proto))
16665 return true;
16666
16668}
16669
16671 SourceLocation OpLoc,
16672 bool *NoArrowOperatorFound) {
16673 assert(Base->getType()->isRecordType() &&
16674 "left-hand side must have class type");
16675
16677 return ExprError();
16678
16679 SourceLocation Loc = Base->getExprLoc();
16680
16681 // C++ [over.ref]p1:
16682 //
16683 // [...] An expression x->m is interpreted as (x.operator->())->m
16684 // for a class object x of type T if T::operator->() exists and if
16685 // the operator is selected as the best match function by the
16686 // overload resolution mechanism (13.3).
16687 DeclarationName OpName =
16688 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16690
16691 if (RequireCompleteType(Loc, Base->getType(),
16692 diag::err_typecheck_incomplete_tag, Base))
16693 return ExprError();
16694
16695 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16696 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16698
16699 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16700 Oper != OperEnd; ++Oper) {
16701 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16702 {}, CandidateSet,
16703 /*SuppressUserConversion=*/false);
16704 }
16705
16706 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16707
16708 // Perform overload resolution.
16710 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16711 case OR_Success:
16712 // Overload resolution succeeded; we'll build the call below.
16713 break;
16714
16715 case OR_No_Viable_Function: {
16716 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16717 if (CandidateSet.empty()) {
16718 QualType BaseType = Base->getType();
16719 if (NoArrowOperatorFound) {
16720 // Report this specific error to the caller instead of emitting a
16721 // diagnostic, as requested.
16722 *NoArrowOperatorFound = true;
16723 return ExprError();
16724 }
16725 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16726 << BaseType << Base->getSourceRange();
16727 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16728 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16729 << FixItHint::CreateReplacement(OpLoc, ".");
16730 }
16731 } else
16732 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16733 << "operator->" << Base->getSourceRange();
16734 CandidateSet.NoteCandidates(*this, Base, Cands);
16735 return ExprError();
16736 }
16737 case OR_Ambiguous:
16738 if (!R.isAmbiguous())
16739 CandidateSet.NoteCandidates(
16740 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16741 << "->" << Base->getType()
16742 << Base->getSourceRange()),
16744 return ExprError();
16745
16746 case OR_Deleted: {
16747 StringLiteral *Msg = Best->Function->getDeletedMessage();
16748 CandidateSet.NoteCandidates(
16749 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16750 << "->" << (Msg != nullptr)
16751 << (Msg ? Msg->getString() : StringRef())
16752 << Base->getSourceRange()),
16753 *this, OCD_AllCandidates, Base);
16754 return ExprError();
16755 }
16756 }
16757
16758 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16759
16760 // Convert the object parameter.
16761 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16762
16763 if (Method->isExplicitObjectMemberFunction()) {
16765 if (R.isInvalid())
16766 return ExprError();
16767 Base = R.get();
16768 } else {
16770 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16771 if (BaseResult.isInvalid())
16772 return ExprError();
16773 Base = BaseResult.get();
16774 }
16775
16776 // Build the operator call.
16777 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16778 Base, HadMultipleCandidates, OpLoc);
16779 if (FnExpr.isInvalid())
16780 return ExprError();
16781
16782 QualType ResultTy = Method->getReturnType();
16784 ResultTy = ResultTy.getNonLValueExprType(Context);
16785
16786 CallExpr *TheCall =
16787 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16788 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16789
16790 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16791 return ExprError();
16792
16793 if (CheckFunctionCall(Method, TheCall,
16794 Method->getType()->castAs<FunctionProtoType>()))
16795 return ExprError();
16796
16798}
16799
16801 DeclarationNameInfo &SuffixInfo,
16802 ArrayRef<Expr*> Args,
16803 SourceLocation LitEndLoc,
16804 TemplateArgumentListInfo *TemplateArgs) {
16805 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16806
16807 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16809 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16810 TemplateArgs);
16811
16812 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16813
16814 // Perform overload resolution. This will usually be trivial, but might need
16815 // to perform substitutions for a literal operator template.
16817 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16818 case OR_Success:
16819 case OR_Deleted:
16820 break;
16821
16823 CandidateSet.NoteCandidates(
16824 PartialDiagnosticAt(UDSuffixLoc,
16825 PDiag(diag::err_ovl_no_viable_function_in_call)
16826 << R.getLookupName()),
16827 *this, OCD_AllCandidates, Args);
16828 return ExprError();
16829
16830 case OR_Ambiguous:
16831 CandidateSet.NoteCandidates(
16832 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16833 << R.getLookupName()),
16834 *this, OCD_AmbiguousCandidates, Args);
16835 return ExprError();
16836 }
16837
16838 FunctionDecl *FD = Best->Function;
16839 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16840 nullptr, HadMultipleCandidates,
16841 SuffixInfo.getLoc(),
16842 SuffixInfo.getInfo());
16843 if (Fn.isInvalid())
16844 return true;
16845
16846 // Check the argument types. This should almost always be a no-op, except
16847 // that array-to-pointer decay is applied to string literals.
16848 Expr *ConvArgs[2];
16849 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16852 SourceLocation(), Args[ArgIdx]);
16853 if (InputInit.isInvalid())
16854 return true;
16855 ConvArgs[ArgIdx] = InputInit.get();
16856 }
16857
16858 QualType ResultTy = FD->getReturnType();
16860 ResultTy = ResultTy.getNonLValueExprType(Context);
16861
16863 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16864 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16865
16866 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16867 return ExprError();
16868
16869 if (CheckFunctionCall(FD, UDL, nullptr))
16870 return ExprError();
16871
16873}
16874
16877 SourceLocation RangeLoc,
16878 const DeclarationNameInfo &NameInfo,
16879 LookupResult &MemberLookup,
16880 OverloadCandidateSet *CandidateSet,
16881 Expr *Range, ExprResult *CallExpr) {
16882 Scope *S = nullptr;
16883
16885 if (!MemberLookup.empty()) {
16886 ExprResult MemberRef =
16887 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16888 /*IsPtr=*/false, CXXScopeSpec(),
16889 /*TemplateKWLoc=*/SourceLocation(),
16890 /*FirstQualifierInScope=*/nullptr,
16891 MemberLookup,
16892 /*TemplateArgs=*/nullptr, S);
16893 if (MemberRef.isInvalid()) {
16894 *CallExpr = ExprError();
16895 return FRS_DiagnosticIssued;
16896 }
16897 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16898 if (CallExpr->isInvalid()) {
16899 *CallExpr = ExprError();
16900 return FRS_DiagnosticIssued;
16901 }
16902 } else {
16903 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16905 NameInfo, UnresolvedSet<0>());
16906 if (FnR.isInvalid())
16907 return FRS_DiagnosticIssued;
16909
16910 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16911 CandidateSet, CallExpr);
16912 if (CandidateSet->empty() || CandidateSetError) {
16913 *CallExpr = ExprError();
16914 return FRS_NoViableFunction;
16915 }
16917 OverloadingResult OverloadResult =
16918 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16919
16920 if (OverloadResult == OR_No_Viable_Function) {
16921 *CallExpr = ExprError();
16922 return FRS_NoViableFunction;
16923 }
16924 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16925 Loc, nullptr, CandidateSet, &Best,
16926 OverloadResult,
16927 /*AllowTypoCorrection=*/false);
16928 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16929 *CallExpr = ExprError();
16930 return FRS_DiagnosticIssued;
16931 }
16932 }
16933 return FRS_Success;
16934}
16935
16937 FunctionDecl *Fn) {
16938 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16939 ExprResult SubExpr =
16940 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16941 if (SubExpr.isInvalid())
16942 return ExprError();
16943 if (SubExpr.get() == PE->getSubExpr())
16944 return PE;
16945
16946 return new (Context)
16947 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16948 }
16949
16950 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16951 ExprResult SubExpr =
16952 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16953 if (SubExpr.isInvalid())
16954 return ExprError();
16955 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16956 SubExpr.get()->getType()) &&
16957 "Implicit cast type cannot be determined from overload");
16958 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16959 if (SubExpr.get() == ICE->getSubExpr())
16960 return ICE;
16961
16962 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16963 SubExpr.get(), nullptr, ICE->getValueKind(),
16965 }
16966
16967 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16968 if (!GSE->isResultDependent()) {
16969 ExprResult SubExpr =
16970 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16971 if (SubExpr.isInvalid())
16972 return ExprError();
16973 if (SubExpr.get() == GSE->getResultExpr())
16974 return GSE;
16975
16976 // Replace the resulting type information before rebuilding the generic
16977 // selection expression.
16978 ArrayRef<Expr *> A = GSE->getAssocExprs();
16979 SmallVector<Expr *, 4> AssocExprs(A);
16980 unsigned ResultIdx = GSE->getResultIndex();
16981 AssocExprs[ResultIdx] = SubExpr.get();
16982
16983 if (GSE->isExprPredicate())
16985 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16986 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16987 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16988 ResultIdx);
16990 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16991 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16992 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16993 ResultIdx);
16994 }
16995 // Rather than fall through to the unreachable, return the original generic
16996 // selection expression.
16997 return GSE;
16998 }
16999
17000 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17001 assert(UnOp->getOpcode() == UO_AddrOf &&
17002 "Can only take the address of an overloaded function");
17003 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17004 if (!Method->isImplicitObjectMemberFunction()) {
17005 // Do nothing: the address of static and
17006 // explicit object member functions is a (non-member) function pointer.
17007 } else {
17008 // Fix the subexpression, which really has to be an
17009 // UnresolvedLookupExpr holding an overloaded member function
17010 // or template.
17011 ExprResult SubExpr =
17012 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17013 if (SubExpr.isInvalid())
17014 return ExprError();
17015 if (SubExpr.get() == UnOp->getSubExpr())
17016 return UnOp;
17017
17018 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17019 SubExpr.get(), Method))
17020 return ExprError();
17021
17022 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17023 "fixed to something other than a decl ref");
17024 NestedNameSpecifier Qualifier =
17025 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17026 assert(Qualifier &&
17027 "fixed to a member ref with no nested name qualifier");
17028
17029 // We have taken the address of a pointer to member
17030 // function. Perform the computation here so that we get the
17031 // appropriate pointer to member type.
17032 QualType MemPtrType = Context.getMemberPointerType(
17033 Fn->getType(), Qualifier,
17034 cast<CXXRecordDecl>(Method->getDeclContext()));
17035 // Under the MS ABI, lock down the inheritance model now.
17036 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17037 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17038
17039 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17040 MemPtrType, VK_PRValue, OK_Ordinary,
17041 UnOp->getOperatorLoc(), false,
17043 }
17044 }
17045 ExprResult SubExpr =
17046 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17047 if (SubExpr.isInvalid())
17048 return ExprError();
17049 if (SubExpr.get() == UnOp->getSubExpr())
17050 return UnOp;
17051
17052 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17053 SubExpr.get());
17054 }
17055
17056 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17057 if (Found.getAccess() == AS_none) {
17059 }
17060 // FIXME: avoid copy.
17061 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17062 if (ULE->hasExplicitTemplateArgs()) {
17063 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17064 TemplateArgs = &TemplateArgsBuffer;
17065 }
17066
17067 QualType Type = Fn->getType();
17068 ExprValueKind ValueKind =
17069 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17070 ? VK_LValue
17071 : VK_PRValue;
17072
17073 // FIXME: Duplicated from BuildDeclarationNameExpr.
17074 if (unsigned BID = Fn->getBuiltinID()) {
17075 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17076 Type = Context.BuiltinFnTy;
17077 ValueKind = VK_PRValue;
17078 }
17079 }
17080
17082 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17083 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17084 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17085 return DRE;
17086 }
17087
17088 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17089 // FIXME: avoid copy.
17090 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17091 if (MemExpr->hasExplicitTemplateArgs()) {
17092 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17093 TemplateArgs = &TemplateArgsBuffer;
17094 }
17095
17096 Expr *Base;
17097
17098 // If we're filling in a static method where we used to have an
17099 // implicit member access, rewrite to a simple decl ref.
17100 if (MemExpr->isImplicitAccess()) {
17101 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17103 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17104 MemExpr->getQualifierLoc(), Found.getDecl(),
17105 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17106 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17107 return DRE;
17108 } else {
17109 SourceLocation Loc = MemExpr->getMemberLoc();
17110 if (MemExpr->getQualifier())
17111 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17112 Base =
17113 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17114 }
17115 } else
17116 Base = MemExpr->getBase();
17117
17118 ExprValueKind valueKind;
17119 QualType type;
17120 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17121 valueKind = VK_LValue;
17122 type = Fn->getType();
17123 } else {
17124 valueKind = VK_PRValue;
17125 type = Context.BoundMemberTy;
17126 }
17127
17128 return BuildMemberExpr(
17129 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17130 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17131 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17132 type, valueKind, OK_Ordinary, TemplateArgs);
17133 }
17134
17135 llvm_unreachable("Invalid reference to overloaded function");
17136}
17137
17143
17144bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17146 if (!PartialOverloading || !Function)
17147 return true;
17148 if (Function->isVariadic())
17149 return false;
17150 if (const auto *Proto =
17151 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17152 if (Proto->isTemplateVariadic())
17153 return false;
17154 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17155 if (const auto *Proto =
17156 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17157 if (Proto->isTemplateVariadic())
17158 return false;
17159 return true;
17160}
17161
17163 DeclarationName Name,
17164 OverloadCandidateSet &CandidateSet,
17165 FunctionDecl *Fn, MultiExprArg Args,
17166 bool IsMember) {
17167 StringLiteral *Msg = Fn->getDeletedMessage();
17168 CandidateSet.NoteCandidates(
17169 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17170 << IsMember << Name << (Msg != nullptr)
17171 << (Msg ? Msg->getString() : StringRef())
17172 << Range),
17173 *this, OCD_AllCandidates, Args);
17174}
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.
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 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 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:463
bool isFloat() const
Definition APValue.h:468
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
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:795
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:945
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:911
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
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:910
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:3893
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:279
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3723
QualType getElementType() const
Definition TypeBase.h:3735
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8092
Attr - This represents one attribute.
Definition Attr.h:45
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2179
StringRef getOpcodeStr() const
Definition Expr.h:4038
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
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:4981
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
Pointer to a block type.
Definition TypeBase.h:3543
This class is used for builtin types like 'int'.
Definition TypeBase.h:3165
Kind getKind() const
Definition TypeBase.h:3213
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:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3019
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:3056
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2975
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2979
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
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:692
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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:2703
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:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
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:1977
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:1736
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:286
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
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:2877
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:1516
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3041
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3259
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:3276
QualType getElementType() const
Definition TypeBase.h:3286
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:5003
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4407
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4404
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:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
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:1270
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:1463
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:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
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:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
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:777
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:762
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:753
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1948
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1932
const Expr * getExpr() const
Definition DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2354
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:337
bool isLValue() const
Definition Expr.h:387
bool isPRValue() const
Definition Expr.h:390
bool isXValue() const
Definition Expr.h:388
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:395
bool isRValue() const
Definition Expr.h:391
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:3094
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:444
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.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
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:3338
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4207
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
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:811
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:4046
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:412
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
ExtVectorType - Extended vector type.
Definition TypeBase.h:4268
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4189
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3758
param_iterator param_end()
Definition Decl.h:2787
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3662
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3861
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
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:4260
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4309
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3743
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3129
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4325
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4253
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3865
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4126
bool isConsteval() const
Definition Decl.h:2482
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3706
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:2862
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:3711
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3822
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5773
unsigned getNumParams() const
Definition TypeBase.h:5547
Qualifiers getMethodQuals() const
Definition TypeBase.h:5695
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5709
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:4576
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4647
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4504
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
ExtInfo getExtInfo() const
Definition TypeBase.h:4821
CallingConv getCallConv() const
Definition TypeBase.h:4820
QualType getReturnType() const
Definition TypeBase.h:4805
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4833
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:4603
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:3787
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2072
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:621
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:672
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:769
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:676
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:826
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:680
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:811
bool hasInitializerListContainerType() const
Definition Overload.h:808
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:733
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:815
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:684
QualType getInitializerListContainerType() const
Definition Overload.h:818
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5348
unsigned getNumInits() const
Definition Expr.h:5263
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2495
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2513
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:974
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3618
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
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
bool isAmbiguous() const
Definition Lookup.h:324
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
const UnresolvedSetImpl & asUnresolvedSet() const
Definition Lookup.h:354
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
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:4352
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3487
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3409
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3395
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3375
void setBase(Expr *E)
Definition Expr.h:3374
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1793
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3493
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3385
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3686
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5449
QualType getPointeeType() const
Definition TypeBase.h:3672
Describes a module or submodule.
Definition Module.h:144
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
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:7855
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7911
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8000
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7969
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7923
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7963
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7975
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1159
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:1359
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:1457
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1391
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:1407
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1349
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1548
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1184
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1180
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1175
@ CSK_Normal
Normal lookup.
Definition Overload.h:1163
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1170
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1375
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:1367
SourceLocation getLocation() const
Definition Overload.h:1347
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1422
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1348
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1382
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:3128
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3280
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3189
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3244
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3241
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3219
decls_iterator decls_begin() const
Definition ExprCXX.h:3221
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3232
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3254
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3250
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:3224
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3238
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:273
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3054
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5075
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8377
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8371
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8382
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3555
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1225
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:8293
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8419
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8333
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:8478
QualType getCanonicalType() const
Definition TypeBase.h:8345
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8387
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:8447
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8366
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8414
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8339
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
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:8458
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8325
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8233
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8240
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4659
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:3636
Represents a struct/union/class.
Definition Decl.h:4321
field_range fields() const
Definition Decl.h:4524
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3574
QualType getPointeeType() const
Definition TypeBase.h:3592
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:1487
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1531
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:186
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:10293
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:6343
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6372
RAII class to control scope of DeferDiags.
Definition Sema.h:10030
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:12436
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12470
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
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:10046
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:9319
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9346
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9331
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9327
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:411
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:168
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:1441
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:10376
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10379
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10385
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10383
@ AR_dependent
Definition Sema.h:1656
@ AR_accessible
Definition Sema.h:1654
@ AR_inaccessible
Definition Sema.h:1655
@ AR_delayed
Definition Sema.h:1657
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:2045
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:1654
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:1283
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:680
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
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:1486
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:754
ASTContext & getASTContext() const
Definition Sema.h:925
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:756
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:10764
@ FRS_DiagnosticIssued
Definition Sema.h:10766
@ FRS_NoViableFunction
Definition Sema.h:10765
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9312
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:10097
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:1191
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:3572
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:12136
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
const LangOptions & getLangOpts() const
Definition Sema.h:918
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:1281
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:1451
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9311
MemberPointerConversionDirection
Definition Sema.h:10217
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:10404
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.
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:639
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:15433
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:6962
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:1414
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
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:8161
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:13909
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:7457
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:13644
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
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:15388
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:123
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:6728
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6697
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:10209
SourceManager & SourceMgr
Definition Sema.h:1286
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1285
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:515
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:6405
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:1421
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:8641
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:362
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
StringRef getString() const
Definition Expr.h:1867
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:678
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:732
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:717
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:3538
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBlockPointerType() const
Definition TypeBase.h:8550
bool isVoidType() const
Definition TypeBase.h:8892
bool isBooleanType() const
Definition TypeBase.h:9022
bool isObjCBuiltinType() const
Definition TypeBase.h:8756
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
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:1951
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isIncompleteArrayType() const
Definition TypeBase.h:8637
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isFloat16Type() const
Definition TypeBase.h:8901
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
bool isRValueReferenceType() const
Definition TypeBase.h:8562
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:8633
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9052
bool isArrayType() const
Definition TypeBase.h:8629
bool isCharType() const
Definition Type.cpp:2132
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:8960
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2337
bool isPointerType() const
Definition TypeBase.h:8530
bool isArrayParameterType() const
Definition TypeBase.h:8645
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8936
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2573
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9179
bool isReferenceType() const
Definition TypeBase.h:8554
bool isEnumeralType() const
Definition TypeBase.h:8661
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8726
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9010
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2168
bool isExtVectorBoolType() const
Definition TypeBase.h:8677
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8713
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2791
bool isLValueReferenceType() const
Definition TypeBase.h:8558
bool isBitIntType() const
Definition TypeBase.h:8801
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2411
bool isAnyComplexType() const
Definition TypeBase.h:8665
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8948
bool isHalfType() const
Definition TypeBase.h:8896
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8874
bool isQueueT() const
Definition TypeBase.h:8782
bool isMemberPointerType() const
Definition TypeBase.h:8611
bool isObjCIdType() const
Definition TypeBase.h:8738
bool isMatrixType() const
Definition TypeBase.h:8693
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9028
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8774
bool isBFloat16Type() const
Definition TypeBase.h:8913
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8526
bool isObjCObjectPointerType() const
Definition TypeBase.h:8705
bool isVectorType() const
Definition TypeBase.h:8669
bool isObjCClassType() const
Definition TypeBase.h:8744
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2594
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2922
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8849
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:2253
bool isAnyPointerType() const
Definition TypeBase.h:8538
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSamplerT() const
Definition TypeBase.h:8770
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9112
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8929
bool isRecordType() const
Definition TypeBase.h:8657
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1429
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:5038
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1405
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:640
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:966
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
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.
bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:224
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:809
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
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:858
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:886
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:895
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:878
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:882
@ 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:923
@ ovl_fail_too_few_arguments
Definition Overload.h:860
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:902
@ ovl_fail_too_many_arguments
Definition Overload.h:859
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:910
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:919
@ ovl_fail_bad_conversion
Definition Overload.h:861
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:891
@ ovl_fail_bad_deduction
Definition Overload.h:862
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:906
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:915
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:899
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:867
@ Comparison
A comparison.
Definition Sema.h:665
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
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:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1042
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:124
@ AS_none
Definition Specifiers.h:127
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:928
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
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:710
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:731
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:689
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:727
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:585
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:214
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:425
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
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:308
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:304
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:417
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:412
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:388
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:374
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:410
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:407
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:377
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:371
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:391
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:380
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:394
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:383
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:404
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:398
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:401
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
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:1518
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:824
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:827
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:832
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:831
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:5882
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:446
__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:521
ConversionSet::const_iterator const_iterator
Definition Overload.h:557
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:522
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:548
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:606
QualType getFromType() const
Definition Overload.h:605
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:1101
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
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:633
Extra information about a function prototype.
Definition TypeBase.h:5354
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5359
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1194
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:1216
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1243
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1205
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1207
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1233
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:932
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:997
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:988
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1062
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1036
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1001
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:978
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:946
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:942
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:937
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1009
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:958
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:972
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1027
unsigned getNumParams() const
Definition Overload.h:1075
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1005
unsigned TookAddressOfOverload
Definition Overload.h:991
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1014
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1018
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:955
DeductionFailureInfo DeductionFailure
Definition Overload.h:1021
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:962
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:950
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1032
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10496
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10503
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13078
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13166
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13204
Abstract class used to diagnose incomplete types.
Definition Sema.h:8242
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:476
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:488
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:510
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:501
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:505
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:496
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:515
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.