clang 20.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/SemaCUDA.h"
34#include "clang/Sema/SemaObjC.h"
35#include "clang/Sema/Template.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include <algorithm>
44#include <cassert>
45#include <cstddef>
46#include <cstdlib>
47#include <optional>
48
49using namespace clang;
50using namespace sema;
51
53
55 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
56 return P->hasAttr<PassObjectSizeAttr>();
57 });
58}
59
60/// A convenience routine for creating a decayed reference to a function.
62 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
63 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
64 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
65 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
66 return ExprError();
67 // If FoundDecl is different from Fn (such as if one is a template
68 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // called on both.
70 // FIXME: This would be more comprehensively addressed by modifying
71 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 // being used.
73 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
74 return ExprError();
75 DeclRefExpr *DRE = new (S.Context)
76 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
77 if (HadMultipleCandidates)
78 DRE->setHadMultipleCandidates(true);
79
81 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
82 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 DRE->setType(Fn->getType());
85 }
86 }
87 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
88 CK_FunctionToPointerDecay);
89}
90
91static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
92 bool InOverloadResolution,
94 bool CStyle,
95 bool AllowObjCWritebackConversion);
96
98 QualType &ToType,
99 bool InOverloadResolution,
101 bool CStyle);
103IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105 OverloadCandidateSet& Conversions,
106 AllowedExplicit AllowExplicit,
107 bool AllowObjCConversionOnExplicit);
108
111 const StandardConversionSequence& SCS1,
112 const StandardConversionSequence& SCS2);
113
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
118
121 const StandardConversionSequence& SCS1,
122 const StandardConversionSequence& SCS2);
123
124/// GetConversionRank - Retrieve the implicit conversion rank
125/// corresponding to the given implicit conversion kind.
127 static const ImplicitConversionRank Rank[] = {
154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Event_Conversion
157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
158 // it was omitted by the patch that added
159 // ICK_Zero_Queue_Conversion
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
173 ImplicitConversionKind Dimension) {
175 if (Rank == ICR_HLSL_Scalar_Widening) {
176 if (Base == ICR_Promotion)
178 if (Base == ICR_Conversion)
180 }
181 if (Rank == ICR_HLSL_Dimension_Reduction) {
182 if (Base == ICR_Promotion)
184 if (Base == ICR_Conversion)
186 }
187 return Rank;
188}
189
190/// GetImplicitConversionName - Return the name of this kind of
191/// implicit conversion.
193 static const char *const Name[] = {
194 "No conversion",
195 "Lvalue-to-rvalue",
196 "Array-to-pointer",
197 "Function-to-pointer",
198 "Function pointer conversion",
199 "Qualification",
200 "Integral promotion",
201 "Floating point promotion",
202 "Complex promotion",
203 "Integral conversion",
204 "Floating conversion",
205 "Complex conversion",
206 "Floating-integral conversion",
207 "Pointer conversion",
208 "Pointer-to-member conversion",
209 "Boolean conversion",
210 "Compatible-types conversion",
211 "Derived-to-base conversion",
212 "Vector conversion",
213 "SVE Vector conversion",
214 "RVV Vector conversion",
215 "Vector splat",
216 "Complex-real conversion",
217 "Block Pointer conversion",
218 "Transparent Union Conversion",
219 "Writeback conversion",
220 "OpenCL Zero Event Conversion",
221 "OpenCL Zero Queue Conversion",
222 "C specific type conversion",
223 "Incompatible pointer conversion",
224 "Fixed point conversion",
225 "HLSL vector truncation",
226 "Non-decaying array conversion",
227 "HLSL vector splat",
228 };
229 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
230 return Name[Kind];
231}
232
233/// StandardConversionSequence - Set the standard conversion
234/// sequence to the identity conversion.
242 ReferenceBinding = false;
243 DirectBinding = false;
244 IsLvalueReference = true;
245 BindsToFunctionLvalue = false;
246 BindsToRvalue = false;
249 CopyConstructor = nullptr;
250}
251
252/// getRank - Retrieve the rank of this standard conversion sequence
253/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
254/// implicit conversions.
257 if (GetConversionRank(First) > Rank)
258 Rank = GetConversionRank(First);
259 if (GetConversionRank(Second) > Rank)
261 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
263 if (GetConversionRank(Third) > Rank)
264 Rank = GetConversionRank(Third);
265 return Rank;
266}
267
268/// isPointerConversionToBool - Determines whether this conversion is
269/// a conversion of a pointer or pointer-to-member to bool. This is
270/// used as part of the ranking of standard conversion sequences
271/// (C++ 13.3.3.2p4).
273 // Note that FromType has not necessarily been transformed by the
274 // array-to-pointer or function-to-pointer implicit conversions, so
275 // check for their presence as well as checking whether FromType is
276 // a pointer.
277 if (getToType(1)->isBooleanType() &&
278 (getFromType()->isPointerType() ||
279 getFromType()->isMemberPointerType() ||
280 getFromType()->isObjCObjectPointerType() ||
281 getFromType()->isBlockPointerType() ||
283 return true;
284
285 return false;
286}
287
288/// isPointerConversionToVoidPointer - Determines whether this
289/// conversion is a conversion of a pointer to a void pointer. This is
290/// used as part of the ranking of standard conversion sequences (C++
291/// 13.3.3.2p4).
292bool
295 QualType FromType = getFromType();
296 QualType ToType = getToType(1);
297
298 // Note that FromType has not necessarily been transformed by the
299 // array-to-pointer implicit conversion, so check for its presence
300 // and redo the conversion to get a pointer.
302 FromType = Context.getArrayDecayedType(FromType);
303
304 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
305 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
306 return ToPtrType->getPointeeType()->isVoidType();
307
308 return false;
309}
310
311/// Skip any implicit casts which could be either part of a narrowing conversion
312/// or after one in an implicit conversion.
314 const Expr *Converted) {
315 // We can have cleanups wrapping the converted expression; these need to be
316 // preserved so that destructors run if necessary.
317 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
318 Expr *Inner =
319 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
320 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
321 EWC->getObjects());
322 }
323
324 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
325 switch (ICE->getCastKind()) {
326 case CK_NoOp:
327 case CK_IntegralCast:
328 case CK_IntegralToBoolean:
329 case CK_IntegralToFloating:
330 case CK_BooleanToSignedIntegral:
331 case CK_FloatingToIntegral:
332 case CK_FloatingToBoolean:
333 case CK_FloatingCast:
334 Converted = ICE->getSubExpr();
335 continue;
336
337 default:
338 return Converted;
339 }
340 }
341
342 return Converted;
343}
344
345/// Check if this standard conversion sequence represents a narrowing
346/// conversion, according to C++11 [dcl.init.list]p7.
347///
348/// \param Ctx The AST context.
349/// \param Converted The result of applying this standard conversion sequence.
350/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
351/// value of the expression prior to the narrowing conversion.
352/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
353/// type of the expression prior to the narrowing conversion.
354/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
355/// from floating point types to integral types should be ignored.
357 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
358 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
359 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
360 "narrowing check outside C++");
361
362 // C++11 [dcl.init.list]p7:
363 // A narrowing conversion is an implicit conversion ...
364 QualType FromType = getToType(0);
365 QualType ToType = getToType(1);
366
367 // A conversion to an enumeration type is narrowing if the conversion to
368 // the underlying type is narrowing. This only arises for expressions of
369 // the form 'Enum{init}'.
370 if (auto *ET = ToType->getAs<EnumType>())
371 ToType = ET->getDecl()->getIntegerType();
372
373 switch (Second) {
374 // 'bool' is an integral type; dispatch to the right place to handle it.
376 if (FromType->isRealFloatingType())
377 goto FloatingIntegralConversion;
379 goto IntegralConversion;
380 // -- from a pointer type or pointer-to-member type to bool, or
381 return NK_Type_Narrowing;
382
383 // -- from a floating-point type to an integer type, or
384 //
385 // -- from an integer type or unscoped enumeration type to a floating-point
386 // type, except where the source is a constant expression and the actual
387 // value after conversion will fit into the target type and will produce
388 // the original value when converted back to the original type, or
390 FloatingIntegralConversion:
391 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
392 return NK_Type_Narrowing;
393 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
394 ToType->isRealFloatingType()) {
395 if (IgnoreFloatToIntegralConversion)
396 return NK_Not_Narrowing;
397 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
398 assert(Initializer && "Unknown conversion expression");
399
400 // If it's value-dependent, we can't tell whether it's narrowing.
401 if (Initializer->isValueDependent())
403
404 if (std::optional<llvm::APSInt> IntConstantValue =
405 Initializer->getIntegerConstantExpr(Ctx)) {
406 // Convert the integer to the floating type.
407 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
408 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
409 llvm::APFloat::rmNearestTiesToEven);
410 // And back.
411 llvm::APSInt ConvertedValue = *IntConstantValue;
412 bool ignored;
413 Result.convertToInteger(ConvertedValue,
414 llvm::APFloat::rmTowardZero, &ignored);
415 // If the resulting value is different, this was a narrowing conversion.
416 if (*IntConstantValue != ConvertedValue) {
417 ConstantValue = APValue(*IntConstantValue);
418 ConstantType = Initializer->getType();
420 }
421 } else {
422 // Variables are always narrowings.
424 }
425 }
426 return NK_Not_Narrowing;
427
428 // -- from long double to double or float, or from double to float, except
429 // where the source is a constant expression and the actual value after
430 // conversion is within the range of values that can be represented (even
431 // if it cannot be represented exactly), or
433 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
434 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
435 // FromType is larger than ToType.
436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
437
438 // If it's value-dependent, we can't tell whether it's narrowing.
439 if (Initializer->isValueDependent())
441
443 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
444 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
445 // Constant!
446 if (Ctx.getLangOpts().C23)
447 ConstantValue = R.Val;
448 assert(ConstantValue.isFloat());
449 llvm::APFloat FloatVal = ConstantValue.getFloat();
450 // Convert the source value into the target type.
451 bool ignored;
452 llvm::APFloat Converted = FloatVal;
453 llvm::APFloat::opStatus ConvertStatus =
454 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
455 llvm::APFloat::rmNearestTiesToEven, &ignored);
456 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
457 llvm::APFloat::rmNearestTiesToEven, &ignored);
458 if (Ctx.getLangOpts().C23) {
459 if (FloatVal.isNaN() && Converted.isNaN() &&
460 !FloatVal.isSignaling() && !Converted.isSignaling()) {
461 // Quiet NaNs are considered the same value, regardless of
462 // payloads.
463 return NK_Not_Narrowing;
464 }
465 // For normal values, check exact equality.
466 if (!Converted.bitwiseIsEqual(FloatVal)) {
467 ConstantType = Initializer->getType();
469 }
470 } else {
471 // If there was no overflow, the source value is within the range of
472 // values that can be represented.
473 if (ConvertStatus & llvm::APFloat::opOverflow) {
474 ConstantType = Initializer->getType();
476 }
477 }
478 } else {
480 }
481 }
482 return NK_Not_Narrowing;
483
484 // -- from an integer type or unscoped enumeration type to an integer type
485 // that cannot represent all the values of the original type, except where
486 // (CWG2627) -- the source is a bit-field whose width w is less than that
487 // of its type (or, for an enumeration type, its underlying type) and the
488 // target type can represent all the values of a hypothetical extended
489 // integer type with width w and with the same signedness as the original
490 // type or
491 // -- the source is a constant expression and the actual value after
492 // conversion will fit into the target type and will produce the original
493 // value when converted back to the original type.
495 IntegralConversion: {
496 assert(FromType->isIntegralOrUnscopedEnumerationType());
497 assert(ToType->isIntegralOrUnscopedEnumerationType());
498 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
499 unsigned FromWidth = Ctx.getIntWidth(FromType);
500 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
501 const unsigned ToWidth = Ctx.getIntWidth(ToType);
502
503 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
504 bool ToSigned, unsigned ToWidth) {
505 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
506 !(FromSigned && !ToSigned);
507 };
508
509 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
510 return NK_Not_Narrowing;
511
512 // Not all values of FromType can be represented in ToType.
513 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
514
515 bool DependentBitField = false;
516 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
517 if (BitField->getBitWidth()->isValueDependent())
518 DependentBitField = true;
519 else if (unsigned BitFieldWidth = BitField->getBitWidthValue(Ctx);
520 BitFieldWidth < FromWidth) {
521 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
522 return NK_Not_Narrowing;
523
524 // The initializer will be truncated to the bit-field width
525 FromWidth = BitFieldWidth;
526 }
527 }
528
529 // If it's value-dependent, we can't tell whether it's narrowing.
530 if (Initializer->isValueDependent())
532
533 std::optional<llvm::APSInt> OptInitializerValue =
534 Initializer->getIntegerConstantExpr(Ctx);
535 if (!OptInitializerValue) {
536 // If the bit-field width was dependent, it might end up being small
537 // enough to fit in the target type (unless the target type is unsigned
538 // and the source type is signed, in which case it will never fit)
539 if (DependentBitField && !(FromSigned && !ToSigned))
541
542 // Otherwise, such a conversion is always narrowing
544 }
545 llvm::APSInt &InitializerValue = *OptInitializerValue;
546 bool Narrowing = false;
547 if (FromWidth < ToWidth) {
548 // Negative -> unsigned is narrowing. Otherwise, more bits is never
549 // narrowing.
550 if (InitializerValue.isSigned() && InitializerValue.isNegative())
551 Narrowing = true;
552 } else {
553 // Add a bit to the InitializerValue so we don't have to worry about
554 // signed vs. unsigned comparisons.
555 InitializerValue =
556 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
557 // Convert the initializer to and from the target width and signed-ness.
558 llvm::APSInt ConvertedValue = InitializerValue;
559 ConvertedValue = ConvertedValue.trunc(ToWidth);
560 ConvertedValue.setIsSigned(ToSigned);
561 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
562 ConvertedValue.setIsSigned(InitializerValue.isSigned());
563 // If the result is different, this was a narrowing conversion.
564 if (ConvertedValue != InitializerValue)
565 Narrowing = true;
566 }
567 if (Narrowing) {
568 ConstantType = Initializer->getType();
569 ConstantValue = APValue(InitializerValue);
571 }
572
573 return NK_Not_Narrowing;
574 }
575 case ICK_Complex_Real:
576 if (FromType->isComplexType() && !ToType->isComplexType())
577 return NK_Type_Narrowing;
578 return NK_Not_Narrowing;
579
581 if (Ctx.getLangOpts().C23) {
582 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
584 if (Initializer->EvaluateAsRValue(R, Ctx)) {
585 ConstantValue = R.Val;
586 assert(ConstantValue.isFloat());
587 llvm::APFloat FloatVal = ConstantValue.getFloat();
588 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
589 // value, the unqualified versions of the type of the initializer and
590 // the corresponding real type of the object declared shall be
591 // compatible.
592 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
593 ConstantType = Initializer->getType();
595 }
596 }
597 }
598 return NK_Not_Narrowing;
599 default:
600 // Other kinds of conversions are not narrowings.
601 return NK_Not_Narrowing;
602 }
603}
604
605/// dump - Print this standard conversion sequence to standard
606/// error. Useful for debugging overloading issues.
607LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
608 raw_ostream &OS = llvm::errs();
609 bool PrintedSomething = false;
610 if (First != ICK_Identity) {
612 PrintedSomething = true;
613 }
614
615 if (Second != ICK_Identity) {
616 if (PrintedSomething) {
617 OS << " -> ";
618 }
620
621 if (CopyConstructor) {
622 OS << " (by copy constructor)";
623 } else if (DirectBinding) {
624 OS << " (direct reference binding)";
625 } else if (ReferenceBinding) {
626 OS << " (reference binding)";
627 }
628 PrintedSomething = true;
629 }
630
631 if (Third != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
636 PrintedSomething = true;
637 }
638
639 if (!PrintedSomething) {
640 OS << "No conversions required";
641 }
642}
643
644/// dump - Print this user-defined conversion sequence to standard
645/// error. Useful for debugging overloading issues.
647 raw_ostream &OS = llvm::errs();
648 if (Before.First || Before.Second || Before.Third) {
649 Before.dump();
650 OS << " -> ";
651 }
653 OS << '\'' << *ConversionFunction << '\'';
654 else
655 OS << "aggregate initialization";
656 if (After.First || After.Second || After.Third) {
657 OS << " -> ";
658 After.dump();
659 }
660}
661
662/// dump - Print this implicit conversion sequence to standard
663/// error. Useful for debugging overloading issues.
665 raw_ostream &OS = llvm::errs();
667 OS << "Worst list element conversion: ";
668 switch (ConversionKind) {
670 OS << "Standard conversion: ";
671 Standard.dump();
672 break;
674 OS << "User-defined conversion: ";
676 break;
678 OS << "Ellipsis conversion";
679 break;
681 OS << "Ambiguous conversion";
682 break;
683 case BadConversion:
684 OS << "Bad conversion";
685 break;
686 }
687
688 OS << "\n";
689}
690
692 new (&conversions()) ConversionSet();
693}
694
696 conversions().~ConversionSet();
697}
698
699void
704}
705
706namespace {
707 // Structure used by DeductionFailureInfo to store
708 // template argument information.
709 struct DFIArguments {
710 TemplateArgument FirstArg;
711 TemplateArgument SecondArg;
712 };
713 // Structure used by DeductionFailureInfo to store
714 // template parameter and template argument information.
715 struct DFIParamWithArguments : DFIArguments {
716 TemplateParameter Param;
717 };
718 // Structure used by DeductionFailureInfo to store template argument
719 // information and the index of the problematic call argument.
720 struct DFIDeducedMismatchArgs : DFIArguments {
721 TemplateArgumentList *TemplateArgs;
722 unsigned CallArgIndex;
723 };
724 // Structure used by DeductionFailureInfo to store information about
725 // unsatisfied constraints.
726 struct CNSInfo {
727 TemplateArgumentList *TemplateArgs;
728 ConstraintSatisfaction Satisfaction;
729 };
730}
731
732/// Convert from Sema's representation of template deduction information
733/// to the form used in overload-candidate information.
737 TemplateDeductionInfo &Info) {
739 Result.Result = static_cast<unsigned>(TDK);
740 Result.HasDiagnostic = false;
741 switch (TDK) {
748 Result.Data = nullptr;
749 break;
750
753 Result.Data = Info.Param.getOpaqueValue();
754 break;
755
758 // FIXME: Should allocate from normal heap so that we can free this later.
759 auto *Saved = new (Context) DFIDeducedMismatchArgs;
760 Saved->FirstArg = Info.FirstArg;
761 Saved->SecondArg = Info.SecondArg;
762 Saved->TemplateArgs = Info.takeSugared();
763 Saved->CallArgIndex = Info.CallArgIndex;
764 Result.Data = Saved;
765 break;
766 }
767
769 // FIXME: Should allocate from normal heap so that we can free this later.
770 DFIArguments *Saved = new (Context) DFIArguments;
771 Saved->FirstArg = Info.FirstArg;
772 Saved->SecondArg = Info.SecondArg;
773 Result.Data = Saved;
774 break;
775 }
776
778 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
781 // FIXME: Should allocate from normal heap so that we can free this later.
782 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
783 Saved->Param = Info.Param;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Result.Data = Saved;
787 break;
788 }
789
791 Result.Data = Info.takeSugared();
792 if (Info.hasSFINAEDiagnostic()) {
796 Result.HasDiagnostic = true;
797 }
798 break;
799
801 CNSInfo *Saved = new (Context) CNSInfo;
802 Saved->TemplateArgs = Info.takeSugared();
803 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
804 Result.Data = Saved;
805 break;
806 }
807
811 llvm_unreachable("not a deduction failure");
812 }
813
814 return Result;
815}
816
818 switch (static_cast<TemplateDeductionResult>(Result)) {
828 break;
829
836 // FIXME: Destroy the data?
837 Data = nullptr;
838 break;
839
841 // FIXME: Destroy the template argument list?
842 Data = nullptr;
844 Diag->~PartialDiagnosticAt();
845 HasDiagnostic = false;
846 }
847 break;
848
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
858 // Unhandled
861 break;
862 }
863}
864
866 if (HasDiagnostic)
867 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
868 return nullptr;
869}
870
872 switch (static_cast<TemplateDeductionResult>(Result)) {
885 return TemplateParameter();
886
889 return TemplateParameter::getFromOpaqueValue(Data);
890
894 return static_cast<DFIParamWithArguments*>(Data)->Param;
895
896 // Unhandled
899 break;
900 }
901
902 return TemplateParameter();
903}
904
906 switch (static_cast<TemplateDeductionResult>(Result)) {
920 return nullptr;
921
924 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
925
927 return static_cast<TemplateArgumentList*>(Data);
928
930 return static_cast<CNSInfo*>(Data)->TemplateArgs;
931
932 // Unhandled
935 break;
936 }
937
938 return nullptr;
939}
940
942 switch (static_cast<TemplateDeductionResult>(Result)) {
954 return nullptr;
955
962 return &static_cast<DFIArguments*>(Data)->FirstArg;
963
964 // Unhandled
967 break;
968 }
969
970 return nullptr;
971}
972
974 switch (static_cast<TemplateDeductionResult>(Result)) {
987 return nullptr;
988
994 return &static_cast<DFIArguments*>(Data)->SecondArg;
995
996 // Unhandled
999 break;
1000 }
1001
1002 return nullptr;
1003}
1004
1005std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
1006 switch (static_cast<TemplateDeductionResult>(Result)) {
1009 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1010
1011 default:
1012 return std::nullopt;
1013 }
1014}
1015
1017 const FunctionDecl *Y) {
1018 if (!X || !Y)
1019 return false;
1020 if (X->getNumParams() != Y->getNumParams())
1021 return false;
1022 // FIXME: when do rewritten comparison operators
1023 // with explicit object parameters correspond?
1024 // https://cplusplus.github.io/CWG/issues/2797.html
1025 for (unsigned I = 0; I < X->getNumParams(); ++I)
1026 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1027 Y->getParamDecl(I)->getType()))
1028 return false;
1029 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1030 auto *FTY = Y->getDescribedFunctionTemplate();
1031 if (!FTY)
1032 return false;
1033 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1034 FTY->getTemplateParameters()))
1035 return false;
1036 }
1037 return true;
1038}
1039
1041 Expr *FirstOperand, FunctionDecl *EqFD) {
1042 assert(EqFD->getOverloadedOperator() ==
1043 OverloadedOperatorKind::OO_EqualEqual);
1044 // C++2a [over.match.oper]p4:
1045 // A non-template function or function template F named operator== is a
1046 // rewrite target with first operand o unless a search for the name operator!=
1047 // in the scope S from the instantiation context of the operator expression
1048 // finds a function or function template that would correspond
1049 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1050 // scope of the class type of o if F is a class member, and the namespace
1051 // scope of which F is a member otherwise. A function template specialization
1052 // named operator== is a rewrite target if its function template is a rewrite
1053 // target.
1055 OverloadedOperatorKind::OO_ExclaimEqual);
1056 if (isa<CXXMethodDecl>(EqFD)) {
1057 // If F is a class member, search scope is class type of first operand.
1058 QualType RHS = FirstOperand->getType();
1059 auto *RHSRec = RHS->getAs<RecordType>();
1060 if (!RHSRec)
1061 return true;
1062 LookupResult Members(S, NotEqOp, OpLoc,
1064 S.LookupQualifiedName(Members, RHSRec->getDecl());
1065 Members.suppressAccessDiagnostics();
1066 for (NamedDecl *Op : Members)
1067 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1068 return false;
1069 return true;
1070 }
1071 // Otherwise the search scope is the namespace scope of which F is a member.
1072 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1073 auto *NotEqFD = Op->getAsFunction();
1074 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1075 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1076 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1078 cast<Decl>(Op->getLexicalDeclContext())))
1079 return false;
1080 }
1081 return true;
1082}
1083
1087 return false;
1088 return Op == OO_EqualEqual || Op == OO_Spaceship;
1089}
1090
1092 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1093 auto Op = FD->getOverloadedOperator();
1094 if (!allowsReversed(Op))
1095 return false;
1096 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1097 assert(OriginalArgs.size() == 2);
1099 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1100 return false;
1101 }
1102 // Don't bother adding a reversed candidate that can never be a better
1103 // match than the non-reversed version.
1104 return FD->getNumNonObjectParams() != 2 ||
1106 FD->getParamDecl(1)->getType()) ||
1107 FD->hasAttr<EnableIfAttr>();
1108}
1109
1110void OverloadCandidateSet::destroyCandidates() {
1111 for (iterator i = begin(), e = end(); i != e; ++i) {
1112 for (auto &C : i->Conversions)
1113 C.~ImplicitConversionSequence();
1114 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1115 i->DeductionFailure.Destroy();
1116 }
1117}
1118
1120 destroyCandidates();
1121 SlabAllocator.Reset();
1122 NumInlineBytesUsed = 0;
1123 Candidates.clear();
1124 Functions.clear();
1125 Kind = CSK;
1126}
1127
1128namespace {
1129 class UnbridgedCastsSet {
1130 struct Entry {
1131 Expr **Addr;
1132 Expr *Saved;
1133 };
1134 SmallVector<Entry, 2> Entries;
1135
1136 public:
1137 void save(Sema &S, Expr *&E) {
1138 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1139 Entry entry = { &E, E };
1140 Entries.push_back(entry);
1142 }
1143
1144 void restore() {
1146 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1147 *i->Addr = i->Saved;
1148 }
1149 };
1150}
1151
1152/// checkPlaceholderForOverload - Do any interesting placeholder-like
1153/// preprocessing on the given expression.
1154///
1155/// \param unbridgedCasts a collection to which to add unbridged casts;
1156/// without this, they will be immediately diagnosed as errors
1157///
1158/// Return true on unrecoverable error.
1159static bool
1161 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1162 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1163 // We can't handle overloaded expressions here because overload
1164 // resolution might reasonably tweak them.
1165 if (placeholder->getKind() == BuiltinType::Overload) return false;
1166
1167 // If the context potentially accepts unbridged ARC casts, strip
1168 // the unbridged cast and add it to the collection for later restoration.
1169 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1170 unbridgedCasts) {
1171 unbridgedCasts->save(S, E);
1172 return false;
1173 }
1174
1175 // Go ahead and check everything else.
1176 ExprResult result = S.CheckPlaceholderExpr(E);
1177 if (result.isInvalid())
1178 return true;
1179
1180 E = result.get();
1181 return false;
1182 }
1183
1184 // Nothing to do.
1185 return false;
1186}
1187
1188/// checkArgPlaceholdersForOverload - Check a set of call operands for
1189/// placeholders.
1191 UnbridgedCastsSet &unbridged) {
1192 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1193 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1194 return true;
1195
1196 return false;
1197}
1198
1201 NamedDecl *&Match, bool NewIsUsingDecl) {
1202 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1203 I != E; ++I) {
1204 NamedDecl *OldD = *I;
1205
1206 bool OldIsUsingDecl = false;
1207 if (isa<UsingShadowDecl>(OldD)) {
1208 OldIsUsingDecl = true;
1209
1210 // We can always introduce two using declarations into the same
1211 // context, even if they have identical signatures.
1212 if (NewIsUsingDecl) continue;
1213
1214 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1215 }
1216
1217 // A using-declaration does not conflict with another declaration
1218 // if one of them is hidden.
1219 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1220 continue;
1221
1222 // If either declaration was introduced by a using declaration,
1223 // we'll need to use slightly different rules for matching.
1224 // Essentially, these rules are the normal rules, except that
1225 // function templates hide function templates with different
1226 // return types or template parameter lists.
1227 bool UseMemberUsingDeclRules =
1228 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1229 !New->getFriendObjectKind();
1230
1231 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1232 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1233 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1234 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1235 continue;
1236 }
1237
1238 if (!isa<FunctionTemplateDecl>(OldD) &&
1239 !shouldLinkPossiblyHiddenDecl(*I, New))
1240 continue;
1241
1242 Match = *I;
1243 return Ovl_Match;
1244 }
1245
1246 // Builtins that have custom typechecking or have a reference should
1247 // not be overloadable or redeclarable.
1248 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1249 Match = *I;
1250 return Ovl_NonFunction;
1251 }
1252 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1253 // We can overload with these, which can show up when doing
1254 // redeclaration checks for UsingDecls.
1255 assert(Old.getLookupKind() == LookupUsingDeclName);
1256 } else if (isa<TagDecl>(OldD)) {
1257 // We can always overload with tags by hiding them.
1258 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1259 // Optimistically assume that an unresolved using decl will
1260 // overload; if it doesn't, we'll have to diagnose during
1261 // template instantiation.
1262 //
1263 // Exception: if the scope is dependent and this is not a class
1264 // member, the using declaration can only introduce an enumerator.
1265 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1266 Match = *I;
1267 return Ovl_NonFunction;
1268 }
1269 } else {
1270 // (C++ 13p1):
1271 // Only function declarations can be overloaded; object and type
1272 // declarations cannot be overloaded.
1273 Match = *I;
1274 return Ovl_NonFunction;
1275 }
1276 }
1277
1278 // C++ [temp.friend]p1:
1279 // For a friend function declaration that is not a template declaration:
1280 // -- if the name of the friend is a qualified or unqualified template-id,
1281 // [...], otherwise
1282 // -- if the name of the friend is a qualified-id and a matching
1283 // non-template function is found in the specified class or namespace,
1284 // the friend declaration refers to that function, otherwise,
1285 // -- if the name of the friend is a qualified-id and a matching function
1286 // template is found in the specified class or namespace, the friend
1287 // declaration refers to the deduced specialization of that function
1288 // template, otherwise
1289 // -- the name shall be an unqualified-id [...]
1290 // If we get here for a qualified friend declaration, we've just reached the
1291 // third bullet. If the type of the friend is dependent, skip this lookup
1292 // until instantiation.
1293 if (New->getFriendObjectKind() && New->getQualifier() &&
1296 !New->getType()->isDependentType()) {
1297 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1298 TemplateSpecResult.addAllDecls(Old);
1299 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1300 /*QualifiedFriend*/true)) {
1301 New->setInvalidDecl();
1302 return Ovl_Overload;
1303 }
1304
1305 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1306 return Ovl_Match;
1307 }
1308
1309 return Ovl_Overload;
1310}
1311
1312static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1313 FunctionDecl *Old,
1314 bool UseMemberUsingDeclRules,
1315 bool ConsiderCudaAttrs,
1316 bool UseOverrideRules = false) {
1317 // C++ [basic.start.main]p2: This function shall not be overloaded.
1318 if (New->isMain())
1319 return false;
1320
1321 // MSVCRT user defined entry points cannot be overloaded.
1322 if (New->isMSVCRTEntryPoint())
1323 return false;
1324
1325 NamedDecl *OldDecl = Old;
1326 NamedDecl *NewDecl = New;
1329
1330 // C++ [temp.fct]p2:
1331 // A function template can be overloaded with other function templates
1332 // and with normal (non-template) functions.
1333 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1334 return true;
1335
1336 // Is the function New an overload of the function Old?
1337 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1338 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1339
1340 // Compare the signatures (C++ 1.3.10) of the two functions to
1341 // determine whether they are overloads. If we find any mismatch
1342 // in the signature, they are overloads.
1343
1344 // If either of these functions is a K&R-style function (no
1345 // prototype), then we consider them to have matching signatures.
1346 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1347 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1348 return false;
1349
1350 const auto *OldType = cast<FunctionProtoType>(OldQType);
1351 const auto *NewType = cast<FunctionProtoType>(NewQType);
1352
1353 // The signature of a function includes the types of its
1354 // parameters (C++ 1.3.10), which includes the presence or absence
1355 // of the ellipsis; see C++ DR 357).
1356 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1357 return true;
1358
1359 // For member-like friends, the enclosing class is part of the signature.
1360 if ((New->isMemberLikeConstrainedFriend() ||
1363 return true;
1364
1365 // Compare the parameter lists.
1366 // This can only be done once we have establish that friend functions
1367 // inhabit the same context, otherwise we might tried to instantiate
1368 // references to non-instantiated entities during constraint substitution.
1369 // GH78101.
1370 if (NewTemplate) {
1371 OldDecl = OldTemplate;
1372 NewDecl = NewTemplate;
1373 // C++ [temp.over.link]p4:
1374 // The signature of a function template consists of its function
1375 // signature, its return type and its template parameter list. The names
1376 // of the template parameters are significant only for establishing the
1377 // relationship between the template parameters and the rest of the
1378 // signature.
1379 //
1380 // We check the return type and template parameter lists for function
1381 // templates first; the remaining checks follow.
1382 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1383 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1384 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1385 bool SameReturnType = SemaRef.Context.hasSameType(
1387 // FIXME(GH58571): Match template parameter list even for non-constrained
1388 // template heads. This currently ensures that the code prior to C++20 is
1389 // not newly broken.
1390 bool ConstraintsInTemplateHead =
1393 // C++ [namespace.udecl]p11:
1394 // The set of declarations named by a using-declarator that inhabits a
1395 // class C does not include member functions and member function
1396 // templates of a base class that "correspond" to (and thus would
1397 // conflict with) a declaration of a function or function template in
1398 // C.
1399 // Comparing return types is not required for the "correspond" check to
1400 // decide whether a member introduced by a shadow declaration is hidden.
1401 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1402 !SameTemplateParameterList)
1403 return true;
1404 if (!UseMemberUsingDeclRules &&
1405 (!SameTemplateParameterList || !SameReturnType))
1406 return true;
1407 }
1408
1409 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1410 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1411
1412 int OldParamsOffset = 0;
1413 int NewParamsOffset = 0;
1414
1415 // When determining if a method is an overload from a base class, act as if
1416 // the implicit object parameter are of the same type.
1417
1418 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1420 auto ThisType = M->getFunctionObjectParameterReferenceType();
1421 if (ThisType.isConstQualified())
1422 Q.removeConst();
1423 return Q;
1424 }
1425
1426 // We do not allow overloading based off of '__restrict'.
1427 Q.removeRestrict();
1428
1429 // We may not have applied the implicit const for a constexpr member
1430 // function yet (because we haven't yet resolved whether this is a static
1431 // or non-static member function). Add it now, on the assumption that this
1432 // is a redeclaration of OldMethod.
1433 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1434 (M->isConstexpr() || M->isConsteval()) &&
1435 !isa<CXXConstructorDecl>(NewMethod))
1436 Q.addConst();
1437 return Q;
1438 };
1439
1440 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1441 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1442 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1443
1444 if (OldMethod->isExplicitObjectMemberFunction()) {
1445 BS.Quals.removeVolatile();
1446 DS.Quals.removeVolatile();
1447 }
1448
1449 return BS.Quals == DS.Quals;
1450 };
1451
1452 auto CompareType = [&](QualType Base, QualType D) {
1453 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1454 auto DS = D.getNonReferenceType().getCanonicalType().split();
1455
1456 if (!AreQualifiersEqual(BS, DS))
1457 return false;
1458
1459 if (OldMethod->isImplicitObjectMemberFunction() &&
1460 OldMethod->getParent() != NewMethod->getParent()) {
1461 QualType ParentType =
1462 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1463 .getCanonicalType();
1464 if (ParentType.getTypePtr() != BS.Ty)
1465 return false;
1466 BS.Ty = DS.Ty;
1467 }
1468
1469 // FIXME: should we ignore some type attributes here?
1470 if (BS.Ty != DS.Ty)
1471 return false;
1472
1473 if (Base->isLValueReferenceType())
1474 return D->isLValueReferenceType();
1475 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1476 };
1477
1478 // If the function is a class member, its signature includes the
1479 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1480 auto DiagnoseInconsistentRefQualifiers = [&]() {
1481 if (SemaRef.LangOpts.CPlusPlus23)
1482 return false;
1483 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1484 return false;
1485 if (OldMethod->isExplicitObjectMemberFunction() ||
1486 NewMethod->isExplicitObjectMemberFunction())
1487 return false;
1488 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1489 NewMethod->getRefQualifier() == RQ_None)) {
1490 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1491 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1492 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1493 return true;
1494 }
1495 return false;
1496 };
1497
1498 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1499 OldParamsOffset++;
1500 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1501 NewParamsOffset++;
1502
1503 if (OldType->getNumParams() - OldParamsOffset !=
1504 NewType->getNumParams() - NewParamsOffset ||
1506 {OldType->param_type_begin() + OldParamsOffset,
1507 OldType->param_type_end()},
1508 {NewType->param_type_begin() + NewParamsOffset,
1509 NewType->param_type_end()},
1510 nullptr)) {
1511 return true;
1512 }
1513
1514 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1515 !NewMethod->isStatic()) {
1516 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1517 const CXXMethodDecl *New) {
1518 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1519 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1520
1521 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1522 return F->getRefQualifier() == RQ_None &&
1523 !F->isExplicitObjectMemberFunction();
1524 };
1525
1526 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1527 CompareType(OldObjectType.getNonReferenceType(),
1528 NewObjectType.getNonReferenceType()))
1529 return true;
1530 return CompareType(OldObjectType, NewObjectType);
1531 }(OldMethod, NewMethod);
1532
1533 if (!HaveCorrespondingObjectParameters) {
1534 if (DiagnoseInconsistentRefQualifiers())
1535 return true;
1536 // CWG2554
1537 // and, if at least one is an explicit object member function, ignoring
1538 // object parameters
1539 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1540 !OldMethod->isExplicitObjectMemberFunction()))
1541 return true;
1542 }
1543 }
1544
1545 if (!UseOverrideRules &&
1547 Expr *NewRC = New->getTrailingRequiresClause(),
1548 *OldRC = Old->getTrailingRequiresClause();
1549 if ((NewRC != nullptr) != (OldRC != nullptr))
1550 return true;
1551 if (NewRC &&
1552 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1553 return true;
1554 }
1555
1556 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1557 NewMethod->isImplicitObjectMemberFunction()) {
1558 if (DiagnoseInconsistentRefQualifiers())
1559 return true;
1560 }
1561
1562 // Though pass_object_size is placed on parameters and takes an argument, we
1563 // consider it to be a function-level modifier for the sake of function
1564 // identity. Either the function has one or more parameters with
1565 // pass_object_size or it doesn't.
1568 return true;
1569
1570 // enable_if attributes are an order-sensitive part of the signature.
1572 NewI = New->specific_attr_begin<EnableIfAttr>(),
1573 NewE = New->specific_attr_end<EnableIfAttr>(),
1574 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1575 OldE = Old->specific_attr_end<EnableIfAttr>();
1576 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1577 if (NewI == NewE || OldI == OldE)
1578 return true;
1579 llvm::FoldingSetNodeID NewID, OldID;
1580 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1581 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1582 if (NewID != OldID)
1583 return true;
1584 }
1585
1586 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1587 // Don't allow overloading of destructors. (In theory we could, but it
1588 // would be a giant change to clang.)
1589 if (!isa<CXXDestructorDecl>(New)) {
1590 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1591 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1592 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1593 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1594 "Unexpected invalid target.");
1595
1596 // Allow overloading of functions with same signature and different CUDA
1597 // target attributes.
1598 if (NewTarget != OldTarget)
1599 return true;
1600 }
1601 }
1602 }
1603
1604 // The signatures match; this is not an overload.
1605 return false;
1606}
1607
1609 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1610 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1611 ConsiderCudaAttrs);
1612}
1613
1615 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1616 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1617 /*UseMemberUsingDeclRules=*/false,
1618 /*ConsiderCudaAttrs=*/true,
1619 /*UseOverrideRules=*/true);
1620}
1621
1622/// Tries a user-defined conversion from From to ToType.
1623///
1624/// Produces an implicit conversion sequence for when a standard conversion
1625/// is not an option. See TryImplicitConversion for more information.
1628 bool SuppressUserConversions,
1629 AllowedExplicit AllowExplicit,
1630 bool InOverloadResolution,
1631 bool CStyle,
1632 bool AllowObjCWritebackConversion,
1633 bool AllowObjCConversionOnExplicit) {
1635
1636 if (SuppressUserConversions) {
1637 // We're not in the case above, so there is no conversion that
1638 // we can perform.
1640 return ICS;
1641 }
1642
1643 // Attempt user-defined conversion.
1644 OverloadCandidateSet Conversions(From->getExprLoc(),
1646 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1647 Conversions, AllowExplicit,
1648 AllowObjCConversionOnExplicit)) {
1649 case OR_Success:
1650 case OR_Deleted:
1651 ICS.setUserDefined();
1652 // C++ [over.ics.user]p4:
1653 // A conversion of an expression of class type to the same class
1654 // type is given Exact Match rank, and a conversion of an
1655 // expression of class type to a base class of that type is
1656 // given Conversion rank, in spite of the fact that a copy
1657 // constructor (i.e., a user-defined conversion function) is
1658 // called for those cases.
1659 if (CXXConstructorDecl *Constructor
1660 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1661 QualType FromType;
1662 SourceLocation FromLoc;
1663 // C++11 [over.ics.list]p6, per DR2137:
1664 // C++17 [over.ics.list]p6:
1665 // If C is not an initializer-list constructor and the initializer list
1666 // has a single element of type cv U, where U is X or a class derived
1667 // from X, the implicit conversion sequence has Exact Match rank if U is
1668 // X, or Conversion rank if U is derived from X.
1669 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1670 InitList && InitList->getNumInits() == 1 &&
1671 !S.isInitListConstructor(Constructor)) {
1672 const Expr *SingleInit = InitList->getInit(0);
1673 FromType = SingleInit->getType();
1674 FromLoc = SingleInit->getBeginLoc();
1675 } else {
1676 FromType = From->getType();
1677 FromLoc = From->getBeginLoc();
1678 }
1679 QualType FromCanon =
1681 QualType ToCanon
1683 if ((FromCanon == ToCanon ||
1684 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1685 // Turn this into a "standard" conversion sequence, so that it
1686 // gets ranked with standard conversion sequences.
1688 ICS.setStandard();
1690 ICS.Standard.setFromType(FromType);
1691 ICS.Standard.setAllToTypes(ToType);
1692 ICS.Standard.CopyConstructor = Constructor;
1694 if (ToCanon != FromCanon)
1696 }
1697 }
1698 break;
1699
1700 case OR_Ambiguous:
1701 ICS.setAmbiguous();
1702 ICS.Ambiguous.setFromType(From->getType());
1703 ICS.Ambiguous.setToType(ToType);
1704 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1705 Cand != Conversions.end(); ++Cand)
1706 if (Cand->Best)
1707 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1708 break;
1709
1710 // Fall through.
1713 break;
1714 }
1715
1716 return ICS;
1717}
1718
1719/// TryImplicitConversion - Attempt to perform an implicit conversion
1720/// from the given expression (Expr) to the given type (ToType). This
1721/// function returns an implicit conversion sequence that can be used
1722/// to perform the initialization. Given
1723///
1724/// void f(float f);
1725/// void g(int i) { f(i); }
1726///
1727/// this routine would produce an implicit conversion sequence to
1728/// describe the initialization of f from i, which will be a standard
1729/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1730/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1731//
1732/// Note that this routine only determines how the conversion can be
1733/// performed; it does not actually perform the conversion. As such,
1734/// it will not produce any diagnostics if no conversion is available,
1735/// but will instead return an implicit conversion sequence of kind
1736/// "BadConversion".
1737///
1738/// If @p SuppressUserConversions, then user-defined conversions are
1739/// not permitted.
1740/// If @p AllowExplicit, then explicit user-defined conversions are
1741/// permitted.
1742///
1743/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1744/// writeback conversion, which allows __autoreleasing id* parameters to
1745/// be initialized with __strong id* or __weak id* arguments.
1748 bool SuppressUserConversions,
1749 AllowedExplicit AllowExplicit,
1750 bool InOverloadResolution,
1751 bool CStyle,
1752 bool AllowObjCWritebackConversion,
1753 bool AllowObjCConversionOnExplicit) {
1755 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1756 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1757 ICS.setStandard();
1758 return ICS;
1759 }
1760
1761 if (!S.getLangOpts().CPlusPlus) {
1763 return ICS;
1764 }
1765
1766 // C++ [over.ics.user]p4:
1767 // A conversion of an expression of class type to the same class
1768 // type is given Exact Match rank, and a conversion of an
1769 // expression of class type to a base class of that type is
1770 // given Conversion rank, in spite of the fact that a copy/move
1771 // constructor (i.e., a user-defined conversion function) is
1772 // called for those cases.
1773 QualType FromType = From->getType();
1774 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1775 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1776 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1777 ICS.setStandard();
1779 ICS.Standard.setFromType(FromType);
1780 ICS.Standard.setAllToTypes(ToType);
1781
1782 // We don't actually check at this point whether there is a valid
1783 // copy/move constructor, since overloading just assumes that it
1784 // exists. When we actually perform initialization, we'll find the
1785 // appropriate constructor to copy the returned object, if needed.
1786 ICS.Standard.CopyConstructor = nullptr;
1787
1788 // Determine whether this is considered a derived-to-base conversion.
1789 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1791
1792 return ICS;
1793 }
1794
1795 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1796 FromType->isHLSLAttributedResourceType()) {
1797 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1798 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1799 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1800 FromResType->getWrappedType()) &&
1801 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1802 FromResType->getContainedType()) &&
1803 ToResType->getAttrs() == FromResType->getAttrs()) {
1804 ICS.setStandard();
1806 ICS.Standard.setFromType(FromType);
1807 ICS.Standard.setAllToTypes(ToType);
1808 return ICS;
1809 }
1810 }
1811
1812 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1813 AllowExplicit, InOverloadResolution, CStyle,
1814 AllowObjCWritebackConversion,
1815 AllowObjCConversionOnExplicit);
1816}
1817
1820 bool SuppressUserConversions,
1821 AllowedExplicit AllowExplicit,
1822 bool InOverloadResolution,
1823 bool CStyle,
1824 bool AllowObjCWritebackConversion) {
1825 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1826 AllowExplicit, InOverloadResolution, CStyle,
1827 AllowObjCWritebackConversion,
1828 /*AllowObjCConversionOnExplicit=*/false);
1829}
1830
1832 AssignmentAction Action,
1833 bool AllowExplicit) {
1834 if (checkPlaceholderForOverload(*this, From))
1835 return ExprError();
1836
1837 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1838 bool AllowObjCWritebackConversion =
1839 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1840 Action == AssignmentAction::Sending);
1841 if (getLangOpts().ObjC)
1842 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1843 From->getType(), From);
1845 *this, From, ToType,
1846 /*SuppressUserConversions=*/false,
1847 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1848 /*InOverloadResolution=*/false,
1849 /*CStyle=*/false, AllowObjCWritebackConversion,
1850 /*AllowObjCConversionOnExplicit=*/false);
1851 return PerformImplicitConversion(From, ToType, ICS, Action);
1852}
1853
1855 QualType &ResultTy) {
1856 if (Context.hasSameUnqualifiedType(FromType, ToType))
1857 return false;
1858
1859 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1860 // or F(t noexcept) -> F(t)
1861 // where F adds one of the following at most once:
1862 // - a pointer
1863 // - a member pointer
1864 // - a block pointer
1865 // Changes here need matching changes in FindCompositePointerType.
1866 CanQualType CanTo = Context.getCanonicalType(ToType);
1867 CanQualType CanFrom = Context.getCanonicalType(FromType);
1868 Type::TypeClass TyClass = CanTo->getTypeClass();
1869 if (TyClass != CanFrom->getTypeClass()) return false;
1870 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1871 if (TyClass == Type::Pointer) {
1872 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1873 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1874 } else if (TyClass == Type::BlockPointer) {
1875 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1876 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1877 } else if (TyClass == Type::MemberPointer) {
1878 auto ToMPT = CanTo.castAs<MemberPointerType>();
1879 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1880 // A function pointer conversion cannot change the class of the function.
1881 if (ToMPT->getClass() != FromMPT->getClass())
1882 return false;
1883 CanTo = ToMPT->getPointeeType();
1884 CanFrom = FromMPT->getPointeeType();
1885 } else {
1886 return false;
1887 }
1888
1889 TyClass = CanTo->getTypeClass();
1890 if (TyClass != CanFrom->getTypeClass()) return false;
1891 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1892 return false;
1893 }
1894
1895 const auto *FromFn = cast<FunctionType>(CanFrom);
1896 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1897
1898 const auto *ToFn = cast<FunctionType>(CanTo);
1899 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1900
1901 bool Changed = false;
1902
1903 // Drop 'noreturn' if not present in target type.
1904 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1905 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1906 Changed = true;
1907 }
1908
1909 // Drop 'noexcept' if not present in target type.
1910 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1911 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1912 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1913 FromFn = cast<FunctionType>(
1914 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1915 EST_None)
1916 .getTypePtr());
1917 Changed = true;
1918 }
1919
1920 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1921 // only if the ExtParameterInfo lists of the two function prototypes can be
1922 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1924 bool CanUseToFPT, CanUseFromFPT;
1925 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1926 CanUseFromFPT, NewParamInfos) &&
1927 CanUseToFPT && !CanUseFromFPT) {
1928 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1929 ExtInfo.ExtParameterInfos =
1930 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1931 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1932 FromFPT->getParamTypes(), ExtInfo);
1933 FromFn = QT->getAs<FunctionType>();
1934 Changed = true;
1935 }
1936
1937 // For C, when called from checkPointerTypesForAssignment,
1938 // we need to not alter FromFn, or else even an innocuous cast
1939 // like dropping effects will fail. In C++ however we do want to
1940 // alter FromFn (because of the way PerformImplicitConversion works).
1941 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1942 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1943
1944 // Transparently add/drop effects; here we are concerned with
1945 // language rules/canonicalization. Adding/dropping effects is a warning.
1946 const auto FromFX = FromFPT->getFunctionEffects();
1947 const auto ToFX = ToFPT->getFunctionEffects();
1948 if (FromFX != ToFX) {
1949 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1950 ExtInfo.FunctionEffects = ToFX;
1951 QualType QT = Context.getFunctionType(
1952 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1953 FromFn = QT->getAs<FunctionType>();
1954 Changed = true;
1955 }
1956 }
1957 }
1958
1959 if (!Changed)
1960 return false;
1961
1962 assert(QualType(FromFn, 0).isCanonical());
1963 if (QualType(FromFn, 0) != CanTo) return false;
1964
1965 ResultTy = ToType;
1966 return true;
1967}
1968
1969/// Determine whether the conversion from FromType to ToType is a valid
1970/// floating point conversion.
1971///
1972static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1973 QualType ToType) {
1974 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1975 return false;
1976 // FIXME: disable conversions between long double, __ibm128 and __float128
1977 // if their representation is different until there is back end support
1978 // We of course allow this conversion if long double is really double.
1979
1980 // Conversions between bfloat16 and float16 are currently not supported.
1981 if ((FromType->isBFloat16Type() &&
1982 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1983 (ToType->isBFloat16Type() &&
1984 (FromType->isFloat16Type() || FromType->isHalfType())))
1985 return false;
1986
1987 // Conversions between IEEE-quad and IBM-extended semantics are not
1988 // permitted.
1989 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1990 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1991 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1992 &ToSem == &llvm::APFloat::IEEEquad()) ||
1993 (&FromSem == &llvm::APFloat::IEEEquad() &&
1994 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1995 return false;
1996 return true;
1997}
1998
1999static bool IsVectorElementConversion(Sema &S, QualType FromType,
2000 QualType ToType,
2001 ImplicitConversionKind &ICK, Expr *From) {
2002 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2003 return true;
2004
2005 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2007 return true;
2008 }
2009
2010 if (IsFloatingPointConversion(S, FromType, ToType)) {
2012 return true;
2013 }
2014
2015 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2017 return true;
2018 }
2019
2020 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2022 ToType->isRealFloatingType())) {
2024 return true;
2025 }
2026
2027 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2029 return true;
2030 }
2031
2032 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2033 ToType->isIntegralType(S.Context)) {
2035 return true;
2036 }
2037
2038 return false;
2039}
2040
2041/// Determine whether the conversion from FromType to ToType is a valid
2042/// vector conversion.
2043///
2044/// \param ICK Will be set to the vector conversion kind, if this is a vector
2045/// conversion.
2046static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2048 ImplicitConversionKind &ElConv, Expr *From,
2049 bool InOverloadResolution, bool CStyle) {
2050 // We need at least one of these types to be a vector type to have a vector
2051 // conversion.
2052 if (!ToType->isVectorType() && !FromType->isVectorType())
2053 return false;
2054
2055 // Identical types require no conversions.
2056 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2057 return false;
2058
2059 // HLSL allows implicit truncation of vector types.
2060 if (S.getLangOpts().HLSL) {
2061 auto *ToExtType = ToType->getAs<ExtVectorType>();
2062 auto *FromExtType = FromType->getAs<ExtVectorType>();
2063
2064 // If both arguments are vectors, handle possible vector truncation and
2065 // element conversion.
2066 if (ToExtType && FromExtType) {
2067 unsigned FromElts = FromExtType->getNumElements();
2068 unsigned ToElts = ToExtType->getNumElements();
2069 if (FromElts < ToElts)
2070 return false;
2071 if (FromElts == ToElts)
2072 ElConv = ICK_Identity;
2073 else
2075
2076 QualType FromElTy = FromExtType->getElementType();
2077 QualType ToElTy = ToExtType->getElementType();
2078 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2079 return true;
2080 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2081 }
2082 if (FromExtType && !ToExtType) {
2084 QualType FromElTy = FromExtType->getElementType();
2085 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2086 return true;
2087 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2088 }
2089 // Fallthrough for the case where ToType is a vector and FromType is not.
2090 }
2091
2092 // There are no conversions between extended vector types, only identity.
2093 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2094 if (FromType->getAs<ExtVectorType>()) {
2095 // There are no conversions between extended vector types other than the
2096 // identity conversion.
2097 return false;
2098 }
2099
2100 // Vector splat from any arithmetic type to a vector.
2101 if (FromType->isArithmeticType()) {
2102 if (S.getLangOpts().HLSL) {
2103 ElConv = ICK_HLSL_Vector_Splat;
2104 QualType ToElTy = ToExtType->getElementType();
2105 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2106 }
2107 ICK = ICK_Vector_Splat;
2108 return true;
2109 }
2110 }
2111
2112 if (ToType->isSVESizelessBuiltinType() ||
2113 FromType->isSVESizelessBuiltinType())
2114 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2115 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2117 return true;
2118 }
2119
2120 if (ToType->isRVVSizelessBuiltinType() ||
2121 FromType->isRVVSizelessBuiltinType())
2122 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2123 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2125 return true;
2126 }
2127
2128 // We can perform the conversion between vector types in the following cases:
2129 // 1)vector types are equivalent AltiVec and GCC vector types
2130 // 2)lax vector conversions are permitted and the vector types are of the
2131 // same size
2132 // 3)the destination type does not have the ARM MVE strict-polymorphism
2133 // attribute, which inhibits lax vector conversion for overload resolution
2134 // only
2135 if (ToType->isVectorType() && FromType->isVectorType()) {
2136 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2137 (S.isLaxVectorConversion(FromType, ToType) &&
2138 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2139 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2140 S.isLaxVectorConversion(FromType, ToType) &&
2141 S.anyAltivecTypes(FromType, ToType) &&
2142 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2143 !InOverloadResolution && !CStyle) {
2144 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2145 << FromType << ToType;
2146 }
2148 return true;
2149 }
2150 }
2151
2152 return false;
2153}
2154
2155static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2156 bool InOverloadResolution,
2158 bool CStyle);
2159
2160/// IsStandardConversion - Determines whether there is a standard
2161/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2162/// expression From to the type ToType. Standard conversion sequences
2163/// only consider non-class types; for conversions that involve class
2164/// types, use TryImplicitConversion. If a conversion exists, SCS will
2165/// contain the standard conversion sequence required to perform this
2166/// conversion and this routine will return true. Otherwise, this
2167/// routine will return false and the value of SCS is unspecified.
2168static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2169 bool InOverloadResolution,
2171 bool CStyle,
2172 bool AllowObjCWritebackConversion) {
2173 QualType FromType = From->getType();
2174
2175 // Standard conversions (C++ [conv])
2177 SCS.IncompatibleObjC = false;
2178 SCS.setFromType(FromType);
2179 SCS.CopyConstructor = nullptr;
2180
2181 // There are no standard conversions for class types in C++, so
2182 // abort early. When overloading in C, however, we do permit them.
2183 if (S.getLangOpts().CPlusPlus &&
2184 (FromType->isRecordType() || ToType->isRecordType()))
2185 return false;
2186
2187 // The first conversion can be an lvalue-to-rvalue conversion,
2188 // array-to-pointer conversion, or function-to-pointer conversion
2189 // (C++ 4p1).
2190
2191 if (FromType == S.Context.OverloadTy) {
2192 DeclAccessPair AccessPair;
2193 if (FunctionDecl *Fn
2194 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2195 AccessPair)) {
2196 // We were able to resolve the address of the overloaded function,
2197 // so we can convert to the type of that function.
2198 FromType = Fn->getType();
2199 SCS.setFromType(FromType);
2200
2201 // we can sometimes resolve &foo<int> regardless of ToType, so check
2202 // if the type matches (identity) or we are converting to bool
2204 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2205 QualType resultTy;
2206 // if the function type matches except for [[noreturn]], it's ok
2207 if (!S.IsFunctionConversion(FromType,
2208 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2209 // otherwise, only a boolean conversion is standard
2210 if (!ToType->isBooleanType())
2211 return false;
2212 }
2213
2214 // Check if the "from" expression is taking the address of an overloaded
2215 // function and recompute the FromType accordingly. Take advantage of the
2216 // fact that non-static member functions *must* have such an address-of
2217 // expression.
2218 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2219 if (Method && !Method->isStatic() &&
2220 !Method->isExplicitObjectMemberFunction()) {
2221 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2222 "Non-unary operator on non-static member address");
2223 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2224 == UO_AddrOf &&
2225 "Non-address-of operator on non-static member address");
2226 const Type *ClassType
2228 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2229 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2230 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2231 UO_AddrOf &&
2232 "Non-address-of operator for overloaded function expression");
2233 FromType = S.Context.getPointerType(FromType);
2234 }
2235 } else {
2236 return false;
2237 }
2238 }
2239
2240 bool argIsLValue = From->isGLValue();
2241 // To handle conversion from ArrayParameterType to ConstantArrayType
2242 // this block must be above the one below because Array parameters
2243 // do not decay and when handling HLSLOutArgExprs and
2244 // the From expression is an LValue.
2245 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2246 ToType->isConstantArrayType()) {
2247 // HLSL constant array parameters do not decay, so if the argument is a
2248 // constant array and the parameter is an ArrayParameterType we have special
2249 // handling here.
2250 if (ToType->isArrayParameterType()) {
2251 FromType = S.Context.getArrayParameterType(FromType);
2253 } else if (FromType->isArrayParameterType()) {
2254 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2255 FromType = APT->getConstantArrayType(S.Context);
2257 } else {
2258 SCS.First = ICK_Identity;
2259 }
2260
2261 if (S.Context.getCanonicalType(FromType) !=
2262 S.Context.getCanonicalType(ToType))
2263 return false;
2264
2265 SCS.setAllToTypes(ToType);
2266 return true;
2267 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2268 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2269 // Lvalue-to-rvalue conversion (C++11 4.1):
2270 // A glvalue (3.10) of a non-function, non-array type T can
2271 // be converted to a prvalue.
2272
2274
2275 // C11 6.3.2.1p2:
2276 // ... if the lvalue has atomic type, the value has the non-atomic version
2277 // of the type of the lvalue ...
2278 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2279 FromType = Atomic->getValueType();
2280
2281 // If T is a non-class type, the type of the rvalue is the
2282 // cv-unqualified version of T. Otherwise, the type of the rvalue
2283 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2284 // just strip the qualifiers because they don't matter.
2285 FromType = FromType.getUnqualifiedType();
2286 } else if (FromType->isArrayType()) {
2287 // Array-to-pointer conversion (C++ 4.2)
2289
2290 // An lvalue or rvalue of type "array of N T" or "array of unknown
2291 // bound of T" can be converted to an rvalue of type "pointer to
2292 // T" (C++ 4.2p1).
2293 FromType = S.Context.getArrayDecayedType(FromType);
2294
2295 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2296 // This conversion is deprecated in C++03 (D.4)
2298
2299 // For the purpose of ranking in overload resolution
2300 // (13.3.3.1.1), this conversion is considered an
2301 // array-to-pointer conversion followed by a qualification
2302 // conversion (4.4). (C++ 4.2p2)
2303 SCS.Second = ICK_Identity;
2306 SCS.setAllToTypes(FromType);
2307 return true;
2308 }
2309 } else if (FromType->isFunctionType() && argIsLValue) {
2310 // Function-to-pointer conversion (C++ 4.3).
2312
2313 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2314 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2316 return false;
2317
2318 // An lvalue of function type T can be converted to an rvalue of
2319 // type "pointer to T." The result is a pointer to the
2320 // function. (C++ 4.3p1).
2321 FromType = S.Context.getPointerType(FromType);
2322 } else {
2323 // We don't require any conversions for the first step.
2324 SCS.First = ICK_Identity;
2325 }
2326 SCS.setToType(0, FromType);
2327
2328 // The second conversion can be an integral promotion, floating
2329 // point promotion, integral conversion, floating point conversion,
2330 // floating-integral conversion, pointer conversion,
2331 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2332 // For overloading in C, this can also be a "compatible-type"
2333 // conversion.
2334 bool IncompatibleObjC = false;
2336 ImplicitConversionKind DimensionICK = ICK_Identity;
2337 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2338 // The unqualified versions of the types are the same: there's no
2339 // conversion to do.
2340 SCS.Second = ICK_Identity;
2341 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2342 // Integral promotion (C++ 4.5).
2344 FromType = ToType.getUnqualifiedType();
2345 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2346 // Floating point promotion (C++ 4.6).
2348 FromType = ToType.getUnqualifiedType();
2349 } else if (S.IsComplexPromotion(FromType, ToType)) {
2350 // Complex promotion (Clang extension)
2352 FromType = ToType.getUnqualifiedType();
2353 } else if (ToType->isBooleanType() &&
2354 (FromType->isArithmeticType() ||
2355 FromType->isAnyPointerType() ||
2356 FromType->isBlockPointerType() ||
2357 FromType->isMemberPointerType())) {
2358 // Boolean conversions (C++ 4.12).
2360 FromType = S.Context.BoolTy;
2361 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2362 ToType->isIntegralType(S.Context)) {
2363 // Integral conversions (C++ 4.7).
2365 FromType = ToType.getUnqualifiedType();
2366 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2367 // Complex conversions (C99 6.3.1.6)
2369 FromType = ToType.getUnqualifiedType();
2370 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2371 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2372 // Complex-real conversions (C99 6.3.1.7)
2374 FromType = ToType.getUnqualifiedType();
2375 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2376 // Floating point conversions (C++ 4.8).
2378 FromType = ToType.getUnqualifiedType();
2379 } else if ((FromType->isRealFloatingType() &&
2380 ToType->isIntegralType(S.Context)) ||
2382 ToType->isRealFloatingType())) {
2383
2384 // Floating-integral conversions (C++ 4.9).
2386 FromType = ToType.getUnqualifiedType();
2387 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2389 } else if (AllowObjCWritebackConversion &&
2390 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2392 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2393 FromType, IncompatibleObjC)) {
2394 // Pointer conversions (C++ 4.10).
2396 SCS.IncompatibleObjC = IncompatibleObjC;
2397 FromType = FromType.getUnqualifiedType();
2398 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2399 InOverloadResolution, FromType)) {
2400 // Pointer to member conversions (4.11).
2402 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2403 From, InOverloadResolution, CStyle)) {
2404 SCS.Second = SecondICK;
2405 SCS.Dimension = DimensionICK;
2406 FromType = ToType.getUnqualifiedType();
2407 } else if (!S.getLangOpts().CPlusPlus &&
2408 S.Context.typesAreCompatible(ToType, FromType)) {
2409 // Compatible conversions (Clang extension for C function overloading)
2411 FromType = ToType.getUnqualifiedType();
2413 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2415 FromType = ToType;
2416 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2417 CStyle)) {
2418 // tryAtomicConversion has updated the standard conversion sequence
2419 // appropriately.
2420 return true;
2421 } else if (ToType->isEventT() &&
2423 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2425 FromType = ToType;
2426 } else if (ToType->isQueueT() &&
2428 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2430 FromType = ToType;
2431 } else if (ToType->isSamplerT() &&
2434 FromType = ToType;
2435 } else if ((ToType->isFixedPointType() &&
2436 FromType->isConvertibleToFixedPointType()) ||
2437 (FromType->isFixedPointType() &&
2438 ToType->isConvertibleToFixedPointType())) {
2440 FromType = ToType;
2441 } else {
2442 // No second conversion required.
2443 SCS.Second = ICK_Identity;
2444 }
2445 SCS.setToType(1, FromType);
2446
2447 // The third conversion can be a function pointer conversion or a
2448 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2449 bool ObjCLifetimeConversion;
2450 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2451 // Function pointer conversions (removing 'noexcept') including removal of
2452 // 'noreturn' (Clang extension).
2454 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2455 ObjCLifetimeConversion)) {
2457 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2458 FromType = ToType;
2459 } else {
2460 // No conversion required
2461 SCS.Third = ICK_Identity;
2462 }
2463
2464 // C++ [over.best.ics]p6:
2465 // [...] Any difference in top-level cv-qualification is
2466 // subsumed by the initialization itself and does not constitute
2467 // a conversion. [...]
2468 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2469 QualType CanonTo = S.Context.getCanonicalType(ToType);
2470 if (CanonFrom.getLocalUnqualifiedType()
2471 == CanonTo.getLocalUnqualifiedType() &&
2472 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2473 FromType = ToType;
2474 CanonFrom = CanonTo;
2475 }
2476
2477 SCS.setToType(2, FromType);
2478
2479 if (CanonFrom == CanonTo)
2480 return true;
2481
2482 // If we have not converted the argument type to the parameter type,
2483 // this is a bad conversion sequence, unless we're resolving an overload in C.
2484 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2485 return false;
2486
2487 ExprResult ER = ExprResult{From};
2490 /*Diagnose=*/false,
2491 /*DiagnoseCFAudited=*/false,
2492 /*ConvertRHS=*/false);
2493 ImplicitConversionKind SecondConv;
2494 switch (Conv) {
2495 case Sema::Compatible:
2496 SecondConv = ICK_C_Only_Conversion;
2497 break;
2498 // For our purposes, discarding qualifiers is just as bad as using an
2499 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2500 // qualifiers, as well.
2505 break;
2506 default:
2507 return false;
2508 }
2509
2510 // First can only be an lvalue conversion, so we pretend that this was the
2511 // second conversion. First should already be valid from earlier in the
2512 // function.
2513 SCS.Second = SecondConv;
2514 SCS.setToType(1, ToType);
2515
2516 // Third is Identity, because Second should rank us worse than any other
2517 // conversion. This could also be ICK_Qualification, but it's simpler to just
2518 // lump everything in with the second conversion, and we don't gain anything
2519 // from making this ICK_Qualification.
2520 SCS.Third = ICK_Identity;
2521 SCS.setToType(2, ToType);
2522 return true;
2523}
2524
2525static bool
2527 QualType &ToType,
2528 bool InOverloadResolution,
2530 bool CStyle) {
2531
2532 const RecordType *UT = ToType->getAsUnionType();
2533 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2534 return false;
2535 // The field to initialize within the transparent union.
2536 RecordDecl *UD = UT->getDecl();
2537 // It's compatible if the expression matches any of the fields.
2538 for (const auto *it : UD->fields()) {
2539 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2540 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2541 ToType = it->getType();
2542 return true;
2543 }
2544 }
2545 return false;
2546}
2547
2548bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2549 const BuiltinType *To = ToType->getAs<BuiltinType>();
2550 // All integers are built-in.
2551 if (!To) {
2552 return false;
2553 }
2554
2555 // An rvalue of type char, signed char, unsigned char, short int, or
2556 // unsigned short int can be converted to an rvalue of type int if
2557 // int can represent all the values of the source type; otherwise,
2558 // the source rvalue can be converted to an rvalue of type unsigned
2559 // int (C++ 4.5p1).
2560 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2561 !FromType->isEnumeralType()) {
2562 if ( // We can promote any signed, promotable integer type to an int
2563 (FromType->isSignedIntegerType() ||
2564 // We can promote any unsigned integer type whose size is
2565 // less than int to an int.
2566 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2567 return To->getKind() == BuiltinType::Int;
2568 }
2569
2570 return To->getKind() == BuiltinType::UInt;
2571 }
2572
2573 // C++11 [conv.prom]p3:
2574 // A prvalue of an unscoped enumeration type whose underlying type is not
2575 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2576 // following types that can represent all the values of the enumeration
2577 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2578 // unsigned int, long int, unsigned long int, long long int, or unsigned
2579 // long long int. If none of the types in that list can represent all the
2580 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2581 // type can be converted to an rvalue a prvalue of the extended integer type
2582 // with lowest integer conversion rank (4.13) greater than the rank of long
2583 // long in which all the values of the enumeration can be represented. If
2584 // there are two such extended types, the signed one is chosen.
2585 // C++11 [conv.prom]p4:
2586 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2587 // can be converted to a prvalue of its underlying type. Moreover, if
2588 // integral promotion can be applied to its underlying type, a prvalue of an
2589 // unscoped enumeration type whose underlying type is fixed can also be
2590 // converted to a prvalue of the promoted underlying type.
2591 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2592 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2593 // provided for a scoped enumeration.
2594 if (FromEnumType->getDecl()->isScoped())
2595 return false;
2596
2597 // We can perform an integral promotion to the underlying type of the enum,
2598 // even if that's not the promoted type. Note that the check for promoting
2599 // the underlying type is based on the type alone, and does not consider
2600 // the bitfield-ness of the actual source expression.
2601 if (FromEnumType->getDecl()->isFixed()) {
2602 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2603 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2604 IsIntegralPromotion(nullptr, Underlying, ToType);
2605 }
2606
2607 // We have already pre-calculated the promotion type, so this is trivial.
2608 if (ToType->isIntegerType() &&
2609 isCompleteType(From->getBeginLoc(), FromType))
2610 return Context.hasSameUnqualifiedType(
2611 ToType, FromEnumType->getDecl()->getPromotionType());
2612
2613 // C++ [conv.prom]p5:
2614 // If the bit-field has an enumerated type, it is treated as any other
2615 // value of that type for promotion purposes.
2616 //
2617 // ... so do not fall through into the bit-field checks below in C++.
2618 if (getLangOpts().CPlusPlus)
2619 return false;
2620 }
2621
2622 // C++0x [conv.prom]p2:
2623 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2624 // to an rvalue a prvalue of the first of the following types that can
2625 // represent all the values of its underlying type: int, unsigned int,
2626 // long int, unsigned long int, long long int, or unsigned long long int.
2627 // If none of the types in that list can represent all the values of its
2628 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2629 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2630 // type.
2631 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2632 ToType->isIntegerType()) {
2633 // Determine whether the type we're converting from is signed or
2634 // unsigned.
2635 bool FromIsSigned = FromType->isSignedIntegerType();
2636 uint64_t FromSize = Context.getTypeSize(FromType);
2637
2638 // The types we'll try to promote to, in the appropriate
2639 // order. Try each of these types.
2640 QualType PromoteTypes[6] = {
2641 Context.IntTy, Context.UnsignedIntTy,
2642 Context.LongTy, Context.UnsignedLongTy ,
2643 Context.LongLongTy, Context.UnsignedLongLongTy
2644 };
2645 for (int Idx = 0; Idx < 6; ++Idx) {
2646 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2647 if (FromSize < ToSize ||
2648 (FromSize == ToSize &&
2649 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2650 // We found the type that we can promote to. If this is the
2651 // type we wanted, we have a promotion. Otherwise, no
2652 // promotion.
2653 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2654 }
2655 }
2656 }
2657
2658 // An rvalue for an integral bit-field (9.6) can be converted to an
2659 // rvalue of type int if int can represent all the values of the
2660 // bit-field; otherwise, it can be converted to unsigned int if
2661 // unsigned int can represent all the values of the bit-field. If
2662 // the bit-field is larger yet, no integral promotion applies to
2663 // it. If the bit-field has an enumerated type, it is treated as any
2664 // other value of that type for promotion purposes (C++ 4.5p3).
2665 // FIXME: We should delay checking of bit-fields until we actually perform the
2666 // conversion.
2667 //
2668 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2669 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2670 // bit-fields and those whose underlying type is larger than int) for GCC
2671 // compatibility.
2672 if (From) {
2673 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2674 std::optional<llvm::APSInt> BitWidth;
2675 if (FromType->isIntegralType(Context) &&
2676 (BitWidth =
2677 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2678 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2679 ToSize = Context.getTypeSize(ToType);
2680
2681 // Are we promoting to an int from a bitfield that fits in an int?
2682 if (*BitWidth < ToSize ||
2683 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2684 return To->getKind() == BuiltinType::Int;
2685 }
2686
2687 // Are we promoting to an unsigned int from an unsigned bitfield
2688 // that fits into an unsigned int?
2689 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2690 return To->getKind() == BuiltinType::UInt;
2691 }
2692
2693 return false;
2694 }
2695 }
2696 }
2697
2698 // An rvalue of type bool can be converted to an rvalue of type int,
2699 // with false becoming zero and true becoming one (C++ 4.5p4).
2700 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2701 return true;
2702 }
2703
2704 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2705 // integral type.
2706 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2707 ToType->isIntegerType())
2708 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2709
2710 return false;
2711}
2712
2714 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2715 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2716 /// An rvalue of type float can be converted to an rvalue of type
2717 /// double. (C++ 4.6p1).
2718 if (FromBuiltin->getKind() == BuiltinType::Float &&
2719 ToBuiltin->getKind() == BuiltinType::Double)
2720 return true;
2721
2722 // C99 6.3.1.5p1:
2723 // When a float is promoted to double or long double, or a
2724 // double is promoted to long double [...].
2725 if (!getLangOpts().CPlusPlus &&
2726 (FromBuiltin->getKind() == BuiltinType::Float ||
2727 FromBuiltin->getKind() == BuiltinType::Double) &&
2728 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2729 ToBuiltin->getKind() == BuiltinType::Float128 ||
2730 ToBuiltin->getKind() == BuiltinType::Ibm128))
2731 return true;
2732
2733 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2734 // or not native half types are enabled.
2735 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2736 (ToBuiltin->getKind() == BuiltinType::Float ||
2737 ToBuiltin->getKind() == BuiltinType::Double))
2738 return true;
2739
2740 // Half can be promoted to float.
2741 if (!getLangOpts().NativeHalfType &&
2742 FromBuiltin->getKind() == BuiltinType::Half &&
2743 ToBuiltin->getKind() == BuiltinType::Float)
2744 return true;
2745 }
2746
2747 return false;
2748}
2749
2751 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2752 if (!FromComplex)
2753 return false;
2754
2755 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2756 if (!ToComplex)
2757 return false;
2758
2759 return IsFloatingPointPromotion(FromComplex->getElementType(),
2760 ToComplex->getElementType()) ||
2761 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2762 ToComplex->getElementType());
2763}
2764
2765/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2766/// the pointer type FromPtr to a pointer to type ToPointee, with the
2767/// same type qualifiers as FromPtr has on its pointee type. ToType,
2768/// if non-empty, will be a pointer to ToType that may or may not have
2769/// the right set of qualifiers on its pointee.
2770///
2771static QualType
2773 QualType ToPointee, QualType ToType,
2774 ASTContext &Context,
2775 bool StripObjCLifetime = false) {
2776 assert((FromPtr->getTypeClass() == Type::Pointer ||
2777 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2778 "Invalid similarly-qualified pointer type");
2779
2780 /// Conversions to 'id' subsume cv-qualifier conversions.
2781 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2782 return ToType.getUnqualifiedType();
2783
2784 QualType CanonFromPointee
2785 = Context.getCanonicalType(FromPtr->getPointeeType());
2786 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2787 Qualifiers Quals = CanonFromPointee.getQualifiers();
2788
2789 if (StripObjCLifetime)
2790 Quals.removeObjCLifetime();
2791
2792 // Exact qualifier match -> return the pointer type we're converting to.
2793 if (CanonToPointee.getLocalQualifiers() == Quals) {
2794 // ToType is exactly what we need. Return it.
2795 if (!ToType.isNull())
2796 return ToType.getUnqualifiedType();
2797
2798 // Build a pointer to ToPointee. It has the right qualifiers
2799 // already.
2800 if (isa<ObjCObjectPointerType>(ToType))
2801 return Context.getObjCObjectPointerType(ToPointee);
2802 return Context.getPointerType(ToPointee);
2803 }
2804
2805 // Just build a canonical type that has the right qualifiers.
2806 QualType QualifiedCanonToPointee
2807 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2808
2809 if (isa<ObjCObjectPointerType>(ToType))
2810 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2811 return Context.getPointerType(QualifiedCanonToPointee);
2812}
2813
2815 bool InOverloadResolution,
2816 ASTContext &Context) {
2817 // Handle value-dependent integral null pointer constants correctly.
2818 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2819 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2821 return !InOverloadResolution;
2822
2823 return Expr->isNullPointerConstant(Context,
2824 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2826}
2827
2829 bool InOverloadResolution,
2830 QualType& ConvertedType,
2831 bool &IncompatibleObjC) {
2832 IncompatibleObjC = false;
2833 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2834 IncompatibleObjC))
2835 return true;
2836
2837 // Conversion from a null pointer constant to any Objective-C pointer type.
2838 if (ToType->isObjCObjectPointerType() &&
2839 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2840 ConvertedType = ToType;
2841 return true;
2842 }
2843
2844 // Blocks: Block pointers can be converted to void*.
2845 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2846 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2847 ConvertedType = ToType;
2848 return true;
2849 }
2850 // Blocks: A null pointer constant can be converted to a block
2851 // pointer type.
2852 if (ToType->isBlockPointerType() &&
2853 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2854 ConvertedType = ToType;
2855 return true;
2856 }
2857
2858 // If the left-hand-side is nullptr_t, the right side can be a null
2859 // pointer constant.
2860 if (ToType->isNullPtrType() &&
2861 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2862 ConvertedType = ToType;
2863 return true;
2864 }
2865
2866 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2867 if (!ToTypePtr)
2868 return false;
2869
2870 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2871 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2872 ConvertedType = ToType;
2873 return true;
2874 }
2875
2876 // Beyond this point, both types need to be pointers
2877 // , including objective-c pointers.
2878 QualType ToPointeeType = ToTypePtr->getPointeeType();
2879 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2880 !getLangOpts().ObjCAutoRefCount) {
2881 ConvertedType = BuildSimilarlyQualifiedPointerType(
2882 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2883 Context);
2884 return true;
2885 }
2886 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2887 if (!FromTypePtr)
2888 return false;
2889
2890 QualType FromPointeeType = FromTypePtr->getPointeeType();
2891
2892 // If the unqualified pointee types are the same, this can't be a
2893 // pointer conversion, so don't do all of the work below.
2894 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2895 return false;
2896
2897 // An rvalue of type "pointer to cv T," where T is an object type,
2898 // can be converted to an rvalue of type "pointer to cv void" (C++
2899 // 4.10p2).
2900 if (FromPointeeType->isIncompleteOrObjectType() &&
2901 ToPointeeType->isVoidType()) {
2902 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2903 ToPointeeType,
2904 ToType, Context,
2905 /*StripObjCLifetime=*/true);
2906 return true;
2907 }
2908
2909 // MSVC allows implicit function to void* type conversion.
2910 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2911 ToPointeeType->isVoidType()) {
2912 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2913 ToPointeeType,
2914 ToType, Context);
2915 return true;
2916 }
2917
2918 // When we're overloading in C, we allow a special kind of pointer
2919 // conversion for compatible-but-not-identical pointee types.
2920 if (!getLangOpts().CPlusPlus &&
2921 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2922 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2923 ToPointeeType,
2924 ToType, Context);
2925 return true;
2926 }
2927
2928 // C++ [conv.ptr]p3:
2929 //
2930 // An rvalue of type "pointer to cv D," where D is a class type,
2931 // can be converted to an rvalue of type "pointer to cv B," where
2932 // B is a base class (clause 10) of D. If B is an inaccessible
2933 // (clause 11) or ambiguous (10.2) base class of D, a program that
2934 // necessitates this conversion is ill-formed. The result of the
2935 // conversion is a pointer to the base class sub-object of the
2936 // derived class object. The null pointer value is converted to
2937 // the null pointer value of the destination type.
2938 //
2939 // Note that we do not check for ambiguity or inaccessibility
2940 // here. That is handled by CheckPointerConversion.
2941 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2942 ToPointeeType->isRecordType() &&
2943 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2944 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2945 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2946 ToPointeeType,
2947 ToType, Context);
2948 return true;
2949 }
2950
2951 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2952 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2954 ToPointeeType,
2955 ToType, Context);
2956 return true;
2957 }
2958
2959 return false;
2960}
2961
2962/// Adopt the given qualifiers for the given type.
2964 Qualifiers TQs = T.getQualifiers();
2965
2966 // Check whether qualifiers already match.
2967 if (TQs == Qs)
2968 return T;
2969
2970 if (Qs.compatiblyIncludes(TQs, Context))
2971 return Context.getQualifiedType(T, Qs);
2972
2973 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2974}
2975
2977 QualType& ConvertedType,
2978 bool &IncompatibleObjC) {
2979 if (!getLangOpts().ObjC)
2980 return false;
2981
2982 // The set of qualifiers on the type we're converting from.
2983 Qualifiers FromQualifiers = FromType.getQualifiers();
2984
2985 // First, we handle all conversions on ObjC object pointer types.
2986 const ObjCObjectPointerType* ToObjCPtr =
2987 ToType->getAs<ObjCObjectPointerType>();
2988 const ObjCObjectPointerType *FromObjCPtr =
2989 FromType->getAs<ObjCObjectPointerType>();
2990
2991 if (ToObjCPtr && FromObjCPtr) {
2992 // If the pointee types are the same (ignoring qualifications),
2993 // then this is not a pointer conversion.
2994 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2995 FromObjCPtr->getPointeeType()))
2996 return false;
2997
2998 // Conversion between Objective-C pointers.
2999 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3000 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3001 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3002 if (getLangOpts().CPlusPlus && LHS && RHS &&
3004 FromObjCPtr->getPointeeType(), getASTContext()))
3005 return false;
3006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3007 ToObjCPtr->getPointeeType(),
3008 ToType, Context);
3009 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3010 return true;
3011 }
3012
3013 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3014 // Okay: this is some kind of implicit downcast of Objective-C
3015 // interfaces, which is permitted. However, we're going to
3016 // complain about it.
3017 IncompatibleObjC = true;
3018 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3019 ToObjCPtr->getPointeeType(),
3020 ToType, Context);
3021 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3022 return true;
3023 }
3024 }
3025 // Beyond this point, both types need to be C pointers or block pointers.
3026 QualType ToPointeeType;
3027 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3028 ToPointeeType = ToCPtr->getPointeeType();
3029 else if (const BlockPointerType *ToBlockPtr =
3030 ToType->getAs<BlockPointerType>()) {
3031 // Objective C++: We're able to convert from a pointer to any object
3032 // to a block pointer type.
3033 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3034 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3035 return true;
3036 }
3037 ToPointeeType = ToBlockPtr->getPointeeType();
3038 }
3039 else if (FromType->getAs<BlockPointerType>() &&
3040 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3041 // Objective C++: We're able to convert from a block pointer type to a
3042 // pointer to any object.
3043 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3044 return true;
3045 }
3046 else
3047 return false;
3048
3049 QualType FromPointeeType;
3050 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3051 FromPointeeType = FromCPtr->getPointeeType();
3052 else if (const BlockPointerType *FromBlockPtr =
3053 FromType->getAs<BlockPointerType>())
3054 FromPointeeType = FromBlockPtr->getPointeeType();
3055 else
3056 return false;
3057
3058 // If we have pointers to pointers, recursively check whether this
3059 // is an Objective-C conversion.
3060 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3061 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3062 IncompatibleObjC)) {
3063 // We always complain about this conversion.
3064 IncompatibleObjC = true;
3065 ConvertedType = Context.getPointerType(ConvertedType);
3066 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3067 return true;
3068 }
3069 // Allow conversion of pointee being objective-c pointer to another one;
3070 // as in I* to id.
3071 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3072 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3073 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3074 IncompatibleObjC)) {
3075
3076 ConvertedType = Context.getPointerType(ConvertedType);
3077 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3078 return true;
3079 }
3080
3081 // If we have pointers to functions or blocks, check whether the only
3082 // differences in the argument and result types are in Objective-C
3083 // pointer conversions. If so, we permit the conversion (but
3084 // complain about it).
3085 const FunctionProtoType *FromFunctionType
3086 = FromPointeeType->getAs<FunctionProtoType>();
3087 const FunctionProtoType *ToFunctionType
3088 = ToPointeeType->getAs<FunctionProtoType>();
3089 if (FromFunctionType && ToFunctionType) {
3090 // If the function types are exactly the same, this isn't an
3091 // Objective-C pointer conversion.
3092 if (Context.getCanonicalType(FromPointeeType)
3093 == Context.getCanonicalType(ToPointeeType))
3094 return false;
3095
3096 // Perform the quick checks that will tell us whether these
3097 // function types are obviously different.
3098 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3099 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3100 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3101 return false;
3102
3103 bool HasObjCConversion = false;
3104 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3105 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3106 // Okay, the types match exactly. Nothing to do.
3107 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3108 ToFunctionType->getReturnType(),
3109 ConvertedType, IncompatibleObjC)) {
3110 // Okay, we have an Objective-C pointer conversion.
3111 HasObjCConversion = true;
3112 } else {
3113 // Function types are too different. Abort.
3114 return false;
3115 }
3116
3117 // Check argument types.
3118 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3119 ArgIdx != NumArgs; ++ArgIdx) {
3120 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3121 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3122 if (Context.getCanonicalType(FromArgType)
3123 == Context.getCanonicalType(ToArgType)) {
3124 // Okay, the types match exactly. Nothing to do.
3125 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3126 ConvertedType, IncompatibleObjC)) {
3127 // Okay, we have an Objective-C pointer conversion.
3128 HasObjCConversion = true;
3129 } else {
3130 // Argument types are too different. Abort.
3131 return false;
3132 }
3133 }
3134
3135 if (HasObjCConversion) {
3136 // We had an Objective-C conversion. Allow this pointer
3137 // conversion, but complain about it.
3138 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3139 IncompatibleObjC = true;
3140 return true;
3141 }
3142 }
3143
3144 return false;
3145}
3146
3148 QualType& ConvertedType) {
3149 QualType ToPointeeType;
3150 if (const BlockPointerType *ToBlockPtr =
3151 ToType->getAs<BlockPointerType>())
3152 ToPointeeType = ToBlockPtr->getPointeeType();
3153 else
3154 return false;
3155
3156 QualType FromPointeeType;
3157 if (const BlockPointerType *FromBlockPtr =
3158 FromType->getAs<BlockPointerType>())
3159 FromPointeeType = FromBlockPtr->getPointeeType();
3160 else
3161 return false;
3162 // We have pointer to blocks, check whether the only
3163 // differences in the argument and result types are in Objective-C
3164 // pointer conversions. If so, we permit the conversion.
3165
3166 const FunctionProtoType *FromFunctionType
3167 = FromPointeeType->getAs<FunctionProtoType>();
3168 const FunctionProtoType *ToFunctionType
3169 = ToPointeeType->getAs<FunctionProtoType>();
3170
3171 if (!FromFunctionType || !ToFunctionType)
3172 return false;
3173
3174 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3175 return true;
3176
3177 // Perform the quick checks that will tell us whether these
3178 // function types are obviously different.
3179 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3180 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3181 return false;
3182
3183 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3184 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3185 if (FromEInfo != ToEInfo)
3186 return false;
3187
3188 bool IncompatibleObjC = false;
3189 if (Context.hasSameType(FromFunctionType->getReturnType(),
3190 ToFunctionType->getReturnType())) {
3191 // Okay, the types match exactly. Nothing to do.
3192 } else {
3193 QualType RHS = FromFunctionType->getReturnType();
3194 QualType LHS = ToFunctionType->getReturnType();
3195 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3196 !RHS.hasQualifiers() && LHS.hasQualifiers())
3197 LHS = LHS.getUnqualifiedType();
3198
3199 if (Context.hasSameType(RHS,LHS)) {
3200 // OK exact match.
3201 } else if (isObjCPointerConversion(RHS, LHS,
3202 ConvertedType, IncompatibleObjC)) {
3203 if (IncompatibleObjC)
3204 return false;
3205 // Okay, we have an Objective-C pointer conversion.
3206 }
3207 else
3208 return false;
3209 }
3210
3211 // Check argument types.
3212 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3213 ArgIdx != NumArgs; ++ArgIdx) {
3214 IncompatibleObjC = false;
3215 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3216 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3217 if (Context.hasSameType(FromArgType, ToArgType)) {
3218 // Okay, the types match exactly. Nothing to do.
3219 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3220 ConvertedType, IncompatibleObjC)) {
3221 if (IncompatibleObjC)
3222 return false;
3223 // Okay, we have an Objective-C pointer conversion.
3224 } else
3225 // Argument types are too different. Abort.
3226 return false;
3227 }
3228
3230 bool CanUseToFPT, CanUseFromFPT;
3231 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3232 CanUseToFPT, CanUseFromFPT,
3233 NewParamInfos))
3234 return false;
3235
3236 ConvertedType = ToType;
3237 return true;
3238}
3239
3240enum {
3249
3250/// Attempts to get the FunctionProtoType from a Type. Handles
3251/// MemberFunctionPointers properly.
3253 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3254 return FPT;
3255
3256 if (auto *MPT = FromType->getAs<MemberPointerType>())
3257 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3258
3259 return nullptr;
3260}
3261
3263 QualType FromType, QualType ToType) {
3264 // If either type is not valid, include no extra info.
3265 if (FromType.isNull() || ToType.isNull()) {
3266 PDiag << ft_default;
3267 return;
3268 }
3269
3270 // Get the function type from the pointers.
3271 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3272 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3273 *ToMember = ToType->castAs<MemberPointerType>();
3274 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3275 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3276 << QualType(FromMember->getClass(), 0);
3277 return;
3278 }
3279 FromType = FromMember->getPointeeType();
3280 ToType = ToMember->getPointeeType();
3281 }
3282
3283 if (FromType->isPointerType())
3284 FromType = FromType->getPointeeType();
3285 if (ToType->isPointerType())
3286 ToType = ToType->getPointeeType();
3287
3288 // Remove references.
3289 FromType = FromType.getNonReferenceType();
3290 ToType = ToType.getNonReferenceType();
3291
3292 // Don't print extra info for non-specialized template functions.
3293 if (FromType->isInstantiationDependentType() &&
3294 !FromType->getAs<TemplateSpecializationType>()) {
3295 PDiag << ft_default;
3296 return;
3297 }
3298
3299 // No extra info for same types.
3300 if (Context.hasSameType(FromType, ToType)) {
3301 PDiag << ft_default;
3302 return;
3303 }
3304
3305 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3306 *ToFunction = tryGetFunctionProtoType(ToType);
3307
3308 // Both types need to be function types.
3309 if (!FromFunction || !ToFunction) {
3310 PDiag << ft_default;
3311 return;
3312 }
3313
3314 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3315 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3316 << FromFunction->getNumParams();
3317 return;
3318 }
3319
3320 // Handle different parameter types.
3321 unsigned ArgPos;
3322 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3323 PDiag << ft_parameter_mismatch << ArgPos + 1
3324 << ToFunction->getParamType(ArgPos)
3325 << FromFunction->getParamType(ArgPos);
3326 return;
3327 }
3328
3329 // Handle different return type.
3330 if (!Context.hasSameType(FromFunction->getReturnType(),
3331 ToFunction->getReturnType())) {
3332 PDiag << ft_return_type << ToFunction->getReturnType()
3333 << FromFunction->getReturnType();
3334 return;
3335 }
3336
3337 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3338 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3339 << FromFunction->getMethodQuals();
3340 return;
3341 }
3342
3343 // Handle exception specification differences on canonical type (in C++17
3344 // onwards).
3345 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3346 ->isNothrow() !=
3347 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3348 ->isNothrow()) {
3349 PDiag << ft_noexcept;
3350 return;
3351 }
3352
3353 // Unable to find a difference, so add no extra info.
3354 PDiag << ft_default;
3355}
3356
3358 ArrayRef<QualType> New, unsigned *ArgPos,
3359 bool Reversed) {
3360 assert(llvm::size(Old) == llvm::size(New) &&
3361 "Can't compare parameters of functions with different number of "
3362 "parameters!");
3363
3364 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3365 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3366 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3367
3368 // Ignore address spaces in pointee type. This is to disallow overloading
3369 // on __ptr32/__ptr64 address spaces.
3370 QualType OldType =
3371 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3372 QualType NewType =
3373 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3374
3375 if (!Context.hasSameType(OldType, NewType)) {
3376 if (ArgPos)
3377 *ArgPos = Idx;
3378 return false;
3379 }
3380 }
3381 return true;
3382}
3383
3385 const FunctionProtoType *NewType,
3386 unsigned *ArgPos, bool Reversed) {
3387 return FunctionParamTypesAreEqual(OldType->param_types(),
3388 NewType->param_types(), ArgPos, Reversed);
3389}
3390
3392 const FunctionDecl *NewFunction,
3393 unsigned *ArgPos,
3394 bool Reversed) {
3395
3396 if (OldFunction->getNumNonObjectParams() !=
3397 NewFunction->getNumNonObjectParams())
3398 return false;
3399
3400 unsigned OldIgnore =
3402 unsigned NewIgnore =
3404
3405 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3406 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3407
3408 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3409 NewPT->param_types().slice(NewIgnore),
3410 ArgPos, Reversed);
3411}
3412
3414 CastKind &Kind,
3415 CXXCastPath& BasePath,
3416 bool IgnoreBaseAccess,
3417 bool Diagnose) {
3418 QualType FromType = From->getType();
3419 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3420
3421 Kind = CK_BitCast;
3422
3423 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3426 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3427 DiagRuntimeBehavior(From->getExprLoc(), From,
3428 PDiag(diag::warn_impcast_bool_to_null_pointer)
3429 << ToType << From->getSourceRange());
3430 else if (!isUnevaluatedContext())
3431 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3432 << ToType << From->getSourceRange();
3433 }
3434 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3435 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3436 QualType FromPointeeType = FromPtrType->getPointeeType(),
3437 ToPointeeType = ToPtrType->getPointeeType();
3438
3439 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3441 // We must have a derived-to-base conversion. Check an
3442 // ambiguous or inaccessible conversion.
3443 unsigned InaccessibleID = 0;
3444 unsigned AmbiguousID = 0;
3445 if (Diagnose) {
3446 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3447 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3448 }
3449 if (CheckDerivedToBaseConversion(
3450 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3451 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3452 &BasePath, IgnoreBaseAccess))
3453 return true;
3454
3455 // The conversion was successful.
3456 Kind = CK_DerivedToBase;
3457 }
3458
3459 if (Diagnose && !IsCStyleOrFunctionalCast &&
3460 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3461 assert(getLangOpts().MSVCCompat &&
3462 "this should only be possible with MSVCCompat!");
3463 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3464 << From->getSourceRange();
3465 }
3466 }
3467 } else if (const ObjCObjectPointerType *ToPtrType =
3468 ToType->getAs<ObjCObjectPointerType>()) {
3469 if (const ObjCObjectPointerType *FromPtrType =
3470 FromType->getAs<ObjCObjectPointerType>()) {
3471 // Objective-C++ conversions are always okay.
3472 // FIXME: We should have a different class of conversions for the
3473 // Objective-C++ implicit conversions.
3474 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3475 return false;
3476 } else if (FromType->isBlockPointerType()) {
3477 Kind = CK_BlockPointerToObjCPointerCast;
3478 } else {
3479 Kind = CK_CPointerToObjCPointerCast;
3480 }
3481 } else if (ToType->isBlockPointerType()) {
3482 if (!FromType->isBlockPointerType())
3483 Kind = CK_AnyPointerToBlockPointerCast;
3484 }
3485
3486 // We shouldn't fall into this case unless it's valid for other
3487 // reasons.
3489 Kind = CK_NullToPointer;
3490
3491 return false;
3492}
3493
3495 QualType ToType,
3496 bool InOverloadResolution,
3497 QualType &ConvertedType) {
3498 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3499 if (!ToTypePtr)
3500 return false;
3501
3502 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3503 if (From->isNullPointerConstant(Context,
3504 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3506 ConvertedType = ToType;
3507 return true;
3508 }
3509
3510 // Otherwise, both types have to be member pointers.
3511 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3512 if (!FromTypePtr)
3513 return false;
3514
3515 // A pointer to member of B can be converted to a pointer to member of D,
3516 // where D is derived from B (C++ 4.11p2).
3517 QualType FromClass(FromTypePtr->getClass(), 0);
3518 QualType ToClass(ToTypePtr->getClass(), 0);
3519
3520 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3521 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3522 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3523 ToClass.getTypePtr());
3524 return true;
3525 }
3526
3527 return false;
3528}
3529
3531 CastKind &Kind,
3532 CXXCastPath &BasePath,
3533 bool IgnoreBaseAccess) {
3534 QualType FromType = From->getType();
3535 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3536 if (!FromPtrType) {
3537 // This must be a null pointer to member pointer conversion
3538 assert(From->isNullPointerConstant(Context,
3540 "Expr must be null pointer constant!");
3541 Kind = CK_NullToMemberPointer;
3542 return false;
3543 }
3544
3545 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3546 assert(ToPtrType && "No member pointer cast has a target type "
3547 "that is not a member pointer.");
3548
3549 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3550 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3551
3552 // FIXME: What about dependent types?
3553 assert(FromClass->isRecordType() && "Pointer into non-class.");
3554 assert(ToClass->isRecordType() && "Pointer into non-class.");
3555
3556 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3557 /*DetectVirtual=*/true);
3558 bool DerivationOkay =
3559 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3560 assert(DerivationOkay &&
3561 "Should not have been called if derivation isn't OK.");
3562 (void)DerivationOkay;
3563
3564 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3565 getUnqualifiedType())) {
3566 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3567 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3568 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3569 return true;
3570 }
3571
3572 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3573 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3574 << FromClass << ToClass << QualType(VBase, 0)
3575 << From->getSourceRange();
3576 return true;
3577 }
3578
3579 if (!IgnoreBaseAccess)
3580 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3581 Paths.front(),
3582 diag::err_downcast_from_inaccessible_base);
3583
3584 // Must be a base to derived member conversion.
3585 BuildBasePathArray(Paths, BasePath);
3586 Kind = CK_BaseToDerivedMemberPointer;
3587 return false;
3588}
3589
3590/// Determine whether the lifetime conversion between the two given
3591/// qualifiers sets is nontrivial.
3593 Qualifiers ToQuals) {
3594 // Converting anything to const __unsafe_unretained is trivial.
3595 if (ToQuals.hasConst() &&
3597 return false;
3598
3599 return true;
3600}
3601
3602/// Perform a single iteration of the loop for checking if a qualification
3603/// conversion is valid.
3604///
3605/// Specifically, check whether any change between the qualifiers of \p
3606/// FromType and \p ToType is permissible, given knowledge about whether every
3607/// outer layer is const-qualified.
3609 bool CStyle, bool IsTopLevel,
3610 bool &PreviousToQualsIncludeConst,
3611 bool &ObjCLifetimeConversion,
3612 const ASTContext &Ctx) {
3613 Qualifiers FromQuals = FromType.getQualifiers();
3614 Qualifiers ToQuals = ToType.getQualifiers();
3615
3616 // Ignore __unaligned qualifier.
3617 FromQuals.removeUnaligned();
3618
3619 // Objective-C ARC:
3620 // Check Objective-C lifetime conversions.
3621 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3622 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3623 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3624 ObjCLifetimeConversion = true;
3625 FromQuals.removeObjCLifetime();
3626 ToQuals.removeObjCLifetime();
3627 } else {
3628 // Qualification conversions cannot cast between different
3629 // Objective-C lifetime qualifiers.
3630 return false;
3631 }
3632 }
3633
3634 // Allow addition/removal of GC attributes but not changing GC attributes.
3635 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3636 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3637 FromQuals.removeObjCGCAttr();
3638 ToQuals.removeObjCGCAttr();
3639 }
3640
3641 // -- for every j > 0, if const is in cv 1,j then const is in cv
3642 // 2,j, and similarly for volatile.
3643 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3644 return false;
3645
3646 // If address spaces mismatch:
3647 // - in top level it is only valid to convert to addr space that is a
3648 // superset in all cases apart from C-style casts where we allow
3649 // conversions between overlapping address spaces.
3650 // - in non-top levels it is not a valid conversion.
3651 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3652 (!IsTopLevel ||
3653 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3654 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3655 return false;
3656
3657 // -- if the cv 1,j and cv 2,j are different, then const is in
3658 // every cv for 0 < k < j.
3659 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3660 !PreviousToQualsIncludeConst)
3661 return false;
3662
3663 // The following wording is from C++20, where the result of the conversion
3664 // is T3, not T2.
3665 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3666 // "array of unknown bound of"
3667 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3668 return false;
3669
3670 // -- if the resulting P3,i is different from P1,i [...], then const is
3671 // added to every cv 3_k for 0 < k < i.
3672 if (!CStyle && FromType->isConstantArrayType() &&
3673 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3674 return false;
3675
3676 // Keep track of whether all prior cv-qualifiers in the "to" type
3677 // include const.
3678 PreviousToQualsIncludeConst =
3679 PreviousToQualsIncludeConst && ToQuals.hasConst();
3680 return true;
3681}
3682
3683bool
3685 bool CStyle, bool &ObjCLifetimeConversion) {
3686 FromType = Context.getCanonicalType(FromType);
3687 ToType = Context.getCanonicalType(ToType);
3688 ObjCLifetimeConversion = false;
3689
3690 // If FromType and ToType are the same type, this is not a
3691 // qualification conversion.
3692 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3693 return false;
3694
3695 // (C++ 4.4p4):
3696 // A conversion can add cv-qualifiers at levels other than the first
3697 // in multi-level pointers, subject to the following rules: [...]
3698 bool PreviousToQualsIncludeConst = true;
3699 bool UnwrappedAnyPointer = false;
3700 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3701 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3702 !UnwrappedAnyPointer,
3703 PreviousToQualsIncludeConst,
3704 ObjCLifetimeConversion, getASTContext()))
3705 return false;
3706 UnwrappedAnyPointer = true;
3707 }
3708
3709 // We are left with FromType and ToType being the pointee types
3710 // after unwrapping the original FromType and ToType the same number
3711 // of times. If we unwrapped any pointers, and if FromType and
3712 // ToType have the same unqualified type (since we checked
3713 // qualifiers above), then this is a qualification conversion.
3714 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3715}
3716
3717/// - Determine whether this is a conversion from a scalar type to an
3718/// atomic type.
3719///
3720/// If successful, updates \c SCS's second and third steps in the conversion
3721/// sequence to finish the conversion.
3722static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3723 bool InOverloadResolution,
3725 bool CStyle) {
3726 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3727 if (!ToAtomic)
3728 return false;
3729
3731 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3732 InOverloadResolution, InnerSCS,
3733 CStyle, /*AllowObjCWritebackConversion=*/false))
3734 return false;
3735
3736 SCS.Second = InnerSCS.Second;
3737 SCS.setToType(1, InnerSCS.getToType(1));
3738 SCS.Third = InnerSCS.Third;
3741 SCS.setToType(2, InnerSCS.getToType(2));
3742 return true;
3743}
3744
3746 CXXConstructorDecl *Constructor,
3747 QualType Type) {
3748 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3749 if (CtorType->getNumParams() > 0) {
3750 QualType FirstArg = CtorType->getParamType(0);
3751 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3752 return true;
3753 }
3754 return false;
3755}
3756
3757static OverloadingResult
3759 CXXRecordDecl *To,
3761 OverloadCandidateSet &CandidateSet,
3762 bool AllowExplicit) {
3764 for (auto *D : S.LookupConstructors(To)) {
3765 auto Info = getConstructorInfo(D);
3766 if (!Info)
3767 continue;
3768
3769 bool Usable = !Info.Constructor->isInvalidDecl() &&
3770 S.isInitListConstructor(Info.Constructor);
3771 if (Usable) {
3772 bool SuppressUserConversions = false;
3773 if (Info.ConstructorTmpl)
3774 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3775 /*ExplicitArgs*/ nullptr, From,
3776 CandidateSet, SuppressUserConversions,
3777 /*PartialOverloading*/ false,
3778 AllowExplicit);
3779 else
3780 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3781 CandidateSet, SuppressUserConversions,
3782 /*PartialOverloading*/ false, AllowExplicit);
3783 }
3784 }
3785
3786 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3787
3789 switch (auto Result =
3790 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3791 case OR_Deleted:
3792 case OR_Success: {
3793 // Record the standard conversion we used and the conversion function.
3794 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3795 QualType ThisType = Constructor->getFunctionObjectParameterType();
3796 // Initializer lists don't have conversions as such.
3798 User.HadMultipleCandidates = HadMultipleCandidates;
3799 User.ConversionFunction = Constructor;
3800 User.FoundConversionFunction = Best->FoundDecl;
3802 User.After.setFromType(ThisType);
3803 User.After.setAllToTypes(ToType);
3804 return Result;
3805 }
3806
3808 return OR_No_Viable_Function;
3809 case OR_Ambiguous:
3810 return OR_Ambiguous;
3811 }
3812
3813 llvm_unreachable("Invalid OverloadResult!");
3814}
3815
3816/// Determines whether there is a user-defined conversion sequence
3817/// (C++ [over.ics.user]) that converts expression From to the type
3818/// ToType. If such a conversion exists, User will contain the
3819/// user-defined conversion sequence that performs such a conversion
3820/// and this routine will return true. Otherwise, this routine returns
3821/// false and User is unspecified.
3822///
3823/// \param AllowExplicit true if the conversion should consider C++0x
3824/// "explicit" conversion functions as well as non-explicit conversion
3825/// functions (C++0x [class.conv.fct]p2).
3826///
3827/// \param AllowObjCConversionOnExplicit true if the conversion should
3828/// allow an extra Objective-C pointer conversion on uses of explicit
3829/// constructors. Requires \c AllowExplicit to also be set.
3830static OverloadingResult
3833 OverloadCandidateSet &CandidateSet,
3834 AllowedExplicit AllowExplicit,
3835 bool AllowObjCConversionOnExplicit) {
3836 assert(AllowExplicit != AllowedExplicit::None ||
3837 !AllowObjCConversionOnExplicit);
3839
3840 // Whether we will only visit constructors.
3841 bool ConstructorsOnly = false;
3842
3843 // If the type we are conversion to is a class type, enumerate its
3844 // constructors.
3845 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3846 // C++ [over.match.ctor]p1:
3847 // When objects of class type are direct-initialized (8.5), or
3848 // copy-initialized from an expression of the same or a
3849 // derived class type (8.5), overload resolution selects the
3850 // constructor. [...] For copy-initialization, the candidate
3851 // functions are all the converting constructors (12.3.1) of
3852 // that class. The argument list is the expression-list within
3853 // the parentheses of the initializer.
3854 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3855 (From->getType()->getAs<RecordType>() &&
3856 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3857 ConstructorsOnly = true;
3858
3859 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3860 // We're not going to find any constructors.
3861 } else if (CXXRecordDecl *ToRecordDecl
3862 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3863
3864 Expr **Args = &From;
3865 unsigned NumArgs = 1;
3866 bool ListInitializing = false;
3867 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3868 // But first, see if there is an init-list-constructor that will work.
3870 S, From, ToType, ToRecordDecl, User, CandidateSet,
3871 AllowExplicit == AllowedExplicit::All);
3873 return Result;
3874 // Never mind.
3875 CandidateSet.clear(
3877
3878 // If we're list-initializing, we pass the individual elements as
3879 // arguments, not the entire list.
3880 Args = InitList->getInits();
3881 NumArgs = InitList->getNumInits();
3882 ListInitializing = true;
3883 }
3884
3885 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3886 auto Info = getConstructorInfo(D);
3887 if (!Info)
3888 continue;
3889
3890 bool Usable = !Info.Constructor->isInvalidDecl();
3891 if (!ListInitializing)
3892 Usable = Usable && Info.Constructor->isConvertingConstructor(
3893 /*AllowExplicit*/ true);
3894 if (Usable) {
3895 bool SuppressUserConversions = !ConstructorsOnly;
3896 // C++20 [over.best.ics.general]/4.5:
3897 // if the target is the first parameter of a constructor [of class
3898 // X] and the constructor [...] is a candidate by [...] the second
3899 // phase of [over.match.list] when the initializer list has exactly
3900 // one element that is itself an initializer list, [...] and the
3901 // conversion is to X or reference to cv X, user-defined conversion
3902 // sequences are not cnosidered.
3903 if (SuppressUserConversions && ListInitializing) {
3904 SuppressUserConversions =
3905 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3906 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3907 ToType);
3908 }
3909 if (Info.ConstructorTmpl)
3911 Info.ConstructorTmpl, Info.FoundDecl,
3912 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3913 CandidateSet, SuppressUserConversions,
3914 /*PartialOverloading*/ false,
3915 AllowExplicit == AllowedExplicit::All);
3916 else
3917 // Allow one user-defined conversion when user specifies a
3918 // From->ToType conversion via an static cast (c-style, etc).
3919 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3920 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3921 SuppressUserConversions,
3922 /*PartialOverloading*/ false,
3923 AllowExplicit == AllowedExplicit::All);
3924 }
3925 }
3926 }
3927 }
3928
3929 // Enumerate conversion functions, if we're allowed to.
3930 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3931 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3932 // No conversion functions from incomplete types.
3933 } else if (const RecordType *FromRecordType =
3934 From->getType()->getAs<RecordType>()) {
3935 if (CXXRecordDecl *FromRecordDecl
3936 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3937 // Add all of the conversion functions as candidates.
3938 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3939 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3940 DeclAccessPair FoundDecl = I.getPair();
3941 NamedDecl *D = FoundDecl.getDecl();
3942 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3943 if (isa<UsingShadowDecl>(D))
3944 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3945
3946 CXXConversionDecl *Conv;
3947 FunctionTemplateDecl *ConvTemplate;
3948 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3949 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3950 else
3951 Conv = cast<CXXConversionDecl>(D);
3952
3953 if (ConvTemplate)
3955 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3956 CandidateSet, AllowObjCConversionOnExplicit,
3957 AllowExplicit != AllowedExplicit::None);
3958 else
3959 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3960 CandidateSet, AllowObjCConversionOnExplicit,
3961 AllowExplicit != AllowedExplicit::None);
3962 }
3963 }
3964 }
3965
3966 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3967
3969 switch (auto Result =
3970 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3971 case OR_Success:
3972 case OR_Deleted:
3973 // Record the standard conversion we used and the conversion function.
3974 if (CXXConstructorDecl *Constructor
3975 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3976 // C++ [over.ics.user]p1:
3977 // If the user-defined conversion is specified by a
3978 // constructor (12.3.1), the initial standard conversion
3979 // sequence converts the source type to the type required by
3980 // the argument of the constructor.
3981 //
3982 if (isa<InitListExpr>(From)) {
3983 // Initializer lists don't have conversions as such.
3985 } else {
3986 if (Best->Conversions[0].isEllipsis())
3987 User.EllipsisConversion = true;
3988 else {
3989 User.Before = Best->Conversions[0].Standard;
3990 User.EllipsisConversion = false;
3991 }
3992 }
3993 User.HadMultipleCandidates = HadMultipleCandidates;
3994 User.ConversionFunction = Constructor;
3995 User.FoundConversionFunction = Best->FoundDecl;
3997 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3998 User.After.setAllToTypes(ToType);
3999 return Result;
4000 }
4001 if (CXXConversionDecl *Conversion
4002 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4003 // C++ [over.ics.user]p1:
4004 //
4005 // [...] If the user-defined conversion is specified by a
4006 // conversion function (12.3.2), the initial standard
4007 // conversion sequence converts the source type to the
4008 // implicit object parameter of the conversion function.
4009 User.Before = Best->Conversions[0].Standard;
4010 User.HadMultipleCandidates = HadMultipleCandidates;
4011 User.ConversionFunction = Conversion;
4012 User.FoundConversionFunction = Best->FoundDecl;
4013 User.EllipsisConversion = false;
4014
4015 // C++ [over.ics.user]p2:
4016 // The second standard conversion sequence converts the
4017 // result of the user-defined conversion to the target type
4018 // for the sequence. Since an implicit conversion sequence
4019 // is an initialization, the special rules for
4020 // initialization by user-defined conversion apply when
4021 // selecting the best user-defined conversion for a
4022 // user-defined conversion sequence (see 13.3.3 and
4023 // 13.3.3.1).
4024 User.After = Best->FinalConversion;
4025 return Result;
4026 }
4027 llvm_unreachable("Not a constructor or conversion function?");
4028
4030 return OR_No_Viable_Function;
4031
4032 case OR_Ambiguous:
4033 return OR_Ambiguous;
4034 }
4035
4036 llvm_unreachable("Invalid OverloadResult!");
4037}
4038
4039bool
4042 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4044 OverloadingResult OvResult =
4045 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4046 CandidateSet, AllowedExplicit::None, false);
4047
4048 if (!(OvResult == OR_Ambiguous ||
4049 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4050 return false;
4051
4052 auto Cands = CandidateSet.CompleteCandidates(
4053 *this,
4055 From);
4056 if (OvResult == OR_Ambiguous)
4057 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4058 << From->getType() << ToType << From->getSourceRange();
4059 else { // OR_No_Viable_Function && !CandidateSet.empty()
4060 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4061 diag::err_typecheck_nonviable_condition_incomplete,
4062 From->getType(), From->getSourceRange()))
4063 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4064 << false << From->getType() << From->getSourceRange() << ToType;
4065 }
4066
4067 CandidateSet.NoteCandidates(
4068 *this, From, Cands);
4069 return true;
4070}
4071
4072// Helper for compareConversionFunctions that gets the FunctionType that the
4073// conversion-operator return value 'points' to, or nullptr.
4074static const FunctionType *
4076 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4077 const PointerType *RetPtrTy =
4078 ConvFuncTy->getReturnType()->getAs<PointerType>();
4079
4080 if (!RetPtrTy)
4081 return nullptr;
4082
4083 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4084}
4085
4086/// Compare the user-defined conversion functions or constructors
4087/// of two user-defined conversion sequences to determine whether any ordering
4088/// is possible.
4091 FunctionDecl *Function2) {
4092 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4093 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4094 if (!Conv1 || !Conv2)
4096
4097 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4099
4100 // Objective-C++:
4101 // If both conversion functions are implicitly-declared conversions from
4102 // a lambda closure type to a function pointer and a block pointer,
4103 // respectively, always prefer the conversion to a function pointer,
4104 // because the function pointer is more lightweight and is more likely
4105 // to keep code working.
4106 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4107 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4108 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4109 if (Block1 != Block2)
4110 return Block1 ? ImplicitConversionSequence::Worse
4112 }
4113
4114 // In order to support multiple calling conventions for the lambda conversion
4115 // operator (such as when the free and member function calling convention is
4116 // different), prefer the 'free' mechanism, followed by the calling-convention
4117 // of operator(). The latter is in place to support the MSVC-like solution of
4118 // defining ALL of the possible conversions in regards to calling-convention.
4119 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4120 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4121
4122 if (Conv1FuncRet && Conv2FuncRet &&
4123 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4124 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4125 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4126
4127 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4128 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4129
4130 CallingConv CallOpCC =
4131 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4133 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4135 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4136
4137 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4138 for (CallingConv CC : PrefOrder) {
4139 if (Conv1CC == CC)
4141 if (Conv2CC == CC)
4143 }
4144 }
4145
4147}
4148
4150 const ImplicitConversionSequence &ICS) {
4152 (ICS.isUserDefined() &&
4154}
4155
4156/// CompareImplicitConversionSequences - Compare two implicit
4157/// conversion sequences to determine whether one is better than the
4158/// other or if they are indistinguishable (C++ 13.3.3.2).
4161 const ImplicitConversionSequence& ICS1,
4162 const ImplicitConversionSequence& ICS2)
4163{
4164 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4165 // conversion sequences (as defined in 13.3.3.1)
4166 // -- a standard conversion sequence (13.3.3.1.1) is a better
4167 // conversion sequence than a user-defined conversion sequence or
4168 // an ellipsis conversion sequence, and
4169 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4170 // conversion sequence than an ellipsis conversion sequence
4171 // (13.3.3.1.3).
4172 //
4173 // C++0x [over.best.ics]p10:
4174 // For the purpose of ranking implicit conversion sequences as
4175 // described in 13.3.3.2, the ambiguous conversion sequence is
4176 // treated as a user-defined sequence that is indistinguishable
4177 // from any other user-defined conversion sequence.
4178
4179 // String literal to 'char *' conversion has been deprecated in C++03. It has
4180 // been removed from C++11. We still accept this conversion, if it happens at
4181 // the best viable function. Otherwise, this conversion is considered worse
4182 // than ellipsis conversion. Consider this as an extension; this is not in the
4183 // standard. For example:
4184 //
4185 // int &f(...); // #1
4186 // void f(char*); // #2
4187 // void g() { int &r = f("foo"); }
4188 //
4189 // In C++03, we pick #2 as the best viable function.
4190 // In C++11, we pick #1 as the best viable function, because ellipsis
4191 // conversion is better than string-literal to char* conversion (since there
4192 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4193 // convert arguments, #2 would be the best viable function in C++11.
4194 // If the best viable function has this conversion, a warning will be issued
4195 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4196
4197 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4200 // Ill-formedness must not differ
4201 ICS1.isBad() == ICS2.isBad())
4205
4206 if (ICS1.getKindRank() < ICS2.getKindRank())
4208 if (ICS2.getKindRank() < ICS1.getKindRank())
4210
4211 // The following checks require both conversion sequences to be of
4212 // the same kind.
4213 if (ICS1.getKind() != ICS2.getKind())
4215
4218
4219 // Two implicit conversion sequences of the same form are
4220 // indistinguishable conversion sequences unless one of the
4221 // following rules apply: (C++ 13.3.3.2p3):
4222
4223 // List-initialization sequence L1 is a better conversion sequence than
4224 // list-initialization sequence L2 if:
4225 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4226 // if not that,
4227 // — L1 and L2 convert to arrays of the same element type, and either the
4228 // number of elements n_1 initialized by L1 is less than the number of
4229 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4230 // an array of unknown bound and L1 does not,
4231 // even if one of the other rules in this paragraph would otherwise apply.
4232 if (!ICS1.isBad()) {
4233 bool StdInit1 = false, StdInit2 = false;
4236 nullptr);
4239 nullptr);
4240 if (StdInit1 != StdInit2)
4241 return StdInit1 ? ImplicitConversionSequence::Better
4243
4246 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4248 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4250 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4251 CAT2->getElementType())) {
4252 // Both to arrays of the same element type
4253 if (CAT1->getSize() != CAT2->getSize())
4254 // Different sized, the smaller wins
4255 return CAT1->getSize().ult(CAT2->getSize())
4260 // One is incomplete, it loses
4264 }
4265 }
4266 }
4267
4268 if (ICS1.isStandard())
4269 // Standard conversion sequence S1 is a better conversion sequence than
4270 // standard conversion sequence S2 if [...]
4272 ICS1.Standard, ICS2.Standard);
4273 else if (ICS1.isUserDefined()) {
4274 // User-defined conversion sequence U1 is a better conversion
4275 // sequence than another user-defined conversion sequence U2 if
4276 // they contain the same user-defined conversion function or
4277 // constructor and if the second standard conversion sequence of
4278 // U1 is better than the second standard conversion sequence of
4279 // U2 (C++ 13.3.3.2p3).
4283 ICS1.UserDefined.After,
4284 ICS2.UserDefined.After);
4285 else
4289 }
4290
4291 return Result;
4292}
4293
4294// Per 13.3.3.2p3, compare the given standard conversion sequences to
4295// determine if one is a proper subset of the other.
4298 const StandardConversionSequence& SCS1,
4299 const StandardConversionSequence& SCS2) {
4302
4303 // the identity conversion sequence is considered to be a subsequence of
4304 // any non-identity conversion sequence
4305 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4307 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4309
4310 if (SCS1.Second != SCS2.Second) {
4311 if (SCS1.Second == ICK_Identity)
4313 else if (SCS2.Second == ICK_Identity)
4315 else
4317 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4319
4320 if (SCS1.Third == SCS2.Third) {
4321 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4323 }
4324
4325 if (SCS1.Third == ICK_Identity)
4329
4330 if (SCS2.Third == ICK_Identity)
4334
4336}
4337
4338/// Determine whether one of the given reference bindings is better
4339/// than the other based on what kind of bindings they are.
4340static bool
4342 const StandardConversionSequence &SCS2) {
4343 // C++0x [over.ics.rank]p3b4:
4344 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4345 // implicit object parameter of a non-static member function declared
4346 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4347 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4348 // lvalue reference to a function lvalue and S2 binds an rvalue
4349 // reference*.
4350 //
4351 // FIXME: Rvalue references. We're going rogue with the above edits,
4352 // because the semantics in the current C++0x working paper (N3225 at the
4353 // time of this writing) break the standard definition of std::forward
4354 // and std::reference_wrapper when dealing with references to functions.
4355 // Proposed wording changes submitted to CWG for consideration.
4358 return false;
4359
4360 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4361 SCS2.IsLvalueReference) ||
4364}
4365
4367 None,
4370};
4371
4372/// Returns kind of fixed enum promotion the \a SCS uses.
4373static FixedEnumPromotion
4375
4376 if (SCS.Second != ICK_Integral_Promotion)
4377 return FixedEnumPromotion::None;
4378
4379 QualType FromType = SCS.getFromType();
4380 if (!FromType->isEnumeralType())
4381 return FixedEnumPromotion::None;
4382
4383 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4384 if (!Enum->isFixed())
4385 return FixedEnumPromotion::None;
4386
4387 QualType UnderlyingType = Enum->getIntegerType();
4388 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4389 return FixedEnumPromotion::ToUnderlyingType;
4390
4391 return FixedEnumPromotion::ToPromotedUnderlyingType;
4392}
4393
4394/// CompareStandardConversionSequences - Compare two standard
4395/// conversion sequences to determine whether one is better than the
4396/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4399 const StandardConversionSequence& SCS1,
4400 const StandardConversionSequence& SCS2)
4401{
4402 // Standard conversion sequence S1 is a better conversion sequence
4403 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4404
4405 // -- S1 is a proper subsequence of S2 (comparing the conversion
4406 // sequences in the canonical form defined by 13.3.3.1.1,
4407 // excluding any Lvalue Transformation; the identity conversion
4408 // sequence is considered to be a subsequence of any
4409 // non-identity conversion sequence) or, if not that,
4412 return CK;
4413
4414 // -- the rank of S1 is better than the rank of S2 (by the rules
4415 // defined below), or, if not that,
4416 ImplicitConversionRank Rank1 = SCS1.getRank();
4417 ImplicitConversionRank Rank2 = SCS2.getRank();
4418 if (Rank1 < Rank2)
4420 else if (Rank2 < Rank1)
4422
4423 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4424 // are indistinguishable unless one of the following rules
4425 // applies:
4426
4427 // A conversion that is not a conversion of a pointer, or
4428 // pointer to member, to bool is better than another conversion
4429 // that is such a conversion.
4431 return SCS2.isPointerConversionToBool()
4434
4435 // C++14 [over.ics.rank]p4b2:
4436 // This is retroactively applied to C++11 by CWG 1601.
4437 //
4438 // A conversion that promotes an enumeration whose underlying type is fixed
4439 // to its underlying type is better than one that promotes to the promoted
4440 // underlying type, if the two are different.
4443 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4444 FEP1 != FEP2)
4445 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4448
4449 // C++ [over.ics.rank]p4b2:
4450 //
4451 // If class B is derived directly or indirectly from class A,
4452 // conversion of B* to A* is better than conversion of B* to
4453 // void*, and conversion of A* to void* is better than conversion
4454 // of B* to void*.
4455 bool SCS1ConvertsToVoid
4457 bool SCS2ConvertsToVoid
4459 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4460 // Exactly one of the conversion sequences is a conversion to
4461 // a void pointer; it's the worse conversion.
4462 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4464 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4465 // Neither conversion sequence converts to a void pointer; compare
4466 // their derived-to-base conversions.
4468 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4469 return DerivedCK;
4470 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4471 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4472 // Both conversion sequences are conversions to void
4473 // pointers. Compare the source types to determine if there's an
4474 // inheritance relationship in their sources.
4475 QualType FromType1 = SCS1.getFromType();
4476 QualType FromType2 = SCS2.getFromType();
4477
4478 // Adjust the types we're converting from via the array-to-pointer
4479 // conversion, if we need to.
4480 if (SCS1.First == ICK_Array_To_Pointer)
4481 FromType1 = S.Context.getArrayDecayedType(FromType1);
4482 if (SCS2.First == ICK_Array_To_Pointer)
4483 FromType2 = S.Context.getArrayDecayedType(FromType2);
4484
4485 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4486 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4487
4488 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4490 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4492
4493 // Objective-C++: If one interface is more specific than the
4494 // other, it is the better one.
4495 const ObjCObjectPointerType* FromObjCPtr1
4496 = FromType1->getAs<ObjCObjectPointerType>();
4497 const ObjCObjectPointerType* FromObjCPtr2
4498 = FromType2->getAs<ObjCObjectPointerType>();
4499 if (FromObjCPtr1 && FromObjCPtr2) {
4500 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4501 FromObjCPtr2);
4502 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4503 FromObjCPtr1);
4504 if (AssignLeft != AssignRight) {
4505 return AssignLeft? ImplicitConversionSequence::Better
4507 }
4508 }
4509 }
4510
4511 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4512 // Check for a better reference binding based on the kind of bindings.
4513 if (isBetterReferenceBindingKind(SCS1, SCS2))
4515 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4517 }
4518
4519 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4520 // bullet 3).
4522 = CompareQualificationConversions(S, SCS1, SCS2))
4523 return QualCK;
4524
4525 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4526 // C++ [over.ics.rank]p3b4:
4527 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4528 // which the references refer are the same type except for
4529 // top-level cv-qualifiers, and the type to which the reference
4530 // initialized by S2 refers is more cv-qualified than the type
4531 // to which the reference initialized by S1 refers.
4532 QualType T1 = SCS1.getToType(2);
4533 QualType T2 = SCS2.getToType(2);
4534 T1 = S.Context.getCanonicalType(T1);
4535 T2 = S.Context.getCanonicalType(T2);
4536 Qualifiers T1Quals, T2Quals;
4537 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4538 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4539 if (UnqualT1 == UnqualT2) {
4540 // Objective-C++ ARC: If the references refer to objects with different
4541 // lifetimes, prefer bindings that don't change lifetime.
4547 }
4548
4549 // If the type is an array type, promote the element qualifiers to the
4550 // type for comparison.
4551 if (isa<ArrayType>(T1) && T1Quals)
4552 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4553 if (isa<ArrayType>(T2) && T2Quals)
4554 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4555 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4557 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4559 }
4560 }
4561
4562 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4563 // floating-to-integral conversion if the integral conversion
4564 // is between types of the same size.
4565 // For example:
4566 // void f(float);
4567 // void f(int);
4568 // int main {
4569 // long a;
4570 // f(a);
4571 // }
4572 // Here, MSVC will call f(int) instead of generating a compile error
4573 // as clang will do in standard mode.
4574 if (S.getLangOpts().MSVCCompat &&
4577 SCS2.Second == ICK_Floating_Integral &&
4578 S.Context.getTypeSize(SCS1.getFromType()) ==
4579 S.Context.getTypeSize(SCS1.getToType(2)))
4581
4582 // Prefer a compatible vector conversion over a lax vector conversion
4583 // For example:
4584 //
4585 // typedef float __v4sf __attribute__((__vector_size__(16)));
4586 // void f(vector float);
4587 // void f(vector signed int);
4588 // int main() {
4589 // __v4sf a;
4590 // f(a);
4591 // }
4592 // Here, we'd like to choose f(vector float) and not
4593 // report an ambiguous call error
4594 if (SCS1.Second == ICK_Vector_Conversion &&
4595 SCS2.Second == ICK_Vector_Conversion) {
4596 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4597 SCS1.getFromType(), SCS1.getToType(2));
4598 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4599 SCS2.getFromType(), SCS2.getToType(2));
4600
4601 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4602 return SCS1IsCompatibleVectorConversion
4605 }
4606
4607 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4609 bool SCS1IsCompatibleSVEVectorConversion =
4611 bool SCS2IsCompatibleSVEVectorConversion =
4613
4614 if (SCS1IsCompatibleSVEVectorConversion !=
4615 SCS2IsCompatibleSVEVectorConversion)
4616 return SCS1IsCompatibleSVEVectorConversion
4619 }
4620
4621 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4623 bool SCS1IsCompatibleRVVVectorConversion =
4625 bool SCS2IsCompatibleRVVVectorConversion =
4627
4628 if (SCS1IsCompatibleRVVVectorConversion !=
4629 SCS2IsCompatibleRVVVectorConversion)
4630 return SCS1IsCompatibleRVVVectorConversion
4633 }
4635}
4636
4637/// CompareQualificationConversions - Compares two standard conversion
4638/// sequences to determine whether they can be ranked based on their
4639/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4642 const StandardConversionSequence& SCS1,
4643 const StandardConversionSequence& SCS2) {
4644 // C++ [over.ics.rank]p3:
4645 // -- S1 and S2 differ only in their qualification conversion and
4646 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4647 // [C++98]
4648 // [...] and the cv-qualification signature of type T1 is a proper subset
4649 // of the cv-qualification signature of type T2, and S1 is not the
4650 // deprecated string literal array-to-pointer conversion (4.2).
4651 // [C++2a]
4652 // [...] where T1 can be converted to T2 by a qualification conversion.
4653 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4654 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4656
4657 // FIXME: the example in the standard doesn't use a qualification
4658 // conversion (!)
4659 QualType T1 = SCS1.getToType(2);
4660 QualType T2 = SCS2.getToType(2);
4661 T1 = S.Context.getCanonicalType(T1);
4662 T2 = S.Context.getCanonicalType(T2);
4663 assert(!T1->isReferenceType() && !T2->isReferenceType());
4664 Qualifiers T1Quals, T2Quals;
4665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4667
4668 // If the types are the same, we won't learn anything by unwrapping
4669 // them.
4670 if (UnqualT1 == UnqualT2)
4672
4673 // Don't ever prefer a standard conversion sequence that uses the deprecated
4674 // string literal array to pointer conversion.
4675 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4676 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4677
4678 // Objective-C++ ARC:
4679 // Prefer qualification conversions not involving a change in lifetime
4680 // to qualification conversions that do change lifetime.
4683 CanPick1 = false;
4686 CanPick2 = false;
4687
4688 bool ObjCLifetimeConversion;
4689 if (CanPick1 &&
4690 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4691 CanPick1 = false;
4692 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4693 // directions, so we can't short-cut this second check in general.
4694 if (CanPick2 &&
4695 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4696 CanPick2 = false;
4697
4698 if (CanPick1 != CanPick2)
4699 return CanPick1 ? ImplicitConversionSequence::Better
4702}
4703
4704/// CompareDerivedToBaseConversions - Compares two standard conversion
4705/// sequences to determine whether they can be ranked based on their
4706/// various kinds of derived-to-base conversions (C++
4707/// [over.ics.rank]p4b3). As part of these checks, we also look at
4708/// conversions between Objective-C interface types.
4711 const StandardConversionSequence& SCS1,
4712 const StandardConversionSequence& SCS2) {
4713 QualType FromType1 = SCS1.getFromType();
4714 QualType ToType1 = SCS1.getToType(1);
4715 QualType FromType2 = SCS2.getFromType();
4716 QualType ToType2 = SCS2.getToType(1);
4717
4718 // Adjust the types we're converting from via the array-to-pointer
4719 // conversion, if we need to.
4720 if (SCS1.First == ICK_Array_To_Pointer)
4721 FromType1 = S.Context.getArrayDecayedType(FromType1);
4722 if (SCS2.First == ICK_Array_To_Pointer)
4723 FromType2 = S.Context.getArrayDecayedType(FromType2);
4724
4725 // Canonicalize all of the types.
4726 FromType1 = S.Context.getCanonicalType(FromType1);
4727 ToType1 = S.Context.getCanonicalType(ToType1);
4728 FromType2 = S.Context.getCanonicalType(FromType2);
4729 ToType2 = S.Context.getCanonicalType(ToType2);
4730
4731 // C++ [over.ics.rank]p4b3:
4732 //
4733 // If class B is derived directly or indirectly from class A and
4734 // class C is derived directly or indirectly from B,
4735 //
4736 // Compare based on pointer conversions.
4737 if (SCS1.Second == ICK_Pointer_Conversion &&
4739 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4740 FromType1->isPointerType() && FromType2->isPointerType() &&
4741 ToType1->isPointerType() && ToType2->isPointerType()) {
4742 QualType FromPointee1 =
4744 QualType ToPointee1 =
4746 QualType FromPointee2 =
4748 QualType ToPointee2 =
4750
4751 // -- conversion of C* to B* is better than conversion of C* to A*,
4752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4753 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4755 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4757 }
4758
4759 // -- conversion of B* to A* is better than conversion of C* to A*,
4760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4765 }
4766 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4768 const ObjCObjectPointerType *FromPtr1
4769 = FromType1->getAs<ObjCObjectPointerType>();
4770 const ObjCObjectPointerType *FromPtr2
4771 = FromType2->getAs<ObjCObjectPointerType>();
4772 const ObjCObjectPointerType *ToPtr1
4773 = ToType1->getAs<ObjCObjectPointerType>();
4774 const ObjCObjectPointerType *ToPtr2
4775 = ToType2->getAs<ObjCObjectPointerType>();
4776
4777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4778 // Apply the same conversion ranking rules for Objective-C pointer types
4779 // that we do for C++ pointers to class types. However, we employ the
4780 // Objective-C pseudo-subtyping relationship used for assignment of
4781 // Objective-C pointer types.
4782 bool FromAssignLeft
4783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4784 bool FromAssignRight
4785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4786 bool ToAssignLeft
4787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4788 bool ToAssignRight
4789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4790
4791 // A conversion to an a non-id object pointer type or qualified 'id'
4792 // type is better than a conversion to 'id'.
4793 if (ToPtr1->isObjCIdType() &&
4794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4796 if (ToPtr2->isObjCIdType() &&
4797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4799
4800 // A conversion to a non-id object pointer type is better than a
4801 // conversion to a qualified 'id' type
4802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4806
4807 // A conversion to an a non-Class object pointer type or qualified 'Class'
4808 // type is better than a conversion to 'Class'.
4809 if (ToPtr1->isObjCClassType() &&
4810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4812 if (ToPtr2->isObjCClassType() &&
4813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4815
4816 // A conversion to a non-Class object pointer type is better than a
4817 // conversion to a qualified 'Class' type.
4818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4822
4823 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4824 if (S.Context.hasSameType(FromType1, FromType2) &&
4825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4826 (ToAssignLeft != ToAssignRight)) {
4827 if (FromPtr1->isSpecialized()) {
4828 // "conversion of B<A> * to B * is better than conversion of B * to
4829 // C *.
4830 bool IsFirstSame =
4831 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4832 bool IsSecondSame =
4833 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4834 if (IsFirstSame) {
4835 if (!IsSecondSame)
4837 } else if (IsSecondSame)
4839 }
4840 return ToAssignLeft? ImplicitConversionSequence::Worse
4842 }
4843
4844 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4845 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4846 (FromAssignLeft != FromAssignRight))
4847 return FromAssignLeft? ImplicitConversionSequence::Better
4849 }
4850 }
4851
4852 // Ranking of member-pointer types.
4853 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4854 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4855 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4856 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4857 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4858 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4859 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4860 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4861 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4862 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4863 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4864 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4865 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4866 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4867 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4868 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4869 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4870 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4872 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4874 }
4875 // conversion of B::* to C::* is better than conversion of A::* to C::*
4876 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4877 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4879 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4881 }
4882 }
4883
4884 if (SCS1.Second == ICK_Derived_To_Base) {
4885 // -- conversion of C to B is better than conversion of C to A,
4886 // -- binding of an expression of type C to a reference of type
4887 // B& is better than binding an expression of type C to a
4888 // reference of type A&,
4889 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4890 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4891 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4893 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4895 }
4896
4897 // -- conversion of B to A is better than conversion of C to A.
4898 // -- binding of an expression of type B to a reference of type
4899 // A& is better than binding an expression of type C to a
4900 // reference of type A&,
4901 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4902 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4903 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4905 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4907 }
4908 }
4909
4911}
4912
4914 if (!T.getQualifiers().hasUnaligned())
4915 return T;
4916
4917 Qualifiers Q;
4918 T = Ctx.getUnqualifiedArrayType(T, Q);
4919 Q.removeUnaligned();
4920 return Ctx.getQualifiedType(T, Q);
4921}
4922
4925 QualType OrigT1, QualType OrigT2,
4926 ReferenceConversions *ConvOut) {
4927 assert(!OrigT1->isReferenceType() &&
4928 "T1 must be the pointee type of the reference type");
4929 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4930
4931 QualType T1 = Context.getCanonicalType(OrigT1);
4932 QualType T2 = Context.getCanonicalType(OrigT2);
4933 Qualifiers T1Quals, T2Quals;
4934 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4935 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4936
4937 ReferenceConversions ConvTmp;
4938 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4939 Conv = ReferenceConversions();
4940
4941 // C++2a [dcl.init.ref]p4:
4942 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4943 // reference-related to "cv2 T2" if T1 is similar to T2, or
4944 // T1 is a base class of T2.
4945 // "cv1 T1" is reference-compatible with "cv2 T2" if
4946 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4947 // "pointer to cv1 T1" via a standard conversion sequence.
4948
4949 // Check for standard conversions we can apply to pointers: derived-to-base
4950 // conversions, ObjC pointer conversions, and function pointer conversions.
4951 // (Qualification conversions are checked last.)
4952 QualType ConvertedT2;
4953 if (UnqualT1 == UnqualT2) {
4954 // Nothing to do.
4955 } else if (isCompleteType(Loc, OrigT2) &&
4956 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4957 Conv |= ReferenceConversions::DerivedToBase;
4958 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4959 UnqualT2->isObjCObjectOrInterfaceType() &&
4960 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4961 Conv |= ReferenceConversions::ObjC;
4962 else if (UnqualT2->isFunctionType() &&
4963 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4964 Conv |= ReferenceConversions::Function;
4965 // No need to check qualifiers; function types don't have them.
4966 return Ref_Compatible;
4967 }
4968 bool ConvertedReferent = Conv != 0;
4969
4970 // We can have a qualification conversion. Compute whether the types are
4971 // similar at the same time.
4972 bool PreviousToQualsIncludeConst = true;
4973 bool TopLevel = true;
4974 do {
4975 if (T1 == T2)
4976 break;
4977
4978 // We will need a qualification conversion.
4979 Conv |= ReferenceConversions::Qualification;
4980
4981 // Track whether we performed a qualification conversion anywhere other
4982 // than the top level. This matters for ranking reference bindings in
4983 // overload resolution.
4984 if (!TopLevel)
4985 Conv |= ReferenceConversions::NestedQualification;
4986
4987 // MS compiler ignores __unaligned qualifier for references; do the same.
4988 T1 = withoutUnaligned(Context, T1);
4989 T2 = withoutUnaligned(Context, T2);
4990
4991 // If we find a qualifier mismatch, the types are not reference-compatible,
4992 // but are still be reference-related if they're similar.
4993 bool ObjCLifetimeConversion = false;
4994 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4995 PreviousToQualsIncludeConst,
4996 ObjCLifetimeConversion, getASTContext()))
4997 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4998 ? Ref_Related
4999 : Ref_Incompatible;
5000
5001 // FIXME: Should we track this for any level other than the first?
5002 if (ObjCLifetimeConversion)
5003 Conv |= ReferenceConversions::ObjCLifetime;
5004
5005 TopLevel = false;
5006 } while (Context.UnwrapSimilarTypes(T1, T2));
5007
5008 // At this point, if the types are reference-related, we must either have the
5009 // same inner type (ignoring qualifiers), or must have already worked out how
5010 // to convert the referent.
5011 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5012 ? Ref_Compatible
5013 : Ref_Incompatible;
5014}
5015
5016/// Look for a user-defined conversion to a value reference-compatible
5017/// with DeclType. Return true if something definite is found.
5018static bool
5020 QualType DeclType, SourceLocation DeclLoc,
5021 Expr *Init, QualType T2, bool AllowRvalues,
5022 bool AllowExplicit) {
5023 assert(T2->isRecordType() && "Can only find conversions of record types.");
5024 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5025
5026 OverloadCandidateSet CandidateSet(
5028 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5029 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5030 NamedDecl *D = *I;
5031 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5032 if (isa<UsingShadowDecl>(D))
5033 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5034
5035 FunctionTemplateDecl *ConvTemplate
5036 = dyn_cast<FunctionTemplateDecl>(D);
5037 CXXConversionDecl *Conv;
5038 if (ConvTemplate)
5039 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5040 else
5041 Conv = cast<CXXConversionDecl>(D);
5042
5043 if (AllowRvalues) {
5044 // If we are initializing an rvalue reference, don't permit conversion
5045 // functions that return lvalues.
5046 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5047 const ReferenceType *RefType
5049 if (RefType && !RefType->getPointeeType()->isFunctionType())
5050 continue;
5051 }
5052
5053 if (!ConvTemplate &&
5055 DeclLoc,
5056 Conv->getConversionType()
5061 continue;
5062 } else {
5063 // If the conversion function doesn't return a reference type,
5064 // it can't be considered for this conversion. An rvalue reference
5065 // is only acceptable if its referencee is a function type.
5066
5067 const ReferenceType *RefType =
5069 if (!RefType ||
5070 (!RefType->isLValueReferenceType() &&
5071 !RefType->getPointeeType()->isFunctionType()))
5072 continue;
5073 }
5074
5075 if (ConvTemplate)
5077 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5078 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5079 else
5081 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5082 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5083 }
5084
5085 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5086
5088 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5089 case OR_Success:
5090 // C++ [over.ics.ref]p1:
5091 //
5092 // [...] If the parameter binds directly to the result of
5093 // applying a conversion function to the argument
5094 // expression, the implicit conversion sequence is a
5095 // user-defined conversion sequence (13.3.3.1.2), with the
5096 // second standard conversion sequence either an identity
5097 // conversion or, if the conversion function returns an
5098 // entity of a type that is a derived class of the parameter
5099 // type, a derived-to-base Conversion.
5100 if (!Best->FinalConversion.DirectBinding)
5101 return false;
5102
5103 ICS.setUserDefined();
5104 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5105 ICS.UserDefined.After = Best->FinalConversion;
5106 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5107 ICS.UserDefined.ConversionFunction = Best->Function;
5108 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5109 ICS.UserDefined.EllipsisConversion = false;
5110 assert(ICS.UserDefined.After.ReferenceBinding &&
5112 "Expected a direct reference binding!");
5113 return true;
5114
5115 case OR_Ambiguous:
5116 ICS.setAmbiguous();
5117 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5118 Cand != CandidateSet.end(); ++Cand)
5119 if (Cand->Best)
5120 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5121 return true;
5122
5124 case OR_Deleted:
5125 // There was no suitable conversion, or we found a deleted
5126 // conversion; continue with other checks.
5127 return false;
5128 }
5129
5130 llvm_unreachable("Invalid OverloadResult!");
5131}
5132
5133/// Compute an implicit conversion sequence for reference
5134/// initialization.
5137 SourceLocation DeclLoc,
5138 bool SuppressUserConversions,
5139 bool AllowExplicit) {
5140 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5141
5142 // Most paths end in a failed conversion.
5145
5146 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5147 QualType T2 = Init->getType();
5148
5149 // If the initializer is the address of an overloaded function, try
5150 // to resolve the overloaded function. If all goes well, T2 is the
5151 // type of the resulting function.
5152 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5155 false, Found))
5156 T2 = Fn->getType();
5157 }
5158
5159 // Compute some basic properties of the types and the initializer.
5160 bool isRValRef = DeclType->isRValueReferenceType();
5161 Expr::Classification InitCategory = Init->Classify(S.Context);
5162
5164 Sema::ReferenceCompareResult RefRelationship =
5165 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5166
5167 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5168 ICS.setStandard();
5170 // FIXME: A reference binding can be a function conversion too. We should
5171 // consider that when ordering reference-to-function bindings.
5172 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5174 : (RefConv & Sema::ReferenceConversions::ObjC)
5176 : ICK_Identity;
5178 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5179 // a reference binding that performs a non-top-level qualification
5180 // conversion as a qualification conversion, not as an identity conversion.
5181 ICS.Standard.Third = (RefConv &
5182 Sema::ReferenceConversions::NestedQualification)
5184 : ICK_Identity;
5185 ICS.Standard.setFromType(T2);
5186 ICS.Standard.setToType(0, T2);
5187 ICS.Standard.setToType(1, T1);
5188 ICS.Standard.setToType(2, T1);
5189 ICS.Standard.ReferenceBinding = true;
5190 ICS.Standard.DirectBinding = BindsDirectly;
5191 ICS.Standard.IsLvalueReference = !isRValRef;
5193 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5196 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5197 ICS.Standard.CopyConstructor = nullptr;
5199 };
5200
5201 // C++0x [dcl.init.ref]p5:
5202 // A reference to type "cv1 T1" is initialized by an expression
5203 // of type "cv2 T2" as follows:
5204
5205 // -- If reference is an lvalue reference and the initializer expression
5206 if (!isRValRef) {
5207 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5208 // reference-compatible with "cv2 T2," or
5209 //
5210 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5211 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5212 // C++ [over.ics.ref]p1:
5213 // When a parameter of reference type binds directly (8.5.3)
5214 // to an argument expression, the implicit conversion sequence
5215 // is the identity conversion, unless the argument expression
5216 // has a type that is a derived class of the parameter type,
5217 // in which case the implicit conversion sequence is a
5218 // derived-to-base Conversion (13.3.3.1).
5219 SetAsReferenceBinding(/*BindsDirectly=*/true);
5220
5221 // Nothing more to do: the inaccessibility/ambiguity check for
5222 // derived-to-base conversions is suppressed when we're
5223 // computing the implicit conversion sequence (C++
5224 // [over.best.ics]p2).
5225 return ICS;
5226 }
5227
5228 // -- has a class type (i.e., T2 is a class type), where T1 is
5229 // not reference-related to T2, and can be implicitly
5230 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5231 // is reference-compatible with "cv3 T3" 92) (this
5232 // conversion is selected by enumerating the applicable
5233 // conversion functions (13.3.1.6) and choosing the best
5234 // one through overload resolution (13.3)),
5235 if (!SuppressUserConversions && T2->isRecordType() &&
5236 S.isCompleteType(DeclLoc, T2) &&
5237 RefRelationship == Sema::Ref_Incompatible) {
5238 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5239 Init, T2, /*AllowRvalues=*/false,
5240 AllowExplicit))
5241 return ICS;
5242 }
5243 }
5244
5245 // -- Otherwise, the reference shall be an lvalue reference to a
5246 // non-volatile const type (i.e., cv1 shall be const), or the reference
5247 // shall be an rvalue reference.
5248 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5249 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5251 return ICS;
5252 }
5253
5254 // -- If the initializer expression
5255 //
5256 // -- is an xvalue, class prvalue, array prvalue or function
5257 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5258 if (RefRelationship == Sema::Ref_Compatible &&
5259 (InitCategory.isXValue() ||
5260 (InitCategory.isPRValue() &&
5261 (T2->isRecordType() || T2->isArrayType())) ||
5262 (InitCategory.isLValue() && T2->isFunctionType()))) {
5263 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5264 // binding unless we're binding to a class prvalue.
5265 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5266 // allow the use of rvalue references in C++98/03 for the benefit of
5267 // standard library implementors; therefore, we need the xvalue check here.
5268 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5269 !(InitCategory.isPRValue() || T2->isRecordType()));
5270 return ICS;
5271 }
5272
5273 // -- has a class type (i.e., T2 is a class type), where T1 is not
5274 // reference-related to T2, and can be implicitly converted to
5275 // an xvalue, class prvalue, or function lvalue of type
5276 // "cv3 T3", where "cv1 T1" is reference-compatible with
5277 // "cv3 T3",
5278 //
5279 // then the reference is bound to the value of the initializer
5280 // expression in the first case and to the result of the conversion
5281 // in the second case (or, in either case, to an appropriate base
5282 // class subobject).
5283 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5284 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5285 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5286 Init, T2, /*AllowRvalues=*/true,
5287 AllowExplicit)) {
5288 // In the second case, if the reference is an rvalue reference
5289 // and the second standard conversion sequence of the
5290 // user-defined conversion sequence includes an lvalue-to-rvalue
5291 // conversion, the program is ill-formed.
5292 if (ICS.isUserDefined() && isRValRef &&
5295
5296 return ICS;
5297 }
5298
5299 // A temporary of function type cannot be created; don't even try.
5300 if (T1->isFunctionType())
5301 return ICS;
5302
5303 // -- Otherwise, a temporary of type "cv1 T1" is created and
5304 // initialized from the initializer expression using the
5305 // rules for a non-reference copy initialization (8.5). The
5306 // reference is then bound to the temporary. If T1 is
5307 // reference-related to T2, cv1 must be the same
5308 // cv-qualification as, or greater cv-qualification than,
5309 // cv2; otherwise, the program is ill-formed.
5310 if (RefRelationship == Sema::Ref_Related) {
5311 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5312 // we would be reference-compatible or reference-compatible with
5313 // added qualification. But that wasn't the case, so the reference
5314 // initialization fails.
5315 //
5316 // Note that we only want to check address spaces and cvr-qualifiers here.
5317 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5318 Qualifiers T1Quals = T1.getQualifiers();
5319 Qualifiers T2Quals = T2.getQualifiers();
5320 T1Quals.removeObjCGCAttr();
5321 T1Quals.removeObjCLifetime();
5322 T2Quals.removeObjCGCAttr();
5323 T2Quals.removeObjCLifetime();
5324 // MS compiler ignores __unaligned qualifier for references; do the same.
5325 T1Quals.removeUnaligned();
5326 T2Quals.removeUnaligned();
5327 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5328 return ICS;
5329 }
5330
5331 // If at least one of the types is a class type, the types are not
5332 // related, and we aren't allowed any user conversions, the
5333 // reference binding fails. This case is important for breaking
5334 // recursion, since TryImplicitConversion below will attempt to
5335 // create a temporary through the use of a copy constructor.
5336 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5337 (T1->isRecordType() || T2->isRecordType()))
5338 return ICS;
5339
5340 // If T1 is reference-related to T2 and the reference is an rvalue
5341 // reference, the initializer expression shall not be an lvalue.
5342 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5343 Init->Classify(S.Context).isLValue()) {
5345 return ICS;
5346 }
5347
5348 // C++ [over.ics.ref]p2:
5349 // When a parameter of reference type is not bound directly to
5350 // an argument expression, the conversion sequence is the one
5351 // required to convert the argument expression to the
5352 // underlying type of the reference according to
5353 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5354 // to copy-initializing a temporary of the underlying type with
5355 // the argument expression. Any difference in top-level
5356 // cv-qualification is subsumed by the initialization itself
5357 // and does not constitute a conversion.
5358 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5359 AllowedExplicit::None,
5360 /*InOverloadResolution=*/false,
5361 /*CStyle=*/false,
5362 /*AllowObjCWritebackConversion=*/false,
5363 /*AllowObjCConversionOnExplicit=*/false);
5364
5365 // Of course, that's still a reference binding.
5366 if (ICS.isStandard()) {
5367 ICS.Standard.ReferenceBinding = true;
5368 ICS.Standard.IsLvalueReference = !isRValRef;
5369 ICS.Standard.BindsToFunctionLvalue = false;
5370 ICS.Standard.BindsToRvalue = true;
5373 } else if (ICS.isUserDefined()) {
5374 const ReferenceType *LValRefType =
5377
5378 // C++ [over.ics.ref]p3:
5379 // Except for an implicit object parameter, for which see 13.3.1, a
5380 // standard conversion sequence cannot be formed if it requires [...]
5381 // binding an rvalue reference to an lvalue other than a function
5382 // lvalue.
5383 // Note that the function case is not possible here.
5384 if (isRValRef && LValRefType) {
5386 return ICS;
5387 }
5388
5390 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5392 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5395 }
5396
5397 return ICS;
5398}
5399
5401TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5402 bool SuppressUserConversions,
5403 bool InOverloadResolution,
5404 bool AllowObjCWritebackConversion,
5405 bool AllowExplicit = false);
5406
5407/// TryListConversion - Try to copy-initialize a value of type ToType from the
5408/// initializer list From.
5411 bool SuppressUserConversions,
5412 bool InOverloadResolution,
5413 bool AllowObjCWritebackConversion) {
5414 // C++11 [over.ics.list]p1:
5415 // When an argument is an initializer list, it is not an expression and
5416 // special rules apply for converting it to a parameter type.
5417
5419 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5420
5421 // We need a complete type for what follows. With one C++20 exception,
5422 // incomplete types can never be initialized from init lists.
5423 QualType InitTy = ToType;
5424 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5425 if (AT && S.getLangOpts().CPlusPlus20)
5426 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5427 // C++20 allows list initialization of an incomplete array type.
5428 InitTy = IAT->getElementType();
5429 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5430 return Result;
5431
5432 // C++20 [over.ics.list]/2:
5433 // If the initializer list is a designated-initializer-list, a conversion
5434 // is only possible if the parameter has an aggregate type
5435 //
5436 // FIXME: The exception for reference initialization here is not part of the
5437 // language rules, but follow other compilers in adding it as a tentative DR
5438 // resolution.
5439 bool IsDesignatedInit = From->hasDesignatedInit();
5440 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5441 IsDesignatedInit)
5442 return Result;
5443
5444 // Per DR1467 and DR2137:
5445 // If the parameter type is an aggregate class X and the initializer list
5446 // has a single element of type cv U, where U is X or a class derived from
5447 // X, the implicit conversion sequence is the one required to convert the
5448 // element to the parameter type.
5449 //
5450 // Otherwise, if the parameter type is a character array [... ]
5451 // and the initializer list has a single element that is an
5452 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5453 // implicit conversion sequence is the identity conversion.
5454 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5455 if (ToType->isRecordType() && ToType->isAggregateType()) {
5456 QualType InitType = From->getInit(0)->getType();
5457 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5458 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5459 return TryCopyInitialization(S, From->getInit(0), ToType,
5460 SuppressUserConversions,
5461 InOverloadResolution,
5462 AllowObjCWritebackConversion);
5463 }
5464
5465 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5466 InitializedEntity Entity =
5468 /*Consumed=*/false);
5469 if (S.CanPerformCopyInitialization(Entity, From)) {
5470 Result.setStandard();
5471 Result.Standard.setAsIdentityConversion();
5472 Result.Standard.setFromType(ToType);
5473 Result.Standard.setAllToTypes(ToType);
5474 return Result;
5475 }
5476 }
5477 }
5478
5479 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5480 // C++11 [over.ics.list]p2:
5481 // If the parameter type is std::initializer_list<X> or "array of X" and
5482 // all the elements can be implicitly converted to X, the implicit
5483 // conversion sequence is the worst conversion necessary to convert an
5484 // element of the list to X.
5485 //
5486 // C++14 [over.ics.list]p3:
5487 // Otherwise, if the parameter type is "array of N X", if the initializer
5488 // list has exactly N elements or if it has fewer than N elements and X is
5489 // default-constructible, and if all the elements of the initializer list
5490 // can be implicitly converted to X, the implicit conversion sequence is
5491 // the worst conversion necessary to convert an element of the list to X.
5492 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5493 unsigned e = From->getNumInits();
5496 QualType());
5497 QualType ContTy = ToType;
5498 bool IsUnbounded = false;
5499 if (AT) {
5500 InitTy = AT->getElementType();
5501 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5502 if (CT->getSize().ult(e)) {
5503 // Too many inits, fatally bad
5505 ToType);
5506 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5507 return Result;
5508 }
5509 if (CT->getSize().ugt(e)) {
5510 // Need an init from empty {}, is there one?
5511 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5512 From->getEndLoc());
5513 EmptyList.setType(S.Context.VoidTy);
5514 DfltElt = TryListConversion(
5515 S, &EmptyList, InitTy, SuppressUserConversions,
5516 InOverloadResolution, AllowObjCWritebackConversion);
5517 if (DfltElt.isBad()) {
5518 // No {} init, fatally bad
5520 ToType);
5521 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5522 return Result;
5523 }
5524 }
5525 } else {
5526 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5527 IsUnbounded = true;
5528 if (!e) {
5529 // Cannot convert to zero-sized.
5531 ToType);
5532 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5533 return Result;
5534 }
5535 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5536 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5538 }
5539 }
5540
5541 Result.setStandard();
5542 Result.Standard.setAsIdentityConversion();
5543 Result.Standard.setFromType(InitTy);
5544 Result.Standard.setAllToTypes(InitTy);
5545 for (unsigned i = 0; i < e; ++i) {
5546 Expr *Init = From->getInit(i);
5548 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5549 AllowObjCWritebackConversion);
5550
5551 // Keep the worse conversion seen so far.
5552 // FIXME: Sequences are not totally ordered, so 'worse' can be
5553 // ambiguous. CWG has been informed.
5555 Result) ==
5557 Result = ICS;
5558 // Bail as soon as we find something unconvertible.
5559 if (Result.isBad()) {
5560 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5561 return Result;
5562 }
5563 }
5564 }
5565
5566 // If we needed any implicit {} initialization, compare that now.
5567 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5568 // has been informed that this might not be the best thing.
5569 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5570 S, From->getEndLoc(), DfltElt, Result) ==
5572 Result = DfltElt;
5573 // Record the type being initialized so that we may compare sequences
5574 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5575 return Result;
5576 }
5577
5578 // C++14 [over.ics.list]p4:
5579 // C++11 [over.ics.list]p3:
5580 // Otherwise, if the parameter is a non-aggregate class X and overload
5581 // resolution chooses a single best constructor [...] the implicit
5582 // conversion sequence is a user-defined conversion sequence. If multiple
5583 // constructors are viable but none is better than the others, the
5584 // implicit conversion sequence is a user-defined conversion sequence.
5585 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5586 // This function can deal with initializer lists.
5587 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5588 AllowedExplicit::None,
5589 InOverloadResolution, /*CStyle=*/false,
5590 AllowObjCWritebackConversion,
5591 /*AllowObjCConversionOnExplicit=*/false);
5592 }
5593
5594 // C++14 [over.ics.list]p5:
5595 // C++11 [over.ics.list]p4:
5596 // Otherwise, if the parameter has an aggregate type which can be
5597 // initialized from the initializer list [...] the implicit conversion
5598 // sequence is a user-defined conversion sequence.
5599 if (ToType->isAggregateType()) {
5600 // Type is an aggregate, argument is an init list. At this point it comes
5601 // down to checking whether the initialization works.
5602 // FIXME: Find out whether this parameter is consumed or not.
5603 InitializedEntity Entity =
5605 /*Consumed=*/false);
5607 From)) {
5608 Result.setUserDefined();
5609 Result.UserDefined.Before.setAsIdentityConversion();
5610 // Initializer lists don't have a type.
5611 Result.UserDefined.Before.setFromType(QualType());
5612 Result.UserDefined.Before.setAllToTypes(QualType());
5613
5614 Result.UserDefined.After.setAsIdentityConversion();
5615 Result.UserDefined.After.setFromType(ToType);
5616 Result.UserDefined.After.setAllToTypes(ToType);
5617 Result.UserDefined.ConversionFunction = nullptr;
5618 }
5619 return Result;
5620 }
5621
5622 // C++14 [over.ics.list]p6:
5623 // C++11 [over.ics.list]p5:
5624 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5625 if (ToType->isReferenceType()) {
5626 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5627 // mention initializer lists in any way. So we go by what list-
5628 // initialization would do and try to extrapolate from that.
5629
5630 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5631
5632 // If the initializer list has a single element that is reference-related
5633 // to the parameter type, we initialize the reference from that.
5634 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5635 Expr *Init = From->getInit(0);
5636
5637 QualType T2 = Init->getType();
5638
5639 // If the initializer is the address of an overloaded function, try
5640 // to resolve the overloaded function. If all goes well, T2 is the
5641 // type of the resulting function.
5642 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5645 Init, ToType, false, Found))
5646 T2 = Fn->getType();
5647 }
5648
5649 // Compute some basic properties of the types and the initializer.
5650 Sema::ReferenceCompareResult RefRelationship =
5651 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5652
5653 if (RefRelationship >= Sema::Ref_Related) {
5654 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5655 SuppressUserConversions,
5656 /*AllowExplicit=*/false);
5657 }
5658 }
5659
5660 // Otherwise, we bind the reference to a temporary created from the
5661 // initializer list.
5662 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5663 InOverloadResolution,
5664 AllowObjCWritebackConversion);
5665 if (Result.isFailure())
5666 return Result;
5667 assert(!Result.isEllipsis() &&
5668 "Sub-initialization cannot result in ellipsis conversion.");
5669
5670 // Can we even bind to a temporary?
5671 if (ToType->isRValueReferenceType() ||
5672 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5673 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5674 Result.UserDefined.After;
5675 SCS.ReferenceBinding = true;
5677 SCS.BindsToRvalue = true;
5678 SCS.BindsToFunctionLvalue = false;
5681 } else
5683 From, ToType);
5684 return Result;
5685 }
5686
5687 // C++14 [over.ics.list]p7:
5688 // C++11 [over.ics.list]p6:
5689 // Otherwise, if the parameter type is not a class:
5690 if (!ToType->isRecordType()) {
5691 // - if the initializer list has one element that is not itself an
5692 // initializer list, the implicit conversion sequence is the one
5693 // required to convert the element to the parameter type.
5694 unsigned NumInits = From->getNumInits();
5695 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5696 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5697 SuppressUserConversions,
5698 InOverloadResolution,
5699 AllowObjCWritebackConversion);
5700 // - if the initializer list has no elements, the implicit conversion
5701 // sequence is the identity conversion.
5702 else if (NumInits == 0) {
5703 Result.setStandard();
5704 Result.Standard.setAsIdentityConversion();
5705 Result.Standard.setFromType(ToType);
5706 Result.Standard.setAllToTypes(ToType);
5707 }
5708 return Result;
5709 }
5710
5711 // C++14 [over.ics.list]p8:
5712 // C++11 [over.ics.list]p7:
5713 // In all cases other than those enumerated above, no conversion is possible
5714 return Result;
5715}
5716
5717/// TryCopyInitialization - Try to copy-initialize a value of type
5718/// ToType from the expression From. Return the implicit conversion
5719/// sequence required to pass this argument, which may be a bad
5720/// conversion sequence (meaning that the argument cannot be passed to
5721/// a parameter of this type). If @p SuppressUserConversions, then we
5722/// do not permit any user-defined conversion sequences.
5725 bool SuppressUserConversions,
5726 bool InOverloadResolution,
5727 bool AllowObjCWritebackConversion,
5728 bool AllowExplicit) {
5729 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5730 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5731 InOverloadResolution,AllowObjCWritebackConversion);
5732
5733 if (ToType->isReferenceType())
5734 return TryReferenceInit(S, From, ToType,
5735 /*FIXME:*/ From->getBeginLoc(),
5736 SuppressUserConversions, AllowExplicit);
5737
5738 return TryImplicitConversion(S, From, ToType,
5739 SuppressUserConversions,
5740 AllowedExplicit::None,
5741 InOverloadResolution,
5742 /*CStyle=*/false,
5743 AllowObjCWritebackConversion,
5744 /*AllowObjCConversionOnExplicit=*/false);
5745}
5746
5747static bool TryCopyInitialization(const CanQualType FromQTy,
5748 const CanQualType ToQTy,
5749 Sema &S,
5750 SourceLocation Loc,
5751 ExprValueKind FromVK) {
5752 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5754 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5755
5756 return !ICS.isBad();
5757}
5758
5759/// TryObjectArgumentInitialization - Try to initialize the object
5760/// parameter of the given member function (@c Method) from the
5761/// expression @p From.
5763 Sema &S, SourceLocation Loc, QualType FromType,
5764 Expr::Classification FromClassification, CXXMethodDecl *Method,
5765 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5766 QualType ExplicitParameterType = QualType(),
5767 bool SuppressUserConversion = false) {
5768
5769 // We need to have an object of class type.
5770 if (const auto *PT = FromType->getAs<PointerType>()) {
5771 FromType = PT->getPointeeType();
5772
5773 // When we had a pointer, it's implicitly dereferenced, so we
5774 // better have an lvalue.
5775 assert(FromClassification.isLValue());
5776 }
5777
5778 auto ValueKindFromClassification = [](Expr::Classification C) {
5779 if (C.isPRValue())
5780 return clang::VK_PRValue;
5781 if (C.isXValue())
5782 return VK_XValue;
5783 return clang::VK_LValue;
5784 };
5785
5786 if (Method->isExplicitObjectMemberFunction()) {
5787 if (ExplicitParameterType.isNull())
5788 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5789 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5790 ValueKindFromClassification(FromClassification));
5792 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5793 /*InOverloadResolution=*/true, false);
5794 if (ICS.isBad())
5795 ICS.Bad.FromExpr = nullptr;
5796 return ICS;
5797 }
5798
5799 assert(FromType->isRecordType());
5800
5801 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5802 // C++98 [class.dtor]p2:
5803 // A destructor can be invoked for a const, volatile or const volatile
5804 // object.
5805 // C++98 [over.match.funcs]p4:
5806 // For static member functions, the implicit object parameter is considered
5807 // to match any object (since if the function is selected, the object is
5808 // discarded).
5809 Qualifiers Quals = Method->getMethodQualifiers();
5810 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5811 Quals.addConst();
5812 Quals.addVolatile();
5813 }
5814
5815 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5816
5817 // Set up the conversion sequence as a "bad" conversion, to allow us
5818 // to exit early.
5820
5821 // C++0x [over.match.funcs]p4:
5822 // For non-static member functions, the type of the implicit object
5823 // parameter is
5824 //
5825 // - "lvalue reference to cv X" for functions declared without a
5826 // ref-qualifier or with the & ref-qualifier
5827 // - "rvalue reference to cv X" for functions declared with the &&
5828 // ref-qualifier
5829 //
5830 // where X is the class of which the function is a member and cv is the
5831 // cv-qualification on the member function declaration.
5832 //
5833 // However, when finding an implicit conversion sequence for the argument, we
5834 // are not allowed to perform user-defined conversions
5835 // (C++ [over.match.funcs]p5). We perform a simplified version of
5836 // reference binding here, that allows class rvalues to bind to
5837 // non-constant references.
5838
5839 // First check the qualifiers.
5840 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5841 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5842 if (ImplicitParamType.getCVRQualifiers() !=
5843 FromTypeCanon.getLocalCVRQualifiers() &&
5844 !ImplicitParamType.isAtLeastAsQualifiedAs(
5845 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5847 FromType, ImplicitParamType);
5848 return ICS;
5849 }
5850
5851 if (FromTypeCanon.hasAddressSpace()) {
5852 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5853 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5854 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5855 S.getASTContext())) {
5857 FromType, ImplicitParamType);
5858 return ICS;
5859 }
5860 }
5861
5862 // Check that we have either the same type or a derived type. It
5863 // affects the conversion rank.
5864 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5865 ImplicitConversionKind SecondKind;
5866 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5867 SecondKind = ICK_Identity;
5868 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5869 SecondKind = ICK_Derived_To_Base;
5870 } else if (!Method->isExplicitObjectMemberFunction()) {
5872 FromType, ImplicitParamType);
5873 return ICS;
5874 }
5875
5876 // Check the ref-qualifier.
5877 switch (Method->getRefQualifier()) {
5878 case RQ_None:
5879 // Do nothing; we don't care about lvalueness or rvalueness.
5880 break;
5881
5882 case RQ_LValue:
5883 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5884 // non-const lvalue reference cannot bind to an rvalue
5886 ImplicitParamType);
5887 return ICS;
5888 }
5889 break;
5890
5891 case RQ_RValue:
5892 if (!FromClassification.isRValue()) {
5893 // rvalue reference cannot bind to an lvalue
5895 ImplicitParamType);
5896 return ICS;
5897 }
5898 break;
5899 }
5900
5901 // Success. Mark this as a reference binding.
5902 ICS.setStandard();
5904 ICS.Standard.Second = SecondKind;
5905 ICS.Standard.setFromType(FromType);
5906 ICS.Standard.setAllToTypes(ImplicitParamType);
5907 ICS.Standard.ReferenceBinding = true;
5908 ICS.Standard.DirectBinding = true;
5910 ICS.Standard.BindsToFunctionLvalue = false;
5911 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5913 = (Method->getRefQualifier() == RQ_None);
5914 return ICS;
5915}
5916
5917/// PerformObjectArgumentInitialization - Perform initialization of
5918/// the implicit object parameter for the given Method with the given
5919/// expression.
5921 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5922 CXXMethodDecl *Method) {
5923 QualType FromRecordType, DestType;
5924 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5925
5926 Expr::Classification FromClassification;
5927 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5928 FromRecordType = PT->getPointeeType();
5929 DestType = Method->getThisType();
5930 FromClassification = Expr::Classification::makeSimpleLValue();
5931 } else {
5932 FromRecordType = From->getType();
5933 DestType = ImplicitParamRecordType;
5934 FromClassification = From->Classify(Context);
5935
5936 // CWG2813 [expr.call]p6:
5937 // If the function is an implicit object member function, the object
5938 // expression of the class member access shall be a glvalue [...]
5939 if (From->isPRValue()) {
5940 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5941 Method->getRefQualifier() !=
5943 }
5944 }
5945
5946 // Note that we always use the true parent context when performing
5947 // the actual argument initialization.
5949 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5950 Method->getParent());
5951 if (ICS.isBad()) {
5952 switch (ICS.Bad.Kind) {
5954 Qualifiers FromQs = FromRecordType.getQualifiers();
5955 Qualifiers ToQs = DestType.getQualifiers();
5956 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5957 if (CVR) {
5958 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5959 << Method->getDeclName() << FromRecordType << (CVR - 1)
5960 << From->getSourceRange();
5961 Diag(Method->getLocation(), diag::note_previous_decl)
5962 << Method->getDeclName();
5963 return ExprError();
5964 }
5965 break;
5966 }
5967
5970 bool IsRValueQualified =
5972 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5973 << Method->getDeclName() << FromClassification.isRValue()
5974 << IsRValueQualified;
5975 Diag(Method->getLocation(), diag::note_previous_decl)
5976 << Method->getDeclName();
5977 return ExprError();
5978 }
5979
5982 break;
5983
5986 llvm_unreachable("Lists are not objects");
5987 }
5988
5989 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5990 << ImplicitParamRecordType << FromRecordType
5991 << From->getSourceRange();
5992 }
5993
5994 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5995 ExprResult FromRes =
5996 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5997 if (FromRes.isInvalid())
5998 return ExprError();
5999 From = FromRes.get();
6000 }
6001
6002 if (!Context.hasSameType(From->getType(), DestType)) {
6003 CastKind CK;
6004 QualType PteeTy = DestType->getPointeeType();
6005 LangAS DestAS =
6006 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6007 if (FromRecordType.getAddressSpace() != DestAS)
6008 CK = CK_AddressSpaceConversion;
6009 else
6010 CK = CK_NoOp;
6011 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6012 }
6013 return From;
6014}
6015
6016/// TryContextuallyConvertToBool - Attempt to contextually convert the
6017/// expression From to bool (C++0x [conv]p3).
6020 // C++ [dcl.init]/17.8:
6021 // - Otherwise, if the initialization is direct-initialization, the source
6022 // type is std::nullptr_t, and the destination type is bool, the initial
6023 // value of the object being initialized is false.
6024 if (From->getType()->isNullPtrType())
6026 S.Context.BoolTy,
6027 From->isGLValue());
6028
6029 // All other direct-initialization of bool is equivalent to an implicit
6030 // conversion to bool in which explicit conversions are permitted.
6031 return TryImplicitConversion(S, From, S.Context.BoolTy,
6032 /*SuppressUserConversions=*/false,
6033 AllowedExplicit::Conversions,
6034 /*InOverloadResolution=*/false,
6035 /*CStyle=*/false,
6036 /*AllowObjCWritebackConversion=*/false,
6037 /*AllowObjCConversionOnExplicit=*/false);
6038}
6039
6041 if (checkPlaceholderForOverload(*this, From))
6042 return ExprError();
6043
6045 if (!ICS.isBad())
6046 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6048
6049 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6050 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6051 << From->getType() << From->getSourceRange();
6052 return ExprError();
6053}
6054
6055/// Check that the specified conversion is permitted in a converted constant
6056/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6057/// is acceptable.
6060 // Since we know that the target type is an integral or unscoped enumeration
6061 // type, most conversion kinds are impossible. All possible First and Third
6062 // conversions are fine.
6063 switch (SCS.Second) {
6064 case ICK_Identity:
6066 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6068 return true;
6069
6071 // Conversion from an integral or unscoped enumeration type to bool is
6072 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6073 // conversion, so we allow it in a converted constant expression.
6074 //
6075 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6076 // a lot of popular code. We should at least add a warning for this
6077 // (non-conforming) extension.
6079 SCS.getToType(2)->isBooleanType();
6080
6082 case ICK_Pointer_Member:
6083 // C++1z: null pointer conversions and null member pointer conversions are
6084 // only permitted if the source type is std::nullptr_t.
6085 return SCS.getFromType()->isNullPtrType();
6086
6098 case ICK_Vector_Splat:
6099 case ICK_Complex_Real:
6108 return false;
6109
6114 llvm_unreachable("found a first conversion kind in Second");
6115
6117 case ICK_Qualification:
6118 llvm_unreachable("found a third conversion kind in Second");
6119
6121 break;
6122 }
6123
6124 llvm_unreachable("unknown conversion kind");
6125}
6126
6127/// BuildConvertedConstantExpression - Check that the expression From is a
6128/// converted constant expression of type T, perform the conversion but
6129/// does not evaluate the expression
6131 QualType T,
6132 Sema::CCEKind CCE,
6133 NamedDecl *Dest,
6134 APValue &PreNarrowingValue) {
6135 assert(S.getLangOpts().CPlusPlus11 &&
6136 "converted constant expression outside C++11");
6137
6138 if (checkPlaceholderForOverload(S, From))
6139 return ExprError();
6140
6141 // C++1z [expr.const]p3:
6142 // A converted constant expression of type T is an expression,
6143 // implicitly converted to type T, where the converted
6144 // expression is a constant expression and the implicit conversion
6145 // sequence contains only [... list of conversions ...].
6149 : TryCopyInitialization(S, From, T,
6150 /*SuppressUserConversions=*/false,
6151 /*InOverloadResolution=*/false,
6152 /*AllowObjCWritebackConversion=*/false,
6153 /*AllowExplicit=*/false);
6154 StandardConversionSequence *SCS = nullptr;
6155 switch (ICS.getKind()) {
6157 SCS = &ICS.Standard;
6158 break;
6160 if (T->isRecordType())
6161 SCS = &ICS.UserDefined.Before;
6162 else
6163 SCS = &ICS.UserDefined.After;
6164 break;
6168 return S.Diag(From->getBeginLoc(),
6169 diag::err_typecheck_converted_constant_expression)
6170 << From->getType() << From->getSourceRange() << T;
6171 return ExprError();
6172
6175 llvm_unreachable("bad conversion in converted constant expression");
6176 }
6177
6178 // Check that we would only use permitted conversions.
6179 if (!CheckConvertedConstantConversions(S, *SCS)) {
6180 return S.Diag(From->getBeginLoc(),
6181 diag::err_typecheck_converted_constant_expression_disallowed)
6182 << From->getType() << From->getSourceRange() << T;
6183 }
6184 // [...] and where the reference binding (if any) binds directly.
6185 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6186 return S.Diag(From->getBeginLoc(),
6187 diag::err_typecheck_converted_constant_expression_indirect)
6188 << From->getType() << From->getSourceRange() << T;
6189 }
6190 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6191 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6192 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6193 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6194 // case explicitly.
6195 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6196 return S.Diag(From->getBeginLoc(),
6197 diag::err_reference_bind_to_bitfield_in_cce)
6198 << From->getSourceRange();
6199 }
6200
6201 // Usually we can simply apply the ImplicitConversionSequence we formed
6202 // earlier, but that's not guaranteed to work when initializing an object of
6203 // class type.
6205 if (T->isRecordType()) {
6206 assert(CCE == Sema::CCEK_TemplateArg &&
6207 "unexpected class type converted constant expr");
6210 T, cast<NonTypeTemplateParmDecl>(Dest)),
6211 SourceLocation(), From);
6212 } else {
6213 Result =
6215 }
6216 if (Result.isInvalid())
6217 return Result;
6218
6219 // C++2a [intro.execution]p5:
6220 // A full-expression is [...] a constant-expression [...]
6221 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6222 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6224 if (Result.isInvalid())
6225 return Result;
6226
6227 // Check for a narrowing implicit conversion.
6228 bool ReturnPreNarrowingValue = false;
6229 QualType PreNarrowingType;
6230 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6231 PreNarrowingType)) {
6233 // Implicit conversion to a narrower type, but the expression is
6234 // value-dependent so we can't tell whether it's actually narrowing.
6236 // Implicit conversion to a narrower type, and the value is not a constant
6237 // expression. We'll diagnose this in a moment.
6238 case NK_Not_Narrowing:
6239 break;
6240
6242 if (CCE == Sema::CCEK_ArrayBound &&
6243 PreNarrowingType->isIntegralOrEnumerationType() &&
6244 PreNarrowingValue.isInt()) {
6245 // Don't diagnose array bound narrowing here; we produce more precise
6246 // errors by allowing the un-narrowed value through.
6247 ReturnPreNarrowingValue = true;
6248 break;
6249 }
6250 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6251 << CCE << /*Constant*/ 1
6252 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6253 break;
6254
6255 case NK_Type_Narrowing:
6256 // FIXME: It would be better to diagnose that the expression is not a
6257 // constant expression.
6258 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6259 << CCE << /*Constant*/ 0 << From->getType() << T;
6260 break;
6261 }
6262 if (!ReturnPreNarrowingValue)
6263 PreNarrowingValue = {};
6264
6265 return Result;
6266}
6267
6268/// CheckConvertedConstantExpression - Check that the expression From is a
6269/// converted constant expression of type T, perform the conversion and produce
6270/// the converted expression, per C++11 [expr.const]p3.
6273 Sema::CCEKind CCE,
6274 bool RequireInt,
6275 NamedDecl *Dest) {
6276
6277 APValue PreNarrowingValue;
6279 PreNarrowingValue);
6280 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6281 Value = APValue();
6282 return Result;
6283 }
6284 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6285 RequireInt, PreNarrowingValue);
6286}
6287
6289 CCEKind CCE,
6290 NamedDecl *Dest) {
6291 APValue PreNarrowingValue;
6292 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6293 PreNarrowingValue);
6294}
6295
6297 APValue &Value, CCEKind CCE,
6298 NamedDecl *Dest) {
6299 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6300 Dest);
6301}
6302
6304 llvm::APSInt &Value,
6305 CCEKind CCE) {
6306 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6307
6308 APValue V;
6309 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6310 /*Dest=*/nullptr);
6311 if (!R.isInvalid() && !R.get()->isValueDependent())
6312 Value = V.getInt();
6313 return R;
6314}
6315
6318 Sema::CCEKind CCE, bool RequireInt,
6319 const APValue &PreNarrowingValue) {
6320
6322 // Check the expression is a constant expression.
6324 Expr::EvalResult Eval;
6325 Eval.Diag = &Notes;
6326
6327 ConstantExprKind Kind;
6328 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6329 Kind = ConstantExprKind::ClassTemplateArgument;
6330 else if (CCE == Sema::CCEK_TemplateArg)
6331 Kind = ConstantExprKind::NonClassTemplateArgument;
6332 else
6333 Kind = ConstantExprKind::Normal;
6334
6335 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6336 (RequireInt && !Eval.Val.isInt())) {
6337 // The expression can't be folded, so we can't keep it at this position in
6338 // the AST.
6339 Result = ExprError();
6340 } else {
6341 Value = Eval.Val;
6342
6343 if (Notes.empty()) {
6344 // It's a constant expression.
6345 Expr *E = Result.get();
6346 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6347 // We expect a ConstantExpr to have a value associated with it
6348 // by this point.
6349 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6350 "ConstantExpr has no value associated with it");
6351 (void)CE;
6352 } else {
6353 E = ConstantExpr::Create(Context, Result.get(), Value);
6354 }
6355 if (!PreNarrowingValue.isAbsent())
6356 Value = std::move(PreNarrowingValue);
6357 return E;
6358 }
6359 }
6360
6361 // It's not a constant expression. Produce an appropriate diagnostic.
6362 if (Notes.size() == 1 &&
6363 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6364 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6365 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6366 diag::note_constexpr_invalid_template_arg) {
6367 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6368 for (unsigned I = 0; I < Notes.size(); ++I)
6369 Diag(Notes[I].first, Notes[I].second);
6370 } else {
6371 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6372 << CCE << E->getSourceRange();
6373 for (unsigned I = 0; I < Notes.size(); ++I)
6374 Diag(Notes[I].first, Notes[I].second);
6375 }
6376 return ExprError();
6377}
6378
6379/// dropPointerConversions - If the given standard conversion sequence
6380/// involves any pointer conversions, remove them. This may change
6381/// the result type of the conversion sequence.
6383 if (SCS.Second == ICK_Pointer_Conversion) {
6384 SCS.Second = ICK_Identity;
6385 SCS.Dimension = ICK_Identity;
6386 SCS.Third = ICK_Identity;
6387 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6388 }
6389}
6390
6391/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6392/// convert the expression From to an Objective-C pointer type.
6395 // Do an implicit conversion to 'id'.
6398 = TryImplicitConversion(S, From, Ty,
6399 // FIXME: Are these flags correct?
6400 /*SuppressUserConversions=*/false,
6401 AllowedExplicit::Conversions,
6402 /*InOverloadResolution=*/false,
6403 /*CStyle=*/false,
6404 /*AllowObjCWritebackConversion=*/false,
6405 /*AllowObjCConversionOnExplicit=*/true);
6406
6407 // Strip off any final conversions to 'id'.
6408 switch (ICS.getKind()) {
6413 break;
6414
6417 break;
6418
6421 break;
6422 }
6423
6424 return ICS;
6425}
6426
6428 if (checkPlaceholderForOverload(*this, From))
6429 return ExprError();
6430
6431 QualType Ty = Context.getObjCIdType();
6434 if (!ICS.isBad())
6435 return PerformImplicitConversion(From, Ty, ICS,
6437 return ExprResult();
6438}
6439
6440static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6441 const Expr *Base = nullptr;
6442 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6443 "expected a member expression");
6444
6445 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6446 M && !M->isImplicitAccess())
6447 Base = M->getBase();
6448 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6449 M && !M->isImplicitAccess())
6450 Base = M->getBase();
6451
6452 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6453
6454 if (T->isPointerType())
6455 T = T->getPointeeType();
6456
6457 return T;
6458}
6459
6461 const FunctionDecl *Fun) {
6462 QualType ObjType = Obj->getType();
6463 if (ObjType->isPointerType()) {
6464 ObjType = ObjType->getPointeeType();
6465 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6467 /*CanOverflow=*/false, FPOptionsOverride());
6468 }
6469 return Obj;
6470}
6471
6473 FunctionDecl *Fun) {
6474 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6477 Obj->getExprLoc(), Obj);
6478}
6479
6481 Expr *Object, MultiExprArg &Args,
6482 SmallVectorImpl<Expr *> &NewArgs) {
6483 assert(Method->isExplicitObjectMemberFunction() &&
6484 "Method is not an explicit member function");
6485 assert(NewArgs.empty() && "NewArgs should be empty");
6486
6487 NewArgs.reserve(Args.size() + 1);
6488 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6489 NewArgs.push_back(This);
6490 NewArgs.append(Args.begin(), Args.end());
6491 Args = NewArgs;
6493 Method, Object->getBeginLoc());
6494}
6495
6496/// Determine whether the provided type is an integral type, or an enumeration
6497/// type of a permitted flavor.
6499 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6501}
6502
6503static ExprResult
6506 QualType T, UnresolvedSetImpl &ViableConversions) {
6507
6508 if (Converter.Suppress)
6509 return ExprError();
6510
6511 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6512 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6513 CXXConversionDecl *Conv =
6514 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6516 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6517 }
6518 return From;
6519}
6520
6521static bool
6524 QualType T, bool HadMultipleCandidates,
6525 UnresolvedSetImpl &ExplicitConversions) {
6526 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6527 DeclAccessPair Found = ExplicitConversions[0];
6528 CXXConversionDecl *Conversion =
6529 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6530
6531 // The user probably meant to invoke the given explicit
6532 // conversion; use it.
6533 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6534 std::string TypeStr;
6535 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6536
6537 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6539 "static_cast<" + TypeStr + ">(")
6541 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6542 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6543
6544 // If we aren't in a SFINAE context, build a call to the
6545 // explicit conversion function.
6546 if (SemaRef.isSFINAEContext())
6547 return true;
6548
6549 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6550 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6551 HadMultipleCandidates);
6552 if (Result.isInvalid())
6553 return true;
6554
6555 // Replace the conversion with a RecoveryExpr, so we don't try to
6556 // instantiate it later, but can further diagnose here.
6557 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6558 From, Result.get()->getType());
6559 if (Result.isInvalid())
6560 return true;
6561 From = Result.get();
6562 }
6563 return false;
6564}
6565
6566static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6568 QualType T, bool HadMultipleCandidates,
6570 CXXConversionDecl *Conversion =
6571 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6572 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6573
6574 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6575 if (!Converter.SuppressConversion) {
6576 if (SemaRef.isSFINAEContext())
6577 return true;
6578
6579 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6580 << From->getSourceRange();
6581 }
6582
6583 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6584 HadMultipleCandidates);
6585 if (Result.isInvalid())
6586 return true;
6587 // Record usage of conversion in an implicit cast.
6588 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6589 CK_UserDefinedConversion, Result.get(),
6590 nullptr, Result.get()->getValueKind(),
6591 SemaRef.CurFPFeatureOverrides());
6592 return false;
6593}
6594
6596 Sema &SemaRef, SourceLocation Loc, Expr *From,
6598 if (!Converter.match(From->getType()) && !Converter.Suppress)
6599 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6600 << From->getSourceRange();
6601
6602 return SemaRef.DefaultLvalueConversion(From);
6603}
6604
6605static void
6607 UnresolvedSetImpl &ViableConversions,
6608 OverloadCandidateSet &CandidateSet) {
6609 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6610 NamedDecl *D = FoundDecl.getDecl();
6611 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6612 if (isa<UsingShadowDecl>(D))
6613 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6614
6615 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6617 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6618 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6619 continue;
6620 }
6621 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6622 SemaRef.AddConversionCandidate(
6623 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6624 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6625 }
6626}
6627
6628/// Attempt to convert the given expression to a type which is accepted
6629/// by the given converter.
6630///
6631/// This routine will attempt to convert an expression of class type to a
6632/// type accepted by the specified converter. In C++11 and before, the class
6633/// must have a single non-explicit conversion function converting to a matching
6634/// type. In C++1y, there can be multiple such conversion functions, but only
6635/// one target type.
6636///
6637/// \param Loc The source location of the construct that requires the
6638/// conversion.
6639///
6640/// \param From The expression we're converting from.
6641///
6642/// \param Converter Used to control and diagnose the conversion process.
6643///
6644/// \returns The expression, converted to an integral or enumeration type if
6645/// successful.
6647 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6648 // We can't perform any more checking for type-dependent expressions.
6649 if (From->isTypeDependent())
6650 return From;
6651
6652 // Process placeholders immediately.
6653 if (From->hasPlaceholderType()) {
6654 ExprResult result = CheckPlaceholderExpr(From);
6655 if (result.isInvalid())
6656 return result;
6657 From = result.get();
6658 }
6659
6660 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6661 ExprResult Converted = DefaultLvalueConversion(From);
6662 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6663 // If the expression already has a matching type, we're golden.
6664 if (Converter.match(T))
6665 return Converted;
6666
6667 // FIXME: Check for missing '()' if T is a function type?
6668
6669 // We can only perform contextual implicit conversions on objects of class
6670 // type.
6671 const RecordType *RecordTy = T->getAs<RecordType>();
6672 if (!RecordTy || !getLangOpts().CPlusPlus) {
6673 if (!Converter.Suppress)
6674 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6675 return From;
6676 }
6677
6678 // We must have a complete class type.
6679 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6680 ContextualImplicitConverter &Converter;
6681 Expr *From;
6682
6683 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6684 : Converter(Converter), From(From) {}
6685
6686 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6687 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6688 }
6689 } IncompleteDiagnoser(Converter, From);
6690
6691 if (Converter.Suppress ? !isCompleteType(Loc, T)
6692 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6693 return From;
6694
6695 // Look for a conversion to an integral or enumeration type.
6697 ViableConversions; // These are *potentially* viable in C++1y.
6698 UnresolvedSet<4> ExplicitConversions;
6699 const auto &Conversions =
6700 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6701
6702 bool HadMultipleCandidates =
6703 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6704
6705 // To check that there is only one target type, in C++1y:
6706 QualType ToType;
6707 bool HasUniqueTargetType = true;
6708
6709 // Collect explicit or viable (potentially in C++1y) conversions.
6710 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6711 NamedDecl *D = (*I)->getUnderlyingDecl();
6712 CXXConversionDecl *Conversion;
6713 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6714 if (ConvTemplate) {
6715 if (getLangOpts().CPlusPlus14)
6716 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6717 else
6718 continue; // C++11 does not consider conversion operator templates(?).
6719 } else
6720 Conversion = cast<CXXConversionDecl>(D);
6721
6722 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6723 "Conversion operator templates are considered potentially "
6724 "viable in C++1y");
6725
6726 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6727 if (Converter.match(CurToType) || ConvTemplate) {
6728
6729 if (Conversion->isExplicit()) {
6730 // FIXME: For C++1y, do we need this restriction?
6731 // cf. diagnoseNoViableConversion()
6732 if (!ConvTemplate)
6733 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6734 } else {
6735 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6736 if (ToType.isNull())
6737 ToType = CurToType.getUnqualifiedType();
6738 else if (HasUniqueTargetType &&
6739 (CurToType.getUnqualifiedType() != ToType))
6740 HasUniqueTargetType = false;
6741 }
6742 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6743 }
6744 }
6745 }
6746
6747 if (getLangOpts().CPlusPlus14) {
6748 // C++1y [conv]p6:
6749 // ... An expression e of class type E appearing in such a context
6750 // is said to be contextually implicitly converted to a specified
6751 // type T and is well-formed if and only if e can be implicitly
6752 // converted to a type T that is determined as follows: E is searched
6753 // for conversion functions whose return type is cv T or reference to
6754 // cv T such that T is allowed by the context. There shall be
6755 // exactly one such T.
6756
6757 // If no unique T is found:
6758 if (ToType.isNull()) {
6759 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6760 HadMultipleCandidates,
6761 ExplicitConversions))
6762 return ExprError();
6763 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6764 }
6765
6766 // If more than one unique Ts are found:
6767 if (!HasUniqueTargetType)
6768 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6769 ViableConversions);
6770
6771 // If one unique T is found:
6772 // First, build a candidate set from the previously recorded
6773 // potentially viable conversions.
6775 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6776 CandidateSet);
6777
6778 // Then, perform overload resolution over the candidate set.
6780 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6781 case OR_Success: {
6782 // Apply this conversion.
6784 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6785 if (recordConversion(*this, Loc, From, Converter, T,
6786 HadMultipleCandidates, Found))
6787 return ExprError();
6788 break;
6789 }
6790 case OR_Ambiguous:
6791 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6792 ViableConversions);
6794 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6795 HadMultipleCandidates,
6796 ExplicitConversions))
6797 return ExprError();
6798 [[fallthrough]];
6799 case OR_Deleted:
6800 // We'll complain below about a non-integral condition type.
6801 break;
6802 }
6803 } else {
6804 switch (ViableConversions.size()) {
6805 case 0: {
6806 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6807 HadMultipleCandidates,
6808 ExplicitConversions))
6809 return ExprError();
6810
6811 // We'll complain below about a non-integral condition type.
6812 break;
6813 }
6814 case 1: {
6815 // Apply this conversion.
6816 DeclAccessPair Found = ViableConversions[0];
6817 if (recordConversion(*this, Loc, From, Converter, T,
6818 HadMultipleCandidates, Found))
6819 return ExprError();
6820 break;
6821 }
6822 default:
6823 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6824 ViableConversions);
6825 }
6826 }
6827
6828 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6829}
6830
6831/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6832/// an acceptable non-member overloaded operator for a call whose
6833/// arguments have types T1 (and, if non-empty, T2). This routine
6834/// implements the check in C++ [over.match.oper]p3b2 concerning
6835/// enumeration types.
6837 FunctionDecl *Fn,
6838 ArrayRef<Expr *> Args) {
6839 QualType T1 = Args[0]->getType();
6840 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6841
6842 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6843 return true;
6844
6845 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6846 return true;
6847
6848 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6849 if (Proto->getNumParams() < 1)
6850 return false;
6851
6852 if (T1->isEnumeralType()) {
6853 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6854 if (Context.hasSameUnqualifiedType(T1, ArgType))
6855 return true;
6856 }
6857
6858 if (Proto->getNumParams() < 2)
6859 return false;
6860
6861 if (!T2.isNull() && T2->isEnumeralType()) {
6862 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6863 if (Context.hasSameUnqualifiedType(T2, ArgType))
6864 return true;
6865 }
6866
6867 return false;
6868}
6869
6872 return false;
6873
6874 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6875 return FD->isTargetMultiVersion();
6876
6877 if (!FD->isMultiVersion())
6878 return false;
6879
6880 // Among multiple target versions consider either the default,
6881 // or the first non-default in the absence of default version.
6882 unsigned SeenAt = 0;
6883 unsigned I = 0;
6884 bool HasDefault = false;
6886 FD, [&](const FunctionDecl *CurFD) {
6887 if (FD == CurFD)
6888 SeenAt = I;
6889 else if (CurFD->isTargetMultiVersionDefault())
6890 HasDefault = true;
6891 ++I;
6892 });
6893 return HasDefault || SeenAt != 0;
6894}
6895
6898 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6899 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6900 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6901 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6902 const FunctionProtoType *Proto
6903 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6904 assert(Proto && "Functions without a prototype cannot be overloaded");
6905 assert(!Function->getDescribedFunctionTemplate() &&
6906 "Use AddTemplateOverloadCandidate for function templates");
6907
6908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6909 if (!isa<CXXConstructorDecl>(Method)) {
6910 // If we get here, it's because we're calling a member function
6911 // that is named without a member access expression (e.g.,
6912 // "this->f") that was either written explicitly or created
6913 // implicitly. This can happen with a qualified call to a member
6914 // function, e.g., X::f(). We use an empty type for the implied
6915 // object argument (C++ [over.call.func]p3), and the acting context
6916 // is irrelevant.
6917 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6919 CandidateSet, SuppressUserConversions,
6920 PartialOverloading, EarlyConversions, PO);
6921 return;
6922 }
6923 // We treat a constructor like a non-member function, since its object
6924 // argument doesn't participate in overload resolution.
6925 }
6926
6927 if (!CandidateSet.isNewCandidate(Function, PO))
6928 return;
6929
6930 // C++11 [class.copy]p11: [DR1402]
6931 // A defaulted move constructor that is defined as deleted is ignored by
6932 // overload resolution.
6933 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6934 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6935 Constructor->isMoveConstructor())
6936 return;
6937
6938 // Overload resolution is always an unevaluated context.
6941
6942 // C++ [over.match.oper]p3:
6943 // if no operand has a class type, only those non-member functions in the
6944 // lookup set that have a first parameter of type T1 or "reference to
6945 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6946 // is a right operand) a second parameter of type T2 or "reference to
6947 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6948 // candidate functions.
6949 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6951 return;
6952
6953 // Add this candidate
6954 OverloadCandidate &Candidate =
6955 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6956 Candidate.FoundDecl = FoundDecl;
6957 Candidate.Function = Function;
6958 Candidate.Viable = true;
6959 Candidate.RewriteKind =
6960 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6961 Candidate.IsADLCandidate = IsADLCandidate;
6962 Candidate.ExplicitCallArguments = Args.size();
6963
6964 // Explicit functions are not actually candidates at all if we're not
6965 // allowing them in this context, but keep them around so we can point
6966 // to them in diagnostics.
6967 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6968 Candidate.Viable = false;
6969 Candidate.FailureKind = ovl_fail_explicit;
6970 return;
6971 }
6972
6973 // Functions with internal linkage are only viable in the same module unit.
6974 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6975 /// FIXME: Currently, the semantics of linkage in clang is slightly
6976 /// different from the semantics in C++ spec. In C++ spec, only names
6977 /// have linkage. So that all entities of the same should share one
6978 /// linkage. But in clang, different entities of the same could have
6979 /// different linkage.
6980 const NamedDecl *ND = Function;
6981 bool IsImplicitlyInstantiated = false;
6982 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
6983 ND = SpecInfo->getTemplate();
6984 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
6986 }
6987
6988 /// Don't remove inline functions with internal linkage from the overload
6989 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
6990 /// However:
6991 /// - Inline functions with internal linkage are a common pattern in
6992 /// headers to avoid ODR issues.
6993 /// - The global module is meant to be a transition mechanism for C and C++
6994 /// headers, and the current rules as written work against that goal.
6995 const bool IsInlineFunctionInGMF =
6996 Function->isFromGlobalModule() &&
6997 (IsImplicitlyInstantiated || Function->isInlined());
6998
6999 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7000 Candidate.Viable = false;
7002 return;
7003 }
7004 }
7005
7007 Candidate.Viable = false;
7009 return;
7010 }
7011
7012 if (Constructor) {
7013 // C++ [class.copy]p3:
7014 // A member function template is never instantiated to perform the copy
7015 // of a class object to an object of its class type.
7016 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7017 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7018 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7019 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7020 ClassType))) {
7021 Candidate.Viable = false;
7023 return;
7024 }
7025
7026 // C++ [over.match.funcs]p8: (proposed DR resolution)
7027 // A constructor inherited from class type C that has a first parameter
7028 // of type "reference to P" (including such a constructor instantiated
7029 // from a template) is excluded from the set of candidate functions when
7030 // constructing an object of type cv D if the argument list has exactly
7031 // one argument and D is reference-related to P and P is reference-related
7032 // to C.
7033 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7034 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7035 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7036 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7037 QualType C = Context.getRecordType(Constructor->getParent());
7038 QualType D = Context.getRecordType(Shadow->getParent());
7039 SourceLocation Loc = Args.front()->getExprLoc();
7040 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7041 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7042 Candidate.Viable = false;
7044 return;
7045 }
7046 }
7047
7048 // Check that the constructor is capable of constructing an object in the
7049 // destination address space.
7051 Constructor->getMethodQualifiers().getAddressSpace(),
7052 CandidateSet.getDestAS(), getASTContext())) {
7053 Candidate.Viable = false;
7055 }
7056 }
7057
7058 unsigned NumParams = Proto->getNumParams();
7059
7060 // (C++ 13.3.2p2): A candidate function having fewer than m
7061 // parameters is viable only if it has an ellipsis in its parameter
7062 // list (8.3.5).
7063 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7064 !Proto->isVariadic() &&
7065 shouldEnforceArgLimit(PartialOverloading, Function)) {
7066 Candidate.Viable = false;
7068 return;
7069 }
7070
7071 // (C++ 13.3.2p2): A candidate function having more than m parameters
7072 // is viable only if the (m+1)st parameter has a default argument
7073 // (8.3.6). For the purposes of overload resolution, the
7074 // parameter list is truncated on the right, so that there are
7075 // exactly m parameters.
7076 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7077 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7078 !PartialOverloading) {
7079 // Not enough arguments.
7080 Candidate.Viable = false;
7082 return;
7083 }
7084
7085 // (CUDA B.1): Check for invalid calls between targets.
7086 if (getLangOpts().CUDA) {
7087 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7088 // Skip the check for callers that are implicit members, because in this
7089 // case we may not yet know what the member's target is; the target is
7090 // inferred for the member automatically, based on the bases and fields of
7091 // the class.
7092 if (!(Caller && Caller->isImplicit()) &&
7093 !CUDA().IsAllowedCall(Caller, Function)) {
7094 Candidate.Viable = false;
7095 Candidate.FailureKind = ovl_fail_bad_target;
7096 return;
7097 }
7098 }
7099
7100 if (Function->getTrailingRequiresClause()) {
7101 ConstraintSatisfaction Satisfaction;
7102 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7103 /*ForOverloadResolution*/ true) ||
7104 !Satisfaction.IsSatisfied) {
7105 Candidate.Viable = false;
7107 return;
7108 }
7109 }
7110
7111 // Determine the implicit conversion sequences for each of the
7112 // arguments.
7113 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7114 unsigned ConvIdx =
7115 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7116 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7117 // We already formed a conversion sequence for this parameter during
7118 // template argument deduction.
7119 } else if (ArgIdx < NumParams) {
7120 // (C++ 13.3.2p3): for F to be a viable function, there shall
7121 // exist for each argument an implicit conversion sequence
7122 // (13.3.3.1) that converts that argument to the corresponding
7123 // parameter of F.
7124 QualType ParamType = Proto->getParamType(ArgIdx);
7125 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7126 if (ParamABI == ParameterABI::HLSLOut ||
7127 ParamABI == ParameterABI::HLSLInOut)
7128 ParamType = ParamType.getNonReferenceType();
7129 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7130 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7131 /*InOverloadResolution=*/true,
7132 /*AllowObjCWritebackConversion=*/
7133 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7134 if (Candidate.Conversions[ConvIdx].isBad()) {
7135 Candidate.Viable = false;
7137 return;
7138 }
7139 } else {
7140 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7141 // argument for which there is no corresponding parameter is
7142 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7143 Candidate.Conversions[ConvIdx].setEllipsis();
7144 }
7145 }
7146
7147 if (EnableIfAttr *FailedAttr =
7148 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7149 Candidate.Viable = false;
7150 Candidate.FailureKind = ovl_fail_enable_if;
7151 Candidate.DeductionFailure.Data = FailedAttr;
7152 return;
7153 }
7154}
7155
7159 if (Methods.size() <= 1)
7160 return nullptr;
7161
7162 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7163 bool Match = true;
7164 ObjCMethodDecl *Method = Methods[b];
7165 unsigned NumNamedArgs = Sel.getNumArgs();
7166 // Method might have more arguments than selector indicates. This is due
7167 // to addition of c-style arguments in method.
7168 if (Method->param_size() > NumNamedArgs)
7169 NumNamedArgs = Method->param_size();
7170 if (Args.size() < NumNamedArgs)
7171 continue;
7172
7173 for (unsigned i = 0; i < NumNamedArgs; i++) {
7174 // We can't do any type-checking on a type-dependent argument.
7175 if (Args[i]->isTypeDependent()) {
7176 Match = false;
7177 break;
7178 }
7179
7180 ParmVarDecl *param = Method->parameters()[i];
7181 Expr *argExpr = Args[i];
7182 assert(argExpr && "SelectBestMethod(): missing expression");
7183
7184 // Strip the unbridged-cast placeholder expression off unless it's
7185 // a consumed argument.
7186 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7187 !param->hasAttr<CFConsumedAttr>())
7188 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7189
7190 // If the parameter is __unknown_anytype, move on to the next method.
7191 if (param->getType() == Context.UnknownAnyTy) {
7192 Match = false;
7193 break;
7194 }
7195
7196 ImplicitConversionSequence ConversionState
7197 = TryCopyInitialization(*this, argExpr, param->getType(),
7198 /*SuppressUserConversions*/false,
7199 /*InOverloadResolution=*/true,
7200 /*AllowObjCWritebackConversion=*/
7201 getLangOpts().ObjCAutoRefCount,
7202 /*AllowExplicit*/false);
7203 // This function looks for a reasonably-exact match, so we consider
7204 // incompatible pointer conversions to be a failure here.
7205 if (ConversionState.isBad() ||
7206 (ConversionState.isStandard() &&
7207 ConversionState.Standard.Second ==
7209 Match = false;
7210 break;
7211 }
7212 }
7213 // Promote additional arguments to variadic methods.
7214 if (Match && Method->isVariadic()) {
7215 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7216 if (Args[i]->isTypeDependent()) {
7217 Match = false;
7218 break;
7219 }
7220 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7221 nullptr);
7222 if (Arg.isInvalid()) {
7223 Match = false;
7224 break;
7225 }
7226 }
7227 } else {
7228 // Check for extra arguments to non-variadic methods.
7229 if (Args.size() != NumNamedArgs)
7230 Match = false;
7231 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7232 // Special case when selectors have no argument. In this case, select
7233 // one with the most general result type of 'id'.
7234 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7235 QualType ReturnT = Methods[b]->getReturnType();
7236 if (ReturnT->isObjCIdType())
7237 return Methods[b];
7238 }
7239 }
7240 }
7241
7242 if (Match)
7243 return Method;
7244 }
7245 return nullptr;
7246}
7247
7249 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7250 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7251 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7252 if (ThisArg) {
7253 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7254 assert(!isa<CXXConstructorDecl>(Method) &&
7255 "Shouldn't have `this` for ctors!");
7256 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7258 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7259 if (R.isInvalid())
7260 return false;
7261 ConvertedThis = R.get();
7262 } else {
7263 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7264 (void)MD;
7265 assert((MissingImplicitThis || MD->isStatic() ||
7266 isa<CXXConstructorDecl>(MD)) &&
7267 "Expected `this` for non-ctor instance methods");
7268 }
7269 ConvertedThis = nullptr;
7270 }
7271
7272 // Ignore any variadic arguments. Converting them is pointless, since the
7273 // user can't refer to them in the function condition.
7274 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7275
7276 // Convert the arguments.
7277 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7278 ExprResult R;
7280 S.Context, Function->getParamDecl(I)),
7281 SourceLocation(), Args[I]);
7282
7283 if (R.isInvalid())
7284 return false;
7285
7286 ConvertedArgs.push_back(R.get());
7287 }
7288
7289 if (Trap.hasErrorOccurred())
7290 return false;
7291
7292 // Push default arguments if needed.
7293 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7294 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7295 ParmVarDecl *P = Function->getParamDecl(i);
7296 if (!P->hasDefaultArg())
7297 return false;
7299 if (R.isInvalid())
7300 return false;
7301 ConvertedArgs.push_back(R.get());
7302 }
7303
7304 if (Trap.hasErrorOccurred())
7305 return false;
7306 }
7307 return true;
7308}
7309
7311 SourceLocation CallLoc,
7312 ArrayRef<Expr *> Args,
7313 bool MissingImplicitThis) {
7314 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7315 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7316 return nullptr;
7317
7318 SFINAETrap Trap(*this);
7319 SmallVector<Expr *, 16> ConvertedArgs;
7320 // FIXME: We should look into making enable_if late-parsed.
7321 Expr *DiscardedThis;
7323 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7324 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7325 return *EnableIfAttrs.begin();
7326
7327 for (auto *EIA : EnableIfAttrs) {
7329 // FIXME: This doesn't consider value-dependent cases, because doing so is
7330 // very difficult. Ideally, we should handle them more gracefully.
7331 if (EIA->getCond()->isValueDependent() ||
7332 !EIA->getCond()->EvaluateWithSubstitution(
7333 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7334 return EIA;
7335
7336 if (!Result.isInt() || !Result.getInt().getBoolValue())
7337 return EIA;
7338 }
7339 return nullptr;
7340}
7341
7342template <typename CheckFn>
7344 bool ArgDependent, SourceLocation Loc,
7345 CheckFn &&IsSuccessful) {
7347 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7348 if (ArgDependent == DIA->getArgDependent())
7349 Attrs.push_back(DIA);
7350 }
7351
7352 // Common case: No diagnose_if attributes, so we can quit early.
7353 if (Attrs.empty())
7354 return false;
7355
7356 auto WarningBegin = std::stable_partition(
7357 Attrs.begin(), Attrs.end(),
7358 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7359
7360 // Note that diagnose_if attributes are late-parsed, so they appear in the
7361 // correct order (unlike enable_if attributes).
7362 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7363 IsSuccessful);
7364 if (ErrAttr != WarningBegin) {
7365 const DiagnoseIfAttr *DIA = *ErrAttr;
7366 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7367 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7368 << DIA->getParent() << DIA->getCond()->getSourceRange();
7369 return true;
7370 }
7371
7372 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7373 if (IsSuccessful(DIA)) {
7374 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7375 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7376 << DIA->getParent() << DIA->getCond()->getSourceRange();
7377 }
7378
7379 return false;
7380}
7381
7383 const Expr *ThisArg,
7385 SourceLocation Loc) {
7387 *this, Function, /*ArgDependent=*/true, Loc,
7388 [&](const DiagnoseIfAttr *DIA) {
7390 // It's sane to use the same Args for any redecl of this function, since
7391 // EvaluateWithSubstitution only cares about the position of each
7392 // argument in the arg list, not the ParmVarDecl* it maps to.
7393 if (!DIA->getCond()->EvaluateWithSubstitution(
7394 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7395 return false;
7396 return Result.isInt() && Result.getInt().getBoolValue();
7397 });
7398}
7399
7401 SourceLocation Loc) {
7403 *this, ND, /*ArgDependent=*/false, Loc,
7404 [&](const DiagnoseIfAttr *DIA) {
7405 bool Result;
7406 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7407 Result;
7408 });
7409}
7410
7412 ArrayRef<Expr *> Args,
7413 OverloadCandidateSet &CandidateSet,
7414 TemplateArgumentListInfo *ExplicitTemplateArgs,
7415 bool SuppressUserConversions,
7416 bool PartialOverloading,
7417 bool FirstArgumentIsBase) {
7418 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7419 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7420 ArrayRef<Expr *> FunctionArgs = Args;
7421
7422 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7423 FunctionDecl *FD =
7424 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7425
7426 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7427 QualType ObjectType;
7428 Expr::Classification ObjectClassification;
7429 if (Args.size() > 0) {
7430 if (Expr *E = Args[0]) {
7431 // Use the explicit base to restrict the lookup:
7432 ObjectType = E->getType();
7433 // Pointers in the object arguments are implicitly dereferenced, so we
7434 // always classify them as l-values.
7435 if (!ObjectType.isNull() && ObjectType->isPointerType())
7436 ObjectClassification = Expr::Classification::makeSimpleLValue();
7437 else
7438 ObjectClassification = E->Classify(Context);
7439 } // .. else there is an implicit base.
7440 FunctionArgs = Args.slice(1);
7441 }
7442 if (FunTmpl) {
7443 AddMethodTemplateCandidate(
7444 FunTmpl, F.getPair(),
7445 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7446 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7447 FunctionArgs, CandidateSet, SuppressUserConversions,
7448 PartialOverloading);
7449 } else {
7450 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7451 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7452 ObjectClassification, FunctionArgs, CandidateSet,
7453 SuppressUserConversions, PartialOverloading);
7454 }
7455 } else {
7456 // This branch handles both standalone functions and static methods.
7457
7458 // Slice the first argument (which is the base) when we access
7459 // static method as non-static.
7460 if (Args.size() > 0 &&
7461 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7462 !isa<CXXConstructorDecl>(FD)))) {
7463 assert(cast<CXXMethodDecl>(FD)->isStatic());
7464 FunctionArgs = Args.slice(1);
7465 }
7466 if (FunTmpl) {
7467 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7468 ExplicitTemplateArgs, FunctionArgs,
7469 CandidateSet, SuppressUserConversions,
7470 PartialOverloading);
7471 } else {
7472 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7473 SuppressUserConversions, PartialOverloading);
7474 }
7475 }
7476 }
7477}
7478
7480 Expr::Classification ObjectClassification,
7481 ArrayRef<Expr *> Args,
7482 OverloadCandidateSet &CandidateSet,
7483 bool SuppressUserConversions,
7485 NamedDecl *Decl = FoundDecl.getDecl();
7486 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7487
7488 if (isa<UsingShadowDecl>(Decl))
7489 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7490
7491 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7492 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7493 "Expected a member function template");
7494 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7495 /*ExplicitArgs*/ nullptr, ObjectType,
7496 ObjectClassification, Args, CandidateSet,
7497 SuppressUserConversions, false, PO);
7498 } else {
7499 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7500 ObjectType, ObjectClassification, Args, CandidateSet,
7501 SuppressUserConversions, false, {}, PO);
7502 }
7503}
7504
7505void
7507 CXXRecordDecl *ActingContext, QualType ObjectType,
7508 Expr::Classification ObjectClassification,
7509 ArrayRef<Expr *> Args,
7510 OverloadCandidateSet &CandidateSet,
7511 bool SuppressUserConversions,
7512 bool PartialOverloading,
7513 ConversionSequenceList EarlyConversions,
7515 const FunctionProtoType *Proto
7516 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7517 assert(Proto && "Methods without a prototype cannot be overloaded");
7518 assert(!isa<CXXConstructorDecl>(Method) &&
7519 "Use AddOverloadCandidate for constructors");
7520
7521 if (!CandidateSet.isNewCandidate(Method, PO))
7522 return;
7523
7524 // C++11 [class.copy]p23: [DR1402]
7525 // A defaulted move assignment operator that is defined as deleted is
7526 // ignored by overload resolution.
7527 if (Method->isDefaulted() && Method->isDeleted() &&
7528 Method->isMoveAssignmentOperator())
7529 return;
7530
7531 // Overload resolution is always an unevaluated context.
7534
7535 // Add this candidate
7536 OverloadCandidate &Candidate =
7537 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7538 Candidate.FoundDecl = FoundDecl;
7539 Candidate.Function = Method;
7540 Candidate.RewriteKind =
7541 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7542 Candidate.TookAddressOfOverload =
7544 Candidate.ExplicitCallArguments = Args.size();
7545
7546 bool IgnoreExplicitObject =
7547 (Method->isExplicitObjectMemberFunction() &&
7548 CandidateSet.getKind() ==
7550 bool ImplicitObjectMethodTreatedAsStatic =
7551 CandidateSet.getKind() ==
7554
7555 unsigned ExplicitOffset =
7556 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7557
7558 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7559 int(ImplicitObjectMethodTreatedAsStatic);
7560
7561 // (C++ 13.3.2p2): A candidate function having fewer than m
7562 // parameters is viable only if it has an ellipsis in its parameter
7563 // list (8.3.5).
7564 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7565 !Proto->isVariadic() &&
7566 shouldEnforceArgLimit(PartialOverloading, Method)) {
7567 Candidate.Viable = false;
7569 return;
7570 }
7571
7572 // (C++ 13.3.2p2): A candidate function having more than m parameters
7573 // is viable only if the (m+1)st parameter has a default argument
7574 // (8.3.6). For the purposes of overload resolution, the
7575 // parameter list is truncated on the right, so that there are
7576 // exactly m parameters.
7577 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7578 ExplicitOffset +
7579 int(ImplicitObjectMethodTreatedAsStatic);
7580
7581 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7582 // Not enough arguments.
7583 Candidate.Viable = false;
7585 return;
7586 }
7587
7588 Candidate.Viable = true;
7589
7590 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7591 if (ObjectType.isNull())
7592 Candidate.IgnoreObjectArgument = true;
7593 else if (Method->isStatic()) {
7594 // [over.best.ics.general]p8
7595 // When the parameter is the implicit object parameter of a static member
7596 // function, the implicit conversion sequence is a standard conversion
7597 // sequence that is neither better nor worse than any other standard
7598 // conversion sequence.
7599 //
7600 // This is a rule that was introduced in C++23 to support static lambdas. We
7601 // apply it retroactively because we want to support static lambdas as an
7602 // extension and it doesn't hurt previous code.
7603 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7604 } else {
7605 // Determine the implicit conversion sequence for the object
7606 // parameter.
7607 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7608 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7609 Method, ActingContext, /*InOverloadResolution=*/true);
7610 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7611 Candidate.Viable = false;
7613 return;
7614 }
7615 }
7616
7617 // (CUDA B.1): Check for invalid calls between targets.
7618 if (getLangOpts().CUDA)
7619 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7620 Method)) {
7621 Candidate.Viable = false;
7622 Candidate.FailureKind = ovl_fail_bad_target;
7623 return;
7624 }
7625
7626 if (Method->getTrailingRequiresClause()) {
7627 ConstraintSatisfaction Satisfaction;
7628 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7629 /*ForOverloadResolution*/ true) ||
7630 !Satisfaction.IsSatisfied) {
7631 Candidate.Viable = false;
7633 return;
7634 }
7635 }
7636
7637 // Determine the implicit conversion sequences for each of the
7638 // arguments.
7639 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7640 unsigned ConvIdx =
7641 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7642 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7643 // We already formed a conversion sequence for this parameter during
7644 // template argument deduction.
7645 } else if (ArgIdx < NumParams) {
7646 // (C++ 13.3.2p3): for F to be a viable function, there shall
7647 // exist for each argument an implicit conversion sequence
7648 // (13.3.3.1) that converts that argument to the corresponding
7649 // parameter of F.
7650 QualType ParamType;
7651 if (ImplicitObjectMethodTreatedAsStatic) {
7652 ParamType = ArgIdx == 0
7654 : Proto->getParamType(ArgIdx - 1);
7655 } else {
7656 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7657 }
7658 Candidate.Conversions[ConvIdx]
7659 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7660 SuppressUserConversions,
7661 /*InOverloadResolution=*/true,
7662 /*AllowObjCWritebackConversion=*/
7663 getLangOpts().ObjCAutoRefCount);
7664 if (Candidate.Conversions[ConvIdx].isBad()) {
7665 Candidate.Viable = false;
7667 return;
7668 }
7669 } else {
7670 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7671 // argument for which there is no corresponding parameter is
7672 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7673 Candidate.Conversions[ConvIdx].setEllipsis();
7674 }
7675 }
7676
7677 if (EnableIfAttr *FailedAttr =
7678 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7679 Candidate.Viable = false;
7680 Candidate.FailureKind = ovl_fail_enable_if;
7681 Candidate.DeductionFailure.Data = FailedAttr;
7682 return;
7683 }
7684
7685 if (isNonViableMultiVersionOverload(Method)) {
7686 Candidate.Viable = false;
7688 }
7689}
7690
7692 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7693 CXXRecordDecl *ActingContext,
7694 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7695 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7696 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7697 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7698 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7699 return;
7700
7701 // C++ [over.match.funcs]p7:
7702 // In each case where a candidate is a function template, candidate
7703 // function template specializations are generated using template argument
7704 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7705 // candidate functions in the usual way.113) A given name can refer to one
7706 // or more function templates and also to a set of overloaded non-template
7707 // functions. In such a case, the candidate functions generated from each
7708 // function template are combined with the set of non-template candidate
7709 // functions.
7710 TemplateDeductionInfo Info(CandidateSet.getLocation());
7711 FunctionDecl *Specialization = nullptr;
7712 ConversionSequenceList Conversions;
7714 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7715 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7716 ObjectClassification,
7717 [&](ArrayRef<QualType> ParamTypes) {
7718 return CheckNonDependentConversions(
7719 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7720 SuppressUserConversions, ActingContext, ObjectType,
7721 ObjectClassification, PO);
7722 });
7724 OverloadCandidate &Candidate =
7725 CandidateSet.addCandidate(Conversions.size(), Conversions);
7726 Candidate.FoundDecl = FoundDecl;
7727 Candidate.Function = MethodTmpl->getTemplatedDecl();
7728 Candidate.Viable = false;
7729 Candidate.RewriteKind =
7730 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7731 Candidate.IsSurrogate = false;
7732 Candidate.IgnoreObjectArgument =
7733 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7734 ObjectType.isNull();
7735 Candidate.ExplicitCallArguments = Args.size();
7738 else {
7741 Info);
7742 }
7743 return;
7744 }
7745
7746 // Add the function template specialization produced by template argument
7747 // deduction as a candidate.
7748 assert(Specialization && "Missing member function template specialization?");
7749 assert(isa<CXXMethodDecl>(Specialization) &&
7750 "Specialization is not a member function?");
7751 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7752 ActingContext, ObjectType, ObjectClassification, Args,
7753 CandidateSet, SuppressUserConversions, PartialOverloading,
7754 Conversions, PO);
7755}
7756
7757/// Determine whether a given function template has a simple explicit specifier
7758/// or a non-value-dependent explicit-specification that evaluates to true.
7761}
7762
7764 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7765 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7766 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7767 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7768 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7769 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7770 return;
7771
7772 // If the function template has a non-dependent explicit specification,
7773 // exclude it now if appropriate; we are not permitted to perform deduction
7774 // and substitution in this case.
7775 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7776 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7777 Candidate.FoundDecl = FoundDecl;
7778 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7779 Candidate.Viable = false;
7780 Candidate.FailureKind = ovl_fail_explicit;
7781 return;
7782 }
7783
7784 // C++ [over.match.funcs]p7:
7785 // In each case where a candidate is a function template, candidate
7786 // function template specializations are generated using template argument
7787 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7788 // candidate functions in the usual way.113) A given name can refer to one
7789 // or more function templates and also to a set of overloaded non-template
7790 // functions. In such a case, the candidate functions generated from each
7791 // function template are combined with the set of non-template candidate
7792 // functions.
7793 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7794 FunctionTemplate->getTemplateDepth());
7795 FunctionDecl *Specialization = nullptr;
7796 ConversionSequenceList Conversions;
7798 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7799 PartialOverloading, AggregateCandidateDeduction,
7800 /*ObjectType=*/QualType(),
7801 /*ObjectClassification=*/Expr::Classification(),
7802 [&](ArrayRef<QualType> ParamTypes) {
7803 return CheckNonDependentConversions(
7804 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7805 SuppressUserConversions, nullptr, QualType(), {}, PO);
7806 });
7808 OverloadCandidate &Candidate =
7809 CandidateSet.addCandidate(Conversions.size(), Conversions);
7810 Candidate.FoundDecl = FoundDecl;
7811 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7812 Candidate.Viable = false;
7813 Candidate.RewriteKind =
7814 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7815 Candidate.IsSurrogate = false;
7816 Candidate.IsADLCandidate = IsADLCandidate;
7817 // Ignore the object argument if there is one, since we don't have an object
7818 // type.
7819 Candidate.IgnoreObjectArgument =
7820 isa<CXXMethodDecl>(Candidate.Function) &&
7821 !isa<CXXConstructorDecl>(Candidate.Function);
7822 Candidate.ExplicitCallArguments = Args.size();
7825 else {
7828 Info);
7829 }
7830 return;
7831 }
7832
7833 // Add the function template specialization produced by template argument
7834 // deduction as a candidate.
7835 assert(Specialization && "Missing function template specialization?");
7836 AddOverloadCandidate(
7837 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7838 PartialOverloading, AllowExplicit,
7839 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7841}
7842
7844 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7845 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7846 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7847 CXXRecordDecl *ActingContext, QualType ObjectType,
7848 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7849 // FIXME: The cases in which we allow explicit conversions for constructor
7850 // arguments never consider calling a constructor template. It's not clear
7851 // that is correct.
7852 const bool AllowExplicit = false;
7853
7854 auto *FD = FunctionTemplate->getTemplatedDecl();
7855 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7856 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7857 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7858
7859 Conversions =
7860 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7861
7862 // Overload resolution is always an unevaluated context.
7865
7866 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7867 // require that, but this check should never result in a hard error, and
7868 // overload resolution is permitted to sidestep instantiations.
7869 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7870 !ObjectType.isNull()) {
7871 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7872 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7873 !ParamTypes[0]->isDependentType()) {
7874 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7875 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7876 Method, ActingContext, /*InOverloadResolution=*/true,
7877 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7878 : QualType());
7879 if (Conversions[ConvIdx].isBad())
7880 return true;
7881 }
7882 }
7883
7884 unsigned Offset =
7885 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7886
7887 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7888 I != N; ++I) {
7889 QualType ParamType = ParamTypes[I + Offset];
7890 if (!ParamType->isDependentType()) {
7891 unsigned ConvIdx;
7893 ConvIdx = Args.size() - 1 - I;
7894 assert(Args.size() + ThisConversions == 2 &&
7895 "number of args (including 'this') must be exactly 2 for "
7896 "reversed order");
7897 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7898 // would also be 0. 'this' got ConvIdx = 1 previously.
7899 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7900 } else {
7901 // For members, 'this' got ConvIdx = 0 previously.
7902 ConvIdx = ThisConversions + I;
7903 }
7904 Conversions[ConvIdx]
7905 = TryCopyInitialization(*this, Args[I], ParamType,
7906 SuppressUserConversions,
7907 /*InOverloadResolution=*/true,
7908 /*AllowObjCWritebackConversion=*/
7909 getLangOpts().ObjCAutoRefCount,
7910 AllowExplicit);
7911 if (Conversions[ConvIdx].isBad())
7912 return true;
7913 }
7914 }
7915
7916 return false;
7917}
7918
7919/// Determine whether this is an allowable conversion from the result
7920/// of an explicit conversion operator to the expected type, per C++
7921/// [over.match.conv]p1 and [over.match.ref]p1.
7922///
7923/// \param ConvType The return type of the conversion function.
7924///
7925/// \param ToType The type we are converting to.
7926///
7927/// \param AllowObjCPointerConversion Allow a conversion from one
7928/// Objective-C pointer to another.
7929///
7930/// \returns true if the conversion is allowable, false otherwise.
7932 QualType ConvType, QualType ToType,
7933 bool AllowObjCPointerConversion) {
7934 QualType ToNonRefType = ToType.getNonReferenceType();
7935
7936 // Easy case: the types are the same.
7937 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7938 return true;
7939
7940 // Allow qualification conversions.
7941 bool ObjCLifetimeConversion;
7942 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7943 ObjCLifetimeConversion))
7944 return true;
7945
7946 // If we're not allowed to consider Objective-C pointer conversions,
7947 // we're done.
7948 if (!AllowObjCPointerConversion)
7949 return false;
7950
7951 // Is this an Objective-C pointer conversion?
7952 bool IncompatibleObjC = false;
7953 QualType ConvertedType;
7954 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7955 IncompatibleObjC);
7956}
7957
7959 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7960 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7961 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7962 bool AllowExplicit, bool AllowResultConversion) {
7963 assert(!Conversion->getDescribedFunctionTemplate() &&
7964 "Conversion function templates use AddTemplateConversionCandidate");
7965 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7966 if (!CandidateSet.isNewCandidate(Conversion))
7967 return;
7968
7969 // If the conversion function has an undeduced return type, trigger its
7970 // deduction now.
7971 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7972 if (DeduceReturnType(Conversion, From->getExprLoc()))
7973 return;
7974 ConvType = Conversion->getConversionType().getNonReferenceType();
7975 }
7976
7977 // If we don't allow any conversion of the result type, ignore conversion
7978 // functions that don't convert to exactly (possibly cv-qualified) T.
7979 if (!AllowResultConversion &&
7980 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7981 return;
7982
7983 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7984 // operator is only a candidate if its return type is the target type or
7985 // can be converted to the target type with a qualification conversion.
7986 //
7987 // FIXME: Include such functions in the candidate list and explain why we
7988 // can't select them.
7989 if (Conversion->isExplicit() &&
7990 !isAllowableExplicitConversion(*this, ConvType, ToType,
7991 AllowObjCConversionOnExplicit))
7992 return;
7993
7994 // Overload resolution is always an unevaluated context.
7997
7998 // Add this candidate
7999 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8000 Candidate.FoundDecl = FoundDecl;
8001 Candidate.Function = Conversion;
8003 Candidate.FinalConversion.setFromType(ConvType);
8004 Candidate.FinalConversion.setAllToTypes(ToType);
8005 Candidate.Viable = true;
8006 Candidate.ExplicitCallArguments = 1;
8007
8008 // Explicit functions are not actually candidates at all if we're not
8009 // allowing them in this context, but keep them around so we can point
8010 // to them in diagnostics.
8011 if (!AllowExplicit && Conversion->isExplicit()) {
8012 Candidate.Viable = false;
8013 Candidate.FailureKind = ovl_fail_explicit;
8014 return;
8015 }
8016
8017 // C++ [over.match.funcs]p4:
8018 // For conversion functions, the function is considered to be a member of
8019 // the class of the implicit implied object argument for the purpose of
8020 // defining the type of the implicit object parameter.
8021 //
8022 // Determine the implicit conversion sequence for the implicit
8023 // object parameter.
8024 QualType ObjectType = From->getType();
8025 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8026 ObjectType = FromPtrType->getPointeeType();
8027 const auto *ConversionContext =
8028 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8029
8030 // C++23 [over.best.ics.general]
8031 // However, if the target is [...]
8032 // - the object parameter of a user-defined conversion function
8033 // [...] user-defined conversion sequences are not considered.
8035 *this, CandidateSet.getLocation(), From->getType(),
8036 From->Classify(Context), Conversion, ConversionContext,
8037 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8038 /*SuppressUserConversion*/ true);
8039
8040 if (Candidate.Conversions[0].isBad()) {
8041 Candidate.Viable = false;
8043 return;
8044 }
8045
8046 if (Conversion->getTrailingRequiresClause()) {
8047 ConstraintSatisfaction Satisfaction;
8048 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8049 !Satisfaction.IsSatisfied) {
8050 Candidate.Viable = false;
8052 return;
8053 }
8054 }
8055
8056 // We won't go through a user-defined type conversion function to convert a
8057 // derived to base as such conversions are given Conversion Rank. They only
8058 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8059 QualType FromCanon
8060 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8061 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8062 if (FromCanon == ToCanon ||
8063 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8064 Candidate.Viable = false;
8066 return;
8067 }
8068
8069 // To determine what the conversion from the result of calling the
8070 // conversion function to the type we're eventually trying to
8071 // convert to (ToType), we need to synthesize a call to the
8072 // conversion function and attempt copy initialization from it. This
8073 // makes sure that we get the right semantics with respect to
8074 // lvalues/rvalues and the type. Fortunately, we can allocate this
8075 // call on the stack and we don't need its arguments to be
8076 // well-formed.
8077 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8078 VK_LValue, From->getBeginLoc());
8080 Context.getPointerType(Conversion->getType()),
8081 CK_FunctionToPointerDecay, &ConversionRef,
8083
8084 QualType ConversionType = Conversion->getConversionType();
8085 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8086 Candidate.Viable = false;
8088 return;
8089 }
8090
8091 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8092
8093 // Note that it is safe to allocate CallExpr on the stack here because
8094 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8095 // allocator).
8096 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8097
8098 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8099 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8100 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8101
8103 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8104 /*SuppressUserConversions=*/true,
8105 /*InOverloadResolution=*/false,
8106 /*AllowObjCWritebackConversion=*/false);
8107
8108 switch (ICS.getKind()) {
8110 Candidate.FinalConversion = ICS.Standard;
8111
8112 // C++ [over.ics.user]p3:
8113 // If the user-defined conversion is specified by a specialization of a
8114 // conversion function template, the second standard conversion sequence
8115 // shall have exact match rank.
8116 if (Conversion->getPrimaryTemplate() &&
8118 Candidate.Viable = false;
8120 return;
8121 }
8122
8123 // C++0x [dcl.init.ref]p5:
8124 // In the second case, if the reference is an rvalue reference and
8125 // the second standard conversion sequence of the user-defined
8126 // conversion sequence includes an lvalue-to-rvalue conversion, the
8127 // program is ill-formed.
8128 if (ToType->isRValueReferenceType() &&
8130 Candidate.Viable = false;
8132 return;
8133 }
8134 break;
8135
8137 Candidate.Viable = false;
8139 return;
8140
8141 default:
8142 llvm_unreachable(
8143 "Can only end up with a standard conversion sequence or failure");
8144 }
8145
8146 if (EnableIfAttr *FailedAttr =
8147 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8148 Candidate.Viable = false;
8149 Candidate.FailureKind = ovl_fail_enable_if;
8150 Candidate.DeductionFailure.Data = FailedAttr;
8151 return;
8152 }
8153
8154 if (isNonViableMultiVersionOverload(Conversion)) {
8155 Candidate.Viable = false;
8157 }
8158}
8159
8161 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8162 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8163 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8164 bool AllowExplicit, bool AllowResultConversion) {
8165 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8166 "Only conversion function templates permitted here");
8167
8168 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8169 return;
8170
8171 // If the function template has a non-dependent explicit specification,
8172 // exclude it now if appropriate; we are not permitted to perform deduction
8173 // and substitution in this case.
8174 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8175 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8176 Candidate.FoundDecl = FoundDecl;
8177 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8178 Candidate.Viable = false;
8179 Candidate.FailureKind = ovl_fail_explicit;
8180 return;
8181 }
8182
8183 QualType ObjectType = From->getType();
8184 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8185
8186 TemplateDeductionInfo Info(CandidateSet.getLocation());
8189 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8190 Specialization, Info);
8192 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8193 Candidate.FoundDecl = FoundDecl;
8194 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8195 Candidate.Viable = false;
8197 Candidate.ExplicitCallArguments = 1;
8199 Info);
8200 return;
8201 }
8202
8203 // Add the conversion function template specialization produced by
8204 // template argument deduction as a candidate.
8205 assert(Specialization && "Missing function template specialization?");
8206 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8207 CandidateSet, AllowObjCConversionOnExplicit,
8208 AllowExplicit, AllowResultConversion);
8209}
8210
8212 DeclAccessPair FoundDecl,
8213 CXXRecordDecl *ActingContext,
8214 const FunctionProtoType *Proto,
8215 Expr *Object,
8216 ArrayRef<Expr *> Args,
8217 OverloadCandidateSet& CandidateSet) {
8218 if (!CandidateSet.isNewCandidate(Conversion))
8219 return;
8220
8221 // Overload resolution is always an unevaluated context.
8224
8225 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8226 Candidate.FoundDecl = FoundDecl;
8227 Candidate.Function = nullptr;
8228 Candidate.Surrogate = Conversion;
8229 Candidate.IsSurrogate = true;
8230 Candidate.Viable = true;
8231 Candidate.ExplicitCallArguments = Args.size();
8232
8233 // Determine the implicit conversion sequence for the implicit
8234 // object parameter.
8235 ImplicitConversionSequence ObjectInit;
8236 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8237 ObjectInit = TryCopyInitialization(*this, Object,
8238 Conversion->getParamDecl(0)->getType(),
8239 /*SuppressUserConversions=*/false,
8240 /*InOverloadResolution=*/true, false);
8241 } else {
8243 *this, CandidateSet.getLocation(), Object->getType(),
8244 Object->Classify(Context), Conversion, ActingContext);
8245 }
8246
8247 if (ObjectInit.isBad()) {
8248 Candidate.Viable = false;
8250 Candidate.Conversions[0] = ObjectInit;
8251 return;
8252 }
8253
8254 // The first conversion is actually a user-defined conversion whose
8255 // first conversion is ObjectInit's standard conversion (which is
8256 // effectively a reference binding). Record it as such.
8257 Candidate.Conversions[0].setUserDefined();
8258 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8259 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8260 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8261 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8262 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8263 Candidate.Conversions[0].UserDefined.After
8264 = Candidate.Conversions[0].UserDefined.Before;
8265 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8266
8267 // Find the
8268 unsigned NumParams = Proto->getNumParams();
8269
8270 // (C++ 13.3.2p2): A candidate function having fewer than m
8271 // parameters is viable only if it has an ellipsis in its parameter
8272 // list (8.3.5).
8273 if (Args.size() > NumParams && !Proto->isVariadic()) {
8274 Candidate.Viable = false;
8276 return;
8277 }
8278
8279 // Function types don't have any default arguments, so just check if
8280 // we have enough arguments.
8281 if (Args.size() < NumParams) {
8282 // Not enough arguments.
8283 Candidate.Viable = false;
8285 return;
8286 }
8287
8288 // Determine the implicit conversion sequences for each of the
8289 // arguments.
8290 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8291 if (ArgIdx < NumParams) {
8292 // (C++ 13.3.2p3): for F to be a viable function, there shall
8293 // exist for each argument an implicit conversion sequence
8294 // (13.3.3.1) that converts that argument to the corresponding
8295 // parameter of F.
8296 QualType ParamType = Proto->getParamType(ArgIdx);
8297 Candidate.Conversions[ArgIdx + 1]
8298 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8299 /*SuppressUserConversions=*/false,
8300 /*InOverloadResolution=*/false,
8301 /*AllowObjCWritebackConversion=*/
8302 getLangOpts().ObjCAutoRefCount);
8303 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8304 Candidate.Viable = false;
8306 return;
8307 }
8308 } else {
8309 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8310 // argument for which there is no corresponding parameter is
8311 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8312 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8313 }
8314 }
8315
8316 if (Conversion->getTrailingRequiresClause()) {
8317 ConstraintSatisfaction Satisfaction;
8318 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8319 /*ForOverloadResolution*/ true) ||
8320 !Satisfaction.IsSatisfied) {
8321 Candidate.Viable = false;
8323 return;
8324 }
8325 }
8326
8327 if (EnableIfAttr *FailedAttr =
8328 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8329 Candidate.Viable = false;
8330 Candidate.FailureKind = ovl_fail_enable_if;
8331 Candidate.DeductionFailure.Data = FailedAttr;
8332 return;
8333 }
8334}
8335
8337 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8338 OverloadCandidateSet &CandidateSet,
8339 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8340 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8341 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8342 ArrayRef<Expr *> FunctionArgs = Args;
8343
8344 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8345 FunctionDecl *FD =
8346 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8347
8348 // Don't consider rewritten functions if we're not rewriting.
8349 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8350 continue;
8351
8352 assert(!isa<CXXMethodDecl>(FD) &&
8353 "unqualified operator lookup found a member function");
8354
8355 if (FunTmpl) {
8356 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8357 FunctionArgs, CandidateSet);
8358 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8359 AddTemplateOverloadCandidate(
8360 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8361 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8362 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8363 } else {
8364 if (ExplicitTemplateArgs)
8365 continue;
8366 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8367 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8368 AddOverloadCandidate(FD, F.getPair(),
8369 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8370 false, false, true, false, ADLCallKind::NotADL, {},
8372 }
8373 }
8374}
8375
8377 SourceLocation OpLoc,
8378 ArrayRef<Expr *> Args,
8379 OverloadCandidateSet &CandidateSet,
8382
8383 // C++ [over.match.oper]p3:
8384 // For a unary operator @ with an operand of a type whose
8385 // cv-unqualified version is T1, and for a binary operator @ with
8386 // a left operand of a type whose cv-unqualified version is T1 and
8387 // a right operand of a type whose cv-unqualified version is T2,
8388 // three sets of candidate functions, designated member
8389 // candidates, non-member candidates and built-in candidates, are
8390 // constructed as follows:
8391 QualType T1 = Args[0]->getType();
8392
8393 // -- If T1 is a complete class type or a class currently being
8394 // defined, the set of member candidates is the result of the
8395 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8396 // the set of member candidates is empty.
8397 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8398 // Complete the type if it can be completed.
8399 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8400 return;
8401 // If the type is neither complete nor being defined, bail out now.
8402 if (!T1Rec->getDecl()->getDefinition())
8403 return;
8404
8405 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8406 LookupQualifiedName(Operators, T1Rec->getDecl());
8407 Operators.suppressAccessDiagnostics();
8408
8409 for (LookupResult::iterator Oper = Operators.begin(),
8410 OperEnd = Operators.end();
8411 Oper != OperEnd; ++Oper) {
8412 if (Oper->getAsFunction() &&
8414 !CandidateSet.getRewriteInfo().shouldAddReversed(
8415 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8416 continue;
8417 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8418 Args[0]->Classify(Context), Args.slice(1),
8419 CandidateSet, /*SuppressUserConversion=*/false, PO);
8420 }
8421 }
8422}
8423
8425 OverloadCandidateSet& CandidateSet,
8426 bool IsAssignmentOperator,
8427 unsigned NumContextualBoolArguments) {
8428 // Overload resolution is always an unevaluated context.
8431
8432 // Add this candidate
8433 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8434 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8435 Candidate.Function = nullptr;
8436 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8437
8438 // Determine the implicit conversion sequences for each of the
8439 // arguments.
8440 Candidate.Viable = true;
8441 Candidate.ExplicitCallArguments = Args.size();
8442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8443 // C++ [over.match.oper]p4:
8444 // For the built-in assignment operators, conversions of the
8445 // left operand are restricted as follows:
8446 // -- no temporaries are introduced to hold the left operand, and
8447 // -- no user-defined conversions are applied to the left
8448 // operand to achieve a type match with the left-most
8449 // parameter of a built-in candidate.
8450 //
8451 // We block these conversions by turning off user-defined
8452 // conversions, since that is the only way that initialization of
8453 // a reference to a non-class type can occur from something that
8454 // is not of the same type.
8455 if (ArgIdx < NumContextualBoolArguments) {
8456 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8457 "Contextual conversion to bool requires bool type");
8458 Candidate.Conversions[ArgIdx]
8459 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8460 } else {
8461 Candidate.Conversions[ArgIdx]
8462 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8463 ArgIdx == 0 && IsAssignmentOperator,
8464 /*InOverloadResolution=*/false,
8465 /*AllowObjCWritebackConversion=*/
8466 getLangOpts().ObjCAutoRefCount);
8467 }
8468 if (Candidate.Conversions[ArgIdx].isBad()) {
8469 Candidate.Viable = false;
8471 break;
8472 }
8473 }
8474}
8475
8476namespace {
8477
8478/// BuiltinCandidateTypeSet - A set of types that will be used for the
8479/// candidate operator functions for built-in operators (C++
8480/// [over.built]). The types are separated into pointer types and
8481/// enumeration types.
8482class BuiltinCandidateTypeSet {
8483 /// TypeSet - A set of types.
8484 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8485
8486 /// PointerTypes - The set of pointer types that will be used in the
8487 /// built-in candidates.
8488 TypeSet PointerTypes;
8489
8490 /// MemberPointerTypes - The set of member pointer types that will be
8491 /// used in the built-in candidates.
8492 TypeSet MemberPointerTypes;
8493
8494 /// EnumerationTypes - The set of enumeration types that will be
8495 /// used in the built-in candidates.
8496 TypeSet EnumerationTypes;
8497
8498 /// The set of vector types that will be used in the built-in
8499 /// candidates.
8500 TypeSet VectorTypes;
8501
8502 /// The set of matrix types that will be used in the built-in
8503 /// candidates.
8504 TypeSet MatrixTypes;
8505
8506 /// The set of _BitInt types that will be used in the built-in candidates.
8507 TypeSet BitIntTypes;
8508
8509 /// A flag indicating non-record types are viable candidates
8510 bool HasNonRecordTypes;
8511
8512 /// A flag indicating whether either arithmetic or enumeration types
8513 /// were present in the candidate set.
8514 bool HasArithmeticOrEnumeralTypes;
8515
8516 /// A flag indicating whether the nullptr type was present in the
8517 /// candidate set.
8518 bool HasNullPtrType;
8519
8520 /// Sema - The semantic analysis instance where we are building the
8521 /// candidate type set.
8522 Sema &SemaRef;
8523
8524 /// Context - The AST context in which we will build the type sets.
8525 ASTContext &Context;
8526
8527 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8528 const Qualifiers &VisibleQuals);
8529 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8530
8531public:
8532 /// iterator - Iterates through the types that are part of the set.
8533 typedef TypeSet::iterator iterator;
8534
8535 BuiltinCandidateTypeSet(Sema &SemaRef)
8536 : HasNonRecordTypes(false),
8537 HasArithmeticOrEnumeralTypes(false),
8538 HasNullPtrType(false),
8539 SemaRef(SemaRef),
8540 Context(SemaRef.Context) { }
8541
8542 void AddTypesConvertedFrom(QualType Ty,
8544 bool AllowUserConversions,
8545 bool AllowExplicitConversions,
8546 const Qualifiers &VisibleTypeConversionsQuals);
8547
8548 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8549 llvm::iterator_range<iterator> member_pointer_types() {
8550 return MemberPointerTypes;
8551 }
8552 llvm::iterator_range<iterator> enumeration_types() {
8553 return EnumerationTypes;
8554 }
8555 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8556 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8557 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8558
8559 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8560 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8561 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8562 bool hasNullPtrType() const { return HasNullPtrType; }
8563};
8564
8565} // end anonymous namespace
8566
8567/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8568/// the set of pointer types along with any more-qualified variants of
8569/// that type. For example, if @p Ty is "int const *", this routine
8570/// will add "int const *", "int const volatile *", "int const
8571/// restrict *", and "int const volatile restrict *" to the set of
8572/// pointer types. Returns true if the add of @p Ty itself succeeded,
8573/// false otherwise.
8574///
8575/// FIXME: what to do about extended qualifiers?
8576bool
8577BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8578 const Qualifiers &VisibleQuals) {
8579
8580 // Insert this type.
8581 if (!PointerTypes.insert(Ty))
8582 return false;
8583
8584 QualType PointeeTy;
8585 const PointerType *PointerTy = Ty->getAs<PointerType>();
8586 bool buildObjCPtr = false;
8587 if (!PointerTy) {
8589 PointeeTy = PTy->getPointeeType();
8590 buildObjCPtr = true;
8591 } else {
8592 PointeeTy = PointerTy->getPointeeType();
8593 }
8594
8595 // Don't add qualified variants of arrays. For one, they're not allowed
8596 // (the qualifier would sink to the element type), and for another, the
8597 // only overload situation where it matters is subscript or pointer +- int,
8598 // and those shouldn't have qualifier variants anyway.
8599 if (PointeeTy->isArrayType())
8600 return true;
8601
8602 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8603 bool hasVolatile = VisibleQuals.hasVolatile();
8604 bool hasRestrict = VisibleQuals.hasRestrict();
8605
8606 // Iterate through all strict supersets of BaseCVR.
8607 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8608 if ((CVR | BaseCVR) != CVR) continue;
8609 // Skip over volatile if no volatile found anywhere in the types.
8610 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8611
8612 // Skip over restrict if no restrict found anywhere in the types, or if
8613 // the type cannot be restrict-qualified.
8614 if ((CVR & Qualifiers::Restrict) &&
8615 (!hasRestrict ||
8616 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8617 continue;
8618
8619 // Build qualified pointee type.
8620 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8621
8622 // Build qualified pointer type.
8623 QualType QPointerTy;
8624 if (!buildObjCPtr)
8625 QPointerTy = Context.getPointerType(QPointeeTy);
8626 else
8627 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8628
8629 // Insert qualified pointer type.
8630 PointerTypes.insert(QPointerTy);
8631 }
8632
8633 return true;
8634}
8635
8636/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8637/// to the set of pointer types along with any more-qualified variants of
8638/// that type. For example, if @p Ty is "int const *", this routine
8639/// will add "int const *", "int const volatile *", "int const
8640/// restrict *", and "int const volatile restrict *" to the set of
8641/// pointer types. Returns true if the add of @p Ty itself succeeded,
8642/// false otherwise.
8643///
8644/// FIXME: what to do about extended qualifiers?
8645bool
8646BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8647 QualType Ty) {
8648 // Insert this type.
8649 if (!MemberPointerTypes.insert(Ty))
8650 return false;
8651
8652 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8653 assert(PointerTy && "type was not a member pointer type!");
8654
8655 QualType PointeeTy = PointerTy->getPointeeType();
8656 // Don't add qualified variants of arrays. For one, they're not allowed
8657 // (the qualifier would sink to the element type), and for another, the
8658 // only overload situation where it matters is subscript or pointer +- int,
8659 // and those shouldn't have qualifier variants anyway.
8660 if (PointeeTy->isArrayType())
8661 return true;
8662 const Type *ClassTy = PointerTy->getClass();
8663
8664 // Iterate through all strict supersets of the pointee type's CVR
8665 // qualifiers.
8666 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8667 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8668 if ((CVR | BaseCVR) != CVR) continue;
8669
8670 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8671 MemberPointerTypes.insert(
8672 Context.getMemberPointerType(QPointeeTy, ClassTy));
8673 }
8674
8675 return true;
8676}
8677
8678/// AddTypesConvertedFrom - Add each of the types to which the type @p
8679/// Ty can be implicit converted to the given set of @p Types. We're
8680/// primarily interested in pointer types and enumeration types. We also
8681/// take member pointer types, for the conditional operator.
8682/// AllowUserConversions is true if we should look at the conversion
8683/// functions of a class type, and AllowExplicitConversions if we
8684/// should also include the explicit conversion functions of a class
8685/// type.
8686void
8687BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8688 SourceLocation Loc,
8689 bool AllowUserConversions,
8690 bool AllowExplicitConversions,
8691 const Qualifiers &VisibleQuals) {
8692 // Only deal with canonical types.
8693 Ty = Context.getCanonicalType(Ty);
8694
8695 // Look through reference types; they aren't part of the type of an
8696 // expression for the purposes of conversions.
8697 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8698 Ty = RefTy->getPointeeType();
8699
8700 // If we're dealing with an array type, decay to the pointer.
8701 if (Ty->isArrayType())
8702 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8703
8704 // Otherwise, we don't care about qualifiers on the type.
8705 Ty = Ty.getLocalUnqualifiedType();
8706
8707 // Flag if we ever add a non-record type.
8708 const RecordType *TyRec = Ty->getAs<RecordType>();
8709 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8710
8711 // Flag if we encounter an arithmetic type.
8712 HasArithmeticOrEnumeralTypes =
8713 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8714
8715 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8716 PointerTypes.insert(Ty);
8717 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8718 // Insert our type, and its more-qualified variants, into the set
8719 // of types.
8720 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8721 return;
8722 } else if (Ty->isMemberPointerType()) {
8723 // Member pointers are far easier, since the pointee can't be converted.
8724 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8725 return;
8726 } else if (Ty->isEnumeralType()) {
8727 HasArithmeticOrEnumeralTypes = true;
8728 EnumerationTypes.insert(Ty);
8729 } else if (Ty->isBitIntType()) {
8730 HasArithmeticOrEnumeralTypes = true;
8731 BitIntTypes.insert(Ty);
8732 } else if (Ty->isVectorType()) {
8733 // We treat vector types as arithmetic types in many contexts as an
8734 // extension.
8735 HasArithmeticOrEnumeralTypes = true;
8736 VectorTypes.insert(Ty);
8737 } else if (Ty->isMatrixType()) {
8738 // Similar to vector types, we treat vector types as arithmetic types in
8739 // many contexts as an extension.
8740 HasArithmeticOrEnumeralTypes = true;
8741 MatrixTypes.insert(Ty);
8742 } else if (Ty->isNullPtrType()) {
8743 HasNullPtrType = true;
8744 } else if (AllowUserConversions && TyRec) {
8745 // No conversion functions in incomplete types.
8746 if (!SemaRef.isCompleteType(Loc, Ty))
8747 return;
8748
8749 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8750 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8751 if (isa<UsingShadowDecl>(D))
8752 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8753
8754 // Skip conversion function templates; they don't tell us anything
8755 // about which builtin types we can convert to.
8756 if (isa<FunctionTemplateDecl>(D))
8757 continue;
8758
8759 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8760 if (AllowExplicitConversions || !Conv->isExplicit()) {
8761 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8762 VisibleQuals);
8763 }
8764 }
8765 }
8766}
8767/// Helper function for adjusting address spaces for the pointer or reference
8768/// operands of builtin operators depending on the argument.
8770 Expr *Arg) {
8772}
8773
8774/// Helper function for AddBuiltinOperatorCandidates() that adds
8775/// the volatile- and non-volatile-qualified assignment operators for the
8776/// given type to the candidate set.
8778 QualType T,
8779 ArrayRef<Expr *> Args,
8780 OverloadCandidateSet &CandidateSet) {
8781 QualType ParamTypes[2];
8782
8783 // T& operator=(T&, T)
8784 ParamTypes[0] = S.Context.getLValueReferenceType(
8786 ParamTypes[1] = T;
8787 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8788 /*IsAssignmentOperator=*/true);
8789
8791 // volatile T& operator=(volatile T&, T)
8792 ParamTypes[0] = S.Context.getLValueReferenceType(
8794 Args[0]));
8795 ParamTypes[1] = T;
8796 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8797 /*IsAssignmentOperator=*/true);
8798 }
8799}
8800
8801/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8802/// if any, found in visible type conversion functions found in ArgExpr's type.
8803static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8804 Qualifiers VRQuals;
8805 const RecordType *TyRec;
8806 if (const MemberPointerType *RHSMPType =
8807 ArgExpr->getType()->getAs<MemberPointerType>())
8808 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8809 else
8810 TyRec = ArgExpr->getType()->getAs<RecordType>();
8811 if (!TyRec) {
8812 // Just to be safe, assume the worst case.
8813 VRQuals.addVolatile();
8814 VRQuals.addRestrict();
8815 return VRQuals;
8816 }
8817
8818 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8819 if (!ClassDecl->hasDefinition())
8820 return VRQuals;
8821
8822 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8823 if (isa<UsingShadowDecl>(D))
8824 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8825 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8826 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8827 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8828 CanTy = ResTypeRef->getPointeeType();
8829 // Need to go down the pointer/mempointer chain and add qualifiers
8830 // as see them.
8831 bool done = false;
8832 while (!done) {
8833 if (CanTy.isRestrictQualified())
8834 VRQuals.addRestrict();
8835 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8836 CanTy = ResTypePtr->getPointeeType();
8837 else if (const MemberPointerType *ResTypeMPtr =
8838 CanTy->getAs<MemberPointerType>())
8839 CanTy = ResTypeMPtr->getPointeeType();
8840 else
8841 done = true;
8842 if (CanTy.isVolatileQualified())
8843 VRQuals.addVolatile();
8844 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8845 return VRQuals;
8846 }
8847 }
8848 }
8849 return VRQuals;
8850}
8851
8852// Note: We're currently only handling qualifiers that are meaningful for the
8853// LHS of compound assignment overloading.
8855 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8856 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8857 // _Atomic
8858 if (Available.hasAtomic()) {
8859 Available.removeAtomic();
8860 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8861 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8862 return;
8863 }
8864
8865 // volatile
8866 if (Available.hasVolatile()) {
8867 Available.removeVolatile();
8868 assert(!Applied.hasVolatile());
8869 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8870 Callback);
8871 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8872 return;
8873 }
8874
8875 Callback(Applied);
8876}
8877
8879 QualifiersAndAtomic Quals,
8880 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8882 Callback);
8883}
8884
8886 QualifiersAndAtomic Quals,
8887 Sema &S) {
8888 if (Quals.hasAtomic())
8890 if (Quals.hasVolatile())
8893}
8894
8895namespace {
8896
8897/// Helper class to manage the addition of builtin operator overload
8898/// candidates. It provides shared state and utility methods used throughout
8899/// the process, as well as a helper method to add each group of builtin
8900/// operator overloads from the standard to a candidate set.
8901class BuiltinOperatorOverloadBuilder {
8902 // Common instance state available to all overload candidate addition methods.
8903 Sema &S;
8904 ArrayRef<Expr *> Args;
8905 QualifiersAndAtomic VisibleTypeConversionsQuals;
8906 bool HasArithmeticOrEnumeralCandidateType;
8908 OverloadCandidateSet &CandidateSet;
8909
8910 static constexpr int ArithmeticTypesCap = 26;
8912
8913 // Define some indices used to iterate over the arithmetic types in
8914 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8915 // types are that preserved by promotion (C++ [over.built]p2).
8916 unsigned FirstIntegralType,
8917 LastIntegralType;
8918 unsigned FirstPromotedIntegralType,
8919 LastPromotedIntegralType;
8920 unsigned FirstPromotedArithmeticType,
8921 LastPromotedArithmeticType;
8922 unsigned NumArithmeticTypes;
8923
8924 void InitArithmeticTypes() {
8925 // Start of promoted types.
8926 FirstPromotedArithmeticType = 0;
8927 ArithmeticTypes.push_back(S.Context.FloatTy);
8928 ArithmeticTypes.push_back(S.Context.DoubleTy);
8929 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8931 ArithmeticTypes.push_back(S.Context.Float128Ty);
8933 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8934
8935 // Start of integral types.
8936 FirstIntegralType = ArithmeticTypes.size();
8937 FirstPromotedIntegralType = ArithmeticTypes.size();
8938 ArithmeticTypes.push_back(S.Context.IntTy);
8939 ArithmeticTypes.push_back(S.Context.LongTy);
8940 ArithmeticTypes.push_back(S.Context.LongLongTy);
8944 ArithmeticTypes.push_back(S.Context.Int128Ty);
8945 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8946 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8947 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8951 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8952
8953 /// We add candidates for the unique, unqualified _BitInt types present in
8954 /// the candidate type set. The candidate set already handled ensuring the
8955 /// type is unqualified and canonical, but because we're adding from N
8956 /// different sets, we need to do some extra work to unique things. Insert
8957 /// the candidates into a unique set, then move from that set into the list
8958 /// of arithmetic types.
8959 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8960 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8961 BuiltinCandidateTypeSet &Candidate) {
8962 for (QualType BitTy : Candidate.bitint_types())
8963 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8964 });
8965 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8966 LastPromotedIntegralType = ArithmeticTypes.size();
8967 LastPromotedArithmeticType = ArithmeticTypes.size();
8968 // End of promoted types.
8969
8970 ArithmeticTypes.push_back(S.Context.BoolTy);
8971 ArithmeticTypes.push_back(S.Context.CharTy);
8972 ArithmeticTypes.push_back(S.Context.WCharTy);
8973 if (S.Context.getLangOpts().Char8)
8974 ArithmeticTypes.push_back(S.Context.Char8Ty);
8975 ArithmeticTypes.push_back(S.Context.Char16Ty);
8976 ArithmeticTypes.push_back(S.Context.Char32Ty);
8977 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8978 ArithmeticTypes.push_back(S.Context.ShortTy);
8979 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8980 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8981 LastIntegralType = ArithmeticTypes.size();
8982 NumArithmeticTypes = ArithmeticTypes.size();
8983 // End of integral types.
8984 // FIXME: What about complex? What about half?
8985
8986 // We don't know for sure how many bit-precise candidates were involved, so
8987 // we subtract those from the total when testing whether we're under the
8988 // cap or not.
8989 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
8990 ArithmeticTypesCap &&
8991 "Enough inline storage for all arithmetic types.");
8992 }
8993
8994 /// Helper method to factor out the common pattern of adding overloads
8995 /// for '++' and '--' builtin operators.
8996 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8997 bool HasVolatile,
8998 bool HasRestrict) {
8999 QualType ParamTypes[2] = {
9000 S.Context.getLValueReferenceType(CandidateTy),
9001 S.Context.IntTy
9002 };
9003
9004 // Non-volatile version.
9005 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9006
9007 // Use a heuristic to reduce number of builtin candidates in the set:
9008 // add volatile version only if there are conversions to a volatile type.
9009 if (HasVolatile) {
9010 ParamTypes[0] =
9012 S.Context.getVolatileType(CandidateTy));
9013 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9014 }
9015
9016 // Add restrict version only if there are conversions to a restrict type
9017 // and our candidate type is a non-restrict-qualified pointer.
9018 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9019 !CandidateTy.isRestrictQualified()) {
9020 ParamTypes[0]
9023 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9024
9025 if (HasVolatile) {
9026 ParamTypes[0]
9028 S.Context.getCVRQualifiedType(CandidateTy,
9031 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9032 }
9033 }
9034
9035 }
9036
9037 /// Helper to add an overload candidate for a binary builtin with types \p L
9038 /// and \p R.
9039 void AddCandidate(QualType L, QualType R) {
9040 QualType LandR[2] = {L, R};
9041 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9042 }
9043
9044public:
9045 BuiltinOperatorOverloadBuilder(
9046 Sema &S, ArrayRef<Expr *> Args,
9047 QualifiersAndAtomic VisibleTypeConversionsQuals,
9048 bool HasArithmeticOrEnumeralCandidateType,
9050 OverloadCandidateSet &CandidateSet)
9051 : S(S), Args(Args),
9052 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9053 HasArithmeticOrEnumeralCandidateType(
9054 HasArithmeticOrEnumeralCandidateType),
9055 CandidateTypes(CandidateTypes),
9056 CandidateSet(CandidateSet) {
9057
9058 InitArithmeticTypes();
9059 }
9060
9061 // Increment is deprecated for bool since C++17.
9062 //
9063 // C++ [over.built]p3:
9064 //
9065 // For every pair (T, VQ), where T is an arithmetic type other
9066 // than bool, and VQ is either volatile or empty, there exist
9067 // candidate operator functions of the form
9068 //
9069 // VQ T& operator++(VQ T&);
9070 // T operator++(VQ T&, int);
9071 //
9072 // C++ [over.built]p4:
9073 //
9074 // For every pair (T, VQ), where T is an arithmetic type other
9075 // than bool, and VQ is either volatile or empty, there exist
9076 // candidate operator functions of the form
9077 //
9078 // VQ T& operator--(VQ T&);
9079 // T operator--(VQ T&, int);
9080 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9081 if (!HasArithmeticOrEnumeralCandidateType)
9082 return;
9083
9084 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9085 const auto TypeOfT = ArithmeticTypes[Arith];
9086 if (TypeOfT == S.Context.BoolTy) {
9087 if (Op == OO_MinusMinus)
9088 continue;
9089 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9090 continue;
9091 }
9092 addPlusPlusMinusMinusStyleOverloads(
9093 TypeOfT,
9094 VisibleTypeConversionsQuals.hasVolatile(),
9095 VisibleTypeConversionsQuals.hasRestrict());
9096 }
9097 }
9098
9099 // C++ [over.built]p5:
9100 //
9101 // For every pair (T, VQ), where T is a cv-qualified or
9102 // cv-unqualified object type, and VQ is either volatile or
9103 // empty, there exist candidate operator functions of the form
9104 //
9105 // T*VQ& operator++(T*VQ&);
9106 // T*VQ& operator--(T*VQ&);
9107 // T* operator++(T*VQ&, int);
9108 // T* operator--(T*VQ&, int);
9109 void addPlusPlusMinusMinusPointerOverloads() {
9110 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9111 // Skip pointer types that aren't pointers to object types.
9112 if (!PtrTy->getPointeeType()->isObjectType())
9113 continue;
9114
9115 addPlusPlusMinusMinusStyleOverloads(
9116 PtrTy,
9117 (!PtrTy.isVolatileQualified() &&
9118 VisibleTypeConversionsQuals.hasVolatile()),
9119 (!PtrTy.isRestrictQualified() &&
9120 VisibleTypeConversionsQuals.hasRestrict()));
9121 }
9122 }
9123
9124 // C++ [over.built]p6:
9125 // For every cv-qualified or cv-unqualified object type T, there
9126 // exist candidate operator functions of the form
9127 //
9128 // T& operator*(T*);
9129 //
9130 // C++ [over.built]p7:
9131 // For every function type T that does not have cv-qualifiers or a
9132 // ref-qualifier, there exist candidate operator functions of the form
9133 // T& operator*(T*);
9134 void addUnaryStarPointerOverloads() {
9135 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9136 QualType PointeeTy = ParamTy->getPointeeType();
9137 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9138 continue;
9139
9140 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9141 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9142 continue;
9143
9144 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9145 }
9146 }
9147
9148 // C++ [over.built]p9:
9149 // For every promoted arithmetic type T, there exist candidate
9150 // operator functions of the form
9151 //
9152 // T operator+(T);
9153 // T operator-(T);
9154 void addUnaryPlusOrMinusArithmeticOverloads() {
9155 if (!HasArithmeticOrEnumeralCandidateType)
9156 return;
9157
9158 for (unsigned Arith = FirstPromotedArithmeticType;
9159 Arith < LastPromotedArithmeticType; ++Arith) {
9160 QualType ArithTy = ArithmeticTypes[Arith];
9161 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9162 }
9163
9164 // Extension: We also add these operators for vector types.
9165 for (QualType VecTy : CandidateTypes[0].vector_types())
9166 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9167 }
9168
9169 // C++ [over.built]p8:
9170 // For every type T, there exist candidate operator functions of
9171 // the form
9172 //
9173 // T* operator+(T*);
9174 void addUnaryPlusPointerOverloads() {
9175 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9176 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9177 }
9178
9179 // C++ [over.built]p10:
9180 // For every promoted integral type T, there exist candidate
9181 // operator functions of the form
9182 //
9183 // T operator~(T);
9184 void addUnaryTildePromotedIntegralOverloads() {
9185 if (!HasArithmeticOrEnumeralCandidateType)
9186 return;
9187
9188 for (unsigned Int = FirstPromotedIntegralType;
9189 Int < LastPromotedIntegralType; ++Int) {
9190 QualType IntTy = ArithmeticTypes[Int];
9191 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9192 }
9193
9194 // Extension: We also add this operator for vector types.
9195 for (QualType VecTy : CandidateTypes[0].vector_types())
9196 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9197 }
9198
9199 // C++ [over.match.oper]p16:
9200 // For every pointer to member type T or type std::nullptr_t, there
9201 // exist candidate operator functions of the form
9202 //
9203 // bool operator==(T,T);
9204 // bool operator!=(T,T);
9205 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9206 /// Set of (canonical) types that we've already handled.
9208
9209 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9210 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9211 // Don't add the same builtin candidate twice.
9212 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9213 continue;
9214
9215 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9216 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9217 }
9218
9219 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9221 if (AddedTypes.insert(NullPtrTy).second) {
9222 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9223 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9224 }
9225 }
9226 }
9227 }
9228
9229 // C++ [over.built]p15:
9230 //
9231 // For every T, where T is an enumeration type or a pointer type,
9232 // there exist candidate operator functions of the form
9233 //
9234 // bool operator<(T, T);
9235 // bool operator>(T, T);
9236 // bool operator<=(T, T);
9237 // bool operator>=(T, T);
9238 // bool operator==(T, T);
9239 // bool operator!=(T, T);
9240 // R operator<=>(T, T)
9241 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9242 // C++ [over.match.oper]p3:
9243 // [...]the built-in candidates include all of the candidate operator
9244 // functions defined in 13.6 that, compared to the given operator, [...]
9245 // do not have the same parameter-type-list as any non-template non-member
9246 // candidate.
9247 //
9248 // Note that in practice, this only affects enumeration types because there
9249 // aren't any built-in candidates of record type, and a user-defined operator
9250 // must have an operand of record or enumeration type. Also, the only other
9251 // overloaded operator with enumeration arguments, operator=,
9252 // cannot be overloaded for enumeration types, so this is the only place
9253 // where we must suppress candidates like this.
9254 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9255 UserDefinedBinaryOperators;
9256
9257 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9258 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9259 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9260 CEnd = CandidateSet.end();
9261 C != CEnd; ++C) {
9262 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9263 continue;
9264
9265 if (C->Function->isFunctionTemplateSpecialization())
9266 continue;
9267
9268 // We interpret "same parameter-type-list" as applying to the
9269 // "synthesized candidate, with the order of the two parameters
9270 // reversed", not to the original function.
9271 bool Reversed = C->isReversed();
9272 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9273 ->getType()
9274 .getUnqualifiedType();
9275 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9276 ->getType()
9277 .getUnqualifiedType();
9278
9279 // Skip if either parameter isn't of enumeral type.
9280 if (!FirstParamType->isEnumeralType() ||
9281 !SecondParamType->isEnumeralType())
9282 continue;
9283
9284 // Add this operator to the set of known user-defined operators.
9285 UserDefinedBinaryOperators.insert(
9286 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9287 S.Context.getCanonicalType(SecondParamType)));
9288 }
9289 }
9290 }
9291
9292 /// Set of (canonical) types that we've already handled.
9294
9295 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9296 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9297 // Don't add the same builtin candidate twice.
9298 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9299 continue;
9300 if (IsSpaceship && PtrTy->isFunctionPointerType())
9301 continue;
9302
9303 QualType ParamTypes[2] = {PtrTy, PtrTy};
9304 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9305 }
9306 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9307 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9308
9309 // Don't add the same builtin candidate twice, or if a user defined
9310 // candidate exists.
9311 if (!AddedTypes.insert(CanonType).second ||
9312 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9313 CanonType)))
9314 continue;
9315 QualType ParamTypes[2] = {EnumTy, EnumTy};
9316 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9317 }
9318 }
9319 }
9320
9321 // C++ [over.built]p13:
9322 //
9323 // For every cv-qualified or cv-unqualified object type T
9324 // there exist candidate operator functions of the form
9325 //
9326 // T* operator+(T*, ptrdiff_t);
9327 // T& operator[](T*, ptrdiff_t); [BELOW]
9328 // T* operator-(T*, ptrdiff_t);
9329 // T* operator+(ptrdiff_t, T*);
9330 // T& operator[](ptrdiff_t, T*); [BELOW]
9331 //
9332 // C++ [over.built]p14:
9333 //
9334 // For every T, where T is a pointer to object type, there
9335 // exist candidate operator functions of the form
9336 //
9337 // ptrdiff_t operator-(T, T);
9338 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9339 /// Set of (canonical) types that we've already handled.
9341
9342 for (int Arg = 0; Arg < 2; ++Arg) {
9343 QualType AsymmetricParamTypes[2] = {
9346 };
9347 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9348 QualType PointeeTy = PtrTy->getPointeeType();
9349 if (!PointeeTy->isObjectType())
9350 continue;
9351
9352 AsymmetricParamTypes[Arg] = PtrTy;
9353 if (Arg == 0 || Op == OO_Plus) {
9354 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9355 // T* operator+(ptrdiff_t, T*);
9356 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9357 }
9358 if (Op == OO_Minus) {
9359 // ptrdiff_t operator-(T, T);
9360 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9361 continue;
9362
9363 QualType ParamTypes[2] = {PtrTy, PtrTy};
9364 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9365 }
9366 }
9367 }
9368 }
9369
9370 // C++ [over.built]p12:
9371 //
9372 // For every pair of promoted arithmetic types L and R, there
9373 // exist candidate operator functions of the form
9374 //
9375 // LR operator*(L, R);
9376 // LR operator/(L, R);
9377 // LR operator+(L, R);
9378 // LR operator-(L, R);
9379 // bool operator<(L, R);
9380 // bool operator>(L, R);
9381 // bool operator<=(L, R);
9382 // bool operator>=(L, R);
9383 // bool operator==(L, R);
9384 // bool operator!=(L, R);
9385 //
9386 // where LR is the result of the usual arithmetic conversions
9387 // between types L and R.
9388 //
9389 // C++ [over.built]p24:
9390 //
9391 // For every pair of promoted arithmetic types L and R, there exist
9392 // candidate operator functions of the form
9393 //
9394 // LR operator?(bool, L, R);
9395 //
9396 // where LR is the result of the usual arithmetic conversions
9397 // between types L and R.
9398 // Our candidates ignore the first parameter.
9399 void addGenericBinaryArithmeticOverloads() {
9400 if (!HasArithmeticOrEnumeralCandidateType)
9401 return;
9402
9403 for (unsigned Left = FirstPromotedArithmeticType;
9404 Left < LastPromotedArithmeticType; ++Left) {
9405 for (unsigned Right = FirstPromotedArithmeticType;
9406 Right < LastPromotedArithmeticType; ++Right) {
9407 QualType LandR[2] = { ArithmeticTypes[Left],
9408 ArithmeticTypes[Right] };
9409 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9410 }
9411 }
9412
9413 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9414 // conditional operator for vector types.
9415 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9416 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9417 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9418 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9419 }
9420 }
9421
9422 /// Add binary operator overloads for each candidate matrix type M1, M2:
9423 /// * (M1, M1) -> M1
9424 /// * (M1, M1.getElementType()) -> M1
9425 /// * (M2.getElementType(), M2) -> M2
9426 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9427 void addMatrixBinaryArithmeticOverloads() {
9428 if (!HasArithmeticOrEnumeralCandidateType)
9429 return;
9430
9431 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9432 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9433 AddCandidate(M1, M1);
9434 }
9435
9436 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9437 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9438 if (!CandidateTypes[0].containsMatrixType(M2))
9439 AddCandidate(M2, M2);
9440 }
9441 }
9442
9443 // C++2a [over.built]p14:
9444 //
9445 // For every integral type T there exists a candidate operator function
9446 // of the form
9447 //
9448 // std::strong_ordering operator<=>(T, T)
9449 //
9450 // C++2a [over.built]p15:
9451 //
9452 // For every pair of floating-point types L and R, there exists a candidate
9453 // operator function of the form
9454 //
9455 // std::partial_ordering operator<=>(L, R);
9456 //
9457 // FIXME: The current specification for integral types doesn't play nice with
9458 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9459 // comparisons. Under the current spec this can lead to ambiguity during
9460 // overload resolution. For example:
9461 //
9462 // enum A : int {a};
9463 // auto x = (a <=> (long)42);
9464 //
9465 // error: call is ambiguous for arguments 'A' and 'long'.
9466 // note: candidate operator<=>(int, int)
9467 // note: candidate operator<=>(long, long)
9468 //
9469 // To avoid this error, this function deviates from the specification and adds
9470 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9471 // arithmetic types (the same as the generic relational overloads).
9472 //
9473 // For now this function acts as a placeholder.
9474 void addThreeWayArithmeticOverloads() {
9475 addGenericBinaryArithmeticOverloads();
9476 }
9477
9478 // C++ [over.built]p17:
9479 //
9480 // For every pair of promoted integral types L and R, there
9481 // exist candidate operator functions of the form
9482 //
9483 // LR operator%(L, R);
9484 // LR operator&(L, R);
9485 // LR operator^(L, R);
9486 // LR operator|(L, R);
9487 // L operator<<(L, R);
9488 // L operator>>(L, R);
9489 //
9490 // where LR is the result of the usual arithmetic conversions
9491 // between types L and R.
9492 void addBinaryBitwiseArithmeticOverloads() {
9493 if (!HasArithmeticOrEnumeralCandidateType)
9494 return;
9495
9496 for (unsigned Left = FirstPromotedIntegralType;
9497 Left < LastPromotedIntegralType; ++Left) {
9498 for (unsigned Right = FirstPromotedIntegralType;
9499 Right < LastPromotedIntegralType; ++Right) {
9500 QualType LandR[2] = { ArithmeticTypes[Left],
9501 ArithmeticTypes[Right] };
9502 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9503 }
9504 }
9505 }
9506
9507 // C++ [over.built]p20:
9508 //
9509 // For every pair (T, VQ), where T is an enumeration or
9510 // pointer to member type and VQ is either volatile or
9511 // empty, there exist candidate operator functions of the form
9512 //
9513 // VQ T& operator=(VQ T&, T);
9514 void addAssignmentMemberPointerOrEnumeralOverloads() {
9515 /// Set of (canonical) types that we've already handled.
9517
9518 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9519 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9520 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9521 continue;
9522
9523 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9524 }
9525
9526 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9527 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9528 continue;
9529
9530 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9531 }
9532 }
9533 }
9534
9535 // C++ [over.built]p19:
9536 //
9537 // For every pair (T, VQ), where T is any type and VQ is either
9538 // volatile or empty, there exist candidate operator functions
9539 // of the form
9540 //
9541 // T*VQ& operator=(T*VQ&, T*);
9542 //
9543 // C++ [over.built]p21:
9544 //
9545 // For every pair (T, VQ), where T is a cv-qualified or
9546 // cv-unqualified object type and VQ is either volatile or
9547 // empty, there exist candidate operator functions of the form
9548 //
9549 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9550 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9551 void addAssignmentPointerOverloads(bool isEqualOp) {
9552 /// Set of (canonical) types that we've already handled.
9554
9555 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9556 // If this is operator=, keep track of the builtin candidates we added.
9557 if (isEqualOp)
9558 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9559 else if (!PtrTy->getPointeeType()->isObjectType())
9560 continue;
9561
9562 // non-volatile version
9563 QualType ParamTypes[2] = {
9565 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9566 };
9567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9568 /*IsAssignmentOperator=*/ isEqualOp);
9569
9570 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9571 VisibleTypeConversionsQuals.hasVolatile();
9572 if (NeedVolatile) {
9573 // volatile version
9574 ParamTypes[0] =
9576 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9577 /*IsAssignmentOperator=*/isEqualOp);
9578 }
9579
9580 if (!PtrTy.isRestrictQualified() &&
9581 VisibleTypeConversionsQuals.hasRestrict()) {
9582 // restrict version
9583 ParamTypes[0] =
9585 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9586 /*IsAssignmentOperator=*/isEqualOp);
9587
9588 if (NeedVolatile) {
9589 // volatile restrict version
9590 ParamTypes[0] =
9593 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9594 /*IsAssignmentOperator=*/isEqualOp);
9595 }
9596 }
9597 }
9598
9599 if (isEqualOp) {
9600 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9601 // Make sure we don't add the same candidate twice.
9602 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9603 continue;
9604
9605 QualType ParamTypes[2] = {
9607 PtrTy,
9608 };
9609
9610 // non-volatile version
9611 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9612 /*IsAssignmentOperator=*/true);
9613
9614 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9615 VisibleTypeConversionsQuals.hasVolatile();
9616 if (NeedVolatile) {
9617 // volatile version
9618 ParamTypes[0] = S.Context.getLValueReferenceType(
9619 S.Context.getVolatileType(PtrTy));
9620 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9621 /*IsAssignmentOperator=*/true);
9622 }
9623
9624 if (!PtrTy.isRestrictQualified() &&
9625 VisibleTypeConversionsQuals.hasRestrict()) {
9626 // restrict version
9627 ParamTypes[0] = S.Context.getLValueReferenceType(
9628 S.Context.getRestrictType(PtrTy));
9629 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9630 /*IsAssignmentOperator=*/true);
9631
9632 if (NeedVolatile) {
9633 // volatile restrict version
9634 ParamTypes[0] =
9637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9638 /*IsAssignmentOperator=*/true);
9639 }
9640 }
9641 }
9642 }
9643 }
9644
9645 // C++ [over.built]p18:
9646 //
9647 // For every triple (L, VQ, R), where L is an arithmetic type,
9648 // VQ is either volatile or empty, and R is a promoted
9649 // arithmetic type, there exist candidate operator functions of
9650 // the form
9651 //
9652 // VQ L& operator=(VQ L&, R);
9653 // VQ L& operator*=(VQ L&, R);
9654 // VQ L& operator/=(VQ L&, R);
9655 // VQ L& operator+=(VQ L&, R);
9656 // VQ L& operator-=(VQ L&, R);
9657 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9658 if (!HasArithmeticOrEnumeralCandidateType)
9659 return;
9660
9661 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9662 for (unsigned Right = FirstPromotedArithmeticType;
9663 Right < LastPromotedArithmeticType; ++Right) {
9664 QualType ParamTypes[2];
9665 ParamTypes[1] = ArithmeticTypes[Right];
9667 S, ArithmeticTypes[Left], Args[0]);
9668
9670 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9671 ParamTypes[0] =
9672 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9673 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9674 /*IsAssignmentOperator=*/isEqualOp);
9675 });
9676 }
9677 }
9678
9679 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9680 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9681 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9682 QualType ParamTypes[2];
9683 ParamTypes[1] = Vec2Ty;
9684 // Add this built-in operator as a candidate (VQ is empty).
9685 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9686 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9687 /*IsAssignmentOperator=*/isEqualOp);
9688
9689 // Add this built-in operator as a candidate (VQ is 'volatile').
9690 if (VisibleTypeConversionsQuals.hasVolatile()) {
9691 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9692 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9693 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9694 /*IsAssignmentOperator=*/isEqualOp);
9695 }
9696 }
9697 }
9698
9699 // C++ [over.built]p22:
9700 //
9701 // For every triple (L, VQ, R), where L is an integral type, VQ
9702 // is either volatile or empty, and R is a promoted integral
9703 // type, there exist candidate operator functions of the form
9704 //
9705 // VQ L& operator%=(VQ L&, R);
9706 // VQ L& operator<<=(VQ L&, R);
9707 // VQ L& operator>>=(VQ L&, R);
9708 // VQ L& operator&=(VQ L&, R);
9709 // VQ L& operator^=(VQ L&, R);
9710 // VQ L& operator|=(VQ L&, R);
9711 void addAssignmentIntegralOverloads() {
9712 if (!HasArithmeticOrEnumeralCandidateType)
9713 return;
9714
9715 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9716 for (unsigned Right = FirstPromotedIntegralType;
9717 Right < LastPromotedIntegralType; ++Right) {
9718 QualType ParamTypes[2];
9719 ParamTypes[1] = ArithmeticTypes[Right];
9721 S, ArithmeticTypes[Left], Args[0]);
9722
9724 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9725 ParamTypes[0] =
9726 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9727 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9728 });
9729 }
9730 }
9731 }
9732
9733 // C++ [over.operator]p23:
9734 //
9735 // There also exist candidate operator functions of the form
9736 //
9737 // bool operator!(bool);
9738 // bool operator&&(bool, bool);
9739 // bool operator||(bool, bool);
9740 void addExclaimOverload() {
9741 QualType ParamTy = S.Context.BoolTy;
9742 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9743 /*IsAssignmentOperator=*/false,
9744 /*NumContextualBoolArguments=*/1);
9745 }
9746 void addAmpAmpOrPipePipeOverload() {
9747 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9748 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9749 /*IsAssignmentOperator=*/false,
9750 /*NumContextualBoolArguments=*/2);
9751 }
9752
9753 // C++ [over.built]p13:
9754 //
9755 // For every cv-qualified or cv-unqualified object type T there
9756 // exist candidate operator functions of the form
9757 //
9758 // T* operator+(T*, ptrdiff_t); [ABOVE]
9759 // T& operator[](T*, ptrdiff_t);
9760 // T* operator-(T*, ptrdiff_t); [ABOVE]
9761 // T* operator+(ptrdiff_t, T*); [ABOVE]
9762 // T& operator[](ptrdiff_t, T*);
9763 void addSubscriptOverloads() {
9764 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9765 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9766 QualType PointeeType = PtrTy->getPointeeType();
9767 if (!PointeeType->isObjectType())
9768 continue;
9769
9770 // T& operator[](T*, ptrdiff_t)
9771 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9772 }
9773
9774 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9775 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9776 QualType PointeeType = PtrTy->getPointeeType();
9777 if (!PointeeType->isObjectType())
9778 continue;
9779
9780 // T& operator[](ptrdiff_t, T*)
9781 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9782 }
9783 }
9784
9785 // C++ [over.built]p11:
9786 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9787 // C1 is the same type as C2 or is a derived class of C2, T is an object
9788 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9789 // there exist candidate operator functions of the form
9790 //
9791 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9792 //
9793 // where CV12 is the union of CV1 and CV2.
9794 void addArrowStarOverloads() {
9795 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9796 QualType C1Ty = PtrTy;
9797 QualType C1;
9799 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9800 if (!isa<RecordType>(C1))
9801 continue;
9802 // heuristic to reduce number of builtin candidates in the set.
9803 // Add volatile/restrict version only if there are conversions to a
9804 // volatile/restrict type.
9805 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9806 continue;
9807 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9808 continue;
9809 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9810 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9811 QualType C2 = QualType(mptr->getClass(), 0);
9812 C2 = C2.getUnqualifiedType();
9813 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9814 break;
9815 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9816 // build CV12 T&
9817 QualType T = mptr->getPointeeType();
9818 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9819 T.isVolatileQualified())
9820 continue;
9821 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9822 T.isRestrictQualified())
9823 continue;
9824 T = Q1.apply(S.Context, T);
9825 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9826 }
9827 }
9828 }
9829
9830 // Note that we don't consider the first argument, since it has been
9831 // contextually converted to bool long ago. The candidates below are
9832 // therefore added as binary.
9833 //
9834 // C++ [over.built]p25:
9835 // For every type T, where T is a pointer, pointer-to-member, or scoped
9836 // enumeration type, there exist candidate operator functions of the form
9837 //
9838 // T operator?(bool, T, T);
9839 //
9840 void addConditionalOperatorOverloads() {
9841 /// Set of (canonical) types that we've already handled.
9843
9844 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9845 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9846 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9847 continue;
9848
9849 QualType ParamTypes[2] = {PtrTy, PtrTy};
9850 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9851 }
9852
9853 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9854 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9855 continue;
9856
9857 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9858 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9859 }
9860
9861 if (S.getLangOpts().CPlusPlus11) {
9862 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9863 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9864 continue;
9865
9866 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9867 continue;
9868
9869 QualType ParamTypes[2] = {EnumTy, EnumTy};
9870 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9871 }
9872 }
9873 }
9874 }
9875};
9876
9877} // end anonymous namespace
9878
9880 SourceLocation OpLoc,
9881 ArrayRef<Expr *> Args,
9882 OverloadCandidateSet &CandidateSet) {
9883 // Find all of the types that the arguments can convert to, but only
9884 // if the operator we're looking at has built-in operator candidates
9885 // that make use of these types. Also record whether we encounter non-record
9886 // candidate types or either arithmetic or enumeral candidate types.
9887 QualifiersAndAtomic VisibleTypeConversionsQuals;
9888 VisibleTypeConversionsQuals.addConst();
9889 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9890 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9891 if (Args[ArgIdx]->getType()->isAtomicType())
9892 VisibleTypeConversionsQuals.addAtomic();
9893 }
9894
9895 bool HasNonRecordCandidateType = false;
9896 bool HasArithmeticOrEnumeralCandidateType = false;
9898 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9899 CandidateTypes.emplace_back(*this);
9900 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9901 OpLoc,
9902 true,
9903 (Op == OO_Exclaim ||
9904 Op == OO_AmpAmp ||
9905 Op == OO_PipePipe),
9906 VisibleTypeConversionsQuals);
9907 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9908 CandidateTypes[ArgIdx].hasNonRecordTypes();
9909 HasArithmeticOrEnumeralCandidateType =
9910 HasArithmeticOrEnumeralCandidateType ||
9911 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9912 }
9913
9914 // Exit early when no non-record types have been added to the candidate set
9915 // for any of the arguments to the operator.
9916 //
9917 // We can't exit early for !, ||, or &&, since there we have always have
9918 // 'bool' overloads.
9919 if (!HasNonRecordCandidateType &&
9920 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9921 return;
9922
9923 // Setup an object to manage the common state for building overloads.
9924 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9925 VisibleTypeConversionsQuals,
9926 HasArithmeticOrEnumeralCandidateType,
9927 CandidateTypes, CandidateSet);
9928
9929 // Dispatch over the operation to add in only those overloads which apply.
9930 switch (Op) {
9931 case OO_None:
9933 llvm_unreachable("Expected an overloaded operator");
9934
9935 case OO_New:
9936 case OO_Delete:
9937 case OO_Array_New:
9938 case OO_Array_Delete:
9939 case OO_Call:
9940 llvm_unreachable(
9941 "Special operators don't use AddBuiltinOperatorCandidates");
9942
9943 case OO_Comma:
9944 case OO_Arrow:
9945 case OO_Coawait:
9946 // C++ [over.match.oper]p3:
9947 // -- For the operator ',', the unary operator '&', the
9948 // operator '->', or the operator 'co_await', the
9949 // built-in candidates set is empty.
9950 break;
9951
9952 case OO_Plus: // '+' is either unary or binary
9953 if (Args.size() == 1)
9954 OpBuilder.addUnaryPlusPointerOverloads();
9955 [[fallthrough]];
9956
9957 case OO_Minus: // '-' is either unary or binary
9958 if (Args.size() == 1) {
9959 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9960 } else {
9961 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9962 OpBuilder.addGenericBinaryArithmeticOverloads();
9963 OpBuilder.addMatrixBinaryArithmeticOverloads();
9964 }
9965 break;
9966
9967 case OO_Star: // '*' is either unary or binary
9968 if (Args.size() == 1)
9969 OpBuilder.addUnaryStarPointerOverloads();
9970 else {
9971 OpBuilder.addGenericBinaryArithmeticOverloads();
9972 OpBuilder.addMatrixBinaryArithmeticOverloads();
9973 }
9974 break;
9975
9976 case OO_Slash:
9977 OpBuilder.addGenericBinaryArithmeticOverloads();
9978 break;
9979
9980 case OO_PlusPlus:
9981 case OO_MinusMinus:
9982 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9983 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9984 break;
9985
9986 case OO_EqualEqual:
9987 case OO_ExclaimEqual:
9988 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9989 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9990 OpBuilder.addGenericBinaryArithmeticOverloads();
9991 break;
9992
9993 case OO_Less:
9994 case OO_Greater:
9995 case OO_LessEqual:
9996 case OO_GreaterEqual:
9997 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9998 OpBuilder.addGenericBinaryArithmeticOverloads();
9999 break;
10000
10001 case OO_Spaceship:
10002 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10003 OpBuilder.addThreeWayArithmeticOverloads();
10004 break;
10005
10006 case OO_Percent:
10007 case OO_Caret:
10008 case OO_Pipe:
10009 case OO_LessLess:
10010 case OO_GreaterGreater:
10011 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10012 break;
10013
10014 case OO_Amp: // '&' is either unary or binary
10015 if (Args.size() == 1)
10016 // C++ [over.match.oper]p3:
10017 // -- For the operator ',', the unary operator '&', or the
10018 // operator '->', the built-in candidates set is empty.
10019 break;
10020
10021 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10022 break;
10023
10024 case OO_Tilde:
10025 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10026 break;
10027
10028 case OO_Equal:
10029 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10030 [[fallthrough]];
10031
10032 case OO_PlusEqual:
10033 case OO_MinusEqual:
10034 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10035 [[fallthrough]];
10036
10037 case OO_StarEqual:
10038 case OO_SlashEqual:
10039 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10040 break;
10041
10042 case OO_PercentEqual:
10043 case OO_LessLessEqual:
10044 case OO_GreaterGreaterEqual:
10045 case OO_AmpEqual:
10046 case OO_CaretEqual:
10047 case OO_PipeEqual:
10048 OpBuilder.addAssignmentIntegralOverloads();
10049 break;
10050
10051 case OO_Exclaim:
10052 OpBuilder.addExclaimOverload();
10053 break;
10054
10055 case OO_AmpAmp:
10056 case OO_PipePipe:
10057 OpBuilder.addAmpAmpOrPipePipeOverload();
10058 break;
10059
10060 case OO_Subscript:
10061 if (Args.size() == 2)
10062 OpBuilder.addSubscriptOverloads();
10063 break;
10064
10065 case OO_ArrowStar:
10066 OpBuilder.addArrowStarOverloads();
10067 break;
10068
10069 case OO_Conditional:
10070 OpBuilder.addConditionalOperatorOverloads();
10071 OpBuilder.addGenericBinaryArithmeticOverloads();
10072 break;
10073 }
10074}
10075
10076void
10078 SourceLocation Loc,
10079 ArrayRef<Expr *> Args,
10080 TemplateArgumentListInfo *ExplicitTemplateArgs,
10081 OverloadCandidateSet& CandidateSet,
10082 bool PartialOverloading) {
10083 ADLResult Fns;
10084
10085 // FIXME: This approach for uniquing ADL results (and removing
10086 // redundant candidates from the set) relies on pointer-equality,
10087 // which means we need to key off the canonical decl. However,
10088 // always going back to the canonical decl might not get us the
10089 // right set of default arguments. What default arguments are
10090 // we supposed to consider on ADL candidates, anyway?
10091
10092 // FIXME: Pass in the explicit template arguments?
10093 ArgumentDependentLookup(Name, Loc, Args, Fns);
10094
10095 // Erase all of the candidates we already knew about.
10096 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10097 CandEnd = CandidateSet.end();
10098 Cand != CandEnd; ++Cand)
10099 if (Cand->Function) {
10100 FunctionDecl *Fn = Cand->Function;
10101 Fns.erase(Fn);
10102 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10103 Fns.erase(FunTmpl);
10104 }
10105
10106 // For each of the ADL candidates we found, add it to the overload
10107 // set.
10108 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10110
10111 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10112 if (ExplicitTemplateArgs)
10113 continue;
10114
10115 AddOverloadCandidate(
10116 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10117 PartialOverloading, /*AllowExplicit=*/true,
10118 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10119 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10120 AddOverloadCandidate(
10121 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10122 /*SuppressUserConversions=*/false, PartialOverloading,
10123 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10124 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10125 }
10126 } else {
10127 auto *FTD = cast<FunctionTemplateDecl>(*I);
10128 AddTemplateOverloadCandidate(
10129 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10130 /*SuppressUserConversions=*/false, PartialOverloading,
10131 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10132 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10133 *this, Args, FTD->getTemplatedDecl())) {
10134 AddTemplateOverloadCandidate(
10135 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10136 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10137 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10139 }
10140 }
10141 }
10142}
10143
10144namespace {
10145enum class Comparison { Equal, Better, Worse };
10146}
10147
10148/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10149/// overload resolution.
10150///
10151/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10152/// Cand1's first N enable_if attributes have precisely the same conditions as
10153/// Cand2's first N enable_if attributes (where N = the number of enable_if
10154/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10155///
10156/// Note that you can have a pair of candidates such that Cand1's enable_if
10157/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10158/// worse than Cand1's.
10159static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10160 const FunctionDecl *Cand2) {
10161 // Common case: One (or both) decls don't have enable_if attrs.
10162 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10163 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10164 if (!Cand1Attr || !Cand2Attr) {
10165 if (Cand1Attr == Cand2Attr)
10166 return Comparison::Equal;
10167 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10168 }
10169
10170 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10171 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10172
10173 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10174 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10175 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10176 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10177
10178 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10179 // has fewer enable_if attributes than Cand2, and vice versa.
10180 if (!Cand1A)
10181 return Comparison::Worse;
10182 if (!Cand2A)
10183 return Comparison::Better;
10184
10185 Cand1ID.clear();
10186 Cand2ID.clear();
10187
10188 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10189 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10190 if (Cand1ID != Cand2ID)
10191 return Comparison::Worse;
10192 }
10193
10194 return Comparison::Equal;
10195}
10196
10197static Comparison
10199 const OverloadCandidate &Cand2) {
10200 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10201 !Cand2.Function->isMultiVersion())
10202 return Comparison::Equal;
10203
10204 // If both are invalid, they are equal. If one of them is invalid, the other
10205 // is better.
10206 if (Cand1.Function->isInvalidDecl()) {
10207 if (Cand2.Function->isInvalidDecl())
10208 return Comparison::Equal;
10209 return Comparison::Worse;
10210 }
10211 if (Cand2.Function->isInvalidDecl())
10212 return Comparison::Better;
10213
10214 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10215 // cpu_dispatch, else arbitrarily based on the identifiers.
10216 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10217 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10218 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10219 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10220
10221 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10222 return Comparison::Equal;
10223
10224 if (Cand1CPUDisp && !Cand2CPUDisp)
10225 return Comparison::Better;
10226 if (Cand2CPUDisp && !Cand1CPUDisp)
10227 return Comparison::Worse;
10228
10229 if (Cand1CPUSpec && Cand2CPUSpec) {
10230 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10231 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10232 ? Comparison::Better
10233 : Comparison::Worse;
10234
10235 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10236 FirstDiff = std::mismatch(
10237 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10238 Cand2CPUSpec->cpus_begin(),
10239 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10240 return LHS->getName() == RHS->getName();
10241 });
10242
10243 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10244 "Two different cpu-specific versions should not have the same "
10245 "identifier list, otherwise they'd be the same decl!");
10246 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10247 ? Comparison::Better
10248 : Comparison::Worse;
10249 }
10250 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10251}
10252
10253/// Compute the type of the implicit object parameter for the given function,
10254/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10255/// null QualType if there is a 'matches anything' implicit object parameter.
10256static std::optional<QualType>
10258 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10259 return std::nullopt;
10260
10261 auto *M = cast<CXXMethodDecl>(F);
10262 // Static member functions' object parameters match all types.
10263 if (M->isStatic())
10264 return QualType();
10265 return M->getFunctionObjectParameterReferenceType();
10266}
10267
10268// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10269// represent the same entity.
10270static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10271 const FunctionDecl *F2) {
10272 if (declaresSameEntity(F1, F2))
10273 return true;
10274 auto PT1 = F1->getPrimaryTemplate();
10275 auto PT2 = F2->getPrimaryTemplate();
10276 if (PT1 && PT2) {
10277 if (declaresSameEntity(PT1, PT2) ||
10278 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10279 PT2->getInstantiatedFromMemberTemplate()))
10280 return true;
10281 }
10282 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10283 // different functions with same params). Consider removing this (as no test
10284 // fail w/o it).
10285 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10286 if (First) {
10287 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10288 return *T;
10289 }
10290 assert(I < F->getNumParams());
10291 return F->getParamDecl(I++)->getType();
10292 };
10293
10294 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10295 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10296
10297 if (F1NumParams != F2NumParams)
10298 return false;
10299
10300 unsigned I1 = 0, I2 = 0;
10301 for (unsigned I = 0; I != F1NumParams; ++I) {
10302 QualType T1 = NextParam(F1, I1, I == 0);
10303 QualType T2 = NextParam(F2, I2, I == 0);
10304 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10305 if (!Context.hasSameUnqualifiedType(T1, T2))
10306 return false;
10307 }
10308 return true;
10309}
10310
10311/// We're allowed to use constraints partial ordering only if the candidates
10312/// have the same parameter types:
10313/// [over.match.best.general]p2.6
10314/// F1 and F2 are non-template functions with the same
10315/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10317 const OverloadCandidate &Cand1,
10318 const OverloadCandidate &Cand2) {
10319 if (!Cand1.Function || !Cand2.Function)
10320 return false;
10321
10322 FunctionDecl *Fn1 = Cand1.Function;
10323 FunctionDecl *Fn2 = Cand2.Function;
10324
10325 if (Fn1->isVariadic() != Fn2->isVariadic())
10326 return false;
10327
10329 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10330 return false;
10331
10332 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10333 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10334 if (Mem1 && Mem2) {
10335 // if they are member functions, both are direct members of the same class,
10336 // and
10337 if (Mem1->getParent() != Mem2->getParent())
10338 return false;
10339 // if both are non-static member functions, they have the same types for
10340 // their object parameters
10341 if (Mem1->isInstance() && Mem2->isInstance() &&
10343 Mem1->getFunctionObjectParameterReferenceType(),
10344 Mem1->getFunctionObjectParameterReferenceType()))
10345 return false;
10346 }
10347 return true;
10348}
10349
10350/// isBetterOverloadCandidate - Determines whether the first overload
10351/// candidate is a better candidate than the second (C++ 13.3.3p1).
10353 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10355 // Define viable functions to be better candidates than non-viable
10356 // functions.
10357 if (!Cand2.Viable)
10358 return Cand1.Viable;
10359 else if (!Cand1.Viable)
10360 return false;
10361
10362 // [CUDA] A function with 'never' preference is marked not viable, therefore
10363 // is never shown up here. The worst preference shown up here is 'wrong side',
10364 // e.g. an H function called by a HD function in device compilation. This is
10365 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10366 // function which is called only by an H function. A deferred diagnostic will
10367 // be triggered if it is emitted. However a wrong-sided function is still
10368 // a viable candidate here.
10369 //
10370 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10371 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10372 // can be emitted, Cand1 is not better than Cand2. This rule should have
10373 // precedence over other rules.
10374 //
10375 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10376 // other rules should be used to determine which is better. This is because
10377 // host/device based overloading resolution is mostly for determining
10378 // viability of a function. If two functions are both viable, other factors
10379 // should take precedence in preference, e.g. the standard-defined preferences
10380 // like argument conversion ranks or enable_if partial-ordering. The
10381 // preference for pass-object-size parameters is probably most similar to a
10382 // type-based-overloading decision and so should take priority.
10383 //
10384 // If other rules cannot determine which is better, CUDA preference will be
10385 // used again to determine which is better.
10386 //
10387 // TODO: Currently IdentifyPreference does not return correct values
10388 // for functions called in global variable initializers due to missing
10389 // correct context about device/host. Therefore we can only enforce this
10390 // rule when there is a caller. We should enforce this rule for functions
10391 // in global variable initializers once proper context is added.
10392 //
10393 // TODO: We can only enable the hostness based overloading resolution when
10394 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10395 // overloading resolution diagnostics.
10396 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10397 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10398 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10399 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10400 bool IsCand1ImplicitHD =
10402 bool IsCand2ImplicitHD =
10404 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10405 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10406 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10407 // The implicit HD function may be a function in a system header which
10408 // is forced by pragma. In device compilation, if we prefer HD candidates
10409 // over wrong-sided candidates, overloading resolution may change, which
10410 // may result in non-deferrable diagnostics. As a workaround, we let
10411 // implicit HD candidates take equal preference as wrong-sided candidates.
10412 // This will preserve the overloading resolution.
10413 // TODO: We still need special handling of implicit HD functions since
10414 // they may incur other diagnostics to be deferred. We should make all
10415 // host/device related diagnostics deferrable and remove special handling
10416 // of implicit HD functions.
10417 auto EmitThreshold =
10418 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10419 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10422 auto Cand1Emittable = P1 > EmitThreshold;
10423 auto Cand2Emittable = P2 > EmitThreshold;
10424 if (Cand1Emittable && !Cand2Emittable)
10425 return true;
10426 if (!Cand1Emittable && Cand2Emittable)
10427 return false;
10428 }
10429 }
10430
10431 // C++ [over.match.best]p1: (Changed in C++23)
10432 //
10433 // -- if F is a static member function, ICS1(F) is defined such
10434 // that ICS1(F) is neither better nor worse than ICS1(G) for
10435 // any function G, and, symmetrically, ICS1(G) is neither
10436 // better nor worse than ICS1(F).
10437 unsigned StartArg = 0;
10438 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10439 StartArg = 1;
10440
10441 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10442 // We don't allow incompatible pointer conversions in C++.
10443 if (!S.getLangOpts().CPlusPlus)
10444 return ICS.isStandard() &&
10445 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10446
10447 // The only ill-formed conversion we allow in C++ is the string literal to
10448 // char* conversion, which is only considered ill-formed after C++11.
10449 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10451 };
10452
10453 // Define functions that don't require ill-formed conversions for a given
10454 // argument to be better candidates than functions that do.
10455 unsigned NumArgs = Cand1.Conversions.size();
10456 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10457 bool HasBetterConversion = false;
10458 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10459 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10460 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10461 if (Cand1Bad != Cand2Bad) {
10462 if (Cand1Bad)
10463 return false;
10464 HasBetterConversion = true;
10465 }
10466 }
10467
10468 if (HasBetterConversion)
10469 return true;
10470
10471 // C++ [over.match.best]p1:
10472 // A viable function F1 is defined to be a better function than another
10473 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10474 // conversion sequence than ICSi(F2), and then...
10475 bool HasWorseConversion = false;
10476 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10478 Cand1.Conversions[ArgIdx],
10479 Cand2.Conversions[ArgIdx])) {
10481 // Cand1 has a better conversion sequence.
10482 HasBetterConversion = true;
10483 break;
10484
10486 if (Cand1.Function && Cand2.Function &&
10487 Cand1.isReversed() != Cand2.isReversed() &&
10488 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10489 // Work around large-scale breakage caused by considering reversed
10490 // forms of operator== in C++20:
10491 //
10492 // When comparing a function against a reversed function, if we have a
10493 // better conversion for one argument and a worse conversion for the
10494 // other, the implicit conversion sequences are treated as being equally
10495 // good.
10496 //
10497 // This prevents a comparison function from being considered ambiguous
10498 // with a reversed form that is written in the same way.
10499 //
10500 // We diagnose this as an extension from CreateOverloadedBinOp.
10501 HasWorseConversion = true;
10502 break;
10503 }
10504
10505 // Cand1 can't be better than Cand2.
10506 return false;
10507
10509 // Do nothing.
10510 break;
10511 }
10512 }
10513
10514 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10515 // ICSj(F2), or, if not that,
10516 if (HasBetterConversion && !HasWorseConversion)
10517 return true;
10518
10519 // -- the context is an initialization by user-defined conversion
10520 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10521 // from the return type of F1 to the destination type (i.e.,
10522 // the type of the entity being initialized) is a better
10523 // conversion sequence than the standard conversion sequence
10524 // from the return type of F2 to the destination type.
10526 Cand1.Function && Cand2.Function &&
10527 isa<CXXConversionDecl>(Cand1.Function) &&
10528 isa<CXXConversionDecl>(Cand2.Function)) {
10529 // First check whether we prefer one of the conversion functions over the
10530 // other. This only distinguishes the results in non-standard, extension
10531 // cases such as the conversion from a lambda closure type to a function
10532 // pointer or block.
10537 Cand1.FinalConversion,
10538 Cand2.FinalConversion);
10539
10542
10543 // FIXME: Compare kind of reference binding if conversion functions
10544 // convert to a reference type used in direct reference binding, per
10545 // C++14 [over.match.best]p1 section 2 bullet 3.
10546 }
10547
10548 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10549 // as combined with the resolution to CWG issue 243.
10550 //
10551 // When the context is initialization by constructor ([over.match.ctor] or
10552 // either phase of [over.match.list]), a constructor is preferred over
10553 // a conversion function.
10554 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10555 Cand1.Function && Cand2.Function &&
10556 isa<CXXConstructorDecl>(Cand1.Function) !=
10557 isa<CXXConstructorDecl>(Cand2.Function))
10558 return isa<CXXConstructorDecl>(Cand1.Function);
10559
10560 // -- F1 is a non-template function and F2 is a function template
10561 // specialization, or, if not that,
10562 bool Cand1IsSpecialization = Cand1.Function &&
10564 bool Cand2IsSpecialization = Cand2.Function &&
10566 if (Cand1IsSpecialization != Cand2IsSpecialization)
10567 return Cand2IsSpecialization;
10568
10569 // -- F1 and F2 are function template specializations, and the function
10570 // template for F1 is more specialized than the template for F2
10571 // according to the partial ordering rules described in 14.5.5.2, or,
10572 // if not that,
10573 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10574 const auto *Obj1Context =
10575 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10576 const auto *Obj2Context =
10577 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10578 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10581 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10582 : TPOC_Call,
10584 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10585 : QualType{},
10586 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10587 : QualType{},
10588 Cand1.isReversed() ^ Cand2.isReversed())) {
10589 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10590 }
10591 }
10592
10593 // -— F1 and F2 are non-template functions with the same
10594 // parameter-type-lists, and F1 is more constrained than F2 [...],
10595 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10596 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10598 Cand1.Function)
10599 return true;
10600
10601 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10602 // class B of D, and for all arguments the corresponding parameters of
10603 // F1 and F2 have the same type.
10604 // FIXME: Implement the "all parameters have the same type" check.
10605 bool Cand1IsInherited =
10606 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10607 bool Cand2IsInherited =
10608 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10609 if (Cand1IsInherited != Cand2IsInherited)
10610 return Cand2IsInherited;
10611 else if (Cand1IsInherited) {
10612 assert(Cand2IsInherited);
10613 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10614 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10615 if (Cand1Class->isDerivedFrom(Cand2Class))
10616 return true;
10617 if (Cand2Class->isDerivedFrom(Cand1Class))
10618 return false;
10619 // Inherited from sibling base classes: still ambiguous.
10620 }
10621
10622 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10623 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10624 // with reversed order of parameters and F1 is not
10625 //
10626 // We rank reversed + different operator as worse than just reversed, but
10627 // that comparison can never happen, because we only consider reversing for
10628 // the maximally-rewritten operator (== or <=>).
10629 if (Cand1.RewriteKind != Cand2.RewriteKind)
10630 return Cand1.RewriteKind < Cand2.RewriteKind;
10631
10632 // Check C++17 tie-breakers for deduction guides.
10633 {
10634 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10635 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10636 if (Guide1 && Guide2) {
10637 // -- F1 is generated from a deduction-guide and F2 is not
10638 if (Guide1->isImplicit() != Guide2->isImplicit())
10639 return Guide2->isImplicit();
10640
10641 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10642 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10643 return true;
10644 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10645 return false;
10646
10647 // --F1 is generated from a non-template constructor and F2 is generated
10648 // from a constructor template
10649 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10650 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10651 if (Constructor1 && Constructor2) {
10652 bool isC1Templated = Constructor1->getTemplatedKind() !=
10654 bool isC2Templated = Constructor2->getTemplatedKind() !=
10656 if (isC1Templated != isC2Templated)
10657 return isC2Templated;
10658 }
10659 }
10660 }
10661
10662 // Check for enable_if value-based overload resolution.
10663 if (Cand1.Function && Cand2.Function) {
10664 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10665 if (Cmp != Comparison::Equal)
10666 return Cmp == Comparison::Better;
10667 }
10668
10669 bool HasPS1 = Cand1.Function != nullptr &&
10671 bool HasPS2 = Cand2.Function != nullptr &&
10673 if (HasPS1 != HasPS2 && HasPS1)
10674 return true;
10675
10676 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10677 if (MV == Comparison::Better)
10678 return true;
10679 if (MV == Comparison::Worse)
10680 return false;
10681
10682 // If other rules cannot determine which is better, CUDA preference is used
10683 // to determine which is better.
10684 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10685 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10686 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10687 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10688 }
10689
10690 // General member function overloading is handled above, so this only handles
10691 // constructors with address spaces.
10692 // This only handles address spaces since C++ has no other
10693 // qualifier that can be used with constructors.
10694 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10695 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10696 if (CD1 && CD2) {
10697 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10698 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10699 if (AS1 != AS2) {
10701 return true;
10703 return false;
10704 }
10705 }
10706
10707 return false;
10708}
10709
10710/// Determine whether two declarations are "equivalent" for the purposes of
10711/// name lookup and overload resolution. This applies when the same internal/no
10712/// linkage entity is defined by two modules (probably by textually including
10713/// the same header). In such a case, we don't consider the declarations to
10714/// declare the same entity, but we also don't want lookups with both
10715/// declarations visible to be ambiguous in some cases (this happens when using
10716/// a modularized libstdc++).
10718 const NamedDecl *B) {
10719 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10720 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10721 if (!VA || !VB)
10722 return false;
10723
10724 // The declarations must be declaring the same name as an internal linkage
10725 // entity in different modules.
10726 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10727 VB->getDeclContext()->getRedeclContext()) ||
10728 getOwningModule(VA) == getOwningModule(VB) ||
10729 VA->isExternallyVisible() || VB->isExternallyVisible())
10730 return false;
10731
10732 // Check that the declarations appear to be equivalent.
10733 //
10734 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10735 // For constants and functions, we should check the initializer or body is
10736 // the same. For non-constant variables, we shouldn't allow it at all.
10737 if (Context.hasSameType(VA->getType(), VB->getType()))
10738 return true;
10739
10740 // Enum constants within unnamed enumerations will have different types, but
10741 // may still be similar enough to be interchangeable for our purposes.
10742 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10743 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10744 // Only handle anonymous enums. If the enumerations were named and
10745 // equivalent, they would have been merged to the same type.
10746 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10747 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10748 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10749 !Context.hasSameType(EnumA->getIntegerType(),
10750 EnumB->getIntegerType()))
10751 return false;
10752 // Allow this only if the value is the same for both enumerators.
10753 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10754 }
10755 }
10756
10757 // Nothing else is sufficiently similar.
10758 return false;
10759}
10760
10763 assert(D && "Unknown declaration");
10764 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10765
10766 Module *M = getOwningModule(D);
10767 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10768 << !M << (M ? M->getFullModuleName() : "");
10769
10770 for (auto *E : Equiv) {
10771 Module *M = getOwningModule(E);
10772 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10773 << !M << (M ? M->getFullModuleName() : "");
10774 }
10775}
10776
10778 return FailureKind == ovl_fail_bad_deduction &&
10779 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10781 static_cast<CNSInfo *>(DeductionFailure.Data)
10782 ->Satisfaction.ContainsErrors;
10783}
10784
10785/// Computes the best viable function (C++ 13.3.3)
10786/// within an overload candidate set.
10787///
10788/// \param Loc The location of the function name (or operator symbol) for
10789/// which overload resolution occurs.
10790///
10791/// \param Best If overload resolution was successful or found a deleted
10792/// function, \p Best points to the candidate function found.
10793///
10794/// \returns The result of overload resolution.
10797 iterator &Best) {
10799 std::transform(begin(), end(), std::back_inserter(Candidates),
10800 [](OverloadCandidate &Cand) { return &Cand; });
10801
10802 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10803 // are accepted by both clang and NVCC. However, during a particular
10804 // compilation mode only one call variant is viable. We need to
10805 // exclude non-viable overload candidates from consideration based
10806 // only on their host/device attributes. Specifically, if one
10807 // candidate call is WrongSide and the other is SameSide, we ignore
10808 // the WrongSide candidate.
10809 // We only need to remove wrong-sided candidates here if
10810 // -fgpu-exclude-wrong-side-overloads is off. When
10811 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10812 // uniformly in isBetterOverloadCandidate.
10813 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10814 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10815 bool ContainsSameSideCandidate =
10816 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10817 // Check viable function only.
10818 return Cand->Viable && Cand->Function &&
10819 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10821 });
10822 if (ContainsSameSideCandidate) {
10823 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10824 // Check viable function only to avoid unnecessary data copying/moving.
10825 return Cand->Viable && Cand->Function &&
10826 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10828 };
10829 llvm::erase_if(Candidates, IsWrongSideCandidate);
10830 }
10831 }
10832
10833 // Find the best viable function.
10834 Best = end();
10835 for (auto *Cand : Candidates) {
10836 Cand->Best = false;
10837 if (Cand->Viable) {
10838 if (Best == end() ||
10839 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10840 Best = Cand;
10841 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10842 // This candidate has constraint that we were unable to evaluate because
10843 // it referenced an expression that contained an error. Rather than fall
10844 // back onto a potentially unintended candidate (made worse by
10845 // subsuming constraints), treat this as 'no viable candidate'.
10846 Best = end();
10847 return OR_No_Viable_Function;
10848 }
10849 }
10850
10851 // If we didn't find any viable functions, abort.
10852 if (Best == end())
10853 return OR_No_Viable_Function;
10854
10856
10858 PendingBest.push_back(&*Best);
10859 Best->Best = true;
10860
10861 // Make sure that this function is better than every other viable
10862 // function. If not, we have an ambiguity.
10863 while (!PendingBest.empty()) {
10864 auto *Curr = PendingBest.pop_back_val();
10865 for (auto *Cand : Candidates) {
10866 if (Cand->Viable && !Cand->Best &&
10867 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10868 PendingBest.push_back(Cand);
10869 Cand->Best = true;
10870
10872 Curr->Function))
10873 EquivalentCands.push_back(Cand->Function);
10874 else
10875 Best = end();
10876 }
10877 }
10878 }
10879
10880 // If we found more than one best candidate, this is ambiguous.
10881 if (Best == end())
10882 return OR_Ambiguous;
10883
10884 // Best is the best viable function.
10885 if (Best->Function && Best->Function->isDeleted())
10886 return OR_Deleted;
10887
10888 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
10889 Kind == CSK_AddressOfOverloadSet && M &&
10890 M->isImplicitObjectMemberFunction()) {
10891 return OR_No_Viable_Function;
10892 }
10893
10894 if (!EquivalentCands.empty())
10896 EquivalentCands);
10897
10898 return OR_Success;
10899}
10900
10901namespace {
10902
10903enum OverloadCandidateKind {
10904 oc_function,
10905 oc_method,
10906 oc_reversed_binary_operator,
10907 oc_constructor,
10908 oc_implicit_default_constructor,
10909 oc_implicit_copy_constructor,
10910 oc_implicit_move_constructor,
10911 oc_implicit_copy_assignment,
10912 oc_implicit_move_assignment,
10913 oc_implicit_equality_comparison,
10914 oc_inherited_constructor
10915};
10916
10917enum OverloadCandidateSelect {
10918 ocs_non_template,
10919 ocs_template,
10920 ocs_described_template,
10921};
10922
10923static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10924ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10925 const FunctionDecl *Fn,
10927 std::string &Description) {
10928
10929 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10930 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10931 isTemplate = true;
10932 Description = S.getTemplateArgumentBindingsText(
10933 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10934 }
10935
10936 OverloadCandidateSelect Select = [&]() {
10937 if (!Description.empty())
10938 return ocs_described_template;
10939 return isTemplate ? ocs_template : ocs_non_template;
10940 }();
10941
10942 OverloadCandidateKind Kind = [&]() {
10943 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10944 return oc_implicit_equality_comparison;
10945
10946 if (CRK & CRK_Reversed)
10947 return oc_reversed_binary_operator;
10948
10949 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10950 if (!Ctor->isImplicit()) {
10951 if (isa<ConstructorUsingShadowDecl>(Found))
10952 return oc_inherited_constructor;
10953 else
10954 return oc_constructor;
10955 }
10956
10957 if (Ctor->isDefaultConstructor())
10958 return oc_implicit_default_constructor;
10959
10960 if (Ctor->isMoveConstructor())
10961 return oc_implicit_move_constructor;
10962
10963 assert(Ctor->isCopyConstructor() &&
10964 "unexpected sort of implicit constructor");
10965 return oc_implicit_copy_constructor;
10966 }
10967
10968 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10969 // This actually gets spelled 'candidate function' for now, but
10970 // it doesn't hurt to split it out.
10971 if (!Meth->isImplicit())
10972 return oc_method;
10973
10974 if (Meth->isMoveAssignmentOperator())
10975 return oc_implicit_move_assignment;
10976
10977 if (Meth->isCopyAssignmentOperator())
10978 return oc_implicit_copy_assignment;
10979
10980 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10981 return oc_method;
10982 }
10983
10984 return oc_function;
10985 }();
10986
10987 return std::make_pair(Kind, Select);
10988}
10989
10990void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10991 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10992 // set.
10993 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10994 S.Diag(FoundDecl->getLocation(),
10995 diag::note_ovl_candidate_inherited_constructor)
10996 << Shadow->getNominatedBaseClass();
10997}
10998
10999} // end anonymous namespace
11000
11002 const FunctionDecl *FD) {
11003 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11004 bool AlwaysTrue;
11005 if (EnableIf->getCond()->isValueDependent() ||
11006 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11007 return false;
11008 if (!AlwaysTrue)
11009 return false;
11010 }
11011 return true;
11012}
11013
11014/// Returns true if we can take the address of the function.
11015///
11016/// \param Complain - If true, we'll emit a diagnostic
11017/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11018/// we in overload resolution?
11019/// \param Loc - The location of the statement we're complaining about. Ignored
11020/// if we're not complaining, or if we're in overload resolution.
11022 bool Complain,
11023 bool InOverloadResolution,
11024 SourceLocation Loc) {
11025 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11026 if (Complain) {
11027 if (InOverloadResolution)
11028 S.Diag(FD->getBeginLoc(),
11029 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11030 else
11031 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11032 }
11033 return false;
11034 }
11035
11036 if (FD->getTrailingRequiresClause()) {
11037 ConstraintSatisfaction Satisfaction;
11038 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11039 return false;
11040 if (!Satisfaction.IsSatisfied) {
11041 if (Complain) {
11042 if (InOverloadResolution) {
11043 SmallString<128> TemplateArgString;
11044 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11045 TemplateArgString += " ";
11046 TemplateArgString += S.getTemplateArgumentBindingsText(
11047 FunTmpl->getTemplateParameters(),
11049 }
11050
11051 S.Diag(FD->getBeginLoc(),
11052 diag::note_ovl_candidate_unsatisfied_constraints)
11053 << TemplateArgString;
11054 } else
11055 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11056 << FD;
11057 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11058 }
11059 return false;
11060 }
11061 }
11062
11063 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11064 return P->hasAttr<PassObjectSizeAttr>();
11065 });
11066 if (I == FD->param_end())
11067 return true;
11068
11069 if (Complain) {
11070 // Add one to ParamNo because it's user-facing
11071 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11072 if (InOverloadResolution)
11073 S.Diag(FD->getLocation(),
11074 diag::note_ovl_candidate_has_pass_object_size_params)
11075 << ParamNo;
11076 else
11077 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11078 << FD << ParamNo;
11079 }
11080 return false;
11081}
11082
11084 const FunctionDecl *FD) {
11085 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11086 /*InOverloadResolution=*/true,
11087 /*Loc=*/SourceLocation());
11088}
11089
11091 bool Complain,
11092 SourceLocation Loc) {
11093 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11094 /*InOverloadResolution=*/false,
11095 Loc);
11096}
11097
11098// Don't print candidates other than the one that matches the calling
11099// convention of the call operator, since that is guaranteed to exist.
11101 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11102
11103 if (!ConvD)
11104 return false;
11105 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11106 if (!RD->isLambda())
11107 return false;
11108
11109 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11110 CallingConv CallOpCC =
11111 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11112 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11113 CallingConv ConvToCC =
11114 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11115
11116 return ConvToCC != CallOpCC;
11117}
11118
11119// Notes the location of an overload candidate.
11121 OverloadCandidateRewriteKind RewriteKind,
11122 QualType DestType, bool TakingAddress) {
11123 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11124 return;
11125 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11126 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11127 return;
11128 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11129 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11130 return;
11132 return;
11133
11134 std::string FnDesc;
11135 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11136 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11137 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11138 << (unsigned)KSPair.first << (unsigned)KSPair.second
11139 << Fn << FnDesc;
11140
11141 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11142 Diag(Fn->getLocation(), PD);
11143 MaybeEmitInheritedConstructorNote(*this, Found);
11144}
11145
11146static void
11148 // Perhaps the ambiguity was caused by two atomic constraints that are
11149 // 'identical' but not equivalent:
11150 //
11151 // void foo() requires (sizeof(T) > 4) { } // #1
11152 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11153 //
11154 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11155 // #2 to subsume #1, but these constraint are not considered equivalent
11156 // according to the subsumption rules because they are not the same
11157 // source-level construct. This behavior is quite confusing and we should try
11158 // to help the user figure out what happened.
11159
11160 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11161 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11162 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11163 if (!I->Function)
11164 continue;
11166 if (auto *Template = I->Function->getPrimaryTemplate())
11167 Template->getAssociatedConstraints(AC);
11168 else
11169 I->Function->getAssociatedConstraints(AC);
11170 if (AC.empty())
11171 continue;
11172 if (FirstCand == nullptr) {
11173 FirstCand = I->Function;
11174 FirstAC = AC;
11175 } else if (SecondCand == nullptr) {
11176 SecondCand = I->Function;
11177 SecondAC = AC;
11178 } else {
11179 // We have more than one pair of constrained functions - this check is
11180 // expensive and we'd rather not try to diagnose it.
11181 return;
11182 }
11183 }
11184 if (!SecondCand)
11185 return;
11186 // The diagnostic can only happen if there are associated constraints on
11187 // both sides (there needs to be some identical atomic constraint).
11188 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11189 SecondCand, SecondAC))
11190 // Just show the user one diagnostic, they'll probably figure it out
11191 // from here.
11192 return;
11193}
11194
11195// Notes the location of all overload candidates designated through
11196// OverloadedExpr
11197void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11198 bool TakingAddress) {
11199 assert(OverloadedExpr->getType() == Context.OverloadTy);
11200
11201 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11202 OverloadExpr *OvlExpr = Ovl.Expression;
11203
11204 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11205 IEnd = OvlExpr->decls_end();
11206 I != IEnd; ++I) {
11207 if (FunctionTemplateDecl *FunTmpl =
11208 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11209 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11210 TakingAddress);
11211 } else if (FunctionDecl *Fun
11212 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11213 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11214 }
11215 }
11216}
11217
11218/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11219/// "lead" diagnostic; it will be given two arguments, the source and
11220/// target types of the conversion.
11222 Sema &S,
11223 SourceLocation CaretLoc,
11224 const PartialDiagnostic &PDiag) const {
11225 S.Diag(CaretLoc, PDiag)
11226 << Ambiguous.getFromType() << Ambiguous.getToType();
11227 unsigned CandsShown = 0;
11229 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11230 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11231 break;
11232 ++CandsShown;
11233 S.NoteOverloadCandidate(I->first, I->second);
11234 }
11235 S.Diags.overloadCandidatesShown(CandsShown);
11236 if (I != E)
11237 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11238}
11239
11241 unsigned I, bool TakingCandidateAddress) {
11242 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11243 assert(Conv.isBad());
11244 assert(Cand->Function && "for now, candidate must be a function");
11245 FunctionDecl *Fn = Cand->Function;
11246
11247 // There's a conversion slot for the object argument if this is a
11248 // non-constructor method. Note that 'I' corresponds the
11249 // conversion-slot index.
11250 bool isObjectArgument = false;
11251 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11252 if (I == 0)
11253 isObjectArgument = true;
11254 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11255 I--;
11256 }
11257
11258 std::string FnDesc;
11259 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11260 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11261 FnDesc);
11262
11263 Expr *FromExpr = Conv.Bad.FromExpr;
11264 QualType FromTy = Conv.Bad.getFromType();
11265 QualType ToTy = Conv.Bad.getToType();
11266 SourceRange ToParamRange;
11267
11268 // FIXME: In presence of parameter packs we can't determine parameter range
11269 // reliably, as we don't have access to instantiation.
11270 bool HasParamPack =
11271 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11272 return Parm->isParameterPack();
11273 });
11274 if (!isObjectArgument && !HasParamPack)
11275 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11276
11277 if (FromTy == S.Context.OverloadTy) {
11278 assert(FromExpr && "overload set argument came from implicit argument?");
11279 Expr *E = FromExpr->IgnoreParens();
11280 if (isa<UnaryOperator>(E))
11281 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11282 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11283
11284 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11285 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11286 << ToParamRange << ToTy << Name << I + 1;
11287 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11288 return;
11289 }
11290
11291 // Do some hand-waving analysis to see if the non-viability is due
11292 // to a qualifier mismatch.
11293 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11294 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11295 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11296 CToTy = RT->getPointeeType();
11297 else {
11298 // TODO: detect and diagnose the full richness of const mismatches.
11299 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11300 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11301 CFromTy = FromPT->getPointeeType();
11302 CToTy = ToPT->getPointeeType();
11303 }
11304 }
11305
11306 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11307 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11308 Qualifiers FromQs = CFromTy.getQualifiers();
11309 Qualifiers ToQs = CToTy.getQualifiers();
11310
11311 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11312 if (isObjectArgument)
11313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11314 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11315 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11316 else
11317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11318 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11319 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11320 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11321 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11322 return;
11323 }
11324
11325 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11326 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11327 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11328 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11329 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11330 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11331 return;
11332 }
11333
11334 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11335 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11336 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11337 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11338 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11339 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11340 return;
11341 }
11342
11343 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11344 assert(CVR && "expected qualifiers mismatch");
11345
11346 if (isObjectArgument) {
11347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11348 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11349 << FromTy << (CVR - 1);
11350 } else {
11351 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11352 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11353 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11354 }
11355 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11356 return;
11357 }
11358
11361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11362 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11363 << (unsigned)isObjectArgument << I + 1
11365 << ToParamRange;
11366 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11367 return;
11368 }
11369
11370 // Special diagnostic for failure to convert an initializer list, since
11371 // telling the user that it has type void is not useful.
11372 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11374 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11375 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11378 ? 2
11379 : 0);
11380 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11381 return;
11382 }
11383
11384 // Diagnose references or pointers to incomplete types differently,
11385 // since it's far from impossible that the incompleteness triggered
11386 // the failure.
11387 QualType TempFromTy = FromTy.getNonReferenceType();
11388 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11389 TempFromTy = PTy->getPointeeType();
11390 if (TempFromTy->isIncompleteType()) {
11391 // Emit the generic diagnostic and, optionally, add the hints to it.
11392 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11393 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11394 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11395 << (unsigned)(Cand->Fix.Kind);
11396
11397 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11398 return;
11399 }
11400
11401 // Diagnose base -> derived pointer conversions.
11402 unsigned BaseToDerivedConversion = 0;
11403 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11404 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11405 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11406 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11407 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11408 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11409 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11410 FromPtrTy->getPointeeType()))
11411 BaseToDerivedConversion = 1;
11412 }
11413 } else if (const ObjCObjectPointerType *FromPtrTy
11414 = FromTy->getAs<ObjCObjectPointerType>()) {
11415 if (const ObjCObjectPointerType *ToPtrTy
11416 = ToTy->getAs<ObjCObjectPointerType>())
11417 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11418 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11419 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11420 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11421 FromIface->isSuperClassOf(ToIface))
11422 BaseToDerivedConversion = 2;
11423 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11424 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11425 S.getASTContext()) &&
11426 !FromTy->isIncompleteType() &&
11427 !ToRefTy->getPointeeType()->isIncompleteType() &&
11428 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11429 BaseToDerivedConversion = 3;
11430 }
11431 }
11432
11433 if (BaseToDerivedConversion) {
11434 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11435 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11436 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11437 << I + 1;
11438 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11439 return;
11440 }
11441
11442 if (isa<ObjCObjectPointerType>(CFromTy) &&
11443 isa<PointerType>(CToTy)) {
11444 Qualifiers FromQs = CFromTy.getQualifiers();
11445 Qualifiers ToQs = CToTy.getQualifiers();
11446 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11447 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11448 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11449 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11450 << I + 1;
11451 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11452 return;
11453 }
11454 }
11455
11456 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11457 return;
11458
11459 // Emit the generic diagnostic and, optionally, add the hints to it.
11460 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11461 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11462 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11463 << (unsigned)(Cand->Fix.Kind);
11464
11465 // Check that location of Fn is not in system header.
11466 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11467 // If we can fix the conversion, suggest the FixIts.
11468 for (const FixItHint &HI : Cand->Fix.Hints)
11469 FDiag << HI;
11470 }
11471
11472 S.Diag(Fn->getLocation(), FDiag);
11473
11474 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11475}
11476
11477/// Additional arity mismatch diagnosis specific to a function overload
11478/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11479/// over a candidate in any candidate set.
11481 unsigned NumArgs, bool IsAddressOf = false) {
11482 assert(Cand->Function && "Candidate is required to be a function.");
11483 FunctionDecl *Fn = Cand->Function;
11484 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11485 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11486
11487 // With invalid overloaded operators, it's possible that we think we
11488 // have an arity mismatch when in fact it looks like we have the
11489 // right number of arguments, because only overloaded operators have
11490 // the weird behavior of overloading member and non-member functions.
11491 // Just don't report anything.
11492 if (Fn->isInvalidDecl() &&
11493 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11494 return true;
11495
11496 if (NumArgs < MinParams) {
11497 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11499 Cand->DeductionFailure.getResult() ==
11501 } else {
11502 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11504 Cand->DeductionFailure.getResult() ==
11506 }
11507
11508 return false;
11509}
11510
11511/// General arity mismatch diagnosis over a candidate in a candidate set.
11513 unsigned NumFormalArgs,
11514 bool IsAddressOf = false) {
11515 assert(isa<FunctionDecl>(D) &&
11516 "The templated declaration should at least be a function"
11517 " when diagnosing bad template argument deduction due to too many"
11518 " or too few arguments");
11519
11520 FunctionDecl *Fn = cast<FunctionDecl>(D);
11521
11522 // TODO: treat calls to a missing default constructor as a special case
11523 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11524 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11525 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11526
11527 // at least / at most / exactly
11528 bool HasExplicitObjectParam =
11529 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11530
11531 unsigned ParamCount =
11532 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11533 unsigned mode, modeCount;
11534
11535 if (NumFormalArgs < MinParams) {
11536 if (MinParams != ParamCount || FnTy->isVariadic() ||
11537 FnTy->isTemplateVariadic())
11538 mode = 0; // "at least"
11539 else
11540 mode = 2; // "exactly"
11541 modeCount = MinParams;
11542 } else {
11543 if (MinParams != ParamCount)
11544 mode = 1; // "at most"
11545 else
11546 mode = 2; // "exactly"
11547 modeCount = ParamCount;
11548 }
11549
11550 std::string Description;
11551 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11552 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11553
11554 if (modeCount == 1 && !IsAddressOf &&
11555 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11556 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11557 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11558 << Description << mode
11559 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11560 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11561 else
11562 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11563 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11564 << Description << mode << modeCount << NumFormalArgs
11565 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11566
11567 MaybeEmitInheritedConstructorNote(S, Found);
11568}
11569
11570/// Arity mismatch diagnosis specific to a function overload candidate.
11572 unsigned NumFormalArgs) {
11573 assert(Cand->Function && "Candidate must be a function");
11574 FunctionDecl *Fn = Cand->Function;
11575 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
11576 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
11577 Cand->TookAddressOfOverload);
11578}
11579
11581 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11582 return TD;
11583 llvm_unreachable("Unsupported: Getting the described template declaration"
11584 " for bad deduction diagnosis");
11585}
11586
11587/// Diagnose a failed template-argument deduction.
11588static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11589 DeductionFailureInfo &DeductionFailure,
11590 unsigned NumArgs,
11591 bool TakingCandidateAddress) {
11592 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11593 NamedDecl *ParamD;
11594 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11595 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11596 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11597 switch (DeductionFailure.getResult()) {
11599 llvm_unreachable(
11600 "TemplateDeductionResult::Success while diagnosing bad deduction");
11602 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11603 "while diagnosing bad deduction");
11606 return;
11607
11609 assert(ParamD && "no parameter found for incomplete deduction result");
11610 S.Diag(Templated->getLocation(),
11611 diag::note_ovl_candidate_incomplete_deduction)
11612 << ParamD->getDeclName();
11613 MaybeEmitInheritedConstructorNote(S, Found);
11614 return;
11615 }
11616
11618 assert(ParamD && "no parameter found for incomplete deduction result");
11619 S.Diag(Templated->getLocation(),
11620 diag::note_ovl_candidate_incomplete_deduction_pack)
11621 << ParamD->getDeclName()
11622 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11623 << *DeductionFailure.getFirstArg();
11624 MaybeEmitInheritedConstructorNote(S, Found);
11625 return;
11626 }
11627
11629 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11630 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11631
11632 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11633
11634 // Param will have been canonicalized, but it should just be a
11635 // qualified version of ParamD, so move the qualifiers to that.
11637 Qs.strip(Param);
11638 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11639 assert(S.Context.hasSameType(Param, NonCanonParam));
11640
11641 // Arg has also been canonicalized, but there's nothing we can do
11642 // about that. It also doesn't matter as much, because it won't
11643 // have any template parameters in it (because deduction isn't
11644 // done on dependent types).
11645 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11646
11647 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11648 << ParamD->getDeclName() << Arg << NonCanonParam;
11649 MaybeEmitInheritedConstructorNote(S, Found);
11650 return;
11651 }
11652
11654 assert(ParamD && "no parameter found for inconsistent deduction result");
11655 int which = 0;
11656 if (isa<TemplateTypeParmDecl>(ParamD))
11657 which = 0;
11658 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11659 // Deduction might have failed because we deduced arguments of two
11660 // different types for a non-type template parameter.
11661 // FIXME: Use a different TDK value for this.
11662 QualType T1 =
11663 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11664 QualType T2 =
11665 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11666 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11667 S.Diag(Templated->getLocation(),
11668 diag::note_ovl_candidate_inconsistent_deduction_types)
11669 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11670 << *DeductionFailure.getSecondArg() << T2;
11671 MaybeEmitInheritedConstructorNote(S, Found);
11672 return;
11673 }
11674
11675 which = 1;
11676 } else {
11677 which = 2;
11678 }
11679
11680 // Tweak the diagnostic if the problem is that we deduced packs of
11681 // different arities. We'll print the actual packs anyway in case that
11682 // includes additional useful information.
11683 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11684 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11685 DeductionFailure.getFirstArg()->pack_size() !=
11686 DeductionFailure.getSecondArg()->pack_size()) {
11687 which = 3;
11688 }
11689
11690 S.Diag(Templated->getLocation(),
11691 diag::note_ovl_candidate_inconsistent_deduction)
11692 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11693 << *DeductionFailure.getSecondArg();
11694 MaybeEmitInheritedConstructorNote(S, Found);
11695 return;
11696 }
11697
11699 assert(ParamD && "no parameter found for invalid explicit arguments");
11700 if (ParamD->getDeclName())
11701 S.Diag(Templated->getLocation(),
11702 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11703 << ParamD->getDeclName();
11704 else {
11705 int index = 0;
11706 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11707 index = TTP->getIndex();
11708 else if (NonTypeTemplateParmDecl *NTTP
11709 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11710 index = NTTP->getIndex();
11711 else
11712 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11713 S.Diag(Templated->getLocation(),
11714 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11715 << (index + 1);
11716 }
11717 MaybeEmitInheritedConstructorNote(S, Found);
11718 return;
11719
11721 // Format the template argument list into the argument string.
11722 SmallString<128> TemplateArgString;
11723 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11724 TemplateArgString = " ";
11725 TemplateArgString += S.getTemplateArgumentBindingsText(
11726 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11727 if (TemplateArgString.size() == 1)
11728 TemplateArgString.clear();
11729 S.Diag(Templated->getLocation(),
11730 diag::note_ovl_candidate_unsatisfied_constraints)
11731 << TemplateArgString;
11732
11734 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11735 return;
11736 }
11739 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11740 return;
11741
11743 S.Diag(Templated->getLocation(),
11744 diag::note_ovl_candidate_instantiation_depth);
11745 MaybeEmitInheritedConstructorNote(S, Found);
11746 return;
11747
11749 // Format the template argument list into the argument string.
11750 SmallString<128> TemplateArgString;
11751 if (TemplateArgumentList *Args =
11752 DeductionFailure.getTemplateArgumentList()) {
11753 TemplateArgString = " ";
11754 TemplateArgString += S.getTemplateArgumentBindingsText(
11755 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11756 if (TemplateArgString.size() == 1)
11757 TemplateArgString.clear();
11758 }
11759
11760 // If this candidate was disabled by enable_if, say so.
11761 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11762 if (PDiag && PDiag->second.getDiagID() ==
11763 diag::err_typename_nested_not_found_enable_if) {
11764 // FIXME: Use the source range of the condition, and the fully-qualified
11765 // name of the enable_if template. These are both present in PDiag.
11766 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11767 << "'enable_if'" << TemplateArgString;
11768 return;
11769 }
11770
11771 // We found a specific requirement that disabled the enable_if.
11772 if (PDiag && PDiag->second.getDiagID() ==
11773 diag::err_typename_nested_not_found_requirement) {
11774 S.Diag(Templated->getLocation(),
11775 diag::note_ovl_candidate_disabled_by_requirement)
11776 << PDiag->second.getStringArg(0) << TemplateArgString;
11777 return;
11778 }
11779
11780 // Format the SFINAE diagnostic into the argument string.
11781 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11782 // formatted message in another diagnostic.
11783 SmallString<128> SFINAEArgString;
11784 SourceRange R;
11785 if (PDiag) {
11786 SFINAEArgString = ": ";
11787 R = SourceRange(PDiag->first, PDiag->first);
11788 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11789 }
11790
11791 S.Diag(Templated->getLocation(),
11792 diag::note_ovl_candidate_substitution_failure)
11793 << TemplateArgString << SFINAEArgString << R;
11794 MaybeEmitInheritedConstructorNote(S, Found);
11795 return;
11796 }
11797
11800 // Format the template argument list into the argument string.
11801 SmallString<128> TemplateArgString;
11802 if (TemplateArgumentList *Args =
11803 DeductionFailure.getTemplateArgumentList()) {
11804 TemplateArgString = " ";
11805 TemplateArgString += S.getTemplateArgumentBindingsText(
11806 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11807 if (TemplateArgString.size() == 1)
11808 TemplateArgString.clear();
11809 }
11810
11811 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11812 << (*DeductionFailure.getCallArgIndex() + 1)
11813 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11814 << TemplateArgString
11815 << (DeductionFailure.getResult() ==
11817 break;
11818 }
11819
11821 // FIXME: Provide a source location to indicate what we couldn't match.
11822 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11823 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11824 if (FirstTA.getKind() == TemplateArgument::Template &&
11825 SecondTA.getKind() == TemplateArgument::Template) {
11826 TemplateName FirstTN = FirstTA.getAsTemplate();
11827 TemplateName SecondTN = SecondTA.getAsTemplate();
11828 if (FirstTN.getKind() == TemplateName::Template &&
11829 SecondTN.getKind() == TemplateName::Template) {
11830 if (FirstTN.getAsTemplateDecl()->getName() ==
11831 SecondTN.getAsTemplateDecl()->getName()) {
11832 // FIXME: This fixes a bad diagnostic where both templates are named
11833 // the same. This particular case is a bit difficult since:
11834 // 1) It is passed as a string to the diagnostic printer.
11835 // 2) The diagnostic printer only attempts to find a better
11836 // name for types, not decls.
11837 // Ideally, this should folded into the diagnostic printer.
11838 S.Diag(Templated->getLocation(),
11839 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11840 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11841 return;
11842 }
11843 }
11844 }
11845
11846 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11847 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11848 return;
11849
11850 // FIXME: For generic lambda parameters, check if the function is a lambda
11851 // call operator, and if so, emit a prettier and more informative
11852 // diagnostic that mentions 'auto' and lambda in addition to
11853 // (or instead of?) the canonical template type parameters.
11854 S.Diag(Templated->getLocation(),
11855 diag::note_ovl_candidate_non_deduced_mismatch)
11856 << FirstTA << SecondTA;
11857 return;
11858 }
11859 // TODO: diagnose these individually, then kill off
11860 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11862 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11863 MaybeEmitInheritedConstructorNote(S, Found);
11864 return;
11866 S.Diag(Templated->getLocation(),
11867 diag::note_cuda_ovl_candidate_target_mismatch);
11868 return;
11869 }
11870}
11871
11872/// Diagnose a failed template-argument deduction, for function calls.
11874 unsigned NumArgs,
11875 bool TakingCandidateAddress) {
11876 assert(Cand->Function && "Candidate must be a function");
11877 FunctionDecl *Fn = Cand->Function;
11881 if (CheckArityMismatch(S, Cand, NumArgs))
11882 return;
11883 }
11884 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
11885 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11886}
11887
11888/// CUDA: diagnose an invalid call across targets.
11890 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11891 assert(Cand->Function && "Candidate must be a Function.");
11892 FunctionDecl *Callee = Cand->Function;
11893
11894 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11895 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11896
11897 std::string FnDesc;
11898 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11899 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11900 Cand->getRewriteKind(), FnDesc);
11901
11902 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11903 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11904 << FnDesc /* Ignored */
11905 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11906
11907 // This could be an implicit constructor for which we could not infer the
11908 // target due to a collsion. Diagnose that case.
11909 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11910 if (Meth != nullptr && Meth->isImplicit()) {
11911 CXXRecordDecl *ParentClass = Meth->getParent();
11913
11914 switch (FnKindPair.first) {
11915 default:
11916 return;
11917 case oc_implicit_default_constructor:
11919 break;
11920 case oc_implicit_copy_constructor:
11922 break;
11923 case oc_implicit_move_constructor:
11925 break;
11926 case oc_implicit_copy_assignment:
11928 break;
11929 case oc_implicit_move_assignment:
11931 break;
11932 };
11933
11934 bool ConstRHS = false;
11935 if (Meth->getNumParams()) {
11936 if (const ReferenceType *RT =
11937 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11938 ConstRHS = RT->getPointeeType().isConstQualified();
11939 }
11940 }
11941
11942 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11943 /* ConstRHS */ ConstRHS,
11944 /* Diagnose */ true);
11945 }
11946}
11947
11949 assert(Cand->Function && "Candidate must be a function");
11950 FunctionDecl *Callee = Cand->Function;
11951 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11952
11953 S.Diag(Callee->getLocation(),
11954 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11955 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11956}
11957
11959 assert(Cand->Function && "Candidate must be a function");
11960 FunctionDecl *Fn = Cand->Function;
11962 assert(ES.isExplicit() && "not an explicit candidate");
11963
11964 unsigned Kind;
11965 switch (Fn->getDeclKind()) {
11966 case Decl::Kind::CXXConstructor:
11967 Kind = 0;
11968 break;
11969 case Decl::Kind::CXXConversion:
11970 Kind = 1;
11971 break;
11972 case Decl::Kind::CXXDeductionGuide:
11973 Kind = Fn->isImplicit() ? 0 : 2;
11974 break;
11975 default:
11976 llvm_unreachable("invalid Decl");
11977 }
11978
11979 // Note the location of the first (in-class) declaration; a redeclaration
11980 // (particularly an out-of-class definition) will typically lack the
11981 // 'explicit' specifier.
11982 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11983 FunctionDecl *First = Fn->getFirstDecl();
11984 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11985 First = Pattern->getFirstDecl();
11986
11987 S.Diag(First->getLocation(),
11988 diag::note_ovl_candidate_explicit)
11989 << Kind << (ES.getExpr() ? 1 : 0)
11990 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11991}
11992
11994 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
11995 if (!DG)
11996 return;
11997 TemplateDecl *OriginTemplate =
11999 // We want to always print synthesized deduction guides for type aliases.
12000 // They would retain the explicit bit of the corresponding constructor.
12001 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12002 return;
12003 std::string FunctionProto;
12004 llvm::raw_string_ostream OS(FunctionProto);
12005 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12006 if (!Template) {
12007 // This also could be an instantiation. Find out the primary template.
12008 FunctionDecl *Pattern =
12009 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12010 if (!Pattern) {
12011 // The implicit deduction guide is built on an explicit non-template
12012 // deduction guide. Currently, this might be the case only for type
12013 // aliases.
12014 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12015 // gets merged.
12016 assert(OriginTemplate->isTypeAlias() &&
12017 "Non-template implicit deduction guides are only possible for "
12018 "type aliases");
12019 DG->print(OS);
12020 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12021 << FunctionProto;
12022 return;
12023 }
12024 Template = Pattern->getDescribedFunctionTemplate();
12025 assert(Template && "Cannot find the associated function template of "
12026 "CXXDeductionGuideDecl?");
12027 }
12028 Template->print(OS);
12029 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12030 << FunctionProto;
12031}
12032
12033/// Generates a 'note' diagnostic for an overload candidate. We've
12034/// already generated a primary error at the call site.
12035///
12036/// It really does need to be a single diagnostic with its caret
12037/// pointed at the candidate declaration. Yes, this creates some
12038/// major challenges of technical writing. Yes, this makes pointing
12039/// out problems with specific arguments quite awkward. It's still
12040/// better than generating twenty screens of text for every failed
12041/// overload.
12042///
12043/// It would be great to be able to express per-candidate problems
12044/// more richly for those diagnostic clients that cared, but we'd
12045/// still have to be just as careful with the default diagnostics.
12046/// \param CtorDestAS Addr space of object being constructed (for ctor
12047/// candidates only).
12049 unsigned NumArgs,
12050 bool TakingCandidateAddress,
12051 LangAS CtorDestAS = LangAS::Default) {
12052 assert(Cand->Function && "Candidate must be a function");
12053 FunctionDecl *Fn = Cand->Function;
12055 return;
12056
12057 // There is no physical candidate declaration to point to for OpenCL builtins.
12058 // Except for failed conversions, the notes are identical for each candidate,
12059 // so do not generate such notes.
12060 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12062 return;
12063
12064 // Skip implicit member functions when trying to resolve
12065 // the address of a an overload set for a function pointer.
12066 if (Cand->TookAddressOfOverload &&
12067 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12068 return;
12069
12070 // Note deleted candidates, but only if they're viable.
12071 if (Cand->Viable) {
12072 if (Fn->isDeleted()) {
12073 std::string FnDesc;
12074 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12075 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12076 Cand->getRewriteKind(), FnDesc);
12077
12078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12079 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12080 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12081 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12082 return;
12083 }
12084
12085 // We don't really have anything else to say about viable candidates.
12086 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12087 return;
12088 }
12089
12090 // If this is a synthesized deduction guide we're deducing against, add a note
12091 // for it. These deduction guides are not explicitly spelled in the source
12092 // code, so simply printing a deduction failure note mentioning synthesized
12093 // template parameters or pointing to the header of the surrounding RecordDecl
12094 // would be confusing.
12095 //
12096 // We prefer adding such notes at the end of the deduction failure because
12097 // duplicate code snippets appearing in the diagnostic would likely become
12098 // noisy.
12099 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12100
12101 switch (Cand->FailureKind) {
12104 return DiagnoseArityMismatch(S, Cand, NumArgs);
12105
12107 return DiagnoseBadDeduction(S, Cand, NumArgs,
12108 TakingCandidateAddress);
12109
12111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12112 << (Fn->getPrimaryTemplate() ? 1 : 0);
12113 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12114 return;
12115 }
12116
12118 Qualifiers QualsForPrinting;
12119 QualsForPrinting.setAddressSpace(CtorDestAS);
12120 S.Diag(Fn->getLocation(),
12121 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12122 << QualsForPrinting;
12123 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12124 return;
12125 }
12126
12130 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12131
12133 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12134 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12135 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12136 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12137
12138 // FIXME: this currently happens when we're called from SemaInit
12139 // when user-conversion overload fails. Figure out how to handle
12140 // those conditions and diagnose them well.
12141 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12142 }
12143
12145 return DiagnoseBadTarget(S, Cand);
12146
12147 case ovl_fail_enable_if:
12148 return DiagnoseFailedEnableIfAttr(S, Cand);
12149
12150 case ovl_fail_explicit:
12151 return DiagnoseFailedExplicitSpec(S, Cand);
12152
12154 // It's generally not interesting to note copy/move constructors here.
12155 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12156 return;
12157 S.Diag(Fn->getLocation(),
12158 diag::note_ovl_candidate_inherited_constructor_slice)
12159 << (Fn->getPrimaryTemplate() ? 1 : 0)
12160 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12161 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12162 return;
12163
12165 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12166 (void)Available;
12167 assert(!Available);
12168 break;
12169 }
12171 // Do nothing, these should simply be ignored.
12172 break;
12173
12175 std::string FnDesc;
12176 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12177 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12178 Cand->getRewriteKind(), FnDesc);
12179
12180 S.Diag(Fn->getLocation(),
12181 diag::note_ovl_candidate_constraints_not_satisfied)
12182 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12183 << FnDesc /* Ignored */;
12184 ConstraintSatisfaction Satisfaction;
12185 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12186 break;
12187 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12188 }
12189 }
12190}
12191
12194 return;
12195
12196 // Desugar the type of the surrogate down to a function type,
12197 // retaining as many typedefs as possible while still showing
12198 // the function type (and, therefore, its parameter types).
12199 QualType FnType = Cand->Surrogate->getConversionType();
12200 bool isLValueReference = false;
12201 bool isRValueReference = false;
12202 bool isPointer = false;
12203 if (const LValueReferenceType *FnTypeRef =
12204 FnType->getAs<LValueReferenceType>()) {
12205 FnType = FnTypeRef->getPointeeType();
12206 isLValueReference = true;
12207 } else if (const RValueReferenceType *FnTypeRef =
12208 FnType->getAs<RValueReferenceType>()) {
12209 FnType = FnTypeRef->getPointeeType();
12210 isRValueReference = true;
12211 }
12212 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12213 FnType = FnTypePtr->getPointeeType();
12214 isPointer = true;
12215 }
12216 // Desugar down to a function type.
12217 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12218 // Reconstruct the pointer/reference as appropriate.
12219 if (isPointer) FnType = S.Context.getPointerType(FnType);
12220 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12221 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12222
12223 if (!Cand->Viable &&
12225 S.Diag(Cand->Surrogate->getLocation(),
12226 diag::note_ovl_surrogate_constraints_not_satisfied)
12227 << Cand->Surrogate;
12228 ConstraintSatisfaction Satisfaction;
12229 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12230 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12231 } else {
12232 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12233 << FnType;
12234 }
12235}
12236
12237static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12238 SourceLocation OpLoc,
12239 OverloadCandidate *Cand) {
12240 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12241 std::string TypeStr("operator");
12242 TypeStr += Opc;
12243 TypeStr += "(";
12244 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12245 if (Cand->Conversions.size() == 1) {
12246 TypeStr += ")";
12247 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12248 } else {
12249 TypeStr += ", ";
12250 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12251 TypeStr += ")";
12252 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12253 }
12254}
12255
12257 OverloadCandidate *Cand) {
12258 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12259 if (ICS.isBad()) break; // all meaningless after first invalid
12260 if (!ICS.isAmbiguous()) continue;
12261
12263 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12264 }
12265}
12266
12268 if (Cand->Function)
12269 return Cand->Function->getLocation();
12270 if (Cand->IsSurrogate)
12271 return Cand->Surrogate->getLocation();
12272 return SourceLocation();
12273}
12274
12275static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12276 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12280 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12281
12285 return 1;
12286
12289 return 2;
12290
12298 return 3;
12299
12301 return 4;
12302
12304 return 5;
12305
12308 return 6;
12309 }
12310 llvm_unreachable("Unhandled deduction result");
12311}
12312
12313namespace {
12314
12315struct CompareOverloadCandidatesForDisplay {
12316 Sema &S;
12318 size_t NumArgs;
12320
12321 CompareOverloadCandidatesForDisplay(
12322 Sema &S, SourceLocation Loc, size_t NArgs,
12324 : S(S), NumArgs(NArgs), CSK(CSK) {}
12325
12326 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12327 // If there are too many or too few arguments, that's the high-order bit we
12328 // want to sort by, even if the immediate failure kind was something else.
12329 if (C->FailureKind == ovl_fail_too_many_arguments ||
12330 C->FailureKind == ovl_fail_too_few_arguments)
12331 return static_cast<OverloadFailureKind>(C->FailureKind);
12332
12333 if (C->Function) {
12334 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12336 if (NumArgs < C->Function->getMinRequiredArguments())
12338 }
12339
12340 return static_cast<OverloadFailureKind>(C->FailureKind);
12341 }
12342
12343 bool operator()(const OverloadCandidate *L,
12344 const OverloadCandidate *R) {
12345 // Fast-path this check.
12346 if (L == R) return false;
12347
12348 // Order first by viability.
12349 if (L->Viable) {
12350 if (!R->Viable) return true;
12351
12352 if (int Ord = CompareConversions(*L, *R))
12353 return Ord < 0;
12354 // Use other tie breakers.
12355 } else if (R->Viable)
12356 return false;
12357
12358 assert(L->Viable == R->Viable);
12359
12360 // Criteria by which we can sort non-viable candidates:
12361 if (!L->Viable) {
12362 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12363 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12364
12365 // 1. Arity mismatches come after other candidates.
12366 if (LFailureKind == ovl_fail_too_many_arguments ||
12367 LFailureKind == ovl_fail_too_few_arguments) {
12368 if (RFailureKind == ovl_fail_too_many_arguments ||
12369 RFailureKind == ovl_fail_too_few_arguments) {
12370 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12371 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12372 if (LDist == RDist) {
12373 if (LFailureKind == RFailureKind)
12374 // Sort non-surrogates before surrogates.
12375 return !L->IsSurrogate && R->IsSurrogate;
12376 // Sort candidates requiring fewer parameters than there were
12377 // arguments given after candidates requiring more parameters
12378 // than there were arguments given.
12379 return LFailureKind == ovl_fail_too_many_arguments;
12380 }
12381 return LDist < RDist;
12382 }
12383 return false;
12384 }
12385 if (RFailureKind == ovl_fail_too_many_arguments ||
12386 RFailureKind == ovl_fail_too_few_arguments)
12387 return true;
12388
12389 // 2. Bad conversions come first and are ordered by the number
12390 // of bad conversions and quality of good conversions.
12391 if (LFailureKind == ovl_fail_bad_conversion) {
12392 if (RFailureKind != ovl_fail_bad_conversion)
12393 return true;
12394
12395 // The conversion that can be fixed with a smaller number of changes,
12396 // comes first.
12397 unsigned numLFixes = L->Fix.NumConversionsFixed;
12398 unsigned numRFixes = R->Fix.NumConversionsFixed;
12399 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12400 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12401 if (numLFixes != numRFixes) {
12402 return numLFixes < numRFixes;
12403 }
12404
12405 // If there's any ordering between the defined conversions...
12406 if (int Ord = CompareConversions(*L, *R))
12407 return Ord < 0;
12408 } else if (RFailureKind == ovl_fail_bad_conversion)
12409 return false;
12410
12411 if (LFailureKind == ovl_fail_bad_deduction) {
12412 if (RFailureKind != ovl_fail_bad_deduction)
12413 return true;
12414
12416 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12417 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12418 if (LRank != RRank)
12419 return LRank < RRank;
12420 }
12421 } else if (RFailureKind == ovl_fail_bad_deduction)
12422 return false;
12423
12424 // TODO: others?
12425 }
12426
12427 // Sort everything else by location.
12430
12431 // Put candidates without locations (e.g. builtins) at the end.
12432 if (LLoc.isValid() && RLoc.isValid())
12433 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12434 if (LLoc.isValid() && !RLoc.isValid())
12435 return true;
12436 if (RLoc.isValid() && !LLoc.isValid())
12437 return false;
12438 assert(!LLoc.isValid() && !RLoc.isValid());
12439 // For builtins and other functions without locations, fallback to the order
12440 // in which they were added into the candidate set.
12441 return L < R;
12442 }
12443
12444private:
12445 struct ConversionSignals {
12446 unsigned KindRank = 0;
12448
12449 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12450 ConversionSignals Sig;
12451 Sig.KindRank = Seq.getKindRank();
12452 if (Seq.isStandard())
12453 Sig.Rank = Seq.Standard.getRank();
12454 else if (Seq.isUserDefined())
12455 Sig.Rank = Seq.UserDefined.After.getRank();
12456 // We intend StaticObjectArgumentConversion to compare the same as
12457 // StandardConversion with ICR_ExactMatch rank.
12458 return Sig;
12459 }
12460
12461 static ConversionSignals ForObjectArgument() {
12462 // We intend StaticObjectArgumentConversion to compare the same as
12463 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12464 return {};
12465 }
12466 };
12467
12468 // Returns -1 if conversions in L are considered better.
12469 // 0 if they are considered indistinguishable.
12470 // 1 if conversions in R are better.
12471 int CompareConversions(const OverloadCandidate &L,
12472 const OverloadCandidate &R) {
12473 // We cannot use `isBetterOverloadCandidate` because it is defined
12474 // according to the C++ standard and provides a partial order, but we need
12475 // a total order as this function is used in sort.
12476 assert(L.Conversions.size() == R.Conversions.size());
12477 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12478 auto LS = L.IgnoreObjectArgument && I == 0
12479 ? ConversionSignals::ForObjectArgument()
12480 : ConversionSignals::ForSequence(L.Conversions[I]);
12481 auto RS = R.IgnoreObjectArgument
12482 ? ConversionSignals::ForObjectArgument()
12483 : ConversionSignals::ForSequence(R.Conversions[I]);
12484 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12485 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12486 ? -1
12487 : 1;
12488 }
12489 // FIXME: find a way to compare templates for being more or less
12490 // specialized that provides a strict weak ordering.
12491 return 0;
12492 }
12493};
12494}
12495
12496/// CompleteNonViableCandidate - Normally, overload resolution only
12497/// computes up to the first bad conversion. Produces the FixIt set if
12498/// possible.
12499static void
12501 ArrayRef<Expr *> Args,
12503 assert(!Cand->Viable);
12504
12505 // Don't do anything on failures other than bad conversion.
12507 return;
12508
12509 // We only want the FixIts if all the arguments can be corrected.
12510 bool Unfixable = false;
12511 // Use a implicit copy initialization to check conversion fixes.
12513
12514 // Attempt to fix the bad conversion.
12515 unsigned ConvCount = Cand->Conversions.size();
12516 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12517 ++ConvIdx) {
12518 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12519 if (Cand->Conversions[ConvIdx].isInitialized() &&
12520 Cand->Conversions[ConvIdx].isBad()) {
12521 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12522 break;
12523 }
12524 }
12525
12526 // FIXME: this should probably be preserved from the overload
12527 // operation somehow.
12528 bool SuppressUserConversions = false;
12529
12530 unsigned ConvIdx = 0;
12531 unsigned ArgIdx = 0;
12532 ArrayRef<QualType> ParamTypes;
12533 bool Reversed = Cand->isReversed();
12534
12535 if (Cand->IsSurrogate) {
12536 QualType ConvType
12538 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12539 ConvType = ConvPtrType->getPointeeType();
12540 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12541 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12542 ConvIdx = 1;
12543 } else if (Cand->Function) {
12544 ParamTypes =
12545 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12546 if (isa<CXXMethodDecl>(Cand->Function) &&
12547 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12548 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12549 ConvIdx = 1;
12551 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12553 OO_Subscript)
12554 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12555 ArgIdx = 1;
12556 }
12557 } else {
12558 // Builtin operator.
12559 assert(ConvCount <= 3);
12560 ParamTypes = Cand->BuiltinParamTypes;
12561 }
12562
12563 // Fill in the rest of the conversions.
12564 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12565 ConvIdx != ConvCount;
12566 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12567 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12568 if (Cand->Conversions[ConvIdx].isInitialized()) {
12569 // We've already checked this conversion.
12570 } else if (ParamIdx < ParamTypes.size()) {
12571 if (ParamTypes[ParamIdx]->isDependentType())
12572 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12573 Args[ArgIdx]->getType());
12574 else {
12575 Cand->Conversions[ConvIdx] =
12576 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12577 SuppressUserConversions,
12578 /*InOverloadResolution=*/true,
12579 /*AllowObjCWritebackConversion=*/
12580 S.getLangOpts().ObjCAutoRefCount);
12581 // Store the FixIt in the candidate if it exists.
12582 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12583 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12584 }
12585 } else
12586 Cand->Conversions[ConvIdx].setEllipsis();
12587 }
12588}
12589
12592 SourceLocation OpLoc,
12593 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12594 // Sort the candidates by viability and position. Sorting directly would
12595 // be prohibitive, so we make a set of pointers and sort those.
12597 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12598 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12599 if (!Filter(*Cand))
12600 continue;
12601 switch (OCD) {
12602 case OCD_AllCandidates:
12603 if (!Cand->Viable) {
12604 if (!Cand->Function && !Cand->IsSurrogate) {
12605 // This a non-viable builtin candidate. We do not, in general,
12606 // want to list every possible builtin candidate.
12607 continue;
12608 }
12609 CompleteNonViableCandidate(S, Cand, Args, Kind);
12610 }
12611 break;
12612
12614 if (!Cand->Viable)
12615 continue;
12616 break;
12617
12619 if (!Cand->Best)
12620 continue;
12621 break;
12622 }
12623
12624 Cands.push_back(Cand);
12625 }
12626
12627 llvm::stable_sort(
12628 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12629
12630 return Cands;
12631}
12632
12634 SourceLocation OpLoc) {
12635 bool DeferHint = false;
12636 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12637 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12638 // host device candidates.
12639 auto WrongSidedCands =
12640 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12641 return (Cand.Viable == false &&
12642 Cand.FailureKind == ovl_fail_bad_target) ||
12643 (Cand.Function &&
12644 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12645 Cand.Function->template hasAttr<CUDADeviceAttr>());
12646 });
12647 DeferHint = !WrongSidedCands.empty();
12648 }
12649 return DeferHint;
12650}
12651
12652/// When overload resolution fails, prints diagnostic messages containing the
12653/// candidates in the candidate set.
12656 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12657 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12658
12659 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12660
12661 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12662
12663 // In WebAssembly we don't want to emit further diagnostics if a table is
12664 // passed as an argument to a function.
12665 bool NoteCands = true;
12666 for (const Expr *Arg : Args) {
12667 if (Arg->getType()->isWebAssemblyTableType())
12668 NoteCands = false;
12669 }
12670
12671 if (NoteCands)
12672 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12673
12674 if (OCD == OCD_AmbiguousCandidates)
12676}
12677
12680 StringRef Opc, SourceLocation OpLoc) {
12681 bool ReportedAmbiguousConversions = false;
12682
12683 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12684 unsigned CandsShown = 0;
12685 auto I = Cands.begin(), E = Cands.end();
12686 for (; I != E; ++I) {
12687 OverloadCandidate *Cand = *I;
12688
12689 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12690 ShowOverloads == Ovl_Best) {
12691 break;
12692 }
12693 ++CandsShown;
12694
12695 if (Cand->Function)
12696 NoteFunctionCandidate(S, Cand, Args.size(),
12697 /*TakingCandidateAddress=*/false, DestAS);
12698 else if (Cand->IsSurrogate)
12699 NoteSurrogateCandidate(S, Cand);
12700 else {
12701 assert(Cand->Viable &&
12702 "Non-viable built-in candidates are not added to Cands.");
12703 // Generally we only see ambiguities including viable builtin
12704 // operators if overload resolution got screwed up by an
12705 // ambiguous user-defined conversion.
12706 //
12707 // FIXME: It's quite possible for different conversions to see
12708 // different ambiguities, though.
12709 if (!ReportedAmbiguousConversions) {
12710 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12711 ReportedAmbiguousConversions = true;
12712 }
12713
12714 // If this is a viable builtin, print it.
12715 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12716 }
12717 }
12718
12719 // Inform S.Diags that we've shown an overload set with N elements. This may
12720 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12721 S.Diags.overloadCandidatesShown(CandsShown);
12722
12723 if (I != E)
12724 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12725 shouldDeferDiags(S, Args, OpLoc))
12726 << int(E - I);
12727}
12728
12729static SourceLocation
12731 return Cand->Specialization ? Cand->Specialization->getLocation()
12732 : SourceLocation();
12733}
12734
12735namespace {
12736struct CompareTemplateSpecCandidatesForDisplay {
12737 Sema &S;
12738 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12739
12740 bool operator()(const TemplateSpecCandidate *L,
12741 const TemplateSpecCandidate *R) {
12742 // Fast-path this check.
12743 if (L == R)
12744 return false;
12745
12746 // Assuming that both candidates are not matches...
12747
12748 // Sort by the ranking of deduction failures.
12752
12753 // Sort everything else by location.
12756
12757 // Put candidates without locations (e.g. builtins) at the end.
12758 if (LLoc.isInvalid())
12759 return false;
12760 if (RLoc.isInvalid())
12761 return true;
12762
12763 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12764 }
12765};
12766}
12767
12768/// Diagnose a template argument deduction failure.
12769/// We are treating these failures as overload failures due to bad
12770/// deductions.
12772 bool ForTakingAddress) {
12773 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12774 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12775}
12776
12777void TemplateSpecCandidateSet::destroyCandidates() {
12778 for (iterator i = begin(), e = end(); i != e; ++i) {
12779 i->DeductionFailure.Destroy();
12780 }
12781}
12782
12784 destroyCandidates();
12785 Candidates.clear();
12786}
12787
12788/// NoteCandidates - When no template specialization match is found, prints
12789/// diagnostic messages containing the non-matching specializations that form
12790/// the candidate set.
12791/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12792/// OCD == OCD_AllCandidates and Cand->Viable == false.
12794 // Sort the candidates by position (assuming no candidate is a match).
12795 // Sorting directly would be prohibitive, so we make a set of pointers
12796 // and sort those.
12798 Cands.reserve(size());
12799 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12800 if (Cand->Specialization)
12801 Cands.push_back(Cand);
12802 // Otherwise, this is a non-matching builtin candidate. We do not,
12803 // in general, want to list every possible builtin candidate.
12804 }
12805
12806 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12807
12808 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12809 // for generalization purposes (?).
12810 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12811
12813 unsigned CandsShown = 0;
12814 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12815 TemplateSpecCandidate *Cand = *I;
12816
12817 // Set an arbitrary limit on the number of candidates we'll spam
12818 // the user with. FIXME: This limit should depend on details of the
12819 // candidate list.
12820 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12821 break;
12822 ++CandsShown;
12823
12824 assert(Cand->Specialization &&
12825 "Non-matching built-in candidates are not added to Cands.");
12826 Cand->NoteDeductionFailure(S, ForTakingAddress);
12827 }
12828
12829 if (I != E)
12830 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12831}
12832
12833// [PossiblyAFunctionType] --> [Return]
12834// NonFunctionType --> NonFunctionType
12835// R (A) --> R(A)
12836// R (*)(A) --> R (A)
12837// R (&)(A) --> R (A)
12838// R (S::*)(A) --> R (A)
12840 QualType Ret = PossiblyAFunctionType;
12841 if (const PointerType *ToTypePtr =
12842 PossiblyAFunctionType->getAs<PointerType>())
12843 Ret = ToTypePtr->getPointeeType();
12844 else if (const ReferenceType *ToTypeRef =
12845 PossiblyAFunctionType->getAs<ReferenceType>())
12846 Ret = ToTypeRef->getPointeeType();
12847 else if (const MemberPointerType *MemTypePtr =
12848 PossiblyAFunctionType->getAs<MemberPointerType>())
12849 Ret = MemTypePtr->getPointeeType();
12850 Ret =
12851 Context.getCanonicalType(Ret).getUnqualifiedType();
12852 return Ret;
12853}
12854
12856 bool Complain = true) {
12857 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12858 S.DeduceReturnType(FD, Loc, Complain))
12859 return true;
12860
12861 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12862 if (S.getLangOpts().CPlusPlus17 &&
12863 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12864 !S.ResolveExceptionSpec(Loc, FPT))
12865 return true;
12866
12867 return false;
12868}
12869
12870namespace {
12871// A helper class to help with address of function resolution
12872// - allows us to avoid passing around all those ugly parameters
12873class AddressOfFunctionResolver {
12874 Sema& S;
12875 Expr* SourceExpr;
12876 const QualType& TargetType;
12877 QualType TargetFunctionType; // Extracted function type from target type
12878
12879 bool Complain;
12880 //DeclAccessPair& ResultFunctionAccessPair;
12881 ASTContext& Context;
12882
12883 bool TargetTypeIsNonStaticMemberFunction;
12884 bool FoundNonTemplateFunction;
12885 bool StaticMemberFunctionFromBoundPointer;
12886 bool HasComplained;
12887
12888 OverloadExpr::FindResult OvlExprInfo;
12889 OverloadExpr *OvlExpr;
12890 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12892 TemplateSpecCandidateSet FailedCandidates;
12893
12894public:
12895 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12896 const QualType &TargetType, bool Complain)
12897 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12898 Complain(Complain), Context(S.getASTContext()),
12899 TargetTypeIsNonStaticMemberFunction(
12900 !!TargetType->getAs<MemberPointerType>()),
12901 FoundNonTemplateFunction(false),
12902 StaticMemberFunctionFromBoundPointer(false),
12903 HasComplained(false),
12904 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12905 OvlExpr(OvlExprInfo.Expression),
12906 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12907 ExtractUnqualifiedFunctionTypeFromTargetType();
12908
12909 if (TargetFunctionType->isFunctionType()) {
12910 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12911 if (!UME->isImplicitAccess() &&
12913 StaticMemberFunctionFromBoundPointer = true;
12914 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12915 DeclAccessPair dap;
12917 OvlExpr, false, &dap)) {
12918 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12919 if (!Method->isStatic()) {
12920 // If the target type is a non-function type and the function found
12921 // is a non-static member function, pretend as if that was the
12922 // target, it's the only possible type to end up with.
12923 TargetTypeIsNonStaticMemberFunction = true;
12924
12925 // And skip adding the function if its not in the proper form.
12926 // We'll diagnose this due to an empty set of functions.
12927 if (!OvlExprInfo.HasFormOfMemberPointer)
12928 return;
12929 }
12930
12931 Matches.push_back(std::make_pair(dap, Fn));
12932 }
12933 return;
12934 }
12935
12936 if (OvlExpr->hasExplicitTemplateArgs())
12937 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12938
12939 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12940 // C++ [over.over]p4:
12941 // If more than one function is selected, [...]
12942 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12943 if (FoundNonTemplateFunction)
12944 EliminateAllTemplateMatches();
12945 else
12946 EliminateAllExceptMostSpecializedTemplate();
12947 }
12948 }
12949
12950 if (S.getLangOpts().CUDA && Matches.size() > 1)
12951 EliminateSuboptimalCudaMatches();
12952 }
12953
12954 bool hasComplained() const { return HasComplained; }
12955
12956private:
12957 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12958 QualType Discard;
12959 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12960 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12961 }
12962
12963 /// \return true if A is considered a better overload candidate for the
12964 /// desired type than B.
12965 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12966 // If A doesn't have exactly the correct type, we don't want to classify it
12967 // as "better" than anything else. This way, the user is required to
12968 // disambiguate for us if there are multiple candidates and no exact match.
12969 return candidateHasExactlyCorrectType(A) &&
12970 (!candidateHasExactlyCorrectType(B) ||
12971 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12972 }
12973
12974 /// \return true if we were able to eliminate all but one overload candidate,
12975 /// false otherwise.
12976 bool eliminiateSuboptimalOverloadCandidates() {
12977 // Same algorithm as overload resolution -- one pass to pick the "best",
12978 // another pass to be sure that nothing is better than the best.
12979 auto Best = Matches.begin();
12980 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12981 if (isBetterCandidate(I->second, Best->second))
12982 Best = I;
12983
12984 const FunctionDecl *BestFn = Best->second;
12985 auto IsBestOrInferiorToBest = [this, BestFn](
12986 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12987 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12988 };
12989
12990 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12991 // option, so we can potentially give the user a better error
12992 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12993 return false;
12994 Matches[0] = *Best;
12995 Matches.resize(1);
12996 return true;
12997 }
12998
12999 bool isTargetTypeAFunction() const {
13000 return TargetFunctionType->isFunctionType();
13001 }
13002
13003 // [ToType] [Return]
13004
13005 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13006 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13007 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13008 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13009 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13010 }
13011
13012 // return true if any matching specializations were found
13013 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13014 const DeclAccessPair& CurAccessFunPair) {
13015 if (CXXMethodDecl *Method
13016 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13017 // Skip non-static function templates when converting to pointer, and
13018 // static when converting to member pointer.
13019 bool CanConvertToFunctionPointer =
13020 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13021 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13022 return false;
13023 }
13024 else if (TargetTypeIsNonStaticMemberFunction)
13025 return false;
13026
13027 // C++ [over.over]p2:
13028 // If the name is a function template, template argument deduction is
13029 // done (14.8.2.2), and if the argument deduction succeeds, the
13030 // resulting template argument list is used to generate a single
13031 // function template specialization, which is added to the set of
13032 // overloaded functions considered.
13033 FunctionDecl *Specialization = nullptr;
13034 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13036 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13037 Specialization, Info, /*IsAddressOfFunction*/ true);
13038 Result != TemplateDeductionResult::Success) {
13039 // Make a note of the failed deduction for diagnostics.
13040 FailedCandidates.addCandidate()
13041 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13042 MakeDeductionFailureInfo(Context, Result, Info));
13043 return false;
13044 }
13045
13046 // Template argument deduction ensures that we have an exact match or
13047 // compatible pointer-to-function arguments that would be adjusted by ICS.
13048 // This function template specicalization works.
13050 Context.getCanonicalType(Specialization->getType()),
13051 Context.getCanonicalType(TargetFunctionType)));
13052
13054 return false;
13055
13056 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13057 return true;
13058 }
13059
13060 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13061 const DeclAccessPair& CurAccessFunPair) {
13062 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13063 // Skip non-static functions when converting to pointer, and static
13064 // when converting to member pointer.
13065 bool CanConvertToFunctionPointer =
13066 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13067 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13068 return false;
13069 }
13070 else if (TargetTypeIsNonStaticMemberFunction)
13071 return false;
13072
13073 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13074 if (S.getLangOpts().CUDA) {
13075 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13076 if (!(Caller && Caller->isImplicit()) &&
13077 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13078 return false;
13079 }
13080 if (FunDecl->isMultiVersion()) {
13081 const auto *TA = FunDecl->getAttr<TargetAttr>();
13082 if (TA && !TA->isDefaultVersion())
13083 return false;
13084 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13085 if (TVA && !TVA->isDefaultVersion())
13086 return false;
13087 }
13088
13089 // If any candidate has a placeholder return type, trigger its deduction
13090 // now.
13091 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13092 Complain)) {
13093 HasComplained |= Complain;
13094 return false;
13095 }
13096
13097 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13098 return false;
13099
13100 // If we're in C, we need to support types that aren't exactly identical.
13101 if (!S.getLangOpts().CPlusPlus ||
13102 candidateHasExactlyCorrectType(FunDecl)) {
13103 Matches.push_back(std::make_pair(
13104 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13105 FoundNonTemplateFunction = true;
13106 return true;
13107 }
13108 }
13109
13110 return false;
13111 }
13112
13113 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13114 bool Ret = false;
13115
13116 // If the overload expression doesn't have the form of a pointer to
13117 // member, don't try to convert it to a pointer-to-member type.
13118 if (IsInvalidFormOfPointerToMemberFunction())
13119 return false;
13120
13121 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13122 E = OvlExpr->decls_end();
13123 I != E; ++I) {
13124 // Look through any using declarations to find the underlying function.
13125 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13126
13127 // C++ [over.over]p3:
13128 // Non-member functions and static member functions match
13129 // targets of type "pointer-to-function" or "reference-to-function."
13130 // Nonstatic member functions match targets of
13131 // type "pointer-to-member-function."
13132 // Note that according to DR 247, the containing class does not matter.
13133 if (FunctionTemplateDecl *FunctionTemplate
13134 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13135 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13136 Ret = true;
13137 }
13138 // If we have explicit template arguments supplied, skip non-templates.
13139 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13140 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13141 Ret = true;
13142 }
13143 assert(Ret || Matches.empty());
13144 return Ret;
13145 }
13146
13147 void EliminateAllExceptMostSpecializedTemplate() {
13148 // [...] and any given function template specialization F1 is
13149 // eliminated if the set contains a second function template
13150 // specialization whose function template is more specialized
13151 // than the function template of F1 according to the partial
13152 // ordering rules of 14.5.5.2.
13153
13154 // The algorithm specified above is quadratic. We instead use a
13155 // two-pass algorithm (similar to the one used to identify the
13156 // best viable function in an overload set) that identifies the
13157 // best function template (if it exists).
13158
13159 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13160 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13161 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13162
13163 // TODO: It looks like FailedCandidates does not serve much purpose
13164 // here, since the no_viable diagnostic has index 0.
13166 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13167 SourceExpr->getBeginLoc(), S.PDiag(),
13168 S.PDiag(diag::err_addr_ovl_ambiguous)
13169 << Matches[0].second->getDeclName(),
13170 S.PDiag(diag::note_ovl_candidate)
13171 << (unsigned)oc_function << (unsigned)ocs_described_template,
13172 Complain, TargetFunctionType);
13173
13174 if (Result != MatchesCopy.end()) {
13175 // Make it the first and only element
13176 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13177 Matches[0].second = cast<FunctionDecl>(*Result);
13178 Matches.resize(1);
13179 } else
13180 HasComplained |= Complain;
13181 }
13182
13183 void EliminateAllTemplateMatches() {
13184 // [...] any function template specializations in the set are
13185 // eliminated if the set also contains a non-template function, [...]
13186 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13187 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13188 ++I;
13189 else {
13190 Matches[I] = Matches[--N];
13191 Matches.resize(N);
13192 }
13193 }
13194 }
13195
13196 void EliminateSuboptimalCudaMatches() {
13197 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13198 Matches);
13199 }
13200
13201public:
13202 void ComplainNoMatchesFound() const {
13203 assert(Matches.empty());
13204 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13205 << OvlExpr->getName() << TargetFunctionType
13206 << OvlExpr->getSourceRange();
13207 if (FailedCandidates.empty())
13208 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13209 /*TakingAddress=*/true);
13210 else {
13211 // We have some deduction failure messages. Use them to diagnose
13212 // the function templates, and diagnose the non-template candidates
13213 // normally.
13214 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13215 IEnd = OvlExpr->decls_end();
13216 I != IEnd; ++I)
13217 if (FunctionDecl *Fun =
13218 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13220 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13221 /*TakingAddress=*/true);
13222 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13223 }
13224 }
13225
13226 bool IsInvalidFormOfPointerToMemberFunction() const {
13227 return TargetTypeIsNonStaticMemberFunction &&
13228 !OvlExprInfo.HasFormOfMemberPointer;
13229 }
13230
13231 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13232 // TODO: Should we condition this on whether any functions might
13233 // have matched, or is it more appropriate to do that in callers?
13234 // TODO: a fixit wouldn't hurt.
13235 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13236 << TargetType << OvlExpr->getSourceRange();
13237 }
13238
13239 bool IsStaticMemberFunctionFromBoundPointer() const {
13240 return StaticMemberFunctionFromBoundPointer;
13241 }
13242
13243 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13244 S.Diag(OvlExpr->getBeginLoc(),
13245 diag::err_invalid_form_pointer_member_function)
13246 << OvlExpr->getSourceRange();
13247 }
13248
13249 void ComplainOfInvalidConversion() const {
13250 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13251 << OvlExpr->getName() << TargetType;
13252 }
13253
13254 void ComplainMultipleMatchesFound() const {
13255 assert(Matches.size() > 1);
13256 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13257 << OvlExpr->getName() << OvlExpr->getSourceRange();
13258 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13259 /*TakingAddress=*/true);
13260 }
13261
13262 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13263
13264 int getNumMatches() const { return Matches.size(); }
13265
13266 FunctionDecl* getMatchingFunctionDecl() const {
13267 if (Matches.size() != 1) return nullptr;
13268 return Matches[0].second;
13269 }
13270
13271 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13272 if (Matches.size() != 1) return nullptr;
13273 return &Matches[0].first;
13274 }
13275};
13276}
13277
13280 QualType TargetType,
13281 bool Complain,
13282 DeclAccessPair &FoundResult,
13283 bool *pHadMultipleCandidates) {
13284 assert(AddressOfExpr->getType() == Context.OverloadTy);
13285
13286 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13287 Complain);
13288 int NumMatches = Resolver.getNumMatches();
13289 FunctionDecl *Fn = nullptr;
13290 bool ShouldComplain = Complain && !Resolver.hasComplained();
13291 if (NumMatches == 0 && ShouldComplain) {
13292 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13293 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13294 else
13295 Resolver.ComplainNoMatchesFound();
13296 }
13297 else if (NumMatches > 1 && ShouldComplain)
13298 Resolver.ComplainMultipleMatchesFound();
13299 else if (NumMatches == 1) {
13300 Fn = Resolver.getMatchingFunctionDecl();
13301 assert(Fn);
13302 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13303 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13304 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13305 if (Complain) {
13306 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13307 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13308 else
13309 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13310 }
13311 }
13312
13313 if (pHadMultipleCandidates)
13314 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13315 return Fn;
13316}
13317
13321 OverloadExpr *Ovl = R.Expression;
13322 bool IsResultAmbiguous = false;
13323 FunctionDecl *Result = nullptr;
13324 DeclAccessPair DAP;
13325 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13326
13327 // Return positive for better, negative for worse, 0 for equal preference.
13328 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13329 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13330 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13331 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13332 };
13333
13334 // Don't use the AddressOfResolver because we're specifically looking for
13335 // cases where we have one overload candidate that lacks
13336 // enable_if/pass_object_size/...
13337 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13338 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13339 if (!FD)
13340 return nullptr;
13341
13343 continue;
13344
13345 // If we found a better result, update Result.
13346 auto FoundBetter = [&]() {
13347 IsResultAmbiguous = false;
13348 DAP = I.getPair();
13349 Result = FD;
13350 };
13351
13352 // We have more than one result - see if it is more constrained than the
13353 // previous one.
13354 if (Result) {
13355 // Check CUDA preference first. If the candidates have differennt CUDA
13356 // preference, choose the one with higher CUDA preference. Otherwise,
13357 // choose the one with more constraints.
13358 if (getLangOpts().CUDA) {
13359 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13360 // FD has different preference than Result.
13361 if (PreferenceByCUDA != 0) {
13362 // FD is more preferable than Result.
13363 if (PreferenceByCUDA > 0)
13364 FoundBetter();
13365 continue;
13366 }
13367 }
13368 // FD has the same CUDA prefernece than Result. Continue check
13369 // constraints.
13370 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13371 if (MoreConstrained != FD) {
13372 if (!MoreConstrained) {
13373 IsResultAmbiguous = true;
13374 AmbiguousDecls.push_back(FD);
13375 }
13376 continue;
13377 }
13378 // FD is more constrained - replace Result with it.
13379 }
13380 FoundBetter();
13381 }
13382
13383 if (IsResultAmbiguous)
13384 return nullptr;
13385
13386 if (Result) {
13388 // We skipped over some ambiguous declarations which might be ambiguous with
13389 // the selected result.
13390 for (FunctionDecl *Skipped : AmbiguousDecls) {
13391 // If skipped candidate has different CUDA preference than the result,
13392 // there is no ambiguity. Otherwise check whether they have different
13393 // constraints.
13394 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13395 continue;
13396 if (!getMoreConstrainedFunction(Skipped, Result))
13397 return nullptr;
13398 }
13399 Pair = DAP;
13400 }
13401 return Result;
13402}
13403
13405 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13406 Expr *E = SrcExpr.get();
13407 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13408
13409 DeclAccessPair DAP;
13410 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13411 if (!Found || Found->isCPUDispatchMultiVersion() ||
13412 Found->isCPUSpecificMultiVersion())
13413 return false;
13414
13415 // Emitting multiple diagnostics for a function that is both inaccessible and
13416 // unavailable is consistent with our behavior elsewhere. So, always check
13417 // for both.
13418 DiagnoseUseOfDecl(Found, E->getExprLoc());
13419 CheckAddressOfMemberAccess(E, DAP);
13420 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13421 if (Res.isInvalid())
13422 return false;
13423 Expr *Fixed = Res.get();
13424 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13425 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13426 else
13427 SrcExpr = Fixed;
13428 return true;
13429}
13430
13432 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13433 TemplateSpecCandidateSet *FailedTSC) {
13434 // C++ [over.over]p1:
13435 // [...] [Note: any redundant set of parentheses surrounding the
13436 // overloaded function name is ignored (5.1). ]
13437 // C++ [over.over]p1:
13438 // [...] The overloaded function name can be preceded by the &
13439 // operator.
13440
13441 // If we didn't actually find any template-ids, we're done.
13442 if (!ovl->hasExplicitTemplateArgs())
13443 return nullptr;
13444
13445 TemplateArgumentListInfo ExplicitTemplateArgs;
13446 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13447
13448 // Look through all of the overloaded functions, searching for one
13449 // whose type matches exactly.
13450 FunctionDecl *Matched = nullptr;
13451 for (UnresolvedSetIterator I = ovl->decls_begin(),
13452 E = ovl->decls_end(); I != E; ++I) {
13453 // C++0x [temp.arg.explicit]p3:
13454 // [...] In contexts where deduction is done and fails, or in contexts
13455 // where deduction is not done, if a template argument list is
13456 // specified and it, along with any default template arguments,
13457 // identifies a single function template specialization, then the
13458 // template-id is an lvalue for the function template specialization.
13459 FunctionTemplateDecl *FunctionTemplate
13460 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13461
13462 // C++ [over.over]p2:
13463 // If the name is a function template, template argument deduction is
13464 // done (14.8.2.2), and if the argument deduction succeeds, the
13465 // resulting template argument list is used to generate a single
13466 // function template specialization, which is added to the set of
13467 // overloaded functions considered.
13468 FunctionDecl *Specialization = nullptr;
13469 TemplateDeductionInfo Info(ovl->getNameLoc());
13471 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13472 /*IsAddressOfFunction*/ true);
13474 // Make a note of the failed deduction for diagnostics.
13475 if (FailedTSC)
13476 FailedTSC->addCandidate().set(
13477 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13478 MakeDeductionFailureInfo(Context, Result, Info));
13479 continue;
13480 }
13481
13482 assert(Specialization && "no specialization and no error?");
13483
13484 // Multiple matches; we can't resolve to a single declaration.
13485 if (Matched) {
13486 if (Complain) {
13487 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13488 << ovl->getName();
13489 NoteAllOverloadCandidates(ovl);
13490 }
13491 return nullptr;
13492 }
13493
13494 Matched = Specialization;
13495 if (FoundResult) *FoundResult = I.getPair();
13496 }
13497
13498 if (Matched &&
13499 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13500 return nullptr;
13501
13502 return Matched;
13503}
13504
13506 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13507 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13508 unsigned DiagIDForComplaining) {
13509 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13510
13512
13513 DeclAccessPair found;
13514 ExprResult SingleFunctionExpression;
13515 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13516 ovl.Expression, /*complain*/ false, &found)) {
13517 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13518 SrcExpr = ExprError();
13519 return true;
13520 }
13521
13522 // It is only correct to resolve to an instance method if we're
13523 // resolving a form that's permitted to be a pointer to member.
13524 // Otherwise we'll end up making a bound member expression, which
13525 // is illegal in all the contexts we resolve like this.
13526 if (!ovl.HasFormOfMemberPointer &&
13527 isa<CXXMethodDecl>(fn) &&
13528 cast<CXXMethodDecl>(fn)->isInstance()) {
13529 if (!complain) return false;
13530
13531 Diag(ovl.Expression->getExprLoc(),
13532 diag::err_bound_member_function)
13533 << 0 << ovl.Expression->getSourceRange();
13534
13535 // TODO: I believe we only end up here if there's a mix of
13536 // static and non-static candidates (otherwise the expression
13537 // would have 'bound member' type, not 'overload' type).
13538 // Ideally we would note which candidate was chosen and why
13539 // the static candidates were rejected.
13540 SrcExpr = ExprError();
13541 return true;
13542 }
13543
13544 // Fix the expression to refer to 'fn'.
13545 SingleFunctionExpression =
13546 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13547
13548 // If desired, do function-to-pointer decay.
13549 if (doFunctionPointerConversion) {
13550 SingleFunctionExpression =
13551 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13552 if (SingleFunctionExpression.isInvalid()) {
13553 SrcExpr = ExprError();
13554 return true;
13555 }
13556 }
13557 }
13558
13559 if (!SingleFunctionExpression.isUsable()) {
13560 if (complain) {
13561 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13562 << ovl.Expression->getName()
13563 << DestTypeForComplaining
13564 << OpRangeForComplaining
13566 NoteAllOverloadCandidates(SrcExpr.get());
13567
13568 SrcExpr = ExprError();
13569 return true;
13570 }
13571
13572 return false;
13573 }
13574
13575 SrcExpr = SingleFunctionExpression;
13576 return true;
13577}
13578
13579/// Add a single candidate to the overload set.
13581 DeclAccessPair FoundDecl,
13582 TemplateArgumentListInfo *ExplicitTemplateArgs,
13583 ArrayRef<Expr *> Args,
13584 OverloadCandidateSet &CandidateSet,
13585 bool PartialOverloading,
13586 bool KnownValid) {
13587 NamedDecl *Callee = FoundDecl.getDecl();
13588 if (isa<UsingShadowDecl>(Callee))
13589 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13590
13591 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13592 if (ExplicitTemplateArgs) {
13593 assert(!KnownValid && "Explicit template arguments?");
13594 return;
13595 }
13596 // Prevent ill-formed function decls to be added as overload candidates.
13597 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13598 return;
13599
13600 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13601 /*SuppressUserConversions=*/false,
13602 PartialOverloading);
13603 return;
13604 }
13605
13606 if (FunctionTemplateDecl *FuncTemplate
13607 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13608 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13609 ExplicitTemplateArgs, Args, CandidateSet,
13610 /*SuppressUserConversions=*/false,
13611 PartialOverloading);
13612 return;
13613 }
13614
13615 assert(!KnownValid && "unhandled case in overloaded call candidate");
13616}
13617
13619 ArrayRef<Expr *> Args,
13620 OverloadCandidateSet &CandidateSet,
13621 bool PartialOverloading) {
13622
13623#ifndef NDEBUG
13624 // Verify that ArgumentDependentLookup is consistent with the rules
13625 // in C++0x [basic.lookup.argdep]p3:
13626 //
13627 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13628 // and let Y be the lookup set produced by argument dependent
13629 // lookup (defined as follows). If X contains
13630 //
13631 // -- a declaration of a class member, or
13632 //
13633 // -- a block-scope function declaration that is not a
13634 // using-declaration, or
13635 //
13636 // -- a declaration that is neither a function or a function
13637 // template
13638 //
13639 // then Y is empty.
13640
13641 if (ULE->requiresADL()) {
13643 E = ULE->decls_end(); I != E; ++I) {
13644 assert(!(*I)->getDeclContext()->isRecord());
13645 assert(isa<UsingShadowDecl>(*I) ||
13646 !(*I)->getDeclContext()->isFunctionOrMethod());
13647 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13648 }
13649 }
13650#endif
13651
13652 // It would be nice to avoid this copy.
13653 TemplateArgumentListInfo TABuffer;
13654 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13655 if (ULE->hasExplicitTemplateArgs()) {
13656 ULE->copyTemplateArgumentsInto(TABuffer);
13657 ExplicitTemplateArgs = &TABuffer;
13658 }
13659
13661 E = ULE->decls_end(); I != E; ++I)
13662 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13663 CandidateSet, PartialOverloading,
13664 /*KnownValid*/ true);
13665
13666 if (ULE->requiresADL())
13667 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13668 Args, ExplicitTemplateArgs,
13669 CandidateSet, PartialOverloading);
13670}
13671
13673 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13674 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13675 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13676 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13677 CandidateSet, false, /*KnownValid*/ false);
13678}
13679
13680/// Determine whether a declaration with the specified name could be moved into
13681/// a different namespace.
13683 switch (Name.getCXXOverloadedOperator()) {
13684 case OO_New: case OO_Array_New:
13685 case OO_Delete: case OO_Array_Delete:
13686 return false;
13687
13688 default:
13689 return true;
13690 }
13691}
13692
13693/// Attempt to recover from an ill-formed use of a non-dependent name in a
13694/// template, where the non-dependent name was declared after the template
13695/// was defined. This is common in code written for a compilers which do not
13696/// correctly implement two-stage name lookup.
13697///
13698/// Returns true if a viable candidate was found and a diagnostic was issued.
13700 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13702 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13703 CXXRecordDecl **FoundInClass = nullptr) {
13704 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13705 return false;
13706
13707 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13708 if (DC->isTransparentContext())
13709 continue;
13710
13711 SemaRef.LookupQualifiedName(R, DC);
13712
13713 if (!R.empty()) {
13715
13716 OverloadCandidateSet Candidates(FnLoc, CSK);
13717 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13718 Candidates);
13719
13722 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13723
13724 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13725 // We either found non-function declarations or a best viable function
13726 // at class scope. A class-scope lookup result disables ADL. Don't
13727 // look past this, but let the caller know that we found something that
13728 // either is, or might be, usable in this class.
13729 if (FoundInClass) {
13730 *FoundInClass = RD;
13731 if (OR == OR_Success) {
13732 R.clear();
13733 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13734 R.resolveKind();
13735 }
13736 }
13737 return false;
13738 }
13739
13740 if (OR != OR_Success) {
13741 // There wasn't a unique best function or function template.
13742 return false;
13743 }
13744
13745 // Find the namespaces where ADL would have looked, and suggest
13746 // declaring the function there instead.
13747 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13748 Sema::AssociatedClassSet AssociatedClasses;
13749 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13750 AssociatedNamespaces,
13751 AssociatedClasses);
13752 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13754 DeclContext *Std = SemaRef.getStdNamespace();
13755 for (Sema::AssociatedNamespaceSet::iterator
13756 it = AssociatedNamespaces.begin(),
13757 end = AssociatedNamespaces.end(); it != end; ++it) {
13758 // Never suggest declaring a function within namespace 'std'.
13759 if (Std && Std->Encloses(*it))
13760 continue;
13761
13762 // Never suggest declaring a function within a namespace with a
13763 // reserved name, like __gnu_cxx.
13764 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13765 if (NS &&
13766 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13767 continue;
13768
13769 SuggestedNamespaces.insert(*it);
13770 }
13771 }
13772
13773 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13774 << R.getLookupName();
13775 if (SuggestedNamespaces.empty()) {
13776 SemaRef.Diag(Best->Function->getLocation(),
13777 diag::note_not_found_by_two_phase_lookup)
13778 << R.getLookupName() << 0;
13779 } else if (SuggestedNamespaces.size() == 1) {
13780 SemaRef.Diag(Best->Function->getLocation(),
13781 diag::note_not_found_by_two_phase_lookup)
13782 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13783 } else {
13784 // FIXME: It would be useful to list the associated namespaces here,
13785 // but the diagnostics infrastructure doesn't provide a way to produce
13786 // a localized representation of a list of items.
13787 SemaRef.Diag(Best->Function->getLocation(),
13788 diag::note_not_found_by_two_phase_lookup)
13789 << R.getLookupName() << 2;
13790 }
13791
13792 // Try to recover by calling this function.
13793 return true;
13794 }
13795
13796 R.clear();
13797 }
13798
13799 return false;
13800}
13801
13802/// Attempt to recover from ill-formed use of a non-dependent operator in a
13803/// template, where the non-dependent operator was declared after the template
13804/// was defined.
13805///
13806/// Returns true if a viable candidate was found and a diagnostic was issued.
13807static bool
13809 SourceLocation OpLoc,
13810 ArrayRef<Expr *> Args) {
13811 DeclarationName OpName =
13813 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13814 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13816 /*ExplicitTemplateArgs=*/nullptr, Args);
13817}
13818
13819namespace {
13820class BuildRecoveryCallExprRAII {
13821 Sema &SemaRef;
13823
13824public:
13825 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13826 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13827 SemaRef.IsBuildingRecoveryCallExpr = true;
13828 }
13829
13830 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13831};
13832}
13833
13834/// Attempts to recover from a call where no functions were found.
13835///
13836/// This function will do one of three things:
13837/// * Diagnose, recover, and return a recovery expression.
13838/// * Diagnose, fail to recover, and return ExprError().
13839/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13840/// expected to diagnose as appropriate.
13841static ExprResult
13844 SourceLocation LParenLoc,
13846 SourceLocation RParenLoc,
13847 bool EmptyLookup, bool AllowTypoCorrection) {
13848 // Do not try to recover if it is already building a recovery call.
13849 // This stops infinite loops for template instantiations like
13850 //
13851 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13852 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13853 if (SemaRef.IsBuildingRecoveryCallExpr)
13854 return ExprResult();
13855 BuildRecoveryCallExprRAII RCE(SemaRef);
13856
13857 CXXScopeSpec SS;
13858 SS.Adopt(ULE->getQualifierLoc());
13859 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13860
13861 TemplateArgumentListInfo TABuffer;
13862 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13863 if (ULE->hasExplicitTemplateArgs()) {
13864 ULE->copyTemplateArgumentsInto(TABuffer);
13865 ExplicitTemplateArgs = &TABuffer;
13866 }
13867
13868 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13870 CXXRecordDecl *FoundInClass = nullptr;
13871 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13873 ExplicitTemplateArgs, Args, &FoundInClass)) {
13874 // OK, diagnosed a two-phase lookup issue.
13875 } else if (EmptyLookup) {
13876 // Try to recover from an empty lookup with typo correction.
13877 R.clear();
13878 NoTypoCorrectionCCC NoTypoValidator{};
13879 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13880 ExplicitTemplateArgs != nullptr,
13881 dyn_cast<MemberExpr>(Fn));
13882 CorrectionCandidateCallback &Validator =
13883 AllowTypoCorrection
13884 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13885 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13886 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13887 Args))
13888 return ExprError();
13889 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13890 // We found a usable declaration of the name in a dependent base of some
13891 // enclosing class.
13892 // FIXME: We should also explain why the candidates found by name lookup
13893 // were not viable.
13894 if (SemaRef.DiagnoseDependentMemberLookup(R))
13895 return ExprError();
13896 } else {
13897 // We had viable candidates and couldn't recover; let the caller diagnose
13898 // this.
13899 return ExprResult();
13900 }
13901
13902 // If we get here, we should have issued a diagnostic and formed a recovery
13903 // lookup result.
13904 assert(!R.empty() && "lookup results empty despite recovery");
13905
13906 // If recovery created an ambiguity, just bail out.
13907 if (R.isAmbiguous()) {
13909 return ExprError();
13910 }
13911
13912 // Build an implicit member call if appropriate. Just drop the
13913 // casts and such from the call, we don't really care.
13914 ExprResult NewFn = ExprError();
13915 if ((*R.begin())->isCXXClassMember())
13916 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13917 ExplicitTemplateArgs, S);
13918 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13919 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13920 ExplicitTemplateArgs);
13921 else
13922 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13923
13924 if (NewFn.isInvalid())
13925 return ExprError();
13926
13927 // This shouldn't cause an infinite loop because we're giving it
13928 // an expression with viable lookup results, which should never
13929 // end up here.
13930 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13931 MultiExprArg(Args.data(), Args.size()),
13932 RParenLoc);
13933}
13934
13937 MultiExprArg Args,
13938 SourceLocation RParenLoc,
13939 OverloadCandidateSet *CandidateSet,
13940 ExprResult *Result) {
13941#ifndef NDEBUG
13942 if (ULE->requiresADL()) {
13943 // To do ADL, we must have found an unqualified name.
13944 assert(!ULE->getQualifier() && "qualified name with ADL");
13945
13946 // We don't perform ADL for implicit declarations of builtins.
13947 // Verify that this was correctly set up.
13948 FunctionDecl *F;
13949 if (ULE->decls_begin() != ULE->decls_end() &&
13950 ULE->decls_begin() + 1 == ULE->decls_end() &&
13951 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13952 F->getBuiltinID() && F->isImplicit())
13953 llvm_unreachable("performing ADL for builtin");
13954
13955 // We don't perform ADL in C.
13956 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13957 }
13958#endif
13959
13960 UnbridgedCastsSet UnbridgedCasts;
13961 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13962 *Result = ExprError();
13963 return true;
13964 }
13965
13966 // Add the functions denoted by the callee to the set of candidate
13967 // functions, including those from argument-dependent lookup.
13968 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13969
13970 if (getLangOpts().MSVCCompat &&
13971 CurContext->isDependentContext() && !isSFINAEContext() &&
13972 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13973
13975 if (CandidateSet->empty() ||
13976 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13978 // In Microsoft mode, if we are inside a template class member function
13979 // then create a type dependent CallExpr. The goal is to postpone name
13980 // lookup to instantiation time to be able to search into type dependent
13981 // base classes.
13982 CallExpr *CE =
13983 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13984 RParenLoc, CurFPFeatureOverrides());
13986 *Result = CE;
13987 return true;
13988 }
13989 }
13990
13991 if (CandidateSet->empty())
13992 return false;
13993
13994 UnbridgedCasts.restore();
13995 return false;
13996}
13997
13998// Guess at what the return type for an unresolvable overload should be.
14001 std::optional<QualType> Result;
14002 // Adjust Type after seeing a candidate.
14003 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14004 if (!Candidate.Function)
14005 return;
14006 if (Candidate.Function->isInvalidDecl())
14007 return;
14008 QualType T = Candidate.Function->getReturnType();
14009 if (T.isNull())
14010 return;
14011 if (!Result)
14012 Result = T;
14013 else if (Result != T)
14014 Result = QualType();
14015 };
14016
14017 // Look for an unambiguous type from a progressively larger subset.
14018 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14019 //
14020 // First, consider only the best candidate.
14021 if (Best && *Best != CS.end())
14022 ConsiderCandidate(**Best);
14023 // Next, consider only viable candidates.
14024 if (!Result)
14025 for (const auto &C : CS)
14026 if (C.Viable)
14027 ConsiderCandidate(C);
14028 // Finally, consider all candidates.
14029 if (!Result)
14030 for (const auto &C : CS)
14031 ConsiderCandidate(C);
14032
14033 if (!Result)
14034 return QualType();
14035 auto Value = *Result;
14036 if (Value.isNull() || Value->isUndeducedType())
14037 return QualType();
14038 return Value;
14039}
14040
14041/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14042/// the completed call expression. If overload resolution fails, emits
14043/// diagnostics and returns ExprError()
14046 SourceLocation LParenLoc,
14047 MultiExprArg Args,
14048 SourceLocation RParenLoc,
14049 Expr *ExecConfig,
14050 OverloadCandidateSet *CandidateSet,
14052 OverloadingResult OverloadResult,
14053 bool AllowTypoCorrection) {
14054 switch (OverloadResult) {
14055 case OR_Success: {
14056 FunctionDecl *FDecl = (*Best)->Function;
14057 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14058 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14059 return ExprError();
14060 ExprResult Res =
14061 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14062 if (Res.isInvalid())
14063 return ExprError();
14064 return SemaRef.BuildResolvedCallExpr(
14065 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14066 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14067 }
14068
14069 case OR_No_Viable_Function: {
14070 if (*Best != CandidateSet->end() &&
14071 CandidateSet->getKind() ==
14073 if (CXXMethodDecl *M =
14074 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14076 CandidateSet->NoteCandidates(
14078 Fn->getBeginLoc(),
14079 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14080 SemaRef, OCD_AmbiguousCandidates, Args);
14081 return ExprError();
14082 }
14083 }
14084
14085 // Try to recover by looking for viable functions which the user might
14086 // have meant to call.
14087 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14088 Args, RParenLoc,
14089 CandidateSet->empty(),
14090 AllowTypoCorrection);
14091 if (Recovery.isInvalid() || Recovery.isUsable())
14092 return Recovery;
14093
14094 // If the user passes in a function that we can't take the address of, we
14095 // generally end up emitting really bad error messages. Here, we attempt to
14096 // emit better ones.
14097 for (const Expr *Arg : Args) {
14098 if (!Arg->getType()->isFunctionType())
14099 continue;
14100 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14101 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14102 if (FD &&
14103 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14104 Arg->getExprLoc()))
14105 return ExprError();
14106 }
14107 }
14108
14109 CandidateSet->NoteCandidates(
14111 Fn->getBeginLoc(),
14112 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14113 << ULE->getName() << Fn->getSourceRange()),
14114 SemaRef, OCD_AllCandidates, Args);
14115 break;
14116 }
14117
14118 case OR_Ambiguous:
14119 CandidateSet->NoteCandidates(
14120 PartialDiagnosticAt(Fn->getBeginLoc(),
14121 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14122 << ULE->getName() << Fn->getSourceRange()),
14123 SemaRef, OCD_AmbiguousCandidates, Args);
14124 break;
14125
14126 case OR_Deleted: {
14127 FunctionDecl *FDecl = (*Best)->Function;
14128 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14129 Fn->getSourceRange(), ULE->getName(),
14130 *CandidateSet, FDecl, Args);
14131
14132 // We emitted an error for the unavailable/deleted function call but keep
14133 // the call in the AST.
14134 ExprResult Res =
14135 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14136 if (Res.isInvalid())
14137 return ExprError();
14138 return SemaRef.BuildResolvedCallExpr(
14139 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14140 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14141 }
14142 }
14143
14144 // Overload resolution failed, try to recover.
14145 SmallVector<Expr *, 8> SubExprs = {Fn};
14146 SubExprs.append(Args.begin(), Args.end());
14147 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14148 chooseRecoveryType(*CandidateSet, Best));
14149}
14150
14153 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14154 if (I->Viable &&
14155 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14156 I->Viable = false;
14157 I->FailureKind = ovl_fail_addr_not_available;
14158 }
14159 }
14160}
14161
14164 SourceLocation LParenLoc,
14165 MultiExprArg Args,
14166 SourceLocation RParenLoc,
14167 Expr *ExecConfig,
14168 bool AllowTypoCorrection,
14169 bool CalleesAddressIsTaken) {
14170 OverloadCandidateSet CandidateSet(
14171 Fn->getExprLoc(), CalleesAddressIsTaken
14174 ExprResult result;
14175
14176 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14177 &result))
14178 return result;
14179
14180 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14181 // functions that aren't addressible are considered unviable.
14182 if (CalleesAddressIsTaken)
14183 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14184
14186 OverloadingResult OverloadResult =
14187 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14188
14189 // Model the case with a call to a templated function whose definition
14190 // encloses the call and whose return type contains a placeholder type as if
14191 // the UnresolvedLookupExpr was type-dependent.
14192 if (OverloadResult == OR_Success) {
14193 const FunctionDecl *FDecl = Best->Function;
14194 if (FDecl && FDecl->isTemplateInstantiation() &&
14195 FDecl->getReturnType()->isUndeducedType()) {
14196 if (const auto *TP =
14197 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14198 TP && TP->willHaveBody()) {
14199 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14200 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14201 }
14202 }
14203 }
14204
14205 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14206 ExecConfig, &CandidateSet, &Best,
14207 OverloadResult, AllowTypoCorrection);
14208}
14209
14213 const UnresolvedSetImpl &Fns,
14214 bool PerformADL) {
14216 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14217 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14218}
14219
14221 CXXConversionDecl *Method,
14222 bool HadMultipleCandidates) {
14223 // Convert the expression to match the conversion function's implicit object
14224 // parameter.
14225 ExprResult Exp;
14226 if (Method->isExplicitObjectMemberFunction())
14227 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14228 else
14229 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14230 FoundDecl, Method);
14231 if (Exp.isInvalid())
14232 return true;
14233
14234 if (Method->getParent()->isLambda() &&
14236 // This is a lambda conversion to block pointer; check if the argument
14237 // was a LambdaExpr.
14238 Expr *SubE = E;
14239 auto *CE = dyn_cast<CastExpr>(SubE);
14240 if (CE && CE->getCastKind() == CK_NoOp)
14241 SubE = CE->getSubExpr();
14242 SubE = SubE->IgnoreParens();
14243 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14244 SubE = BE->getSubExpr();
14245 if (isa<LambdaExpr>(SubE)) {
14246 // For the conversion to block pointer on a lambda expression, we
14247 // construct a special BlockLiteral instead; this doesn't really make
14248 // a difference in ARC, but outside of ARC the resulting block literal
14249 // follows the normal lifetime rules for block literals instead of being
14250 // autoreleased.
14251 PushExpressionEvaluationContext(
14252 ExpressionEvaluationContext::PotentiallyEvaluated);
14253 ExprResult BlockExp = BuildBlockForLambdaConversion(
14254 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14255 PopExpressionEvaluationContext();
14256
14257 // FIXME: This note should be produced by a CodeSynthesisContext.
14258 if (BlockExp.isInvalid())
14259 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14260 return BlockExp;
14261 }
14262 }
14263 CallExpr *CE;
14264 QualType ResultType = Method->getReturnType();
14266 ResultType = ResultType.getNonLValueExprType(Context);
14267 if (Method->isExplicitObjectMemberFunction()) {
14268 ExprResult FnExpr =
14269 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14270 HadMultipleCandidates, E->getBeginLoc());
14271 if (FnExpr.isInvalid())
14272 return ExprError();
14273 Expr *ObjectParam = Exp.get();
14274 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14275 ResultType, VK, Exp.get()->getEndLoc(),
14276 CurFPFeatureOverrides());
14277 } else {
14278 MemberExpr *ME =
14279 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14281 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14282 HadMultipleCandidates, DeclarationNameInfo(),
14284
14285 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14286 Exp.get()->getEndLoc(),
14287 CurFPFeatureOverrides());
14288 }
14289
14290 if (CheckFunctionCall(Method, CE,
14291 Method->getType()->castAs<FunctionProtoType>()))
14292 return ExprError();
14293
14294 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14295}
14296
14299 const UnresolvedSetImpl &Fns,
14300 Expr *Input, bool PerformADL) {
14302 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14304 // TODO: provide better source location info.
14305 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14306
14307 if (checkPlaceholderForOverload(*this, Input))
14308 return ExprError();
14309
14310 Expr *Args[2] = { Input, nullptr };
14311 unsigned NumArgs = 1;
14312
14313 // For post-increment and post-decrement, add the implicit '0' as
14314 // the second argument, so that we know this is a post-increment or
14315 // post-decrement.
14316 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14317 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14318 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14319 SourceLocation());
14320 NumArgs = 2;
14321 }
14322
14323 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14324
14325 if (Input->isTypeDependent()) {
14327 // [C++26][expr.unary.op][expr.pre.incr]
14328 // The * operator yields an lvalue of type
14329 // The pre/post increment operators yied an lvalue.
14330 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14331 VK = VK_LValue;
14332
14333 if (Fns.empty())
14334 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14335 OK_Ordinary, OpLoc, false,
14336 CurFPFeatureOverrides());
14337
14338 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14339 ExprResult Fn = CreateUnresolvedLookupExpr(
14340 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14341 if (Fn.isInvalid())
14342 return ExprError();
14343 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14344 Context.DependentTy, VK_PRValue, OpLoc,
14345 CurFPFeatureOverrides());
14346 }
14347
14348 // Build an empty overload set.
14350
14351 // Add the candidates from the given function set.
14352 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14353
14354 // Add operator candidates that are member functions.
14355 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14356
14357 // Add candidates from ADL.
14358 if (PerformADL) {
14359 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14360 /*ExplicitTemplateArgs*/nullptr,
14361 CandidateSet);
14362 }
14363
14364 // Add builtin operator candidates.
14365 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14366
14367 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14368
14369 // Perform overload resolution.
14371 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14372 case OR_Success: {
14373 // We found a built-in operator or an overloaded operator.
14374 FunctionDecl *FnDecl = Best->Function;
14375
14376 if (FnDecl) {
14377 Expr *Base = nullptr;
14378 // We matched an overloaded operator. Build a call to that
14379 // operator.
14380
14381 // Convert the arguments.
14382 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14383 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14384
14385 ExprResult InputInit;
14386 if (Method->isExplicitObjectMemberFunction())
14387 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14388 else
14389 InputInit = PerformImplicitObjectArgumentInitialization(
14390 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14391 if (InputInit.isInvalid())
14392 return ExprError();
14393 Base = Input = InputInit.get();
14394 } else {
14395 // Convert the arguments.
14396 ExprResult InputInit
14397 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14398 Context,
14399 FnDecl->getParamDecl(0)),
14401 Input);
14402 if (InputInit.isInvalid())
14403 return ExprError();
14404 Input = InputInit.get();
14405 }
14406
14407 // Build the actual expression node.
14408 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14409 Base, HadMultipleCandidates,
14410 OpLoc);
14411 if (FnExpr.isInvalid())
14412 return ExprError();
14413
14414 // Determine the result type.
14415 QualType ResultTy = FnDecl->getReturnType();
14417 ResultTy = ResultTy.getNonLValueExprType(Context);
14418
14419 Args[0] = Input;
14421 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14422 CurFPFeatureOverrides(), Best->IsADLCandidate);
14423
14424 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14425 return ExprError();
14426
14427 if (CheckFunctionCall(FnDecl, TheCall,
14428 FnDecl->getType()->castAs<FunctionProtoType>()))
14429 return ExprError();
14430 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14431 } else {
14432 // We matched a built-in operator. Convert the arguments, then
14433 // break out so that we will build the appropriate built-in
14434 // operator node.
14435 ExprResult InputRes = PerformImplicitConversion(
14436 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
14439 if (InputRes.isInvalid())
14440 return ExprError();
14441 Input = InputRes.get();
14442 break;
14443 }
14444 }
14445
14447 // This is an erroneous use of an operator which can be overloaded by
14448 // a non-member function. Check for non-member operators which were
14449 // defined too late to be candidates.
14450 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14451 // FIXME: Recover by calling the found function.
14452 return ExprError();
14453
14454 // No viable function; fall through to handling this as a
14455 // built-in operator, which will produce an error message for us.
14456 break;
14457
14458 case OR_Ambiguous:
14459 CandidateSet.NoteCandidates(
14460 PartialDiagnosticAt(OpLoc,
14461 PDiag(diag::err_ovl_ambiguous_oper_unary)
14463 << Input->getType() << Input->getSourceRange()),
14464 *this, OCD_AmbiguousCandidates, ArgsArray,
14465 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14466 return ExprError();
14467
14468 case OR_Deleted: {
14469 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14470 // object whose method was called. Later in NoteCandidates size of ArgsArray
14471 // is passed further and it eventually ends up compared to number of
14472 // function candidate parameters which never includes the object parameter,
14473 // so slice ArgsArray to make sure apples are compared to apples.
14474 StringLiteral *Msg = Best->Function->getDeletedMessage();
14475 CandidateSet.NoteCandidates(
14476 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14478 << (Msg != nullptr)
14479 << (Msg ? Msg->getString() : StringRef())
14480 << Input->getSourceRange()),
14481 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14482 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14483 return ExprError();
14484 }
14485 }
14486
14487 // Either we found no viable overloaded operator or we matched a
14488 // built-in operator. In either case, fall through to trying to
14489 // build a built-in operation.
14490 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14491}
14492
14495 const UnresolvedSetImpl &Fns,
14496 ArrayRef<Expr *> Args, bool PerformADL) {
14497 SourceLocation OpLoc = CandidateSet.getLocation();
14498
14499 OverloadedOperatorKind ExtraOp =
14502 : OO_None;
14503
14504 // Add the candidates from the given function set. This also adds the
14505 // rewritten candidates using these functions if necessary.
14506 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14507
14508 // Add operator candidates that are member functions.
14509 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14510 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14511 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14513
14514 // In C++20, also add any rewritten member candidates.
14515 if (ExtraOp) {
14516 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14517 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14518 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14519 CandidateSet,
14521 }
14522
14523 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14524 // performed for an assignment operator (nor for operator[] nor operator->,
14525 // which don't get here).
14526 if (Op != OO_Equal && PerformADL) {
14528 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14529 /*ExplicitTemplateArgs*/ nullptr,
14530 CandidateSet);
14531 if (ExtraOp) {
14532 DeclarationName ExtraOpName =
14533 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14534 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14535 /*ExplicitTemplateArgs*/ nullptr,
14536 CandidateSet);
14537 }
14538 }
14539
14540 // Add builtin operator candidates.
14541 //
14542 // FIXME: We don't add any rewritten candidates here. This is strictly
14543 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14544 // resulting in our selecting a rewritten builtin candidate. For example:
14545 //
14546 // enum class E { e };
14547 // bool operator!=(E, E) requires false;
14548 // bool k = E::e != E::e;
14549 //
14550 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14551 // it seems unreasonable to consider rewritten builtin candidates. A core
14552 // issue has been filed proposing to removed this requirement.
14553 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14554}
14555
14558 const UnresolvedSetImpl &Fns, Expr *LHS,
14559 Expr *RHS, bool PerformADL,
14560 bool AllowRewrittenCandidates,
14561 FunctionDecl *DefaultedFn) {
14562 Expr *Args[2] = { LHS, RHS };
14563 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14564
14565 if (!getLangOpts().CPlusPlus20)
14566 AllowRewrittenCandidates = false;
14567
14569
14570 // If either side is type-dependent, create an appropriate dependent
14571 // expression.
14572 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14573 if (Fns.empty()) {
14574 // If there are no functions to store, just build a dependent
14575 // BinaryOperator or CompoundAssignment.
14578 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14579 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14580 Context.DependentTy);
14582 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14583 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14584 }
14585
14586 // FIXME: save results of ADL from here?
14587 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14588 // TODO: provide better source location info in DNLoc component.
14590 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14591 ExprResult Fn = CreateUnresolvedLookupExpr(
14592 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14593 if (Fn.isInvalid())
14594 return ExprError();
14595 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14596 Context.DependentTy, VK_PRValue, OpLoc,
14597 CurFPFeatureOverrides());
14598 }
14599
14600 // If this is the .* operator, which is not overloadable, just
14601 // create a built-in binary operator.
14602 if (Opc == BO_PtrMemD) {
14603 auto CheckPlaceholder = [&](Expr *&Arg) {
14604 ExprResult Res = CheckPlaceholderExpr(Arg);
14605 if (Res.isUsable())
14606 Arg = Res.get();
14607 return !Res.isUsable();
14608 };
14609
14610 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14611 // expression that contains placeholders (in either the LHS or RHS).
14612 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14613 return ExprError();
14614 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14615 }
14616
14617 // Always do placeholder-like conversions on the RHS.
14618 if (checkPlaceholderForOverload(*this, Args[1]))
14619 return ExprError();
14620
14621 // Do placeholder-like conversion on the LHS; note that we should
14622 // not get here with a PseudoObject LHS.
14623 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14624 if (checkPlaceholderForOverload(*this, Args[0]))
14625 return ExprError();
14626
14627 // If this is the assignment operator, we only perform overload resolution
14628 // if the left-hand side is a class or enumeration type. This is actually
14629 // a hack. The standard requires that we do overload resolution between the
14630 // various built-in candidates, but as DR507 points out, this can lead to
14631 // problems. So we do it this way, which pretty much follows what GCC does.
14632 // Note that we go the traditional code path for compound assignment forms.
14633 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14634 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14635
14636 // Build the overload set.
14639 Op, OpLoc, AllowRewrittenCandidates));
14640 if (DefaultedFn)
14641 CandidateSet.exclude(DefaultedFn);
14642 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14643
14644 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14645
14646 // Perform overload resolution.
14648 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14649 case OR_Success: {
14650 // We found a built-in operator or an overloaded operator.
14651 FunctionDecl *FnDecl = Best->Function;
14652
14653 bool IsReversed = Best->isReversed();
14654 if (IsReversed)
14655 std::swap(Args[0], Args[1]);
14656
14657 if (FnDecl) {
14658
14659 if (FnDecl->isInvalidDecl())
14660 return ExprError();
14661
14662 Expr *Base = nullptr;
14663 // We matched an overloaded operator. Build a call to that
14664 // operator.
14665
14666 OverloadedOperatorKind ChosenOp =
14668
14669 // C++2a [over.match.oper]p9:
14670 // If a rewritten operator== candidate is selected by overload
14671 // resolution for an operator@, its return type shall be cv bool
14672 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14673 !FnDecl->getReturnType()->isBooleanType()) {
14674 bool IsExtension =
14676 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14677 : diag::err_ovl_rewrite_equalequal_not_bool)
14678 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14679 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14680 Diag(FnDecl->getLocation(), diag::note_declared_at);
14681 if (!IsExtension)
14682 return ExprError();
14683 }
14684
14685 if (AllowRewrittenCandidates && !IsReversed &&
14686 CandidateSet.getRewriteInfo().isReversible()) {
14687 // We could have reversed this operator, but didn't. Check if some
14688 // reversed form was a viable candidate, and if so, if it had a
14689 // better conversion for either parameter. If so, this call is
14690 // formally ambiguous, and allowing it is an extension.
14692 for (OverloadCandidate &Cand : CandidateSet) {
14693 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14694 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14695 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14697 *this, OpLoc, Cand.Conversions[ArgIdx],
14698 Best->Conversions[ArgIdx]) ==
14700 AmbiguousWith.push_back(Cand.Function);
14701 break;
14702 }
14703 }
14704 }
14705 }
14706
14707 if (!AmbiguousWith.empty()) {
14708 bool AmbiguousWithSelf =
14709 AmbiguousWith.size() == 1 &&
14710 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14711 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14713 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14714 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14715 if (AmbiguousWithSelf) {
14716 Diag(FnDecl->getLocation(),
14717 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14718 // Mark member== const or provide matching != to disallow reversed
14719 // args. Eg.
14720 // struct S { bool operator==(const S&); };
14721 // S()==S();
14722 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14723 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14724 !MD->isConst() &&
14725 !MD->hasCXXExplicitFunctionObjectParameter() &&
14726 Context.hasSameUnqualifiedType(
14727 MD->getFunctionObjectParameterType(),
14728 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14729 Context.hasSameUnqualifiedType(
14730 MD->getFunctionObjectParameterType(),
14731 Args[0]->getType()) &&
14732 Context.hasSameUnqualifiedType(
14733 MD->getFunctionObjectParameterType(),
14734 Args[1]->getType()))
14735 Diag(FnDecl->getLocation(),
14736 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14737 } else {
14738 Diag(FnDecl->getLocation(),
14739 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14740 for (auto *F : AmbiguousWith)
14741 Diag(F->getLocation(),
14742 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14743 }
14744 }
14745 }
14746
14747 // Check for nonnull = nullable.
14748 // This won't be caught in the arg's initialization: the parameter to
14749 // the assignment operator is not marked nonnull.
14750 if (Op == OO_Equal)
14751 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14752 Args[1]->getType(), OpLoc);
14753
14754 // Convert the arguments.
14755 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14756 // Best->Access is only meaningful for class members.
14757 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14758
14759 ExprResult Arg0, Arg1;
14760 unsigned ParamIdx = 0;
14761 if (Method->isExplicitObjectMemberFunction()) {
14762 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14763 ParamIdx = 1;
14764 } else {
14765 Arg0 = PerformImplicitObjectArgumentInitialization(
14766 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14767 }
14768 Arg1 = PerformCopyInitialization(
14770 Context, FnDecl->getParamDecl(ParamIdx)),
14771 SourceLocation(), Args[1]);
14772 if (Arg0.isInvalid() || Arg1.isInvalid())
14773 return ExprError();
14774
14775 Base = Args[0] = Arg0.getAs<Expr>();
14776 Args[1] = RHS = Arg1.getAs<Expr>();
14777 } else {
14778 // Convert the arguments.
14779 ExprResult Arg0 = PerformCopyInitialization(
14781 FnDecl->getParamDecl(0)),
14782 SourceLocation(), Args[0]);
14783 if (Arg0.isInvalid())
14784 return ExprError();
14785
14786 ExprResult Arg1 =
14787 PerformCopyInitialization(
14789 FnDecl->getParamDecl(1)),
14790 SourceLocation(), Args[1]);
14791 if (Arg1.isInvalid())
14792 return ExprError();
14793 Args[0] = LHS = Arg0.getAs<Expr>();
14794 Args[1] = RHS = Arg1.getAs<Expr>();
14795 }
14796
14797 // Build the actual expression node.
14798 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14799 Best->FoundDecl, Base,
14800 HadMultipleCandidates, OpLoc);
14801 if (FnExpr.isInvalid())
14802 return ExprError();
14803
14804 // Determine the result type.
14805 QualType ResultTy = FnDecl->getReturnType();
14807 ResultTy = ResultTy.getNonLValueExprType(Context);
14808
14809 CallExpr *TheCall;
14810 ArrayRef<const Expr *> ArgsArray(Args, 2);
14811 const Expr *ImplicitThis = nullptr;
14812
14813 // We always create a CXXOperatorCallExpr, even for explicit object
14814 // members; CodeGen should take care not to emit the this pointer.
14816 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14817 CurFPFeatureOverrides(), Best->IsADLCandidate);
14818
14819 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14820 Method && Method->isImplicitObjectMemberFunction()) {
14821 // Cut off the implicit 'this'.
14822 ImplicitThis = ArgsArray[0];
14823 ArgsArray = ArgsArray.slice(1);
14824 }
14825
14826 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14827 FnDecl))
14828 return ExprError();
14829
14830 if (Op == OO_Equal) {
14831 // Check for a self move.
14832 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14833 // lifetime check.
14835 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
14836 Args[1]);
14837 }
14838 if (ImplicitThis) {
14839 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14840 QualType ThisTypeFromDecl = Context.getPointerType(
14841 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14842
14843 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14844 ThisTypeFromDecl);
14845 }
14846
14847 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14848 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14849 VariadicDoesNotApply);
14850
14851 ExprResult R = MaybeBindToTemporary(TheCall);
14852 if (R.isInvalid())
14853 return ExprError();
14854
14855 R = CheckForImmediateInvocation(R, FnDecl);
14856 if (R.isInvalid())
14857 return ExprError();
14858
14859 // For a rewritten candidate, we've already reversed the arguments
14860 // if needed. Perform the rest of the rewrite now.
14861 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14862 (Op == OO_Spaceship && IsReversed)) {
14863 if (Op == OO_ExclaimEqual) {
14864 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14865 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14866 } else {
14867 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14868 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14869 Expr *ZeroLiteral =
14870 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14871
14874 Ctx.Entity = FnDecl;
14875 pushCodeSynthesisContext(Ctx);
14876
14877 R = CreateOverloadedBinOp(
14878 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14879 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14880 /*AllowRewrittenCandidates=*/false);
14881
14882 popCodeSynthesisContext();
14883 }
14884 if (R.isInvalid())
14885 return ExprError();
14886 } else {
14887 assert(ChosenOp == Op && "unexpected operator name");
14888 }
14889
14890 // Make a note in the AST if we did any rewriting.
14891 if (Best->RewriteKind != CRK_None)
14892 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14893
14894 return R;
14895 } else {
14896 // We matched a built-in operator. Convert the arguments, then
14897 // break out so that we will build the appropriate built-in
14898 // operator node.
14899 ExprResult ArgsRes0 = PerformImplicitConversion(
14900 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14903 if (ArgsRes0.isInvalid())
14904 return ExprError();
14905 Args[0] = ArgsRes0.get();
14906
14907 ExprResult ArgsRes1 = PerformImplicitConversion(
14908 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14911 if (ArgsRes1.isInvalid())
14912 return ExprError();
14913 Args[1] = ArgsRes1.get();
14914 break;
14915 }
14916 }
14917
14918 case OR_No_Viable_Function: {
14919 // C++ [over.match.oper]p9:
14920 // If the operator is the operator , [...] and there are no
14921 // viable functions, then the operator is assumed to be the
14922 // built-in operator and interpreted according to clause 5.
14923 if (Opc == BO_Comma)
14924 break;
14925
14926 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14927 // compare result using '==' and '<'.
14928 if (DefaultedFn && Opc == BO_Cmp) {
14929 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14930 Args[1], DefaultedFn);
14931 if (E.isInvalid() || E.isUsable())
14932 return E;
14933 }
14934
14935 // For class as left operand for assignment or compound assignment
14936 // operator do not fall through to handling in built-in, but report that
14937 // no overloaded assignment operator found
14939 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14940 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14941 Args, OpLoc);
14942 DeferDiagsRAII DDR(*this,
14943 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14944 if (Args[0]->getType()->isRecordType() &&
14945 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14946 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14948 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14949 if (Args[0]->getType()->isIncompleteType()) {
14950 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14951 << Args[0]->getType()
14952 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14953 }
14954 } else {
14955 // This is an erroneous use of an operator which can be overloaded by
14956 // a non-member function. Check for non-member operators which were
14957 // defined too late to be candidates.
14958 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14959 // FIXME: Recover by calling the found function.
14960 return ExprError();
14961
14962 // No viable function; try to create a built-in operation, which will
14963 // produce an error. Then, show the non-viable candidates.
14964 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14965 }
14966 assert(Result.isInvalid() &&
14967 "C++ binary operator overloading is missing candidates!");
14968 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14969 return Result;
14970 }
14971
14972 case OR_Ambiguous:
14973 CandidateSet.NoteCandidates(
14974 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14976 << Args[0]->getType()
14977 << Args[1]->getType()
14978 << Args[0]->getSourceRange()
14979 << Args[1]->getSourceRange()),
14981 OpLoc);
14982 return ExprError();
14983
14984 case OR_Deleted: {
14985 if (isImplicitlyDeleted(Best->Function)) {
14986 FunctionDecl *DeletedFD = Best->Function;
14987 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14988 if (DFK.isSpecialMember()) {
14989 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14990 << Args[0]->getType()
14991 << llvm::to_underlying(DFK.asSpecialMember());
14992 } else {
14993 assert(DFK.isComparison());
14994 Diag(OpLoc, diag::err_ovl_deleted_comparison)
14995 << Args[0]->getType() << DeletedFD;
14996 }
14997
14998 // The user probably meant to call this special member. Just
14999 // explain why it's deleted.
15000 NoteDeletedFunction(DeletedFD);
15001 return ExprError();
15002 }
15003
15004 StringLiteral *Msg = Best->Function->getDeletedMessage();
15005 CandidateSet.NoteCandidates(
15007 OpLoc,
15008 PDiag(diag::err_ovl_deleted_oper)
15009 << getOperatorSpelling(Best->Function->getDeclName()
15010 .getCXXOverloadedOperator())
15011 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15012 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15014 OpLoc);
15015 return ExprError();
15016 }
15017 }
15018
15019 // We matched a built-in operator; build it.
15020 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15021}
15022
15024 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15025 FunctionDecl *DefaultedFn) {
15026 const ComparisonCategoryInfo *Info =
15027 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15028 // If we're not producing a known comparison category type, we can't
15029 // synthesize a three-way comparison. Let the caller diagnose this.
15030 if (!Info)
15031 return ExprResult((Expr*)nullptr);
15032
15033 // If we ever want to perform this synthesis more generally, we will need to
15034 // apply the temporary materialization conversion to the operands.
15035 assert(LHS->isGLValue() && RHS->isGLValue() &&
15036 "cannot use prvalue expressions more than once");
15037 Expr *OrigLHS = LHS;
15038 Expr *OrigRHS = RHS;
15039
15040 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15041 // each of them multiple times below.
15042 LHS = new (Context)
15043 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15044 LHS->getObjectKind(), LHS);
15045 RHS = new (Context)
15046 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15047 RHS->getObjectKind(), RHS);
15048
15049 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15050 DefaultedFn);
15051 if (Eq.isInvalid())
15052 return ExprError();
15053
15054 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15055 true, DefaultedFn);
15056 if (Less.isInvalid())
15057 return ExprError();
15058
15060 if (Info->isPartial()) {
15061 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15062 DefaultedFn);
15063 if (Greater.isInvalid())
15064 return ExprError();
15065 }
15066
15067 // Form the list of comparisons we're going to perform.
15068 struct Comparison {
15069 ExprResult Cmp;
15071 } Comparisons[4] =
15077 };
15078
15079 int I = Info->isPartial() ? 3 : 2;
15080
15081 // Combine the comparisons with suitable conditional expressions.
15083 for (; I >= 0; --I) {
15084 // Build a reference to the comparison category constant.
15085 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15086 // FIXME: Missing a constant for a comparison category. Diagnose this?
15087 if (!VI)
15088 return ExprResult((Expr*)nullptr);
15089 ExprResult ThisResult =
15090 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15091 if (ThisResult.isInvalid())
15092 return ExprError();
15093
15094 // Build a conditional unless this is the final case.
15095 if (Result.get()) {
15096 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15097 ThisResult.get(), Result.get());
15098 if (Result.isInvalid())
15099 return ExprError();
15100 } else {
15101 Result = ThisResult;
15102 }
15103 }
15104
15105 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15106 // bind the OpaqueValueExprs before they're (repeatedly) used.
15107 Expr *SyntacticForm = BinaryOperator::Create(
15108 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15109 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15110 CurFPFeatureOverrides());
15111 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15112 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15113}
15114
15116 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15117 MultiExprArg Args, SourceLocation LParenLoc) {
15118
15119 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15120 unsigned NumParams = Proto->getNumParams();
15121 unsigned NumArgsSlots =
15122 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15123 // Build the full argument list for the method call (the implicit object
15124 // parameter is placed at the beginning of the list).
15125 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15126 bool IsError = false;
15127 // Initialize the implicit object parameter.
15128 // Check the argument types.
15129 for (unsigned i = 0; i != NumParams; i++) {
15130 Expr *Arg;
15131 if (i < Args.size()) {
15132 Arg = Args[i];
15133 ExprResult InputInit =
15135 S.Context, Method->getParamDecl(i)),
15136 SourceLocation(), Arg);
15137 IsError |= InputInit.isInvalid();
15138 Arg = InputInit.getAs<Expr>();
15139 } else {
15140 ExprResult DefArg =
15141 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15142 if (DefArg.isInvalid()) {
15143 IsError = true;
15144 break;
15145 }
15146 Arg = DefArg.getAs<Expr>();
15147 }
15148
15149 MethodArgs.push_back(Arg);
15150 }
15151 return IsError;
15152}
15153
15155 SourceLocation RLoc,
15156 Expr *Base,
15157 MultiExprArg ArgExpr) {
15159 Args.push_back(Base);
15160 for (auto *e : ArgExpr) {
15161 Args.push_back(e);
15162 }
15163 DeclarationName OpName =
15164 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15165
15166 SourceRange Range = ArgExpr.empty()
15167 ? SourceRange{}
15168 : SourceRange(ArgExpr.front()->getBeginLoc(),
15169 ArgExpr.back()->getEndLoc());
15170
15171 // If either side is type-dependent, create an appropriate dependent
15172 // expression.
15174
15175 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15176 // CHECKME: no 'operator' keyword?
15177 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15178 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15179 ExprResult Fn = CreateUnresolvedLookupExpr(
15180 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15181 if (Fn.isInvalid())
15182 return ExprError();
15183 // Can't add any actual overloads yet
15184
15185 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15186 Context.DependentTy, VK_PRValue, RLoc,
15187 CurFPFeatureOverrides());
15188 }
15189
15190 // Handle placeholders
15191 UnbridgedCastsSet UnbridgedCasts;
15192 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15193 return ExprError();
15194 }
15195 // Build an empty overload set.
15197
15198 // Subscript can only be overloaded as a member function.
15199
15200 // Add operator candidates that are member functions.
15201 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15202
15203 // Add builtin operator candidates.
15204 if (Args.size() == 2)
15205 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15206
15207 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15208
15209 // Perform overload resolution.
15211 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15212 case OR_Success: {
15213 // We found a built-in operator or an overloaded operator.
15214 FunctionDecl *FnDecl = Best->Function;
15215
15216 if (FnDecl) {
15217 // We matched an overloaded operator. Build a call to that
15218 // operator.
15219
15220 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15221
15222 // Convert the arguments.
15223 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15224 SmallVector<Expr *, 2> MethodArgs;
15225
15226 // Initialize the object parameter.
15227 if (Method->isExplicitObjectMemberFunction()) {
15228 ExprResult Res =
15229 InitializeExplicitObjectArgument(*this, Args[0], Method);
15230 if (Res.isInvalid())
15231 return ExprError();
15232 Args[0] = Res.get();
15233 ArgExpr = Args;
15234 } else {
15235 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15236 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15237 if (Arg0.isInvalid())
15238 return ExprError();
15239
15240 MethodArgs.push_back(Arg0.get());
15241 }
15242
15244 *this, MethodArgs, Method, ArgExpr, LLoc);
15245 if (IsError)
15246 return ExprError();
15247
15248 // Build the actual expression node.
15249 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15250 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15252 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15253 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15254 if (FnExpr.isInvalid())
15255 return ExprError();
15256
15257 // Determine the result type
15258 QualType ResultTy = FnDecl->getReturnType();
15260 ResultTy = ResultTy.getNonLValueExprType(Context);
15261
15263 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15264 CurFPFeatureOverrides());
15265
15266 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15267 return ExprError();
15268
15269 if (CheckFunctionCall(Method, TheCall,
15270 Method->getType()->castAs<FunctionProtoType>()))
15271 return ExprError();
15272
15273 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15274 FnDecl);
15275 } else {
15276 // We matched a built-in operator. Convert the arguments, then
15277 // break out so that we will build the appropriate built-in
15278 // operator node.
15279 ExprResult ArgsRes0 = PerformImplicitConversion(
15280 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15283 if (ArgsRes0.isInvalid())
15284 return ExprError();
15285 Args[0] = ArgsRes0.get();
15286
15287 ExprResult ArgsRes1 = PerformImplicitConversion(
15288 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15291 if (ArgsRes1.isInvalid())
15292 return ExprError();
15293 Args[1] = ArgsRes1.get();
15294
15295 break;
15296 }
15297 }
15298
15299 case OR_No_Viable_Function: {
15301 CandidateSet.empty()
15302 ? (PDiag(diag::err_ovl_no_oper)
15303 << Args[0]->getType() << /*subscript*/ 0
15304 << Args[0]->getSourceRange() << Range)
15305 : (PDiag(diag::err_ovl_no_viable_subscript)
15306 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15307 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15308 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15309 return ExprError();
15310 }
15311
15312 case OR_Ambiguous:
15313 if (Args.size() == 2) {
15314 CandidateSet.NoteCandidates(
15316 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15317 << "[]" << Args[0]->getType() << Args[1]->getType()
15318 << Args[0]->getSourceRange() << Range),
15319 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15320 } else {
15321 CandidateSet.NoteCandidates(
15323 PDiag(diag::err_ovl_ambiguous_subscript_call)
15324 << Args[0]->getType()
15325 << Args[0]->getSourceRange() << Range),
15326 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15327 }
15328 return ExprError();
15329
15330 case OR_Deleted: {
15331 StringLiteral *Msg = Best->Function->getDeletedMessage();
15332 CandidateSet.NoteCandidates(
15334 PDiag(diag::err_ovl_deleted_oper)
15335 << "[]" << (Msg != nullptr)
15336 << (Msg ? Msg->getString() : StringRef())
15337 << Args[0]->getSourceRange() << Range),
15338 *this, OCD_AllCandidates, Args, "[]", LLoc);
15339 return ExprError();
15340 }
15341 }
15342
15343 // We matched a built-in operator; build it.
15344 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15345}
15346
15348 SourceLocation LParenLoc,
15349 MultiExprArg Args,
15350 SourceLocation RParenLoc,
15351 Expr *ExecConfig, bool IsExecConfig,
15352 bool AllowRecovery) {
15353 assert(MemExprE->getType() == Context.BoundMemberTy ||
15354 MemExprE->getType() == Context.OverloadTy);
15355
15356 // Dig out the member expression. This holds both the object
15357 // argument and the member function we're referring to.
15358 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15359
15360 // Determine whether this is a call to a pointer-to-member function.
15361 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15362 assert(op->getType() == Context.BoundMemberTy);
15363 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15364
15365 QualType fnType =
15366 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15367
15368 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15369 QualType resultType = proto->getCallResultType(Context);
15371
15372 // Check that the object type isn't more qualified than the
15373 // member function we're calling.
15374 Qualifiers funcQuals = proto->getMethodQuals();
15375
15376 QualType objectType = op->getLHS()->getType();
15377 if (op->getOpcode() == BO_PtrMemI)
15378 objectType = objectType->castAs<PointerType>()->getPointeeType();
15379 Qualifiers objectQuals = objectType.getQualifiers();
15380
15381 Qualifiers difference = objectQuals - funcQuals;
15382 difference.removeObjCGCAttr();
15383 difference.removeAddressSpace();
15384 if (difference) {
15385 std::string qualsString = difference.getAsString();
15386 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15387 << fnType.getUnqualifiedType()
15388 << qualsString
15389 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15390 }
15391
15393 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15394 CurFPFeatureOverrides(), proto->getNumParams());
15395
15396 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15397 call, nullptr))
15398 return ExprError();
15399
15400 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15401 return ExprError();
15402
15403 if (CheckOtherCall(call, proto))
15404 return ExprError();
15405
15406 return MaybeBindToTemporary(call);
15407 }
15408
15409 // We only try to build a recovery expr at this level if we can preserve
15410 // the return type, otherwise we return ExprError() and let the caller
15411 // recover.
15412 auto BuildRecoveryExpr = [&](QualType Type) {
15413 if (!AllowRecovery)
15414 return ExprError();
15415 std::vector<Expr *> SubExprs = {MemExprE};
15416 llvm::append_range(SubExprs, Args);
15417 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15418 Type);
15419 };
15420 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15421 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15422 RParenLoc, CurFPFeatureOverrides());
15423
15424 UnbridgedCastsSet UnbridgedCasts;
15425 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15426 return ExprError();
15427
15428 MemberExpr *MemExpr;
15429 CXXMethodDecl *Method = nullptr;
15430 bool HadMultipleCandidates = false;
15431 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15432 NestedNameSpecifier *Qualifier = nullptr;
15433 if (isa<MemberExpr>(NakedMemExpr)) {
15434 MemExpr = cast<MemberExpr>(NakedMemExpr);
15435 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15436 FoundDecl = MemExpr->getFoundDecl();
15437 Qualifier = MemExpr->getQualifier();
15438 UnbridgedCasts.restore();
15439 } else {
15440 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15441 Qualifier = UnresExpr->getQualifier();
15442
15443 QualType ObjectType = UnresExpr->getBaseType();
15444 Expr::Classification ObjectClassification
15446 : UnresExpr->getBase()->Classify(Context);
15447
15448 // Add overload candidates
15449 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15451
15452 // FIXME: avoid copy.
15453 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15454 if (UnresExpr->hasExplicitTemplateArgs()) {
15455 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15456 TemplateArgs = &TemplateArgsBuffer;
15457 }
15458
15460 E = UnresExpr->decls_end(); I != E; ++I) {
15461
15462 QualType ExplicitObjectType = ObjectType;
15463
15464 NamedDecl *Func = *I;
15465 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15466 if (isa<UsingShadowDecl>(Func))
15467 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15468
15469 bool HasExplicitParameter = false;
15470 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15471 M && M->hasCXXExplicitFunctionObjectParameter())
15472 HasExplicitParameter = true;
15473 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15474 M &&
15475 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15476 HasExplicitParameter = true;
15477
15478 if (HasExplicitParameter)
15479 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15480
15481 // Microsoft supports direct constructor calls.
15482 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15483 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15484 CandidateSet,
15485 /*SuppressUserConversions*/ false);
15486 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15487 // If explicit template arguments were provided, we can't call a
15488 // non-template member function.
15489 if (TemplateArgs)
15490 continue;
15491
15492 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15493 ObjectClassification, Args, CandidateSet,
15494 /*SuppressUserConversions=*/false);
15495 } else {
15496 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15497 I.getPair(), ActingDC, TemplateArgs,
15498 ExplicitObjectType, ObjectClassification,
15499 Args, CandidateSet,
15500 /*SuppressUserConversions=*/false);
15501 }
15502 }
15503
15504 HadMultipleCandidates = (CandidateSet.size() > 1);
15505
15506 DeclarationName DeclName = UnresExpr->getMemberName();
15507
15508 UnbridgedCasts.restore();
15509
15511 bool Succeeded = false;
15512 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15513 Best)) {
15514 case OR_Success:
15515 Method = cast<CXXMethodDecl>(Best->Function);
15516 FoundDecl = Best->FoundDecl;
15517 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15518 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15519 break;
15520 // If FoundDecl is different from Method (such as if one is a template
15521 // and the other a specialization), make sure DiagnoseUseOfDecl is
15522 // called on both.
15523 // FIXME: This would be more comprehensively addressed by modifying
15524 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15525 // being used.
15526 if (Method != FoundDecl.getDecl() &&
15527 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15528 break;
15529 Succeeded = true;
15530 break;
15531
15533 CandidateSet.NoteCandidates(
15535 UnresExpr->getMemberLoc(),
15536 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15537 << DeclName << MemExprE->getSourceRange()),
15538 *this, OCD_AllCandidates, Args);
15539 break;
15540 case OR_Ambiguous:
15541 CandidateSet.NoteCandidates(
15542 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15543 PDiag(diag::err_ovl_ambiguous_member_call)
15544 << DeclName << MemExprE->getSourceRange()),
15545 *this, OCD_AmbiguousCandidates, Args);
15546 break;
15547 case OR_Deleted:
15548 DiagnoseUseOfDeletedFunction(
15549 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15550 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15551 break;
15552 }
15553 // Overload resolution fails, try to recover.
15554 if (!Succeeded)
15555 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15556
15557 ExprResult Res =
15558 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15559 if (Res.isInvalid())
15560 return ExprError();
15561 MemExprE = Res.get();
15562
15563 // If overload resolution picked a static member
15564 // build a non-member call based on that function.
15565 if (Method->isStatic()) {
15566 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15567 ExecConfig, IsExecConfig);
15568 }
15569
15570 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15571 }
15572
15573 QualType ResultType = Method->getReturnType();
15575 ResultType = ResultType.getNonLValueExprType(Context);
15576
15577 assert(Method && "Member call to something that isn't a method?");
15578 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15579
15580 CallExpr *TheCall = nullptr;
15582 if (Method->isExplicitObjectMemberFunction()) {
15583 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15584 NewArgs))
15585 return ExprError();
15586
15587 // Build the actual expression node.
15588 ExprResult FnExpr =
15589 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15590 HadMultipleCandidates, MemExpr->getExprLoc());
15591 if (FnExpr.isInvalid())
15592 return ExprError();
15593
15594 TheCall =
15595 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15596 CurFPFeatureOverrides(), Proto->getNumParams());
15597 } else {
15598 // Convert the object argument (for a non-static member function call).
15599 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15600 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15601 if (ObjectArg.isInvalid())
15602 return ExprError();
15603 MemExpr->setBase(ObjectArg.get());
15604 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15605 RParenLoc, CurFPFeatureOverrides(),
15606 Proto->getNumParams());
15607 }
15608
15609 // Check for a valid return type.
15610 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15611 TheCall, Method))
15612 return BuildRecoveryExpr(ResultType);
15613
15614 // Convert the rest of the arguments
15615 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15616 RParenLoc))
15617 return BuildRecoveryExpr(ResultType);
15618
15619 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15620
15621 if (CheckFunctionCall(Method, TheCall, Proto))
15622 return ExprError();
15623
15624 // In the case the method to call was not selected by the overloading
15625 // resolution process, we still need to handle the enable_if attribute. Do
15626 // that here, so it will not hide previous -- and more relevant -- errors.
15627 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15628 if (const EnableIfAttr *Attr =
15629 CheckEnableIf(Method, LParenLoc, Args, true)) {
15630 Diag(MemE->getMemberLoc(),
15631 diag::err_ovl_no_viable_member_function_in_call)
15632 << Method << Method->getSourceRange();
15633 Diag(Method->getLocation(),
15634 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15635 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15636 return ExprError();
15637 }
15638 }
15639
15640 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15641 TheCall->getDirectCallee()->isPureVirtual()) {
15642 const FunctionDecl *MD = TheCall->getDirectCallee();
15643
15644 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15645 MemExpr->performsVirtualDispatch(getLangOpts())) {
15646 Diag(MemExpr->getBeginLoc(),
15647 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15648 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15649 << MD->getParent();
15650
15651 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15652 if (getLangOpts().AppleKext)
15653 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15654 << MD->getParent() << MD->getDeclName();
15655 }
15656 }
15657
15658 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15659 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15660 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15661 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15662 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15663 MemExpr->getMemberLoc());
15664 }
15665
15666 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15667 TheCall->getDirectCallee());
15668}
15669
15672 SourceLocation LParenLoc,
15673 MultiExprArg Args,
15674 SourceLocation RParenLoc) {
15675 if (checkPlaceholderForOverload(*this, Obj))
15676 return ExprError();
15677 ExprResult Object = Obj;
15678
15679 UnbridgedCastsSet UnbridgedCasts;
15680 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15681 return ExprError();
15682
15683 assert(Object.get()->getType()->isRecordType() &&
15684 "Requires object type argument");
15685
15686 // C++ [over.call.object]p1:
15687 // If the primary-expression E in the function call syntax
15688 // evaluates to a class object of type "cv T", then the set of
15689 // candidate functions includes at least the function call
15690 // operators of T. The function call operators of T are obtained by
15691 // ordinary lookup of the name operator() in the context of
15692 // (E).operator().
15693 OverloadCandidateSet CandidateSet(LParenLoc,
15695 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15696
15697 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15698 diag::err_incomplete_object_call, Object.get()))
15699 return true;
15700
15701 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15702 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15703 LookupQualifiedName(R, Record->getDecl());
15704 R.suppressAccessDiagnostics();
15705
15706 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15707 Oper != OperEnd; ++Oper) {
15708 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15709 Object.get()->Classify(Context), Args, CandidateSet,
15710 /*SuppressUserConversion=*/false);
15711 }
15712
15713 // When calling a lambda, both the call operator, and
15714 // the conversion operator to function pointer
15715 // are considered. But when constraint checking
15716 // on the call operator fails, it will also fail on the
15717 // conversion operator as the constraints are always the same.
15718 // As the user probably does not intend to perform a surrogate call,
15719 // we filter them out to produce better error diagnostics, ie to avoid
15720 // showing 2 failed overloads instead of one.
15721 bool IgnoreSurrogateFunctions = false;
15722 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15723 const OverloadCandidate &Candidate = *CandidateSet.begin();
15724 if (!Candidate.Viable &&
15726 IgnoreSurrogateFunctions = true;
15727 }
15728
15729 // C++ [over.call.object]p2:
15730 // In addition, for each (non-explicit in C++0x) conversion function
15731 // declared in T of the form
15732 //
15733 // operator conversion-type-id () cv-qualifier;
15734 //
15735 // where cv-qualifier is the same cv-qualification as, or a
15736 // greater cv-qualification than, cv, and where conversion-type-id
15737 // denotes the type "pointer to function of (P1,...,Pn) returning
15738 // R", or the type "reference to pointer to function of
15739 // (P1,...,Pn) returning R", or the type "reference to function
15740 // of (P1,...,Pn) returning R", a surrogate call function [...]
15741 // is also considered as a candidate function. Similarly,
15742 // surrogate call functions are added to the set of candidate
15743 // functions for each conversion function declared in an
15744 // accessible base class provided the function is not hidden
15745 // within T by another intervening declaration.
15746 const auto &Conversions =
15747 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15748 for (auto I = Conversions.begin(), E = Conversions.end();
15749 !IgnoreSurrogateFunctions && I != E; ++I) {
15750 NamedDecl *D = *I;
15751 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15752 if (isa<UsingShadowDecl>(D))
15753 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15754
15755 // Skip over templated conversion functions; they aren't
15756 // surrogates.
15757 if (isa<FunctionTemplateDecl>(D))
15758 continue;
15759
15760 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15761 if (!Conv->isExplicit()) {
15762 // Strip the reference type (if any) and then the pointer type (if
15763 // any) to get down to what might be a function type.
15764 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15765 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15766 ConvType = ConvPtrType->getPointeeType();
15767
15768 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15769 {
15770 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15771 Object.get(), Args, CandidateSet);
15772 }
15773 }
15774 }
15775
15776 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15777
15778 // Perform overload resolution.
15780 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15781 Best)) {
15782 case OR_Success:
15783 // Overload resolution succeeded; we'll build the appropriate call
15784 // below.
15785 break;
15786
15787 case OR_No_Viable_Function: {
15789 CandidateSet.empty()
15790 ? (PDiag(diag::err_ovl_no_oper)
15791 << Object.get()->getType() << /*call*/ 1
15792 << Object.get()->getSourceRange())
15793 : (PDiag(diag::err_ovl_no_viable_object_call)
15794 << Object.get()->getType() << Object.get()->getSourceRange());
15795 CandidateSet.NoteCandidates(
15796 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15797 OCD_AllCandidates, Args);
15798 break;
15799 }
15800 case OR_Ambiguous:
15801 if (!R.isAmbiguous())
15802 CandidateSet.NoteCandidates(
15803 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15804 PDiag(diag::err_ovl_ambiguous_object_call)
15805 << Object.get()->getType()
15806 << Object.get()->getSourceRange()),
15807 *this, OCD_AmbiguousCandidates, Args);
15808 break;
15809
15810 case OR_Deleted: {
15811 // FIXME: Is this diagnostic here really necessary? It seems that
15812 // 1. we don't have any tests for this diagnostic, and
15813 // 2. we already issue err_deleted_function_use for this later on anyway.
15814 StringLiteral *Msg = Best->Function->getDeletedMessage();
15815 CandidateSet.NoteCandidates(
15816 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15817 PDiag(diag::err_ovl_deleted_object_call)
15818 << Object.get()->getType() << (Msg != nullptr)
15819 << (Msg ? Msg->getString() : StringRef())
15820 << Object.get()->getSourceRange()),
15821 *this, OCD_AllCandidates, Args);
15822 break;
15823 }
15824 }
15825
15826 if (Best == CandidateSet.end())
15827 return true;
15828
15829 UnbridgedCasts.restore();
15830
15831 if (Best->Function == nullptr) {
15832 // Since there is no function declaration, this is one of the
15833 // surrogate candidates. Dig out the conversion function.
15834 CXXConversionDecl *Conv
15835 = cast<CXXConversionDecl>(
15836 Best->Conversions[0].UserDefined.ConversionFunction);
15837
15838 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15839 Best->FoundDecl);
15840 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15841 return ExprError();
15842 assert(Conv == Best->FoundDecl.getDecl() &&
15843 "Found Decl & conversion-to-functionptr should be same, right?!");
15844 // We selected one of the surrogate functions that converts the
15845 // object parameter to a function pointer. Perform the conversion
15846 // on the object argument, then let BuildCallExpr finish the job.
15847
15848 // Create an implicit member expr to refer to the conversion operator.
15849 // and then call it.
15850 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15851 Conv, HadMultipleCandidates);
15852 if (Call.isInvalid())
15853 return ExprError();
15854 // Record usage of conversion in an implicit cast.
15856 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15857 nullptr, VK_PRValue, CurFPFeatureOverrides());
15858
15859 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15860 }
15861
15862 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15863
15864 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15865 // that calls this method, using Object for the implicit object
15866 // parameter and passing along the remaining arguments.
15867 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15868
15869 // An error diagnostic has already been printed when parsing the declaration.
15870 if (Method->isInvalidDecl())
15871 return ExprError();
15872
15873 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15874 unsigned NumParams = Proto->getNumParams();
15875
15876 DeclarationNameInfo OpLocInfo(
15877 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15878 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15879 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15880 Obj, HadMultipleCandidates,
15881 OpLocInfo.getLoc(),
15882 OpLocInfo.getInfo());
15883 if (NewFn.isInvalid())
15884 return true;
15885
15886 SmallVector<Expr *, 8> MethodArgs;
15887 MethodArgs.reserve(NumParams + 1);
15888
15889 bool IsError = false;
15890
15891 // Initialize the object parameter.
15893 if (Method->isExplicitObjectMemberFunction()) {
15894 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15895 } else {
15896 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15897 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15898 if (ObjRes.isInvalid())
15899 IsError = true;
15900 else
15901 Object = ObjRes;
15902 MethodArgs.push_back(Object.get());
15903 }
15904
15906 *this, MethodArgs, Method, Args, LParenLoc);
15907
15908 // If this is a variadic call, handle args passed through "...".
15909 if (Proto->isVariadic()) {
15910 // Promote the arguments (C99 6.5.2.2p7).
15911 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15912 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15913 nullptr);
15914 IsError |= Arg.isInvalid();
15915 MethodArgs.push_back(Arg.get());
15916 }
15917 }
15918
15919 if (IsError)
15920 return true;
15921
15922 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15923
15924 // Once we've built TheCall, all of the expressions are properly owned.
15925 QualType ResultTy = Method->getReturnType();
15927 ResultTy = ResultTy.getNonLValueExprType(Context);
15928
15930 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15931 CurFPFeatureOverrides());
15932
15933 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15934 return true;
15935
15936 if (CheckFunctionCall(Method, TheCall, Proto))
15937 return true;
15938
15939 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15940}
15941
15944 bool *NoArrowOperatorFound) {
15945 assert(Base->getType()->isRecordType() &&
15946 "left-hand side must have class type");
15947
15949 return ExprError();
15950
15951 SourceLocation Loc = Base->getExprLoc();
15952
15953 // C++ [over.ref]p1:
15954 //
15955 // [...] An expression x->m is interpreted as (x.operator->())->m
15956 // for a class object x of type T if T::operator->() exists and if
15957 // the operator is selected as the best match function by the
15958 // overload resolution mechanism (13.3).
15959 DeclarationName OpName =
15960 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15962
15963 if (RequireCompleteType(Loc, Base->getType(),
15964 diag::err_typecheck_incomplete_tag, Base))
15965 return ExprError();
15966
15967 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15968 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15970
15971 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15972 Oper != OperEnd; ++Oper) {
15973 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15974 {}, CandidateSet,
15975 /*SuppressUserConversion=*/false);
15976 }
15977
15978 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15979
15980 // Perform overload resolution.
15982 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15983 case OR_Success:
15984 // Overload resolution succeeded; we'll build the call below.
15985 break;
15986
15987 case OR_No_Viable_Function: {
15988 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15989 if (CandidateSet.empty()) {
15990 QualType BaseType = Base->getType();
15991 if (NoArrowOperatorFound) {
15992 // Report this specific error to the caller instead of emitting a
15993 // diagnostic, as requested.
15994 *NoArrowOperatorFound = true;
15995 return ExprError();
15996 }
15997 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15998 << BaseType << Base->getSourceRange();
15999 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16000 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16001 << FixItHint::CreateReplacement(OpLoc, ".");
16002 }
16003 } else
16004 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16005 << "operator->" << Base->getSourceRange();
16006 CandidateSet.NoteCandidates(*this, Base, Cands);
16007 return ExprError();
16008 }
16009 case OR_Ambiguous:
16010 if (!R.isAmbiguous())
16011 CandidateSet.NoteCandidates(
16012 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16013 << "->" << Base->getType()
16014 << Base->getSourceRange()),
16016 return ExprError();
16017
16018 case OR_Deleted: {
16019 StringLiteral *Msg = Best->Function->getDeletedMessage();
16020 CandidateSet.NoteCandidates(
16021 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16022 << "->" << (Msg != nullptr)
16023 << (Msg ? Msg->getString() : StringRef())
16024 << Base->getSourceRange()),
16025 *this, OCD_AllCandidates, Base);
16026 return ExprError();
16027 }
16028 }
16029
16030 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16031
16032 // Convert the object parameter.
16033 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16034
16035 if (Method->isExplicitObjectMemberFunction()) {
16036 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16037 if (R.isInvalid())
16038 return ExprError();
16039 Base = R.get();
16040 } else {
16041 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16042 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16043 if (BaseResult.isInvalid())
16044 return ExprError();
16045 Base = BaseResult.get();
16046 }
16047
16048 // Build the operator call.
16049 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16050 Base, HadMultipleCandidates, OpLoc);
16051 if (FnExpr.isInvalid())
16052 return ExprError();
16053
16054 QualType ResultTy = Method->getReturnType();
16056 ResultTy = ResultTy.getNonLValueExprType(Context);
16057
16058 CallExpr *TheCall =
16059 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16060 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16061
16062 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16063 return ExprError();
16064
16065 if (CheckFunctionCall(Method, TheCall,
16066 Method->getType()->castAs<FunctionProtoType>()))
16067 return ExprError();
16068
16069 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16070}
16071
16073 DeclarationNameInfo &SuffixInfo,
16074 ArrayRef<Expr*> Args,
16075 SourceLocation LitEndLoc,
16076 TemplateArgumentListInfo *TemplateArgs) {
16077 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16078
16079 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16081 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16082 TemplateArgs);
16083
16084 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16085
16086 // Perform overload resolution. This will usually be trivial, but might need
16087 // to perform substitutions for a literal operator template.
16089 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16090 case OR_Success:
16091 case OR_Deleted:
16092 break;
16093
16095 CandidateSet.NoteCandidates(
16096 PartialDiagnosticAt(UDSuffixLoc,
16097 PDiag(diag::err_ovl_no_viable_function_in_call)
16098 << R.getLookupName()),
16099 *this, OCD_AllCandidates, Args);
16100 return ExprError();
16101
16102 case OR_Ambiguous:
16103 CandidateSet.NoteCandidates(
16104 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16105 << R.getLookupName()),
16106 *this, OCD_AmbiguousCandidates, Args);
16107 return ExprError();
16108 }
16109
16110 FunctionDecl *FD = Best->Function;
16111 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16112 nullptr, HadMultipleCandidates,
16113 SuffixInfo.getLoc(),
16114 SuffixInfo.getInfo());
16115 if (Fn.isInvalid())
16116 return true;
16117
16118 // Check the argument types. This should almost always be a no-op, except
16119 // that array-to-pointer decay is applied to string literals.
16120 Expr *ConvArgs[2];
16121 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16122 ExprResult InputInit = PerformCopyInitialization(
16124 SourceLocation(), Args[ArgIdx]);
16125 if (InputInit.isInvalid())
16126 return true;
16127 ConvArgs[ArgIdx] = InputInit.get();
16128 }
16129
16130 QualType ResultTy = FD->getReturnType();
16132 ResultTy = ResultTy.getNonLValueExprType(Context);
16133
16135 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16136 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16137
16138 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16139 return ExprError();
16140
16141 if (CheckFunctionCall(FD, UDL, nullptr))
16142 return ExprError();
16143
16144 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16145}
16146
16149 SourceLocation RangeLoc,
16150 const DeclarationNameInfo &NameInfo,
16151 LookupResult &MemberLookup,
16152 OverloadCandidateSet *CandidateSet,
16154 Scope *S = nullptr;
16155
16157 if (!MemberLookup.empty()) {
16158 ExprResult MemberRef =
16159 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16160 /*IsPtr=*/false, CXXScopeSpec(),
16161 /*TemplateKWLoc=*/SourceLocation(),
16162 /*FirstQualifierInScope=*/nullptr,
16163 MemberLookup,
16164 /*TemplateArgs=*/nullptr, S);
16165 if (MemberRef.isInvalid()) {
16166 *CallExpr = ExprError();
16167 return FRS_DiagnosticIssued;
16168 }
16169 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16170 if (CallExpr->isInvalid()) {
16171 *CallExpr = ExprError();
16172 return FRS_DiagnosticIssued;
16173 }
16174 } else {
16175 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16177 NameInfo, UnresolvedSet<0>());
16178 if (FnR.isInvalid())
16179 return FRS_DiagnosticIssued;
16180 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16181
16182 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16183 CandidateSet, CallExpr);
16184 if (CandidateSet->empty() || CandidateSetError) {
16185 *CallExpr = ExprError();
16186 return FRS_NoViableFunction;
16187 }
16189 OverloadingResult OverloadResult =
16190 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16191
16192 if (OverloadResult == OR_No_Viable_Function) {
16193 *CallExpr = ExprError();
16194 return FRS_NoViableFunction;
16195 }
16196 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16197 Loc, nullptr, CandidateSet, &Best,
16198 OverloadResult,
16199 /*AllowTypoCorrection=*/false);
16200 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16201 *CallExpr = ExprError();
16202 return FRS_DiagnosticIssued;
16203 }
16204 }
16205 return FRS_Success;
16206}
16207
16209 FunctionDecl *Fn) {
16210 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16211 ExprResult SubExpr =
16212 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16213 if (SubExpr.isInvalid())
16214 return ExprError();
16215 if (SubExpr.get() == PE->getSubExpr())
16216 return PE;
16217
16218 return new (Context)
16219 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16220 }
16221
16222 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16223 ExprResult SubExpr =
16224 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16225 if (SubExpr.isInvalid())
16226 return ExprError();
16227 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16228 SubExpr.get()->getType()) &&
16229 "Implicit cast type cannot be determined from overload");
16230 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16231 if (SubExpr.get() == ICE->getSubExpr())
16232 return ICE;
16233
16234 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16235 SubExpr.get(), nullptr, ICE->getValueKind(),
16236 CurFPFeatureOverrides());
16237 }
16238
16239 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16240 if (!GSE->isResultDependent()) {
16241 ExprResult SubExpr =
16242 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16243 if (SubExpr.isInvalid())
16244 return ExprError();
16245 if (SubExpr.get() == GSE->getResultExpr())
16246 return GSE;
16247
16248 // Replace the resulting type information before rebuilding the generic
16249 // selection expression.
16250 ArrayRef<Expr *> A = GSE->getAssocExprs();
16251 SmallVector<Expr *, 4> AssocExprs(A);
16252 unsigned ResultIdx = GSE->getResultIndex();
16253 AssocExprs[ResultIdx] = SubExpr.get();
16254
16255 if (GSE->isExprPredicate())
16257 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16258 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16259 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16260 ResultIdx);
16262 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16263 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16264 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16265 ResultIdx);
16266 }
16267 // Rather than fall through to the unreachable, return the original generic
16268 // selection expression.
16269 return GSE;
16270 }
16271
16272 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16273 assert(UnOp->getOpcode() == UO_AddrOf &&
16274 "Can only take the address of an overloaded function");
16275 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16276 if (!Method->isImplicitObjectMemberFunction()) {
16277 // Do nothing: the address of static and
16278 // explicit object member functions is a (non-member) function pointer.
16279 } else {
16280 // Fix the subexpression, which really has to be an
16281 // UnresolvedLookupExpr holding an overloaded member function
16282 // or template.
16283 ExprResult SubExpr =
16284 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16285 if (SubExpr.isInvalid())
16286 return ExprError();
16287 if (SubExpr.get() == UnOp->getSubExpr())
16288 return UnOp;
16289
16290 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16291 SubExpr.get(), Method))
16292 return ExprError();
16293
16294 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16295 "fixed to something other than a decl ref");
16296 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16297 "fixed to a member ref with no nested name qualifier");
16298
16299 // We have taken the address of a pointer to member
16300 // function. Perform the computation here so that we get the
16301 // appropriate pointer to member type.
16302 QualType ClassType
16303 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16304 QualType MemPtrType
16305 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16306 // Under the MS ABI, lock down the inheritance model now.
16307 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16308 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16309
16310 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16311 MemPtrType, VK_PRValue, OK_Ordinary,
16312 UnOp->getOperatorLoc(), false,
16313 CurFPFeatureOverrides());
16314 }
16315 }
16316 ExprResult SubExpr =
16317 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16318 if (SubExpr.isInvalid())
16319 return ExprError();
16320 if (SubExpr.get() == UnOp->getSubExpr())
16321 return UnOp;
16322
16323 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16324 SubExpr.get());
16325 }
16326
16327 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16328 // FIXME: avoid copy.
16329 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16330 if (ULE->hasExplicitTemplateArgs()) {
16331 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16332 TemplateArgs = &TemplateArgsBuffer;
16333 }
16334
16335 QualType Type = Fn->getType();
16336 ExprValueKind ValueKind =
16337 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16338 ? VK_LValue
16339 : VK_PRValue;
16340
16341 // FIXME: Duplicated from BuildDeclarationNameExpr.
16342 if (unsigned BID = Fn->getBuiltinID()) {
16343 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16344 Type = Context.BuiltinFnTy;
16345 ValueKind = VK_PRValue;
16346 }
16347 }
16348
16349 DeclRefExpr *DRE = BuildDeclRefExpr(
16350 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16351 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16352 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16353 return DRE;
16354 }
16355
16356 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16357 // FIXME: avoid copy.
16358 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16359 if (MemExpr->hasExplicitTemplateArgs()) {
16360 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16361 TemplateArgs = &TemplateArgsBuffer;
16362 }
16363
16364 Expr *Base;
16365
16366 // If we're filling in a static method where we used to have an
16367 // implicit member access, rewrite to a simple decl ref.
16368 if (MemExpr->isImplicitAccess()) {
16369 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16370 DeclRefExpr *DRE = BuildDeclRefExpr(
16371 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16372 MemExpr->getQualifierLoc(), Found.getDecl(),
16373 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16374 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16375 return DRE;
16376 } else {
16377 SourceLocation Loc = MemExpr->getMemberLoc();
16378 if (MemExpr->getQualifier())
16379 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16380 Base =
16381 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16382 }
16383 } else
16384 Base = MemExpr->getBase();
16385
16386 ExprValueKind valueKind;
16387 QualType type;
16388 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16389 valueKind = VK_LValue;
16390 type = Fn->getType();
16391 } else {
16392 valueKind = VK_PRValue;
16393 type = Context.BoundMemberTy;
16394 }
16395
16396 return BuildMemberExpr(
16397 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16398 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16399 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16400 type, valueKind, OK_Ordinary, TemplateArgs);
16401 }
16402
16403 llvm_unreachable("Invalid reference to overloaded function");
16404}
16405
16408 FunctionDecl *Fn) {
16409 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16410}
16411
16412bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16414 if (!PartialOverloading || !Function)
16415 return true;
16416 if (Function->isVariadic())
16417 return false;
16418 if (const auto *Proto =
16419 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16420 if (Proto->isTemplateVariadic())
16421 return false;
16422 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16423 if (const auto *Proto =
16424 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16425 if (Proto->isTemplateVariadic())
16426 return false;
16427 return true;
16428}
16429
16431 DeclarationName Name,
16432 OverloadCandidateSet &CandidateSet,
16433 FunctionDecl *Fn, MultiExprArg Args,
16434 bool IsMember) {
16435 StringLiteral *Msg = Fn->getDeletedMessage();
16436 CandidateSet.NoteCandidates(
16437 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16438 << IsMember << Name << (Msg != nullptr)
16439 << (Msg ? Msg->getString() : StringRef())
16440 << Range),
16441 *this, OCD_AllCandidates, Args);
16442}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
StringRef P
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
LangStandard::Kind Std
#define X(type, name)
Definition: Value.h:144
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.
static std::string getName(const CallEvent &Call)
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...
Definition: SemaInit.cpp:5929
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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 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.
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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 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 ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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 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 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 ...
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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 bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
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 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)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
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 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 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 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
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:869
iterator end()
Definition: Lookup.h:893
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:885
iterator begin()
Definition: Lookup.h:892
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:890
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:439
bool isFloat() const
Definition: APValue.h:444
bool isInt() const
Definition: APValue.h:443
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
APFloat & getFloat()
Definition: APValue.h:479
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
Definition: ASTContext.h:1169
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.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1172
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
CanQualType DoubleTy
Definition: ASTContext.h:1172
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType Char16Ty
Definition: ASTContext.h:1167
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
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 DependentTy
Definition: ASTContext.h:1188
CanQualType NullPtrTy
Definition: ASTContext.h:1187
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
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:834
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
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...
bool canBindObjCObjectType(QualType To, QualType From)
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType Ibm128Ty
Definition: ASTContext.h:1172
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>.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2413
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
Definition: ASTContext.h:1161
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:800
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3014
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1372
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType CharTy
Definition: ASTContext.h:1162
CanQualType IntTy
Definition: ASTContext.h:1169
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1188
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2196
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
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.
Definition: ASTContext.h:2482
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1171
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1381
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
CanQualType ShortTy
Definition: ASTContext.h:1169
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
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...
CanQualType Char32Ty
Definition: ASTContext.h:1168
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2284
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:799
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
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
Definition: ASTContext.h:1169
CanQualType WCharTy
Definition: ASTContext.h:1163
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1166
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:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3747
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition: Type.cpp:270
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7761
Attr - This represents one attribute.
Definition: Attr.h:43
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2189
StringRef getOpcodeStr() const
Definition: Expr.h:3975
bool isCompoundAssignmentOp() const
Definition: Expr.h:4053
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:4895
Pointer to a block type.
Definition: Type.h:3408
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:189
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2880
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2916
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2920
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
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:675
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:2549
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:2556
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2668
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2254
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2657
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2228
bool isStatic() const
Definition: DeclCXX.cpp:2280
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:611
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:1030
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1927
bool hasDefinition() const
Definition: DeclCXX.h:572
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1688
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
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:1492
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3206
static CallExpr * CreateTemporary(void *Mem, Expr *Fn, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, ADLCallKind UsesADL=NotADL)
Create a temporary call expression with no arguments in the memory pointed to by Mem.
Definition: Expr.cpp:1506
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)
Builds a canonical type from a QualType.
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 ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
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: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
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:4917
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
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:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2008
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
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:1452
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:258
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1179
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:293
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
bool isInvalidDecl() const
Definition: DeclBase.h:591
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:572
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:567
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
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...
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:792
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:810
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:769
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:754
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:745
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3847
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4052
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1936
const Expr * getExpr() const
Definition: DeclCXX.h:1921
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2237
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1446
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
bool isPRValue() const
Definition: Expr.h:383
bool isXValue() const
Definition: Expr.h:381
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition: Expr.h:388
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3095
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) 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:3086
bool isPRValue() const
Definition: Expr.h:278
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3310
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4124
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
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:3963
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
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:101
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3723
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
param_iterator param_end()
Definition: Decl.h:2662
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3542
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3741
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
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:4123
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
param_iterator param_begin()
Definition: Decl.h:2661
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4247
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4188
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3320
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4116
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3745
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3313
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4405
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4276
bool isConsteval() const
Definition: Decl.h:2410
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3586
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:2737
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:3591
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5568
unsigned getNumParams() const
Definition: Type.h:5355
Qualifiers getMethodQuals() const
Definition: Type.h:5497
QualType getParamType(unsigned i) const
Definition: Type.h:5357
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
ArrayRef< QualType > param_types() const
Definition: Type.h:5511
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getNoReturn() const
Definition: Type.h:4480
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4360
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4655
CallingConv getCallConv() const
Definition: Type.h:4654
QualType getReturnType() const
Definition: Type.h:4643
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4667
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:4515
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:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2082
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
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:618
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:715
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:622
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:766
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:626
bool hasInitializerListContainerType() const
Definition: Overload.h:748
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:679
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:755
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:630
QualType getInitializerListContainerType() const
Definition: Overload.h:758
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5088
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:5195
unsigned getNumInits() const
Definition: Expr.h:5118
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2494
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5134
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2512
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, NonTypeTemplateParmDecl *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:973
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:672
Represents the results of name lookup.
Definition: Lookup.h:46
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:605
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.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
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:641
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
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
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3425
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3333
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3454
Expr * getBase() const
Definition: Expr.h:3313
void setBase(Expr *E)
Definition: Expr.h:3312
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3347
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1806
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3431
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3323
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
Describes a module or submodule.
Definition: Module.h:115
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:240
This represents a decl that may have a name.
Definition: Decl.h:253
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1668
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:551
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:1153
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7524
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
unsigned param_size() const
Definition: DeclObjC.h:347
bool isVariadic() const
Definition: DeclObjC.h:431
Represents a pointer to an Objective C object.
Definition: Type.h:7580
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7669
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7638
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7592
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7632
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7644
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition: Overload.h:1169
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1196
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1162
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition: Overload.h:1033
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1029
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:1024
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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:1177
SourceLocation getLocation() const
Definition: Overload.h:1160
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1209
CandidateSetKind getKind() const
Definition: Overload.h:1161
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:2983
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3099
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3135
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3044
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3096
decls_iterator decls_begin() const
Definition: ExprCXX.h:3076
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3087
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3109
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3105
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3155
decls_iterator decls_end() const
Definition: ExprCXX.h:3079
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3093
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
Represents a parameter to a function.
Definition: Decl.h:1725
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4989
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8009
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8020
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
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: Type.h:8134
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1081
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: Type.h:8103
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8052
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7977
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
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: Type.h:8114
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7963
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7871
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7878
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4420
bool hasAtomic() const
Definition: Type.h:833
bool hasRestrict() const
Definition: Type.h:832
QualifiersAndAtomic withVolatile()
Definition: Type.h:845
QualifiersAndAtomic withAtomic()
Definition: Type.h:852
bool hasVolatile() const
Definition: Type.h:830
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:512
bool hasOnlyConst() const
Definition: Type.h:451
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
void removeObjCLifetime()
Definition: Type.h:544
bool hasConst() const
Definition: Type.h:450
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:720
void addRestrict()
Definition: Type.h:473
bool hasRestrict() const
Definition: Type.h:470
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: Type.h:701
void removeObjCGCAttr()
Definition: Type.h:516
void removeUnaligned()
Definition: Type.h:508
void removeAddressSpace()
Definition: Type.h:589
void addConst()
Definition: Type.h:453
void setAddressSpace(LangAS space)
Definition: Type.h:584
bool hasVolatile() const
Definition: Type.h:460
bool hasObjCGCAttr() const
Definition: Type.h:511
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
void removeVolatile()
Definition: Type.h:462
std::string getAsString() const
LangAS getAddressSpace() const
Definition: Type.h:564
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:743
void addVolatile()
Definition: Type.h:463
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
Represents a struct/union/class.
Definition: Decl.h:4148
field_range fields() const
Definition: Decl.h:4354
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
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
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
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:134
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:370
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:312
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:318
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:225
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Definition: SemaObjC.cpp:1318
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:10031
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:5891
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5920
RAII class to control scope of DeferDiags.
Definition: Sema.h:9758
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:12086
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12116
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
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.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:9774
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:9002
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2452
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:165
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:1071
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
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:10114
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10117
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10123
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10121
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.
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:1665
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.
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:1570
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:909
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
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 isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition: Sema.h:1111
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...
ASTContext & getASTContext() const
Definition: Sema.h:532
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)
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:692
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....
ForRangeStatus
Definition: Sema.h:10479
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
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...
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AllowedExplicit
Definition: Sema.h:9834
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:817
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
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:11789
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
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...
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...
bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
const LangOptions & getLangOpts() const
Definition: Sema.h:525
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,...
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.
Definition: SemaExpr.cpp:6475
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
const LangOptions & LangOpts
Definition: Sema.h:907
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.
Definition: SemaExpr.cpp:6732
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
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)
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.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
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.
Definition: SemaExpr.cpp:9628
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.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
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...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15002
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
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:1044
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.
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7580
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7619
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7598
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7582
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7615
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20008
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20964
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:13502
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 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...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5487
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7563
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7600
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 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:216
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:14957
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3454
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,...
CCEKind
Contexts in which a converted constant expression is required.
Definition: Sema.h:9998
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10003
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:10004
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10002
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:10001
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.
OverloadKind
Definition: Sema.h:9776
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 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...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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.
SourceManager & SourceMgr
Definition: Sema.h:912
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2393
DiagnosticsEngine & Diags
Definition: Sema.h:911
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9713
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...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21161
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
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.
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:9698
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:393
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, 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...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
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)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
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:292
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:381
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:379
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:351
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
QualType getFromType() const
Definition: Overload.h:394
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:356
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:333
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:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:378
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:328
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:361
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:312
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:323
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:383
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:371
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:343
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition: Overload.h:308
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:347
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:338
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...
void setAllToTypes(QualType T)
Definition: Overload.h:388
QualType getToType(unsigned Idx) const
Definition: Overload.h:398
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
StringRef getString() const
Definition: Expr.h:1855
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:665
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:718
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:703
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:250
Represents a template argument.
Definition: TemplateBase.h:61
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.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
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.
Definition: TemplateName.h:237
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.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6661
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3395
The base class of the type hierarchy.
Definition: Type.h:1828
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isObjCBuiltinType() const
Definition: Type.h:8379
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
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:1933
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8266
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isFloat16Type() const
Definition: Type.h:8519
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isRValueReferenceType() const
Definition: Type.h:8212
bool isConstantArrayType() const
Definition: Type.h:8262
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8668
bool isArrayType() const
Definition: Type.h:8258
bool isCharType() const
Definition: Type.cpp:2123
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:8575
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isPointerType() const
Definition: Type.h:8186
bool isArrayParameterType() const
Definition: Type.h:8274
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isEnumeralType() const
Definition: Type.h:8290
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
bool isObjCQualifiedIdType() const
Definition: Type.h:8349
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2159
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8336
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8208
bool isBitIntType() const
Definition: Type.h:8424
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isAnyComplexType() const
Definition: Type.h:8294
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
bool isHalfType() const
Definition: Type.h:8514
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8492
bool isQueueT() const
Definition: Type.h:8405
bool isMemberPointerType() const
Definition: Type.h:8240
bool isObjCIdType() const
Definition: Type.h:8361
bool isMatrixType() const
Definition: Type.h:8316
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isEventT() const
Definition: Type.h:8397
bool isBFloat16Type() const
Definition: Type.h:8531
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool isVectorType() const
Definition: Type.h:8298
bool isObjCClassType() const
Definition: Type.h:8367
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
bool isHLSLAttributedResourceType() const
Definition: Type.h:8471
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:2230
bool isAnyPointerType() const
Definition: Type.h:8194
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSamplerT() const
Definition: Type.h:8393
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1425
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:4952
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1401
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3203
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3272
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:419
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3943
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4051
QualType getBaseType() const
Definition: ExprCXX.h:4025
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4035
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4016
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4061
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4055
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:90
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
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:637
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition: ExprCXX.cpp:949
QualType getType() const
Definition: Decl.h:682
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
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...
Definition: AttrIterator.h:35
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC)
Definition: Interp.h:318
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)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
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:145
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:798
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:826
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:835
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:818
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:822
@ 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:863
@ ovl_fail_too_few_arguments
Definition: Overload.h:800
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:842
@ ovl_fail_too_many_arguments
Definition: Overload.h:799
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:850
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:859
@ ovl_fail_bad_conversion
Definition: Overload.h:801
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:831
@ ovl_fail_bad_deduction
Definition: Overload.h:802
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:846
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:855
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:839
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:807
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1771
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:215
@ ICR_Conversion
Conversion.
Definition: Overload.h:229
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:241
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition: Overload.h:251
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition: Overload.h:257
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition: Overload.h:220
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:244
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:232
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:238
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition: Overload.h:235
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition: Overload.h:254
@ ICR_Promotion
Promotion.
Definition: Overload.h:223
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:217
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:248
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition: Overload.h:226
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
BinaryOperatorKind
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition: Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
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
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
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:205
@ 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:202
@ 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:208
@ 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_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
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
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:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition: Sema.h:211
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:423
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
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 isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
const FunctionProtoType * T
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition: Overload.h:268
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:365
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
@ 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.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1272
@ None
The alignment was not explicit in code.
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.
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:467
ConversionSet::const_iterator const_iterator
Definition: Overload.h:503
ConversionSet & conversions()
Definition: Overload.h:486
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:494
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:469
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:552
QualType getFromType() const
Definition: Overload.h:551
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.
std::optional< unsigned > getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, 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.
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.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
Extra information about a function prototype.
Definition: Type.h:5187
FunctionEffectsRef FunctionEffects
Definition: Type.h:5197
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5195
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1038
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition: Overload.h:1051
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1087
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1060
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1077
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
CallExpr::ADLCallKind IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:929
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:971
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:959
bool IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:915
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:886
bool IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:924
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:882
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:877
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:901
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:933
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:898
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:950
unsigned getNumParams() const
Definition: Overload.h:984
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:941
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:937
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:895
DeductionFailureInfo DeductionFailure
Definition: Overload.h:944
bool Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:910
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:890
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:955
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12660
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12748
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12780
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10131
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7858
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:862
const Type * Ty
The locally-unqualified type.
Definition: Type.h:864
Qualifiers Quals
The local qualifiers.
Definition: Type.h:867
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.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition: Overload.h:422
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:434
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:456
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:447
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:451
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:442
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:461
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.